Processes a loaded database.
@param {!Object} argv Parsed optimist arguments.
@param {string} outputBaseFile Base filename for output (without extension).
@param {!wtf.db.Database} db Database.
@param {function(number)} done Done callback. 0 for success.
167558
function processDatabase(argv, outputBaseFile, db, done) {
  var templates = {
    header: fs.readFileSync(path.join(templatePath, 'webgl-header.cc'), 'utf8')
  };

  var zones = db.getZones();
  if (!zones.length) {
    console.log('No zones');
    done(1);
    return;
  }

  // TODO(benvanik): find the right zone.
  var zone = zones[0];

  // Build a step list.
  console.log("Building step list...");
  var eventList = zone.getEventList();
  var frameList = zone.getFrameList();
  var steps = wtf.replay.graphics.Step.constructStepsList(eventList, frameList);

  // Open bin file.
  var binFile = new BinFile(outputBaseFile + '.bin');

  console.log("Generating code...");
  var tempDir;
  if (argv['src_output']) {
    tempDir = argv['src_output'];
  } else {
    var tempDirObj = new tmp.Dir();
    tempDir = tempDirObj.path;
    process.on('exit', function() {
      tempDirObj.rmdir();
    });
  }
  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir);
  }

  // Add all steps.
  var ccFiles = [];
  for (var n = 0; n < steps.length; n++) {
    var step = steps[n];

    // Prep file.
    var output = [];
    output.push(templates.header);

    // Add step function.
    output.push('void step_' + n + '(Replay* replay) {');
    addStep(eventList, n, step, output, binFile);
    output.push('}');

    // Flush.
    var finalOutput = output.join(os.EOL);
    var ccFile = path.basename(outputBaseFile) + '_step_' + n + '.cc';
    ccFile = path.join(tempDir, ccFile);
    fs.writeFileSync(ccFile, finalOutput);
    ccFiles.push(ccFile);
  }

  // Build statics file.
  var output = [];
  output.push(templates.header);

  // Add step list variable.
  var stepFnList = [];
  for (var n = 0; n < steps.length; n++) {
    stepFnList.push('step_' + n + ',');
    output.push('extern void step_' + n + '(Replay* replay);');
  }
  output.push(
      'StepFunction __steps[] = { ' + stepFnList.join(' ') + ' };');
  output.push(
      'int __step_count = ' + stepFnList.length + ';');
  output.push('StepFunction* __get_steps() { return __steps; }');

  // Static info.
  output.push(
      'const char* __trace_name = "' +
          path.basename(outputBaseFile) + '";');
  output.push(
      'const char* __bin_name = "' +
          path.basename(outputBaseFile) + '.bin";');

  // Write output cc file.
  console.log("Writing .cc file...");
  var finalOutput = output.join(os.EOL);
  var ccFile = path.join(tempDir, path.basename(outputBaseFile) + '.cc');
  fs.writeFileSync(ccFile, finalOutput);
  ccFiles.push(ccFile);

  // Finish bin file.
  binFile.dispose();

  // Build!
  console.log("Building executable...");
  build(argv, tempDir, outputBaseFile, ccFiles, done);
}
67364
function runProgramLogic() {
  var entries = db.getCollection("entries");
  var entryCount = entries.count();
  var now = new Date();

  console.log("old number of entries in database : " + entryCount);

  entries.insert({ x: now.getTime(), y: 100 - entryCount });
  entryCount = entries.count();

  console.log("new number of entries in database : " + entryCount);
  console.log("");
  
  // manually save
  db.saveDatabase(function(err) {
    if (err) {
      console.log(err);
    }
    else {
      console.log("saved... it can now be loaded or reloaded with up to date data");
    }
  });
}
121798
static int execute(CallInfo callInfo, DB db, String sql, Object[] args) {
    return db.access(callInfo, () -> {
      db.logSetup(callInfo, sql);
      try (WrappedStatement ws = db.compile(sql)) {
        PreparedStatement stmt = ws.getStatement();
        if (args != null && args.length != 0) {
          for (int i=0; i < args.length; i++) {
            stmt.setObject(i + 1, args[i]);
          }
        }
        stmt.execute();
        return stmt.getUpdateCount();
      }
    });
  }
