For example I have a table named myTable
in my database file (Android, p.s. it doesn't support column renaming, deleting and so on).
This table has idx
, name
columns
I want to delete and recreate this table but with new columns
Here how I do it:
db.transaction {
var cursor = query("myTable", null, null, null, null, null, null)
// save info to a list and insert it later to a recreated table with new columns
cursor.close()
// delete table "myTable"
execSQL("DROP TABLE IF EXISTS myTable")
// create table "myTable" but with new columns
execSQL("CREATE TABLE myTable(id, title)")
// get columns
cursor = query("myTable", null, null, null, null, null, null)
val columnNames = cursor.columnNames
cursor.close()
Log.i(TAG, "columns of new table ${Arrays.toString(columnNames)}")
}
But cursor.columnNames
doesn't return new columns (id
, title
)
It returns the old columns (e.g., idx
, name
)
Though when I close the app and open again everything is ok (old columns are gone and new ones are available)
So annoying!
So new columns are created ok in main.db/myTable
during all this process but seems the app still keeps old columns in memory
I can't even use cursor.getString(cursor.getColumnIndex("title"))
(would return -1
) because it still thinks that this column doesn't exist yet until I restart this app
BUT! Recreating a table with new columns works fine if I don't use cursor
to backup data (info) before I delete the old table
db.transaction {
// !! I COMMENTED THESE LINES
// var cursor = query("myTable", null, null, null, null, null, null)
// save info to a list and insert it later to a recreated table with new columns
// cursor.close()
// delete table "myTable"
execSQL("DROP TABLE IF EXISTS myTable")
// create table "myTable" but with new columns
execSQL("CREATE TABLE myTable(id, title)")
// get columns
cursor = query("myTable", null, null, null, null, null, null)
val columnNames = cursor.columnNames
cursor.close()
Log.i(TAG, "columns of new table ${Arrays.toString(columnNames)}")
}
In this case cursor.columnNames
returns new columns id
, title
This is crazy!
So it seems query table1
, drop table1
, create table1
, query table1
sequence would lead to an unexpected behavior
And we can only do drop table1
, create table1
, query table1
sequence