Command for reflection database objects
10875
def run():
    """"""
    parser = OptionParser(
        version=__version__, description=__doc__,
    )

    parser.add_option(
        '-u', '--url', dest='url',
        help='Database URL (connection string)',
    )

    parser.add_option(
        '-r', '--render', dest='render', default='dot',
        choices=['plantuml', 'dot'],
        help='Output format - plantuml or dot',
    )

    parser.add_option(
        '-l', '--list', dest='list', action='store_true',
        help='Output database list of tables and exit',
    )

    parser.add_option(
        '-i', '--include', dest='include',
        help='List of tables to include through ","',
    )

    parser.add_option(
        '-e', '--exclude', dest='exclude',
        help='List of tables to exlude through ","',
    )

    (options, args) = parser.parse_args()

    if not options.url:
        print('-u/--url option required')
        exit(1)

    engine = create_engine(options.url)
    meta = MetaData()

    meta.reflect(bind=engine)

    if options.list:
        print('Database tables:')
        tables = sorted(meta.tables.keys())

        def _g(l, i):
            try:
                return tables[i]
            except IndexError:
                return ''

        for i in range(0, len(tables), 2):
            print(' {0}{1}{2}'.format(
                _g(tables, i),
                ' ' * (38 - len(_g(tables, i))),
                _g(tables, i + 1),
            ))

        exit(0)

    tables = set(meta.tables.keys())

    if options.include:
        tables &= set(map(string.strip, options.include.split(',')))

    if options.exclude:
        tables -= set(map(string.strip, options.exclude.split(',')))

    desc = describe(map(lambda x: operator.getitem(meta.tables, x), tables))
    print(getattr(render, options.render)(desc))
820482
public static void main(String[] args) {
		String dbName;
		if (args.length == 0) {
			dbName = DB_NAME;
		} else {
			dbName = args[0];
		}
		
		if (!ZooHelper.getDataStoreManager().dbExists(dbName)) {
			err.println("ERROR Database not found: " + dbName);
			return;
		}
		
		out.println("Checking database: " + dbName);

		ZooJdoProperties props = new ZooJdoProperties(dbName);
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(props);
		PersistenceManager pm = pmf.getPersistenceManager();
		Session s = (Session) pm.getDataStoreConnection().getNativeConnection();
		String report = s.getPrimaryNode().checkDb();
		out.println();
		out.println("Report");
		out.println("======");

		out.println(report);

		out.println("======");
		pm.close();
		pmf.close();
		out.println("Checking database done.");
	}
725613
private function handleProperties($data, $object, \ReflectionClass $reflection, $fields)
    {
        foreach ($fields as $field) {
            $property = $reflection->getProperty($field);
            $name     = $property->getName();

            if (property_exists($data, $name) === false ) {
                continue;
            }
            $property->setAccessible(true);
            $type  = $this->propertyHandler->propertyTypeOverride(null, $property);
            $value = $this->propertyHandler->handleTypeConversion($type, $data->$name);

            $property->setValue($object, $value);
        }
    }
1355764
public final void loadInterproceduralDatabases() {
        loadPropertyDatabase(getFieldStoreTypeDatabase(), FieldStoreTypeDatabase.DEFAULT_FILENAME, "field store type database");
        loadPropertyDatabase(getUnconditionalDerefParamDatabase(), UNCONDITIONAL_DEREF_DB_FILENAME,
                "unconditional param deref database");
        loadPropertyDatabase(getReturnValueNullnessPropertyDatabase(), NONNULL_RETURN_DB_FILENAME, "nonnull return db database");
    }
621719
def complete_db(self, text, line, begidx, endidx):
        '''  '''
        return  [i for i in PsiturkNetworkShell.db_commands if \
                 i.startswith(text)]
1047127
def update_object_in_db(self,
                            obj: Any,
                            table: str,
                            fieldlist: Sequence[str]) -> None:
        """"""
        self.ensure_db_open()
        pkvalue = getattr(obj, fieldlist[0])
        valuelist = []
        # Non-PK fields first
        for f in fieldlist[1:]:
            valuelist.append(getattr(obj, f))
        # Then PK
        valuelist.append(pkvalue)
        cursor = self.db.cursor()
        self.db_exec_with_cursor(
            cursor,
            get_sql_update_by_first_field(table, fieldlist, self.get_delims()),
            *valuelist
        )
