I'm currently trying to make changes to an existing DB using the migrations plugin for PersistenceJS. I can add/edit/delete items in the DB just fine — but…
- How to add a column to an existing(!) table?
How to change the type of an existing(!) column, e.g. from 'text' to 'integer'?
These changes should retain currently existing data.
Sadly, the documentation is a little scarce, maybe you could help?
Here's the current, working setup:
persistence.store.websql.config(persistence, 'tododatabase', 'todos are fun', 5*1024*1024);
var Todo = persistence.define('Todo', {
task: 'TEXT',
priority: 'INT',
done: 'BOOL'
});
persistence.schemaSync();
function addTodo( item ){
var todo = new Todo();
todo.task = item.task;
todo.priority = item.priority;
todo.done = item.done;
persistence.add(todo);
persistence.flush();
};
function deleteTodo( item, callback ){
// item.id was created automatically by calling "new Todo()"
Todo.all().filter('id','=', item.id ).destroyAll( function(){
persistence.flush( callback );
});
};
The migration code that kinda works:
persistence.defineMigration(1, {
up: function() {
this.createTable('Todo', function(t){
t.text('task');
t.integer('priority');
t.boolean('done');
});
},
down: function() {
this.dropTable('Todo');
}
});
persistence.defineMigration(2, {
up: function() {
this.addColumn('Todo', 'due', 'DATE');
},
down: function() {
this.removeColumn('Todo', 'due');
}
});
function migrate( callback ){
console.log('migrating...');
persistence.migrations.init( function(){
console.log('migration init');
// this should migrate up to the latest version, in our case: 2
persistence.migrate( function(){
console.log('migration complete!');
} );
});
}
Results…
- calling migrate() will only log up to "migration init", the complete handler is never called, the "due" column is not created
- not calling schemaSync() before calling migrate() as Zef Hemel himself proposed in this post yields the same result as 1.
- changing the first line to
persistence.store.websql.config(persistence, 'newdatabase', 'testing migration', 5*1024*1024);
, not calling schemaSync() and only calling migrate() will successfully log "migration complete!" — but it does so in a new, completely empty database "newdatabase", which will of course not retain any exsiting data.
Summary
There is a database that was created using persistence.store.websql.config(...)
, persistence.define('Todo',...)
and persistence.schemaSync()
.
I now want to keep all the data that already exist in that database, but want to
- change the type of column
priority
from 'integer' to 'text' - add a column
due
with type 'date' to all existing Todos
If you could push me in the right direction, I'd greatly appreciate it!
Thanks!