Parses database drivers from config
426903
function parseDriverConfig() {
  var cfg, def, x, y, z,
      config = this.config.drivers,
      drivers = this.drivers;
  
  if (!config) config = this.config.drivers = {};
  
  if (Object.keys(config).length === 0) return;

  for (x in config) {
    cfg = config[x];
    if (x == 'default') { def = cfg; continue; }
    for (y in cfg) {
      if (typeof cfg[y] == 'object') {
        if (typeof drivers[x] == 'undefined') drivers[x] = {};
        drivers[x][y] = [x, cfg[y]];
      } else {
        drivers[x] = [x, cfg];
        break;
      }
    }
  }

}
1012415
public void gatherAndDisplayMetaDataInfo(Connection conn, WSManagedConnectionFactoryImpl mcf) throws SQLException
    {
        java.sql.DatabaseMetaData mData = conn.getMetaData();

        String databaseProductName = mData.getDatabaseProductName();
        String driverName = mData.getDriverName(); 

        String driverVersion = null;
        String databaseProductVersion = null;
        try {
            driverVersion = mData.getDriverVersion();
            databaseProductVersion = mData.getDatabaseProductVersion();
        } catch (Exception e) {
            // Ignore any Runtime errors as the info collected are solely for FFDC purpose.
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "Exception occurred while getting metaData info. Exception is: ", e);
            }
        }

        setDatabaseProductName(databaseProductName);
        setDriverName(driverName); 
        setDriverMajorVersion(mData.getDriverMajorVersion()); 

        Tr.info(tc, "DB_PRODUCT_NAME", databaseProductName);
        Tr.info(tc, "DB_PRODUCT_VERSION", databaseProductVersion); 
        Tr.info(tc, "JDBC_DRIVER_NAME", driverName); 
        Tr.info(tc, "JDBC_DRIVER_VERSION", driverVersion); 

        try {
            if (mData.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT) &&
                mData.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT)) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "Holdabiliy is supported");
                }
                holdabilitySupported = true;
            } else {
                if (tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "Holdability not supported");
                }
                holdabilitySupported = false;
            }

        } catch (Throwable x) {
            if (x instanceof SQLException) {
                SQLException sqe = (SQLException) x;
                if ((isConnectionError(sqe))) {
                    throw sqe; // if this is a stale we need to throw exception here.
                }

                // Some DB drivers throw SQLException when the JDBC version is 2.x.
                // Holdability is not supported in 2.0

                holdabilitySupported = false;
                if (tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "getHoldability is not supported in this JDBC driver. Encounter a java.sql.SQLException", sqe);
                }
            } else 
            {
                //NO FFDC needed
                // just log it and do nothing
                if (tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "caught an exception when testing the holdability from metadata, will call the holdability itself to know if supported", x);
                }

            }
        }
        try {
            mcf.jdbcDriverSpecVersion = mData.getJDBCMajorVersion() * 10;
        } catch (AbstractMethodError methError) {
            // No FFDC code needed. JDBC driver version is less than 3.0.
            mcf.jdbcDriverSpecVersion = 20;
        }
        catch (UnsupportedOperationException supportX) // raised by old Sybase driver
        {
            // No FFDC code needed. Driver is not JDBC 3.0 compliant because it does not
            // support getJDBCMajorVersion,
            mcf.jdbcDriverSpecVersion = 20;
        }
        catch (SQLException sqlX) {
            // No FFDC code needed.
            // Informix driver throws SQLException when the JDBC version is 2.x.

            mcf.jdbcDriverSpecVersion = 20;

            if (tc.isDebugEnabled())
                Tr.debug(this, tc, "metadata.getJDBCMajorVersion", sqlX);

            // Need to fail if it was a connection error.
            if (isConnectionError(sqlX))
                throw sqlX;
        }

        if (mcf.jdbcDriverSpecVersion > 30)
            try {
                mcf.jdbcDriverSpecVersion += mData.getJDBCMinorVersion();
            } catch (SQLException x) {
            } catch (UnsupportedOperationException x) {
            }

        if (mcf.jdbcDriverSpecVersion >= 40)
            try 
            {
                // Reset to the default client info of the data source (based on an initial connection),
                // instead of using the default values for the JDBC driver--which could differ from the
                // defaults specified for the data source.
                Properties clientInfo = conn.getClientInfo();
                if (clientInfo != null)
                    mcf.defaultClientInfo.putAll(clientInfo);
            }
            catch (SQLFeatureNotSupportedException featureX) {
                // No FFDC code needed.
                // The JDBC 4.0 driver ought to implement the getClientInfOProperties method,
                // but doesn't.  Issue a warning, but tolerate the error so that WAS can still
                // interoperate with the JDBC driver.
                Tr.warning(tc, "FEATURE_NOT_IMPLEMENTED", "java.sql.Connection.getClientInfo");
            }
            catch (AbstractMethodError methErr) {
                // No FFDC code needed.
                // Work around a bug in Oracle where the driver reports "10" instead
                // of the JDBC specification level.
                // If the JDBC 4.0 metadata operation cannot be found on the driver,
                // then it must really be a JDBC 3.0 driver.
                if (tc.isDebugEnabled())
                    Tr.debug(this, tc,
                             "JDBC spec level, " + mcf.jdbcDriverSpecVersion +
                                             ", reported by the driver is not valid. Using 30 (3.0) instead.");
                mcf.jdbcDriverSpecVersion = 30;
            }
            catch (UnsupportedOperationException operationX) 
            {
                // No FFDC code needed.
                // Returned by Sybase jconn4.jar versions that are older than jConnect-7.07.
                // The JDBC 4.0 driver ought to throw SQLFeatureNotSupportedException,
                // but doesn't.  Issue a warning, but tolerate the error so that WAS can still
                // interoperate with the JDBC driver.
                Tr.warning(tc, "FEATURE_NOT_IMPLEMENTED", "java.sql.Connection.getClientInfo");
            }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(this, tc, "JDBC spec version implemented by driver", mcf.jdbcDriverSpecVersion);
    }
