1

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)")
}
bodich
  • 1,708
  • 12
  • 31

2 Answers2

1

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")
}
sbooth
  • 16,646
  • 2
  • 55
  • 81
  • Thanks! Maybe you know any older way for those who did not update this lib to 0.14.0? – bodich Jan 19 '23 at 09:40
  • 1
    Raw SQL would be another option- `ALTER TABLE DROP COLUMN xxx`. See https://sqlite.org/lang_altertable.html – sbooth Jan 19 '23 at 15:54
  • You can extend your answer with such working solution for SQLite.swift and I'll pick it as the correct answer then. – bodich Jan 25 '23 at 10:57
0

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()
    }
}
bodich
  • 1,708
  • 12
  • 31