Skip to content

Commit 7d87337

Browse files
authored
Merge pull request #88 from vapor/alter-table-drop
add ALTER TABLE drop actions
2 parents c34533e + 6133e94 commit 7d87337

File tree

1 file changed

+60
-1
lines changed

1 file changed

+60
-1
lines changed

Sources/PostgreSQL/SQL/PostgreSQLAlterTable.swift

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,62 @@ public struct PostgreSQLAlterTable: SQLAlterTable {
2020
/// See `SQLAlterTable`.
2121
public var constraints: [PostgreSQLTableConstraint]
2222

23+
/// DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]
24+
/// DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ]
25+
public struct DropAction: SQLSerializable {
26+
public enum Method {
27+
case restrict
28+
case cascade
29+
}
30+
31+
public enum Kind {
32+
case column
33+
case constraint
34+
}
35+
36+
public var kind: Kind
37+
38+
public var ifExists: Bool
39+
40+
public var column: PostgreSQLIdentifier
41+
42+
public var method: Method?
43+
44+
public init(
45+
_ kind: Kind,
46+
ifExists: Bool = false,
47+
_ column: PostgreSQLIdentifier,
48+
_ method: Method? = nil
49+
) {
50+
self.kind = kind
51+
self.ifExists = ifExists
52+
self.column = column
53+
self.method = method
54+
}
55+
56+
/// See `SQLSerializable`.
57+
public func serialize(_ binds: inout [Encodable]) -> String {
58+
var sql: [String] = []
59+
sql.append("DROP")
60+
switch kind {
61+
case .column: sql.append("COLUMN")
62+
case .constraint: sql.append("CONSTRAINT")
63+
}
64+
if ifExists {
65+
sql.append("IF EXISTS")
66+
}
67+
sql.append(column.serialize(&binds))
68+
if let method = method {
69+
switch method {
70+
case .cascade: sql.append("CASCADE")
71+
case .restrict: sql.append("RESTRICT")
72+
}
73+
}
74+
return sql.joined(separator: " ")
75+
}
76+
}
77+
78+
public var dropActions: [DropAction]
2379

2480
/// Creates a new `AlterTable`.
2581
///
@@ -29,14 +85,17 @@ public struct PostgreSQLAlterTable: SQLAlterTable {
2985
self.table = table
3086
self.columns = []
3187
self.constraints = []
88+
self.dropActions = []
3289
}
3390

3491
/// See `SQLSerializable`.
3592
public func serialize(_ binds: inout [Encodable]) -> String {
3693
var sql: [String] = []
3794
sql.append("ALTER TABLE")
3895
sql.append(table.serialize(&binds))
39-
let actions = columns.map { "ADD COLUMN " + $0.serialize(&binds) } + constraints.map { "ADD " + $0.serialize(&binds) }
96+
let actions = columns.map { "ADD COLUMN " + $0.serialize(&binds) }
97+
+ constraints.map { "ADD " + $0.serialize(&binds) }
98+
+ dropActions.map { $0.serialize(&binds) }
4099
sql.append(actions.joined(separator: ", "))
41100
return sql.joined(separator: " ")
42101
}

0 commit comments

Comments
 (0)