788968
def get_config():
        
        db_type = os.environ['DB_TYPE']
        db_host = os.environ['DB_HOST']
        db_user = os.environ['DB_USER']
        db_database = os.environ['DB_NAME']
        db_password = os.environ['DB_PASSWORD']
        db_prefix = os.environ['DB_PREFIX']

        check = Migration.check_packages(db_type)

        return check, {
            db_type: {
                'driver': db_type.strip(),
                'host': db_host.strip(),
                'database': db_database.strip(),
                'user': db_user.strip(),
                'password': db_password.strip(),
                'prefix': db_prefix.strip()
            }
        }
567055
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
            knowledge_base):
    """"""
    _ = time_taken, args, knowledge_base  # Unused.
    rpm_re = re.compile(r"^(\w[-\w\+]+?)-(\d.*)$")
    self.CheckReturn(cmd, return_val)
    packages = []
    for line in stdout.splitlines():
      pkg_match = rpm_re.match(line.strip())
      if pkg_match:
        name, version = pkg_match.groups()
        status = rdf_client.SoftwarePackage.InstallState.INSTALLED
        packages.append(
            rdf_client.SoftwarePackage(
                name=name, version=version, install_state=status))
    if packages:
      yield rdf_client.SoftwarePackages(packages=packages)

    for line in stderr.splitlines():
      if "error: rpmdbNextIterator: skipping h#" in line:
        yield rdf_anomaly.Anomaly(
            type="PARSER_ANOMALY", symptom="Broken rpm database.")
        break
276739
def _get_db_options(args):
    
    import optik, getpass,sys
    from optik import OptionParser
    parser=OptionParser()
    parser.add_option("-d","--database",
                  action="store", type="string", dest="database",
                  default="cfht",
                  help="Name of the SYBASE database containing TABLE",
                  metavar="FILE")
    parser.add_option("-u","--user",
                  action="store", type="string", dest="user",
                  default=getpass.getuser(),
                  help="User name to access db with",
                  metavar="USER")
    (opt, unused_args) = parser.parse_args(args)
    return opt.database,opt.user,unused_args
361289
def parse_bind(bind):
    """"""
    if isinstance(bind, Connection):
        engine = bind.engine
    else:
        engine = bind
    m = re.match(r"Engine\((.*?)\)", str(engine))
    if m is not None:
        u = urlparse(m.group(1))
        # Add Scheme to uses_netloc or // will be missing from url.
        uses_netloc.append(u.scheme)
        safe_url = ""
        if u.password is None:
            safe_url = u.geturl()
        else:
            # Strip password from URL
            host_info = u.netloc.rpartition('@')[-1]
            parts = u._replace(netloc='{}@{}'.format(u.username, host_info))
            safe_url = parts.geturl()
        sql = {}
        sql['database_type'] = u.scheme
        sql['url'] = safe_url
        if u.username is not None:
            sql['user'] = "{}".format(u.username)
    return sql
944742
protected function conn($db_config_name = '')
    {
        $db_config_name = $db_config_name ? $db_config_name : $this->db_config_name;
        if (! isset(self::$_db_handle[$db_config_name])) {
            if (true == C('sql_log')) {
                wlog('SQL-Log', '#'.$db_config_name);
            }
            $dbdriver = 'db_'.C('dbdriver');
            include_once FW_PATH.'/dbdrivers/'. $dbdriver .'.class.php';
            self::$_db_handle[$db_config_name] = $this->db = new $dbdriver($db_config_name);
        } else {
            $this->db = self::$_db_handle[$db_config_name];
        }
        return $this->db;
    }
615103
def get_config(self):
        
        rows = list(self._conn.execute("SELECT * FROM config"))
        if not rows:
            raise ValueError("work-db has no config")
        (config_str,) = rows[0]

        return deserialize_config(config_str)
1098230
def db_url_from_hass_config(path):
    """"""
    config = load_hass_config(path)
    default_path = os.path.join(path, "home-assistant_v2.db")
    default_url = "sqlite:///{}".format(default_path)

    recorder = config.get("recorder")

    if recorder:
        db_url = recorder.get("db_url")
        if db_url is not None:
            return db_url

    if not os.path.isfile(default_path):
        raise ValueError(
            "Unable to determine DB url from hass config at {}".format(path)
        )

    return default_url
