Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0c8b379

Browse files
implement proper PSQL upsert support
1 parent 652f565 commit 0c8b379

File tree

4 files changed

+31
-5
lines changed

4 files changed

+31
-5
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
extension _PostgreSQLModel {
2+
public func create(orUpdate: Bool, on conn: DatabaseConnectable) -> Future<Self> {
3+
return Self.query(on: conn).create(orUpdate: orUpdate, self)
4+
}
5+
}
6+
7+
extension QueryBuilder where Result: _PostgreSQLModel, Result.Database == Database {
8+
public func create(orUpdate: Bool, _ model: Result) -> Future<Result> {
9+
if orUpdate {
10+
let row = SQLQueryEncoder(PostgreSQLExpression.self).encode(model)
11+
let values = row.map { row -> (PostgreSQLIdentifier, PostgreSQLExpression) in
12+
return (.identifier(row.key), row.value)
13+
}
14+
self.query.upsert = .upsert([.keyPath(Result.idKey)], values)
15+
}
16+
return create(model)
17+
}
18+
19+
}

‎Sources/FluentPostgreSQL/PostgreSQLModel.swift‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
1-
public protocol PostgreSQLModel: Model where Self.Database == PostgreSQLDatabase, Self.ID == Int {
1+
public protocol _PostgreSQLModel: Model, PostgreSQLTable where Self.Database == PostgreSQLDatabase { }
2+
3+
extension _PostgreSQLModel {
4+
/// See `SQLTable`.
5+
public static var sqlTableIdentifierString: String {
6+
return entity
7+
}
8+
}
9+
10+
public protocol PostgreSQLModel: _PostgreSQLModel where Self.ID == Int {
211
/// This model's unique identifier.
312
var id: Int? { get set }
413
}

‎Sources/FluentPostgreSQL/PostgreSQLStringModel.swift‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import Foundation
2-
3-
public protocol PostgreSQLStringModel: Model where Self.Database == PostgreSQLDatabase, Self.ID == String {
1+
public protocol PostgreSQLStringModel: _PostgreSQLModel where Self.ID == String {
42
/// This model's unique identifier.
53
var id: String? { get set }
64
}

‎Sources/FluentPostgreSQL/PostgreSQLUUIDModel.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
public protocol PostgreSQLUUIDModel: Model where Self.Database ==PostgreSQLDatabase, Self.ID == UUID {
1+
public protocol PostgreSQLUUIDModel: _PostgreSQLModel where Self.ID == UUID {
22
/// This model's unique identifier.
33
var id: UUID? { get set }
44
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /