localStorageDB icon indicating copy to clipboard operation
localStorageDB copied to clipboard

How to Drop Column with alterTable?

Open Valkhan opened this issue 7 years ago • 2 comments

I read the docs and it seems that alterTable only ADDs new columns, is there any default drop column method for alter table?

Valkhan avatar Aug 07 '17 21:08 Valkhan

You're right, looks like it was forgotten. I'll try to commit it to the repo sometime soon.

knadh avatar Aug 08 '17 03:08 knadh

@knadh In my case scenario I've created a DB Wrapper to make somethings easier and organized, some helper functions could be consider to merge in your main project if you think it's aligned with your goals of course.

Here's my example class (extract of my main class):

//-- Database Wrapper 
function DBWrapper(){

    //-- Self instance
    var db = this;

    //-- Schema for my database as:
    var schema = {
        'tablename': [{'field': {'some attributes'}},'...'],
        '__getFields': function(table){
            return typeof schema[table] !== 'undefined' ? Object.keys(schema[table]) : [];
        }
    };

    //-- Instance of localStorageDB
    var lsdb = new localStorageDB('mydbname', localStorage);

   //-- Get an array of tables: [CONSIDER MERGING THIS ONE]
    db.getTables = function()
    {
        var obj = JSON.parse(lsdb.serialize());
        return Object.keys(obj.tables);
    };

    //-- Check structural integrity
    db.structuralIntegrity = function(){
        var validTables = [];
        for (var table in schema) {
            if(!lsdb.tableExists(table)){
                validTables.push(table);
                lsdb.createTable(table,schema.__getFields(table));
            } else {
                validTables.push(table);
                var colsSchema = schema.__getFields(table).sort();
                //-- Check for new columns
                colsSchema.forEach(function(campo){
                    if(!lsdb.columnExists(table,campo)){
                        lsdb.alterTable(table,campo);
                    }
                });

                //-- @TODO: need to drop extra columns here
            }
        }
        //-- Remove invalid tables (not present on schema)
        db.getTables().forEach(function(table){
            if(validTables.indexOf(table) === -1){
                lsdb.dropTable(table);
            }
        });
    };

    //-- Runs structural check upon instantiation
    db.structuralIntegrity();
}

Thank you, I'll be waiting for dropColumn to be add.

Valkhan avatar Aug 08 '17 12:08 Valkhan