forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLInsert.swift
59 lines (49 loc) · 1.94 KB
/
PostgreSQLInsert.swift
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/// PostgreSQL specific `SQLInsert`.
public struct PostgreSQLInsert: SQLInsert {
/// See `SQLInsert`.
public static func insert(_ table: PostgreSQLTableIdentifier) -> PostgreSQLInsert {
return self.init(table: table, columns: [], values: [], upsert: nil, returning: [])
}
/// See `SQLInsert`.
public typealias TableIdentifier = PostgreSQLTableIdentifier
/// See `SQLInsert`.
public typealias ColumnIdentifier = PostgreSQLColumnIdentifier
/// See `SQLInsert`.
public typealias Expression = PostgreSQLExpression
/// See `SQLInsert`.
public typealias Upsert = PostgreSQLUpsert
/// Table to insert into.
public var table: TableIdentifier
/// See `SQLInsert`.
public var columns: [PostgreSQLColumnIdentifier]
/// See `SQLInsert`.
public var values: [[PostgreSQLExpression]]
/// Optional "upsert" condition.
public var upsert: PostgreSQLUpsert?
/// `RETURNING *`
public var returning: [PostgreSQLSelectExpression]
/// See `SQLSerializable`.
public func serialize(_ binds: inout [Encodable]) -> String {
var sql: [String] = []
sql.append("INSERT INTO")
sql.append(table.serialize(&binds))
sql.append("(" + columns.serialize(&binds) + ")")
sql.append("VALUES")
sql.append(values.map { "(" + $0.serialize(&binds) + ")"}.joined(separator: ", "))
if let upsert = upsert {
sql.append(upsert.serialize(&binds))
}
if !returning.isEmpty {
sql.append("RETURNING")
sql.append(returning.serialize(&binds))
}
return sql.joined(separator: " ")
}
}
extension SQLInsertBuilder where Connectable.Connection.Query.Insert == PostgreSQLInsert {
/// Adds a `RETURNING` expression to the insert query.
public func returning(_ exprs: PostgreSQLSelectExpression...) -> Self {
insert.returning += exprs
return self
}
}