bodich
bodich

Reputation: 2215

How to delete column in SQLite.swift

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)")
}

Upvotes: 0

Views: 179

Answers (2)

bodich
bodich

Reputation: 2215

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()
    }
}

Upvotes: 0

sbooth
sbooth

Reputation: 16976

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")
}

Upvotes: 1

Related Questions