xavierlacot / joli.js

joli.js is an Activerecord-like javascript ORM, particularly suited for being used in the Appcelerator Titanium Mobile framework.
MIT License
267 stars 60 forks source link

Why is migrate always dropping table by default? #35

Open patakijv opened 11 years ago

patakijv commented 11 years ago

I really like this little js orm library and have used it most of its functionality with success.

I see an under utilized area (from our use and through lack of examples out there) for the built in migration capability.

Other than the fact that there no actual specific migrate commands (such create, add, remove, rename, etc), one major obstacle I see is that ( https://github.com/xavierlacot/joli.js/blob/master/joli.js#L394) any migration is always dropping the table if it exists. This basically makes it a destructive migration and seems to me to question the point of migrating vs just recreating whenever you want.

Here is the function below and the line in question is the DROP for each model... - its not wrapped with any conditional other than if the version is outdated...

    migrate: function(version, migrationCallback) {
        // create migration table
        var query = 'CREATE TABLE IF NOT EXISTS ' + this.migration.table + ' (version)';
        joli.connection.execute(query);

        if (this.migration.getVersion() < version) {
            joli.each(this.models, function(model, modelName) {
                var query = 'DROP TABLE IF EXISTS ' + modelName;
                joli.connection.execute(query);
            });
            // optional migration callback
            if (migrationCallback && 'function' === joli.getType(migrationCallback)) {
                migrationCallback({
                    table: this.migration.table,
                    newVersion: version
                });
            }

            // insert migration
            this.migration.setVersion(version);
        }
    },

A true migration, in my experience, would be able to add/modify an existing database table (one with rows, data, etc already) without destroying it first.

Am I missing something here?

My plan is to update / modify this functionality so that the default migration path does not destroy the table and only as an optional argument passed into the function would the drop occur first. This way you can always preserve existing user data in the database and still migrate in a non destructive manner. This will also be followed up with adding in the basic expected migrate specific commands

createTable dropTable addColumn removeColumn etc

Before I get too far down this path, I'd like to know the reason the current default is to drop first when migrating table in case there is some glaring problem with this thinking. Was it simply to avoid the need for having the additional commands listed above?