1234752
function run () {
  if (argv.file) {
    const models = require(argv.file)
    return validate(models)
  }

  const json = argv.model || argv.references
  if (json) {
    return validate(JSON.parse(json))
  }

  printUsage()
  process.exit(1)
}
332764
function runTool(platform, args_, done) {
  var args = optimist.argv;
  var allzones = args['allzones'];

  var inputFile = args['_'][0];
  if (!inputFile) {
    console.log('usage: dump.js [--allzones] file.wtf-trace');
    done(1);
    return;
  }
  console.log('Dumping ' + inputFile + '...');
  console.log('');

  wtf.db.load(inputFile, function(db) {
    if (db instanceof Error) {
      console.log('ERROR: unable to open ' + inputFile, db, db.stack);
      done(1);
    } else {
      done(dumpDatabase(db, allzones));
    }
  });
}
1190413
function closeDatabase (name) {
  var deferred = q.defer();

  // We need to be sure the database location exists
  ready.then(function () {
    clearTimeout(timeouts[name]);

    // Write to file
    write(name).then(function () {
      // Remove database from memory
      delete databases[name];

      deferred.resolve();
    }, function (err) {
      deferred.reject(err);
    });
  }, function () {
    deferred.reject('Database couldn\'t instantiate');
  });

  return deferred.promise;
}
1152911
public function process()
    {
        /*
         | Check for argument database name if not given we will use default
         |  database connection
         */
        $this->database = (!is_null($this->argument('database'))) ?
            $this->argument('database') :
            $this->table()->getDefaultDatabaseConnection();

        $this->tableName = (!is_null($this->argument('name'))) ?
            $this->argument('name') :
            'Form';

        $this->columns = $this->getColumns();
        $this->applicationDir = realpath(CYGNITE_BASE.DS.APPPATH);
        $this->generateForm();

        $this->info('Form '.APPPATH.'/Form/'.Inflector::classify($this->tableName).'Form'.EXT.' Generated Successfully!.');
    }
124972
def report(output)
      output.title('Request database created')

      output <<  "A database file has been created with all parsed request information.\n"
      output <<  "#{@request_count} requests have been added to the database.\n"
      output << "\n"
      output <<  "To open a Ruby console to inspect the database, run the following command.\n"
      output <<  output.colorize("  $ request-log-analyzer console -d #{options[:database]}\n", :bold)
      output << "\n"
    end
490808
function get_db (ent, done) {
    var folder = internals.makefolderpath(opts.folder, ent)
    var db = dbmap[folder]
    if (db) {
      return done(null, db)
    }
    internals.ensurefolder(folder, internals.error(done, function () {
      db = dbmap[folder]
      if (db) {
        return done(null, db)
      }
      try {
        db = dbmap[folder] = LevelQuery(Levelup(folder, opts))
        db.query.use(JsonqueryEngine())
      }
      catch (e) {
        db = dbmap[folder]
        if (db) {
          return done(null, db)
        }
        return done(e)
      }
      return done(null, db)
    }))
  }
1316200
async function run () {
  const {host, port, database, username: user, password, idleTimeoutMillis} = config()
  const client = new Client({host, port, database: 'postgres', user, password, idleTimeoutMillis})

  await client.connect()
  await client.query(`DROP DATABASE IF EXISTS ${database}`)
  await client.query(`CREATE DATABASE ${database}`)
  await client.end()
  console.log(`\x1b[32m\u2714 Database \x1b[1m${database}\x1b[22m created successfully!\x1b[0m`)
}
807526
function write (database) {
  var deferred = q.defer();

  // Write database to file under database name
  fs.writeFile(globalConfig.db.location + database + '.db.json', JSON.stringify(databases[database]), function (err) {
    if(err) return deferred.reject(err);

    deferred.resolve();
  });

  return deferred.promise;
}
542574
private static void createDB(String dbName) {
        // remove database if it exists
        if (ZooHelper.dbExists(dbName)) {
            ZooHelper.removeDb(dbName);
        }

        // create database
        // By default, all database files will be created in %USER_HOME%/zoodb
        ZooHelper.createDb(dbName);
    }
