Skip to content

Commit

Permalink
Merge pull request #88 from vapor/alter-table-drop
Browse files Browse the repository at this point in the history
add ALTER TABLE drop actions
  • Loading branch information
tanner0101 authored Jul 6, 2018
2 parents c34533e + 6133e94 commit 7d87337
Showing 1 changed file with 60 additions and 1 deletion.
61 changes: 60 additions & 1 deletion Sources/PostgreSQL/SQL/PostgreSQLAlterTable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,62 @@ public struct PostgreSQLAlterTable: SQLAlterTable {
/// 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`.
///
Expand All @@ -29,14 +85,17 @@ public struct PostgreSQLAlterTable: SQLAlterTable {
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) }
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: " ")
}
Expand Down

0 comments on commit 7d87337

Please sign in to comment.