666008
public Object doRemoteCommand(String strCommand, Map<String, Object> properties)
    {
        if (SET_DEFAULT_COMMAND.equalsIgnoreCase(strCommand))
            if (properties != null)
                if (properties.get(DBConstants.SYSTEM_NAME) != null)
        {
            if (this.getTask() != null)
            if (this.getTask().getApplication() instanceof BaseApplication)
            if (((BaseApplication)this.getTask().getApplication()).getEnvironment() != null)
            {
                String systemName = properties.get(DBConstants.SYSTEM_NAME).toString();
                Environment env = ((BaseApplication)this.getTask().getApplication()).getEnvironment();
                properties.put(DBConstants.SYSTEM_NAME, "base");
                BaseApplication app = new MainApplication(env, properties, null);
                try {
                    Task task = new AutoTask(app, null, properties);
                    RecordOwner recordOwner = new BaseProcess(task, null, properties);
                    Menus menus = new Menus(recordOwner);
                    menus.setKeyArea(Menus.CODE_KEY);
                    menus.getField(Menus.CODE).setString(ResourceConstants.DEFAULT_RESOURCE);
                    if (menus.seek(null))
                        menus.edit();
                    else
                        menus.addNew();
                    menus.getField(Menus.CODE).setString(ResourceConstants.DEFAULT_RESOURCE);
                    ((PropertiesField)menus.getField(Menus.PARAMS)).setProperty(DBConstants.SYSTEM_NAME, systemName);
                    if (menus.getEditMode() == DBConstants.EDIT_ADD)
                        menus.add();
                    else
                        menus.set();
                } catch (DBException e) {
                    e.printStackTrace();
                } finally {
                    app.free();
                }
                env.getDefaultApplication().getSystemRecordOwner().setProperty(DBConstants.DEFAULT_SYSTEM_NAME, systemName);
                return Boolean.TRUE;    // Success
            }
        }
        return super.doRemoteCommand(strCommand, properties);
    }
231098
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName=False
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    if os.path.isfile(pathToYaml):
        from fundamentals.mysql import yaml_to_database
        # PARSE YAML FILE CONTENTS AND ADD TO DATABASE
        yaml2db = yaml_to_database(
            log=log,
            settings=settings,
            dbConn=dbConn
        )
        yaml2db.add_yaml_file_content_to_database(
            filepath=pathToYaml,
            deleteFile=deleteFlag
        )
        basename = os.path.basename(pathToYaml)
        print "Content of %(basename)s added to database" % locals()

    else:
        from fundamentals.mysql import yaml_to_database
        yaml2db = yaml_to_database(
            log=log,
            settings=settings,
            dbConn=dbConn,
            pathToInputDir=pathToYaml,
            deleteFiles=deleteFlag
        )
        yaml2db.ingest()
        print "Content of %(pathToYaml)s directory added to database" % locals()

    return
1090599
protected function updateReflectionData()
    {
        $this->log(sprintf('Found %s classes whose reflection data was not cached previously.', count($this->updatedReflectionData)), LogLevel::DEBUG);

        foreach (array_keys($this->updatedReflectionData) as $className) {
            $this->statusCache->set($this->produceCacheIdentifierFromClassName($className), '');
        }

        $data = [];
        $propertyNames = [
            'classReflectionData',
            'classSchemata',
            'annotatedClasses',
            'classesByMethodAnnotations'
        ];

        foreach ($propertyNames as $propertyName) {
            $data[$propertyName] = $this->$propertyName;
        }

        $this->reflectionDataCompiletimeCache->set('ReflectionData', $data);
    }
347166
public boolean processServletCommand()
        throws DBException
    {
        String strCommand = this.getProperty(DBParams.COMMAND);        // Display record
        if (strCommand == null)
            strCommand = Constants.BLANK;
        boolean bSuccess = false;
        if (this.getScreenField() instanceof BasePanel)
        {   // Always
            if (strCommand.equalsIgnoreCase(ThinMenuConstants.FIRST))
                bSuccess = ((BasePanel)this.getScreenField()).onMove(DBConstants.FIRST_RECORD);
            else if (strCommand.equalsIgnoreCase(ThinMenuConstants.PREVIOUS))
                bSuccess = ((BasePanel)this.getScreenField()).onMove(DBConstants.PREVIOUS_RECORD);
            else if (strCommand.equalsIgnoreCase(ThinMenuConstants.NEXT))
                bSuccess = ((BasePanel)this.getScreenField()).onMove(DBConstants.NEXT_RECORD);
            else if (strCommand.equalsIgnoreCase(ThinMenuConstants.LAST))
                bSuccess = ((BasePanel)this.getScreenField()).onMove(DBConstants.LAST_RECORD);
            else if (strCommand.equalsIgnoreCase(ThinMenuConstants.SUBMIT))
                bSuccess = ((BasePanel)this.getScreenField()).onAdd();
            else if (strCommand.equalsIgnoreCase(ThinMenuConstants.DELETE))
                bSuccess = ((BasePanel)this.getScreenField()).onDelete();
            else
            { // Must have sent a user-defined command (send command to this screen)
                bSuccess = false;   // Too dangerous ((BasePanel)this.getScreenField()).handleCommand(strCommand, this.getScreenField(), false);
            }
        }
        return bSuccess;
    }
