How to delete column in SQLite.swift

120 Views Asked by At

I am trying to do a SQLite.swift (v 0.12.2) migration which will delete column. But I can't found any method in documentation for that. I see only addColumn, but no any for deletion. How is it designed to work to Delete Column?

The only way I've found for now is getting all data, dropping table and recreating table. But that doesn't look efficient at all.

let cachedItems = ... //Getting all items
let table = Table("TableName")
do {
    try Database.db.run(table())
    SomeTableModel().createTable()
    cachedItems.saveAllToDB()
} catch {
    print("Can't finish migration \(version)")
}
2

There are 2 best solutions below

0
bodich On BEST ANSWER

For the SQLite.swift version lower than 0.14.0

extension Connection {
    func dropColumn(tableName: String, columnName: String) throws {
        let dropStatement = try self.prepare("ALTER TABLE \(tableName) DROP COLUMN \(columnName)")
        try dropStatement.run()
    }
}
3
sbooth On

The docs for SchemaChanger give an example of dropping a column:

let schemaChanger = SchemaChanger(connection: db)
try schemaChanger.alter(table: "users") { table in
    table.drop(column: "email")
}