## NDDB constructor

Creates a new instance of NDDB

@param {object} options Optional. Configuration options
@param {db} db Optional. An initial set of items to import
765200
function NDDB(options, db) {
        var that;
        that = this;
        options = options || {};

        // ## Public properties.

        // ### nddbid
        // A global index of all objects.
        this.nddbid = new NDDBIndex('nddbid', this);

        // ### db
        // The default database.
        this.db = [];

        // ### lastSelection
        // The subset of items that were selected during the last operation
        // Notice: some of the items might not exist any more in the database.
        // @see NDDB.fetch
        this.lastSelection = [];

        // ### nddbid
        // A global index of all hashed objects
        // @see NDDBHashtray
        this.hashtray = new NDDBHashtray();

        // ###tags
        // The tags list.
        this.tags = {};

        // ### hooks
        // The list of hooks and associated callbacks
        this.hooks = {
            insert: [],
            remove: [],
            update: []
        };

        // ### nddb_pointer
        // Pointer for iterating along all the elements
        this.nddb_pointer = 0;

        // ### query
        // QueryBuilder obj
        // @see QueryBuilder
        this.query = new QueryBuilder();

        // ### filters
        // Available db filters
        this.addDefaultFilters();

        // ### __userDefinedFilters
        // Filters that are defined with addFilter
        // The field is needed by cloneSettings
        // @see NDDB.addFilter
        this.__userDefinedFilters = {};

        // ### __C
        // List of comparator functions
        this.__C = {};

        // ### __H
        // List of hash functions
        this.__H = {};

        // ### __I
        // List of index functions
        this.__I = {};

        // ### __I
        // List of view functions
        this.__V = {};

        // ### __update
        // Auto update options container
        this.__update = {};

        // ### __update.pointer
        // If TRUE, nddb_pointer always points to the last insert
        this.__update.pointer = false;

        // ### __update.indexes
        // If TRUE, rebuild indexes on every insert and remove
        this.__update.indexes = false;

        // ### __update.sort
        // If TRUE, sort db on every insert and remove
        this.__update.sort = false;

        // ### __shared
        // Objects shared (not cloned) among breeded NDDB instances
        this.__shared = {};

        // ### __formats
        // Currently supported formats for saving/loading items.
        this.__formats = {};

        // ### __defaultFormat
        // Default format for saving and loading items.
        this.__defaultFormat = null;

        // ### __wd
        // Default working directory for saving and loading files.
        this.__wd = null;

        // ### log
        // Std out for log messages
        //
        // It can be overriden in options by another function (`options.log`).
        // `options.logCtx` specif the context of execution.
        // @see NDDB.initLog
        this.log = console.log;

        // ### globalCompare
        // Dummy compare function used to sort elements in the database
        //
        // It can be overriden with a compare function returning:
        //
        //  - 0 if the objects are the same
        //  - a positive number if o2 precedes o1
        //  - a negative number if o1 precedes o2
        //
        this.globalCompare = function(o1, o2) {
            return -1;
        };

        // Adding the "compareInAllFields" function.
        //
        // @see NDDB.comparator
        this.comparator('*', function(o1, o2, trigger1, trigger2) {
            var d, c, res;
            for (d in o1) {
               c = that.getComparator(d);
               o2[d] = o2['*'];
               res = c(o1, o2);
               if (res === trigger1) return res;
               if ('undefined' !== trigger2 && res === trigger2) return res;
               // No need to delete o2[d] afer comparison.
            }

           // We are not interested in sorting.
           // Figuring out the right return value.
           if (trigger1 === 0) {
               return trigger2 === 1 ? -1 : 1;
           }
           if (trigger1 === 1) {
               return trigger2 === 0 ? -1 : 0;
           }

           return trigger2 === 0 ? 1 : 0;
        });

        // Add default formats (e.g. CSV, JSON in Node.js).
        // See `/lib/fs.js`.
        if ('function' === typeof this.addDefaultFormats) {
            this.addDefaultFormats();
        }

        // Mixing in user options and defaults.
        this.init(options);

        // Importing items, if any.
        if (db) this.importDB(db);
    }
