@@ -27,6 +27,8 @@ import Foundation
2727 12. If foreign keys constraints were originally enabled, reenable them now.
2828*/
2929public class SchemaChanger : CustomStringConvertible {
30+ typealias SQLiteVersion = ( Int , Int , Int )
31+
3032 enum SchemaChangeError : LocalizedError {
3133 case foreignKeyError( [ ForeignKeyError ] )
3234
@@ -46,9 +48,14 @@ public class SchemaChanger: CustomStringConvertible {
4648 case renameTable( String )
4749
4850 /// Returns non-nil if the operation can be executed with a simple SQL statement
49- func toSQL( _ table: String ) -> String ? {
51+ func toSQL( _ table: String , version : SQLiteVersion ) -> String ? {
5052 switch self {
51- case . add( let definition) : return " ALTER TABLE \( table. quote ( ) ) ADD COLUMN \( definition. toSQL ( ) ) "
53+ case . add( let definition) :
54+ return " ALTER TABLE \( table. quote ( ) ) ADD COLUMN \( definition. toSQL ( ) ) "
55+ case . renameColumn( let from, let to) where version. 0 >= 3 && version. 1 >= 25 :
56+ return " ALTER TABLE \( table. quote ( ) ) RENAME COLUMN \( from. quote ( ) ) TO \( to. quote ( ) ) "
57+ case . remove( let column) where version. 0 >= 3 && version. 1 >= 35 :
58+ return " ALTER TABLE \( table. quote ( ) ) DROP COLUMN \( column. quote ( ) ) "
5259 default : return nil
5360 }
5461 }
@@ -77,6 +84,7 @@ public class SchemaChanger: CustomStringConvertible {
7784 }
7885
7986 private let connection : Connection
87+ private let version : SQLiteVersion
8088 static let tempPrefix = " tmp_ "
8189 typealias Block = ( ) throws -> Void
8290 public typealias AlterTableDefinitionBlock = ( AlterTableDefinition ) -> Void
@@ -87,8 +95,14 @@ public class SchemaChanger: CustomStringConvertible {
8795 static let temp = Options ( rawValue: 1 )
8896 }
8997
90- public init ( connection: Connection ) {
98+ public convenience init ( connection: Connection ) {
99+ self . init ( connection: connection,
100+ version: connection. sqliteVersionTriple)
101+ }
102+
103+ init ( connection: Connection , version: SQLiteVersion ) {
91104 self . connection = connection
105+ self . version = version
92106 }
93107
94108 public func alter( table: String , block: AlterTableDefinitionBlock ) throws {
@@ -105,7 +119,7 @@ public class SchemaChanger: CustomStringConvertible {
105119 }
106120
107121 private func run( table: String , operation: Operation ) throws {
108- if let sql = operation. toSQL ( table) {
122+ if let sql = operation. toSQL ( table, version : version ) {
109123 try connection. run ( sql)
110124 } else {
111125 try doTheTableDance ( table: table, operation: operation)
0 commit comments