1103416
function(type, name, opts, cb) {
  var key = [type, name].join('-');
  logger.debug('Storing command in DB: ' + key);
  storage.set(key, { command: type, target: name, options: opts }, cb);
}
827854
def _pretend_to_run(self, migration, method):
        
        self._note("")
        names = []
        for query in self._get_queries(migration, method):
            name = migration.__class__.__name__
            bindings = None

            if isinstance(query, tuple):
                query, bindings = query

            query = highlight(query, SqlLexer(), CommandFormatter()).strip()

            if bindings:
                query = (query, bindings)

            if name not in names:
                self._note("[<info>{}</info>]".format(name))
                names.append(name)

            self._note(query)
1148760
public static void sqldatabase(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
    zeroArgumentFunctionCall(buf, "current_database()", "database", parsedArgs);
  }
693990
function db(objectName) {
    if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded);
    if (!_.has(objects, objectName)) objects[objectName] = {};
    return createMethods(objects[objectName], save.bind(null, objectName));
  }
511890
private void findParamDescMethods() {
        for (Method method : m_commandClass.getMethods()) {
            if (method.isAnnotationPresent(ParamDescription.class)) {
                try {
                    RESTParameter cmdParam = (RESTParameter) method.invoke(null, (Object[])null);
                    addParameter(cmdParam);
                } catch (Exception e) {
                    LOGGER.warn("Method '{}' for class '{}' could not be invoked: {}",
                                new Object[]{method.getName(), m_commandClass.getName(), e.toString()});
                }
            }
        }
    }
1118774
def DBObject(table_name, versioning=VersioningTypes.NONE):
    """"""
    def wrapped(cls):
        field_names = set()
        all_fields = []

        for name in dir(cls):
            fld = getattr(cls, name)
            if fld and isinstance(fld, Field):
                fld.name = name
                all_fields.append(fld)
                field_names.add(name)

        def add_missing_field(name, default='', insert_pos=None):
            if name not in field_names:
                fld = Field(default=default)
                fld.name = name
                all_fields.insert(
                    len(all_fields) if insert_pos is None else insert_pos,
                    fld
                )

        add_missing_field('id', insert_pos=0)
        add_missing_field('_create_date')
        add_missing_field('_last_update')
        if versioning == VersioningTypes.DELTA_HISTORY:
            add_missing_field('_version_hist', default=list)

        # Things we count on as part of our processing
        cls.__table_name__ = table_name
        cls.__versioning__ = versioning
        cls.__fields__ = all_fields

        # Give them a ctor for free - but make sure we aren't clobbering one
        if not ctor_overridable(cls):
            raise TypeError(
                'Classes with user-supplied __init__ should not be decorated '
                'with DBObject. Use the setup method'
            )
        cls.__init__ = _auto_init

        # Duck-type the class for our data methods
        cls.get_table_name = classmethod(_get_table_name)
        cls.get_id = _get_id
        cls.set_id = _set_id
        cls.to_data = _to_data
        cls.from_data = classmethod(_from_data)
        cls.index_names = classmethod(_index_names)
        cls.indexes = _indexes
        # Bonus methods they get for using gludb.simple
        cls.get_version_hist = _get_version_hist

        # Register with our abc since we actually implement all necessary
        # functionality
        Storable.register(cls)

        # And now that we're registered, we can also get the database
        # read/write functionality for free
        cls = DatabaseEnabled(cls)

        if versioning == VersioningTypes.DELTA_HISTORY:
            cls.save = _delta_save(cls.save)

        return cls

    return wrapped
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);
}