knadh / localStorageDB

A simple database layer for localStorage and sessionStorage for creating structured data in the form of databases and tables
http://nadh.in/code/localstoragedb
814 stars 128 forks source link

How to Drop Column with alterTable? #79

Closed Valkhan closed 2 years ago

Valkhan commented 7 years ago

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

knadh commented 7 years ago

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

Valkhan commented 7 years ago

@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.