-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathUpsert.swift
More file actions
41 lines (36 loc) · 1.39 KB
/
Upsert.swift
File metadata and controls
41 lines (36 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// Upsert.swift
// PostgresStORM
//
// Created by Jonathan Guthrie on 2016-09-24.
//
//
import StORM
import PerfectLogger
/// An extention ot the main class that provides PostgreSQL-specific "upsert" functionality.
extension PostgresStORM {
/// Inserts the row with the specified data, on conflict (conflickkeys columns) it will perform an update.
/// Specify matching arrays of columns and parameters, and an array of conflict key columns.
public func upsert(cols: [String], params: [Any], conflictkeys: [String]) throws {
var paramsString = [String]()
var substString = [String]()
var upsertString = [String]()
for i in 0..<params.count {
paramsString.append(String(describing: params[i]))
substString.append("$\(i+1)")
if i >= conflictkeys.count {
upsertString.append("\"\(String(describing: cols[i]))\" = $\(i+1)")
}
}
let colsjoined = "\"" + cols.joined(separator: "\",\"") + "\""
let conflictcolsjoined = "\"" + conflictkeys.joined(separator: "\",\"") + "\""
let str = "INSERT INTO \(self.table()) (\(colsjoined.lowercased())) VALUES(\(substString.joined(separator: ","))) ON CONFLICT (\(conflictcolsjoined.lowercased())) DO UPDATE SET \(upsertString.joined(separator: ","))"
do {
try exec(str, params: paramsString)
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
self.error = StORMError.error("\(error)")
throw error
}
}
}