Skip to content

Commit e31ab0c

Browse files
committed
Add FluentSQLKitExtras utilities for SQLInsertBuilder.ignoringConflicts(with:) and SQLInsertBuilder.onConflict(with:do:)
1 parent 785f0bb commit e31ab0c

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Sources/SQLKitExtras/FluentSQLKitExtras/Builders/SQLInsertBuilder+FluentKeypaths.swift

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,29 @@ extension SQLInsertBuilder {
1818
}
1919
return self
2020
}
21+
22+
/// Allow specifying a column or columns for ignoring insert conflicts using Fluent model keypaths.
23+
@discardableResult
24+
public func ignoringConflicts<each F: Fields, each P: QueryAddressableProperty>(with keypaths: repeat KeyPath<each F, each P>) -> Self {
25+
var identifiers: [SQLIdentifier] = []
26+
for keypath in repeat each keypaths {
27+
identifiers.append(.identifier(keypath))
28+
}
29+
return self.ignoringConflicts(with: identifiers)
30+
}
31+
32+
/// Allow specifying a column or columns for resolving insert conflicts using Fluent model keypaths.
33+
@discardableResult
34+
public func onConflict<each F: Fields, each P: QueryAddressableProperty>(
35+
with keypaths: repeat KeyPath<each F, each P>,
36+
`do` updatePredicate: (SQLConflictUpdateBuilder) throws -> SQLConflictUpdateBuilder
37+
) rethrows -> Self {
38+
var identifiers: [SQLIdentifier] = []
39+
for keypath in repeat each keypaths {
40+
identifiers.append(.identifier(keypath))
41+
}
42+
return try self.onConflict(with: identifiers, do: updatePredicate)
43+
}
2144
}
2245

2346
extension SQLDatabase {

Tests/SQLKitExtrasTests/FluentSQLKitExtrasTests.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,8 @@ struct FluentSQLKitExtrasTests {
164164
@Test
165165
func insertBuilderExtensions() {
166166
#expect(serialize(MockSQLDatabase().insert(into: FooModel.self).columns(\FooModel.$field, \FooModel.$parent)) == #"INSERT INTO "foos" ("field", "parent_id")"#)
167+
#expect(serialize(MockSQLDatabase().insert(into: FooModel.self).ignoringConflicts(with: \FooModel.$field)) == #"INSERT INTO "foos" () ON CONFLICT ("field") DO NOTHING"#)
168+
#expect(serialize(MockSQLDatabase().insert(into: FooModel.self).onConflict(with: \FooModel.$field, do: { $0 })) == #"INSERT INTO "foos" () ON CONFLICT ("field") DO UPDATE SET"#)
167169
}
168170

169171
@Test

0 commit comments

Comments
 (0)