200185
function (params) {
  assert.ok(params.__fhdb, "__fhdb parameter required for shared database");

  /**
   * Copy the default options that are always required by ditcher
   * @param target The options object to copy them to
   * @returns The options object plus the default properties
   */
  this.copyDefaultOptions = function (target) {
    target.__fhdb = params.__fhdb;
    target.__dbperapp = params.__dbperapp;
    return target;
  };

  /**
   * Create a new collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createCollection
   * @param name collection name
   * @param (optional) options
   * @param (optional) callback results callback
   * @returns Promise if no callback passed
   */
  this.createCollection = function (name, options, callback) {
    assert.ok(name, "collection name required");

    if (typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = name;

    if (callback) {
      params.ditcher.doCreate(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doCreate(options, function (err, collection) {
          if (err) {
            return reject(err);
          }

          resolve(collection);
        });
      });
    }
  };

  /**
   * Drop a collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#dropCollection
   * @param name
   * @param (optional) callback
   * @returns Promise if no callback passed
   */
  this.dropCollection = function (name, callback) {
    assert.ok(name, "collection name required");

    var options = {
      type: name
    };

    options = this.copyDefaultOptions(options || {});

    if (callback) {
      params.ditcher.doDropCollection(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doDropCollection(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * List all collections
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#listCollections
   * @param filter Query to filter collections by
   * @param options (optional) Optional settings
   * @returns Cursor
   */
  this.listCollections = function (filter, options) {
    options = this.copyDefaultOptions(options || {});
    return params.ditcher.doGetCollectionsListCursor(filter, options);
  };

  /**
   * Return collections instance
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#collection
   * @param name Query to filter collections by
   * @param options (optional) Optional settings
   * @param callback (optional) result callback
   * @returns Collection instance if no callback passed
   */
  this.collection = function (name, options, callback) {
    assert.ok(name, "collection name required");

    options = this.copyDefaultOptions(options || {});
    options.type = name;

    return params.ditcher.doGetCollectionInstance(options, callback);
  };

  /**
   * Create an index on collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#createIndex
   * @param name Name of the collection
   * @param fieldOrSpec Field to use for the index
   * @param options (optional) Options
   * @param callback (optional) result callback
   * @returns Promise if no callback passed
   */
  this.createIndex = function (name, fieldOrSpec, options, callback) {
    assert.ok(name, "collection name required");
    assert.ok(fieldOrSpec, "index spec required");

    if(typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = name;
    options.index = fieldOrSpec;

    if (callback) {
      params.ditcher.doIndex(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doIndex(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * Rename a collection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#renameCollection
   * @param fromCollection Current name
   * @param toCollection New name
   * @param options (optional) Options
   * @param callback (optional) Result callback
   */
  this.renameCollection = function (fromCollection, toCollection, options, callback) {
    assert.ok(fromCollection, "current collection name required");
    assert.ok(toCollection, "new collection name required");

    if(typeof options === "function") {
      callback = options;
      options = {};
    }

    options = this.copyDefaultOptions(options || {});
    options.type = fromCollection;
    options.toCollection = toCollection;

    if (callback) {
      params.ditcher.doRenameCollection(options, callback);
    } else {
      return new Promise(function (resolve, reject) {
        params.ditcher.doRenameCollection(options, function (err, result) {
          if (err) {
            return reject(err);
          }

          resolve(result);
        });
      });
    }
  };

  /**
   * Close the database connection
   * http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html#close
   * @param force Force close, emitting no events
   * @param callback (optional) result callback
   */
  this.close = function (force, callback) {
    if (typeof force === "function") {
      callback = force;
      force = false;
    }

    return params.ditcher.database.close(force, callback);
  };
}
330123
function DocumentDBDatabase(config) {
        // Store node for further use
        node = this;
        var nodeConfig = config;

        // Create the Node-RED node
        RED.nodes.createNode(this, config);
        dbendpoint = node.credentials.endpoint;
        dbkey = node.credentials.authkey;

        this.on('input', function (msg) {
            client = new DocumentDBClient(dbendpoint, { "masterKey": dbkey });
            var messageJSON = null;
            if (typeof (msg.payload) != "string") {
                node.log("JSON");
                messageJSON = msg.payload;
            } else {
                node.log("String");
                //Converting string to JSON Object
                //Sample string: {"dbname": "name", "action": "C"}
                messageJSON = JSON.parse(msg.payload);
            }
            var action = messageJSON.action;
            if  (action != "L")
            {
                dbName = messageJSON.dbname;
                databaseUrl = `dbs/${dbName}`;
            }
            // Sending action to Azure DocumentDB
            setStatus(statusEnum.sending);
            switch (action) {
                case "C":
                    node.log('Trying to create database');
                    getDatabase().then((resolve) => { 
                        node.log('Completed successfully: -> ' + JSON.stringify(resolve));
                        setStatus(statusEnum.sent);
                        node.send(messageJSON.dbname); 
                    }).catch((error) => { 
                        setStatus(statusEnum.error);
                        node.error('Completed with error ' +JSON.stringify(error), msg);
                        node.log('Completed with error ' +JSON.stringify(error));
                    });
                    break;
                case "L":
                    node.log('Trying to list databases');
                    var listNames = [];
                    listDatabases(function (dbs) {
                        setStatus(statusEnum.sent);
                        if (dbs.length == 1) {
                            node.send(dbs[0].id)
                        } else {
                            for (var i = 0; i < dbs.length; i++) {
                                listNames.push(dbs[i].id);
                            }
                            node.send(JSON.stringify(listNames));
                        }
                    });
                    break;
                case "D":
                    node.log('Trying to delete database');
                    deleteDatabase().then((resolve) => { 
                        setStatus(statusEnum.sent);
                        node.log('Delete successfully: -> ' + JSON.stringify(resolve));
                     }).catch((error) => { 
                        setStatus(statusEnum.error);
                        node.error('Completed with error ' +JSON.stringify(error), msg);
                        node.log('Completed with error ' +JSON.stringify(error));
                    });
                    break;
                default:
                    node.log('action was not detected');
                    node.error('action was not detected', msg);
                    setStatus(statusEnum.error);
                    break;
            }
        });

        this.on('close', function () {
            disconnectFrom(this);
        });
    }
80683
function (config) {
        // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
        if (Transaction.databases[config.identity]) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: duplicate setup of connection found in Transactions.setup');
            this.teardown();
        }

        var _db;

        // clone the configuration
        config = util.clone(config);
        delete config.replication;

        // allow special transaction related config
        util.each(config, function (value, name, config) {
            if (!/^transaction.+/g.test(name)) { return; }

            // remove transaction config prefix
            var baseName = name.replace(/^transaction/g, '');
            baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);

            delete config[name];
            config[baseName] = value;
        });

        _db = db.createSource(config);

        // Save a few configurations
        _db && (_db.transactionConfig = {
            rollbackOnError: config.rollbackTransactionOnError
        });

        Transaction.databases[config.identity] = _db;
    }
1269659
function Batch(db, options) {
  this.options = options || {};
  this.ops = [];
  this.db = db;
  this.written = false;
}
1093400
function GameDB(options, db) {
        var that;
        that = this;
        options = options || {};
        options.name = options.name || 'gamedb';

        if (!options.update) options.update = {};

        // Auto build indexes by default.
        options.update.indexes = true;

        NDDB.call(this, options, db);

        this.comparator('stage', function(o1, o2) {
            var _o2;
            if ('string' === typeof o2.stage && that.node) {
                if (false === J.isInt(o2.stage)) {
                    _o2 = that.node.game.plot.normalizeGameStage(o2.stage);
                    if (_o2) o2.stage = _o2;
                }
            }
            return GameStage.compare(o1.stage, o2.stage);
        });

        if (!this.player) {
            this.hash('player', function(o) {
                return o.player;
            });
        }
        if (!this.stage) {
            this.hash('stage', function(o) {
                if (o.stage) {
                    return GameStage.toHash(o.stage, 'S.s.r');
                }
            });
        }

        this.node = this.__shared.node;
    }
1369442
function _initStorage$1(options) {
    var self = this;
    var dbInfo = {
        db: null
    };

    if (options) {
        for (var i in options) {
            dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
        }
    }

    var dbInfoPromise = new Promise$1(function (resolve, reject) {
        // Open the database; the openDatabase API will automatically
        // create it for us if it doesn't exist.
        try {
            dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
        } catch (e) {
            return reject(e);
        }

        // Create our key/value table if it doesn't exist.
        dbInfo.db.transaction(function (t) {
            createDbTable(t, dbInfo, function () {
                self._dbInfo = dbInfo;
                resolve();
            }, function (t, error) {
                reject(error);
            });
        }, reject);
    });

    dbInfo.serializer = localforageSerializer;
    return dbInfoPromise;
}
404487
function createDatabase() {
  var idx, a, b;
  
  db = new loki('sorting-bench.db');
   
  coll = db.addCollection('profile', { indices: ['a', 'b', 'c'] });
  
  for(idx=0;idx<INITIAL_DOCUMENT_COUNT;idx++) {
    coll.insert(genRandomObject());
  }
}
623332
function(next) {
            if (options.noDb || core.noDb) return next();
            db.init(options, next);
        }
144519
function connect(options) {
  // Default driver is MySQL.
  activeBackend = options.driver || 'mysql';

  // Save the connection options for later use.
  connectionOptions = options;

  if (activeBackend === 'mysql') {
    // Save a reference to the MySQL client object for later use.
    activeDb = mysql.createClient(options);

    if (activeDb !== null) {
      activeDb.on('error', function (err) {
        console.log(err);
      });
    }
  }

  return activeDb;
}
713084
function ArrayDB( a ){

            var init = [], i, _l;

            if ( arguments.length === 1 && arguments[0] instanceof Array ) {

                init = a;

            } else if ( arguments.length >= 1 ) {

                init = arguments;

            }

            for ( i=0, _l=init.length; i<_l; i++ ) {

                this[ this.length++ ] = init[ i ];

            }

        }
457165
function EasyMySQL(config)
{
	this.debug = config.error_debug || false;

	if(db)
		db.configure(config);
}
334886
function(result) {
        var errors, db;
        errors = [];

        if ('undefined' === typeof NDDB) {
            errors.push('NDDB not found.');
        }

        if ('undefined' === typeof JSUS) {
            errors.push('JSUS not found.');
        }

        if ('undefined' === typeof J) {
            errors.push('J not found.');
        }

        if ('undefined' === typeof node.window) {
            errors.push('node.window not found.');
        }

        if ('undefined' === typeof W) {
            errors.push('W not found.');
        }

        if ('undefined' === typeof node.widgets) {
            errors.push('node.widgets not found.');
        }

        if ('undefined' !== typeof NDDB) {
            try {
                db = new NDDB();
            }
            catch(e) {
                errors.push('An error occurred manipulating the NDDB object: ' +
                            e.message);
            }
        }

        // We need to test node.Stager because it will be used in other tests.
        if ('undefined' === typeof node.Stager) {
            errors.push('node.Stager not found.');
        }

        return { success: !errors.length, errors: errors };
    }
56178
function (i) {
                    if (i >= columns.length) {
                        insertIntoDB();
                        return;
                    }

                    var dbField = columns[i];
                    var field = dbField.Field;

                    //Check required fields
                    if (dbField.Null === 'NO' && 
                        dbField.Default === '' && 
                        dbField.Extra !== 'auto_increment' && 
                        dbField.Extra.search('on update')===-1) {

                        //Check if field not set
                        if (undefOrEmpty(req.body[field])) {
                            return sendError(res,"Field " + field + " is NOT NULL but not specified in this request");
                        } else {
                            //Check if the set values are roughly okay
                            value = checkIfSentvaluesAreSufficient(req,dbField);
                            console.log(value);
                            if(value !== false) {
                                //Value seems okay, go to the next field
                                insertJson[field] = value;
                                iterator(i + 1);
                            } else {
                                return sendError(res,'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field] );
                            }
                        }
                    }  else {
                        //Check for not required fields
                        //Skip auto_incremented fields
                        if(dbField.Extra === 'auto_increment') {
                            iterator(i + 1);
                        } else {
                            //Check if the field was provided by the client
                            var defined = false;
                            if(dbField.Default == "FILE") {
                                if(req.files.hasOwnProperty(dbField.Field)) {
                                    defined = true;
                                }
                            } else {
                                if(typeof req.body[field] !== "undefined") {
                                    defined = true;
                                }
                            }

                            //If it was provided, check if the values are okay
                            if(defined) {
                                value = checkIfSentvaluesAreSufficient(req,dbField);
                                if(value !== false) {
                                    insertJson[field] = value;
                                    iterator(i + 1);
                                } else {
                                    if(dbField.Default == "FILE") {
                                        return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
                                    } else {
                                        return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
                                    }
                                }
                            } else {
                                //If not, don't mind
                                iterator(i + 1);
                            }

                        }
                    }

                }
587920
function NDDBIndex(idx, nddb) {
        // The name of the index.
        this.idx = idx;
        // Reference to the whole nddb database.
        this.nddb = nddb;
        // Map indexed-item to a position in the original database.
        this.resolve = {};
        // List of all keys in `resolve` object.
        this.keys = [];
        // Map indexed-item to a position in `keys` array (for fast deletion).
        this.resolveKeys = {};
    }
1354891
function (options) {
  if (!(this instanceof Store)) {
    return new Store(options)
  }

  this._opts = options || {}
  this.db = new Datastore({ filename: this._opts.filename, autoload: true })
}
854297
function getDatabaseConnector(database, options, callback) {
    if (typeof options === "function") {
        callback = options
        options = {}
    }

    options = extend({}, defaults, options)

    var server = new Server(options.host, options.port, options.serverOptions)
        , databaseConnector = new Db(database, server, options.dbOptions)

    databaseConnector.open(authOrReturn)

    function authOrReturn(err, db) {
        if (err) {
            return callback(err)
        }

        if (options.user || options.password) {
            db.authenticate(options.user, options.password
                , options.authenticateOptions, returnDb)
        } else {
            callback(null, db)
        }

        function returnDb(err, success) {
            if (err) {
                return callback(err)
            }

            if (!success) {
                return callback(new Error("auth failed"))
            }

            callback(null, db)
        }
    }
}