761671
def run(self):
        
        self.print_message("\nBeginning database replacement process.\n")

        if self.args.source_settings:
            settings = self.parse_db_settings(self.args.source_settings)
            self.initialize_db_args(settings, 'source')

        if self.args.settings:
            settings = self.parse_db_settings(self.args.settings)
            self.initialize_db_args(settings, 'destination')

        if self.args.capture:
            self.capture_heroku_database()

        file_url = self.args.url
        if self.args.source_app:
            self.print_message("Sourcing data from backup for Heroku app '%s'"
                               % self.args.source_app)
            file_url = self.get_file_url_for_heroku_app(self.args.source_app)

        if self.args.destination_app:
            self.replace_heroku_db(file_url)
        elif self.databases['destination']['name']:
            self.replace_postgres_db(file_url)

        self.print_message("\nDone.\n\nDon't forget to update the Django Site entry if necessary!")
628457
function(data, done) {
            try {
                // Retrieve all the dependencies
                _.forEach(data._dependencies || {}, function(value, key) {
                    if(this.sandbox[key] !== undefined) {
                        // Do nothing if the dependency is already defined
                        return;
                    }

                    this.sandbox[key] = module.parent.require(value);
                }.bind(this));

                // Remove the dependencies property
                delete data._dependencies;
            }
            catch(e) {
                // Stop execution and return the MODULE_NOT_FOUND error
                return done(e);
            }

            // Iterate over all the data objects
            async.eachSeries(Object.keys(data), function(key, next) {
                _this.result[key] = {};

                var value = data[key];

                try {
                    if(!value._model) {
                        // Throw an error if the model could not be found
                        throw new Error('Please provide a _model property that describes which database model should be used.');
                    }

                    var modelName = value._model;

                    // Remove model and unique properties
                    delete value._model;

                    // retrieve the model depending on the name provided
                    var Model = mongoose.model(modelName);

                    async.series([
                        function(callback) {
                            if(_this.options.dropCollections === true) {
                                // Drop the collection
                                mongoose.connection.db.dropCollection(Model.collection.name, function(err) {
                                    callback();
                                });
                            }
                            else {
                                callback();
                            }
                        },
                        function(callback) {
                            async.eachSeries(Object.keys(value), function(k, innerNext) {
                                var modelData = value[k],
                                    data = _this._unwind(modelData);

                                // Create the model
                                Model.create(data, function(err, result) {
                                    if(err) {
                                        // Do not stop execution if an error occurs
                                        return innerNext(err);
                                    }

                                    _this.result[key][k] = result;

                                    innerNext();
                                });
                            }, callback);
                        }
                    ], next);
                }
                catch(err) {
                    // If the model does not exist, stop the execution
                    return next(err);
                }
            }, function(err) {
                if(err) {
                    // Make sure to not return the result
                    return done(err);
                }

                done(undefined, _this.result);
            });
        }
104572
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);
        if (((QueryRecord)record).getBaseRecord() != null)
            m_tableNext = ((QueryRecord)record).getBaseRecord().getTable();   // Pass most commands thru to the main record's table
    }
1325370
function (args, done) {
      var q = _.clone(args.q)
      var qent = args.qent
      q.limit$ = 1
      var qs = schemastm(qent)

      self.connection.all(qs.text, function (err, results) {
        if (err) {
          return done(err)
        }
        var schema = {}
        results.forEach(function (row) {
          schema[row.name] = row.type.toLowerCase()
        })

        var query = selectstm(qent, q)

        self.connection.get(query.text, query.values, function (err, row) {
          if (err) {
            return done(err)
          }
          if (row) {
            var fent = makeent(qent, row, schema)
            seneca.log.debug('load', q, fent, desc)
            return done(null, fent)
          }
          return done(null, null)
        })
      })
    }
1050597
def execute(db_name):
    
    try:
        with use_db(db_name, mode=WorkDB.Mode.open) as work_db:
            _update_progress(work_db)
            config = work_db.get_config()
            engine = get_execution_engine(config.execution_engine_name)

            def on_task_complete(job_id, work_result):
                work_db.set_result(job_id, work_result)
                _update_progress(work_db)
                log.info("Job %s complete", job_id)

            log.info("Beginning execution")
            engine(
                work_db.pending_work_items,
                config,
                on_task_complete=on_task_complete)
            log.info("Execution finished")

    except FileNotFoundError as exc:
        raise FileNotFoundError(
            str(exc).replace('Requested file', 'Corresponding database',
                             1)) from exc