forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLAlterTable.swift
102 lines (86 loc) · 3.11 KB
/
PostgreSQLAlterTable.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/// Represents an `ALTER TABLE ...` query.
public struct PostgreSQLAlterTable: SQLAlterTable {
/// See `SQLAlterTable`.
public typealias ColumnDefinition = PostgreSQLColumnDefinition
/// See `SQLAlterTable`.
public typealias TableIdentifier = PostgreSQLTableIdentifier
/// See `SQLAlterTable`.
public static func alterTable(_ table: PostgreSQLTableIdentifier) -> PostgreSQLAlterTable {
return .init(table: table)
}
/// Name of table to alter.
public var table: PostgreSQLTableIdentifier
/// See `SQLAlterTable`.
public var columns: [PostgreSQLColumnDefinition]
/// See `SQLAlterTable`.
public var constraints: [PostgreSQLTableConstraint]
/// DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]
/// DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ]
public struct DropAction: SQLSerializable {
public enum Method {
case restrict
case cascade
}
public enum Kind {
case column
case constraint
}
public var kind: Kind
public var ifExists: Bool
public var column: PostgreSQLIdentifier
public var method: Method?
public init(
_ kind: Kind,
ifExists: Bool = false,
_ column: PostgreSQLIdentifier,
_ method: Method? = nil
) {
self.kind = kind
self.ifExists = ifExists
self.column = column
self.method = method
}
/// See `SQLSerializable`.
public func serialize(_ binds: inout [Encodable]) -> String {
var sql: [String] = []
sql.append("DROP")
switch kind {
case .column: sql.append("COLUMN")
case .constraint: sql.append("CONSTRAINT")
}
if ifExists {
sql.append("IF EXISTS")
}
sql.append(column.serialize(&binds))
if let method = method {
switch method {
case .cascade: sql.append("CASCADE")
case .restrict: sql.append("RESTRICT")
}
}
return sql.joined(separator: " ")
}
}
public var dropActions: [DropAction]
/// Creates a new `AlterTable`.
///
/// - parameters:
/// - table: Name of table to alter.
public init(table: PostgreSQLTableIdentifier) {
self.table = table
self.columns = []
self.constraints = []
self.dropActions = []
}
/// See `SQLSerializable`.
public func serialize(_ binds: inout [Encodable]) -> String {
var sql: [String] = []
sql.append("ALTER TABLE")
sql.append(table.serialize(&binds))
let actions = columns.map { "ADD COLUMN " + $0.serialize(&binds) }
+ constraints.map { "ADD " + $0.serialize(&binds) }
+ dropActions.map { $0.serialize(&binds) }
sql.append(actions.joined(separator: ", "))
return sql.joined(separator: " ")
}
}