Created by Adrian on 02-Apr-16.
 /*
Checks if the given error contains any kind of sequelize information.
If it does, we will mutate it so that the error ns is SQL
186386
function parseError(e) {
  let sqlError = (e.source || e);
  if(e.code && e.code.indexOf('SQL') === 0) {
    e.ns = 'STORE.SQL';
  }
  if(typeof sqlError.name !== 'string' || sqlError.name.indexOf('Sequelize') !== 0) return;
  e.ns = 'STORE.SQL';
  switch(sqlError.name) {
    case 'SequelizeUniqueConstraintError':
      e.code = 'VALIDATION_ERROR';
      break;
    case 'SequelizeDatabaseError':
      e.code = 'QUERY_ERROR';
      break;
    case 'SequelizeValidationError':
      e.code = 'VALIDATION_ERROR';
      e.statusCode = 400;
      try {
        e.message = sqlError.errors[0].message;
      } catch(er) {}
      break;
    default:
      e.code = 'DATABASE_ERROR';
  }
  return true;
}
1142971
function(sql, val, callback) {
  let qry = (typeof sql === 'object') ? sql : mysql.format(sql, val);
  if (!callback && typeof val === 'function') callback = val; // Handle 2 parm scenario

  _pool.getConnection((err, conn) => {
    _pool.query(qry, (err, items, fields) => {
      if (err) return callback(err);

      conn.release();

      callback(err, items);
    });
  });
}
480337
function(sql, attrs, callback) {
    var promise = this.definition.store.connection.raw(sql, attrs)

    if (typeof callback === 'function') {
      promise.then(callback)
    }

    return promise
  }
978966
function validateQuery(query) {
        Validate.isObject(query);
        Validate.notNull(query);
        
        var components = query.getComponents();
        
        for (var i in components.ordering) {
            throw new Error('orderBy and orderByDescending clauses are not supported in the pull query');
        }
        
        if (components.skip) {
            throw new Error('skip is not supported in the pull query');
        }

        if (components.take) {
            throw new Error('take is not supported in the pull query');
        }

        if (components.selections && components.selections.length !== 0) {
            throw new Error('select is not supported in the pull query');
        }

        if (components.includeTotalCount) {
            throw new Error('includeTotalCount is not supported in the pull query');
        }
    }
1185139
function throwError (msg, select) {
    // create error message
    var msg = msg+' at select.'+select.history.join('.')+' in context '+select.context
    // create error
    var err = new Error(msg)
    // add select data to error
    err.data = _.pick(select, ['context', 'contextData', 'expectColumn', 'history', 'query'])
    // throw error
    throw new Error(err)
}
982068
function appendSQLComments( $def, &$sql )
    {
        if ( isset( $def['comments'] ) )
        {
            if ( count( $def['comments'] ) > 0 )
                $sql .= "\n";
            foreach ( $def['comments'] as $comment )
            {
                $commentLines = explode( "\n", $comment );
                foreach ( $commentLines as $commentLine )
                {
                    $sql .= '-- ' . $commentLine . "\n";
                }
            }
            return true;
        }
        return false;
    }
687680
function lambdaError(fn, settings){
    var log = (settings && settings.log === false ? false : true);
    var map = (settings && settings.map ? settings.map : undefined);
    var exclude = (settings && settings.exclude ? settings.exclude : undefined);
    
    return (event, context, callback) => {
        fn(event, context, (err, result) => {
            if(err){
                if(log){
                    console.error(Errors.stack(err));
                }
                
                if(typeof err !== 'object'){
                    console.error('Error must be an object:', err);
                    err = new InvalidErrorValue(err);
                }
                
                return callback(Errors.json(err, false, map, exclude));
            }
            
            return callback(null, result);
        });
    };
}
545315
function createClause (options) {
  options = options || {}
  if (!options.where) return ''

  // AST parsing requires a complete SQL.
  const whereTree = parser.parse('SELECT * WHERE ' + options.where).where
  return traverse(whereTree, options)
}
826869
function newError(errorCode, errorMessage) {
		
		var errObj;
		
		if (_.isObject(errorCode)) {
			errObj = errorCode;
		}
		else if (typeof(errorCode) === 'number') {
			errObj = {
				errorCode: errorCode,
			};
			
			if (errorMessage) {
				errObj.message = errorMessage;
			}
		}
		else {
			errObj = {errorCode: 500};
		}
		
		return new Promise(function(resolve, reject) {
			reject(errObj);
		});
	}
1205777
function initTable(error) {
    if (error) {
      console.log(error);
      callback(error);
    }

    var try_table_init_n_times = function( rounds_left ) {
      database.get("SELECT name FROM sqlite_master WHERE type='table' AND name='"+table_name+"'", function( err, row ) {
        if ( row ) {
          finalizeInitialization();
        }
        else {
          var table = [
            [ "id", "INTEGER PRIMARY KEY" ],
            [ "at", "DATETIME" ],
            [ "task", "BLOB" ],
            [ "disabled", "BOOL" ],
          ];
          var columns_create = table.map( function ( column ) { return column.join( " " ) } ).join( ", ");
          var table_init = "CREATE TABLE IF NOT EXISTS " + table_name + " ( " + columns_create + " )";

          log.debug('sqlite-adapter', 'Running query:', table_init);

          database.run( table_init, function(error) {
            if ( error ) {
              if ( rounds_left > 1 ) {
                setTimeout( function() {
                  log.debug('sqlite-adapter', 'Retrying query:', table_init);
                  try_table_init_n_times( rounds_left - 1 );
                }, 100 + Math.floor( Math.random() * 900 ) );
              }
              else {
                console.log("Could not initialize sqlite database after 10 tries");
                callback(error);
              }
            }
            else {
              finalizeInitialization();
            }
          } );

        }
      });
    }

    try_table_init_n_times( 10 );
  }
64905
function onError (e) {
            switch (e.target.errorCode) {
            case 12:
                console.log('Error - Attempt to open db with a lower version than the ' +
                        'current one.');
                break;
            default:
                console.log('errorCode: ' + e.target.errorCode);
            }

            console.log(e, e.code, e.message);
        }
1018708
private boolean isSuccessful(String sql) throws SQLException {
        Statement statement = connection.createStatement();
        try {
            statement.execute(substitute(sql));
        } catch (SQLException e) {
            return false;
        } finally {
            DbUtils.closeQuietly(statement);
        }
        return true;
    }
485522
function pgsqlBulkUpsert(model, data) {
  var queries = [];

  // Transform data
  _.each(data, function(d) {
    // TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns
    var query = "INSERT INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
    query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));
    query = query.replace("[[VALUES]]", _.map(d, function(v) {
      return sequelizeSS.escape(v, undefined, "postgres");
    }).join(", "));
    queries.push(query);
  });

  // Create final output and format
  return queries.join("; ");
}
1196927
function InitDB(db_name) {

    var sequelize = new Sequelize(db_name, config.db.username, config.db.password, {
        host: config.db.host
        ,dialect: config.db.type
        ,logging: config.db.logging ? function(msg) {
            fs.appendFileSync("db.log", msg.replace("Executing (default): ", "") + "\n\n");
            //logger.debug(msg);
        } : false
        ,pool: {
            idle: 20000
        }
        ,define: {
            createdAt: 'created_at'
            ,updatedAt: 'updated_at'
        }
    });

    var db = {};
    fs.readdirSync("./src/db").forEach(function(file) {
        var model = sequelize.import("../src/db/" + file);
        db[model.name] = model;
    });

    Object.keys(db).reduce(function(acc, modelName) {
        var model = db[modelName];
        if("associate" in model) {
            return acc.concat([model]);
        }
        return acc;
    }, []).forEach(function(model) {
        model.associate.apply(model, [db]);
    });

    return [sequelize, db];
}
1070785
function dbError(tx, err) {
            if (calledDBError) {
                return;
            }
            err = idbModules.util.findError(arguments);
            req.readyState = "done";
            req.error = err || "DOMError";
            var e = idbModules.util.createEvent("error");
            e.debug = arguments;
            idbModules.util.callback("onerror", req, e);
            calledDBError = true;
        }
1303486
function isSqlQuery(literal) {
  if (!literal) {
    return false;
  }

  try {
    parser.parse(literal);
  } catch (error) {
    return false;
  }

  return true;
}
1242670
function parseError(e) {
  if(e.ns === 'STORE.REDIS') return true;
  if(e.code && e.code.indexOf('REDIS') === 0) {
    e.ns = 'STORE.REDIS';
    return true;
  }
}