216732
public static function getDBHelper(string $driver): string
    {
        $drivers = [
            'pdo_mysql'  => MySQL::class,
            'mysql'      => MySQL::class,
            'mysql2'     => MySQL::class,

            'pdo_pgsql'  => PostgreSQL::class,
            'pgsql'      => PostgreSQL::class,
            'postgres'   => PostgreSQL::class,
            'postgresql' => PostgreSQL::class,

            'pdo_sqlsrv' => SQLServer::class,
            'mssql'      => SQLServer::class,
        ];

        if (!array_key_exists($driver, $drivers)) {
            throw new \InvalidArgumentException("$driver unknown");
        }

        return $drivers[$driver];
    }
560972
def db_from_hass_config(path=None, **kwargs):
    """"""
    if path is None:
        path = config.find_hass_config()

    url = config.db_url_from_hass_config(path)
    return HassDatabase(url, **kwargs)
703407
def _parse_conf(conf_file=default_conf):
    '''
    
    '''
    ret = {}
    with salt.utils.files.fopen(conf_file, 'r') as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line).strip()
            if not line:
                continue
            if line.startswith('#'):
                continue
            splitline = line.split(' ', 1)
            ret[splitline[0]] = splitline[1]
    return ret
1363886
protected function getDatabaseConfig()
    {
        /** @skipUpgrade */
        $databaseConfig = [
            "type" => Environment::getEnv('SS_DATABASE_CLASS') ?: 'MySQLDatabase',
            "server" => Environment::getEnv('SS_DATABASE_SERVER') ?: 'localhost',
            "username" => Environment::getEnv('SS_DATABASE_USERNAME') ?: null,
            "password" => Environment::getEnv('SS_DATABASE_PASSWORD') ?: null,
        ];

        // Set the port if called for
        $dbPort = Environment::getEnv('SS_DATABASE_PORT');
        if ($dbPort) {
            $databaseConfig['port'] = $dbPort;
        }

        // Set the timezone if called for
        $dbTZ = Environment::getEnv('SS_DATABASE_TIMEZONE');
        if ($dbTZ) {
            $databaseConfig['timezone'] = $dbTZ;
        }

        // For schema enabled drivers:
        $dbSchema = Environment::getEnv('SS_DATABASE_SCHEMA');
        if ($dbSchema) {
            $databaseConfig["schema"] = $dbSchema;
        }

        // For SQlite3 memory databases (mainly for testing purposes)
        $dbMemory = Environment::getEnv('SS_DATABASE_MEMORY');
        if ($dbMemory) {
            $databaseConfig["memory"] = $dbMemory;
        }

        // Allow database adapters to handle their own configuration
        DatabaseAdapterRegistry::autoconfigure($databaseConfig);
        return $databaseConfig;
    }
1161201
def db_config
      @db_config ||= begin
        opts = OptionsHash.new(YamlConfig.user_config.options)
        opts.merge!(YamlConfig.local_config.options)
        opts.merge!(EnvConfig.new.options)
        opts
      end
    end
1120745
def _parse_db_lib(cls, library):
        
        database_name = library.split('.', 2)
        if len(database_name) == 2:
            library = database_name[1]
            if database_name[0].startswith(cls.DB_PREFIX):
                database_name = database_name[0]
            else:
                database_name = cls.DB_PREFIX + '_' + database_name[0]
        else:
            database_name = cls.DB_PREFIX
        return database_name, library
797783
def check_packages(db_name):
        
        print('Checking for required Database Driver')

        reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
        installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

        # print(installed_packages)

        if db_name.lower() == 'mysql':
            if 'PyMySQL' not in installed_packages:
                print('Installing required Database Driver')
                os.system('pip install pymysql')

        if db_name.lower() == 'postgresql':
            if 'psycopg2-binary' not in installed_packages:
                print('Installing required Database Driver')
                os.system('pip install psycopg2-binary')

        return True
855010
def parse_conf_files(conf_paths):
    
    conf_file = ConfigParser.RawConfigParser()
    conf_read = conf_file.read(conf_paths)
    conf = {}
    try:
        if conf_read:
            conf['client_id'] = conf_file.get('runkeeper', 'client_id')
            conf['client_secret'] = conf_file.get('runkeeper', 'client_secret')
            if conf_file.has_option('runkeeper', 'bindport'):
                conf['bindport'] = conf_file.getint('runkeeper', 'bindport')
            if conf_file.has_option('runkeeper', 'bindaddr'):
                conf['bindaddr'] = conf_file.get('runkeeper', 'bindaddr')
            if conf_file.has_option('runkeeper', 'baseurl'):
                conf['baseurl'] = conf_file.get('runkeeper', 'baseurl')
            return conf
    except ConfigParser.Error:
        raise ConfigurationError("Error parsing configuration file(s): %s\n" 
                                 % sys.exc_info()[1])
    else:
        raise ConfigurationError("No valid configuration file (%s) found." 
                                 % defaultConfFilename)