forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLSerializer.swift
51 lines (46 loc) · 1.63 KB
/
PostgreSQLSerializer.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
/// PostgreSQL-flavored `SQLSerializer`.
public final class PostgreSQLSerializer: SQLSerializer {
public typealias Database = PostgreSQLDatabase
/// The current placeholder offset used to create PostgreSQL
/// placeholders for parameterized queries.
public var placeholderOffset: Int
/// Creates a new `PostgreSQLSQLSerializer`
public init() {
self.placeholderOffset = 1
}
/// See `SQLSerializer`
public func serialize(columnType: Query<PostgreSQLDatabase>.ColumnType) -> String {
var sql: [String] = []
if columnType.parameters.isEmpty {
sql.append(columnType.name)
} else {
sql.append(columnType.name + "(" + columnType.parameters.joined(separator: ", ") + ")")
}
if columnType.primaryKey {
sql.append("PRIMARY KEY")
}
if !columnType.nullable {
sql.append("NOT NULL")
}
if columnType.generatedIdentity {
sql.append("GENERATED BY DEFAULT AS IDENTITY")
}
if let d = columnType.default {
sql.append("DEFAULT")
switch d {
case .computed(let computed): sql.append(serialize(column: computed))
case .unescaped(let string): sql.append(string)
}
}
return sql.joined(separator: " ")
}
/// See `SQLSerializer`
public func makeEscapedString(from string: String) -> String {
return "\"\(string)\""
}
/// See `SQLSerializer`
public func makePlaceholder() -> String {
defer { placeholderOffset += 1 }
return "$\(placeholderOffset)"
}
}