from DatabaseLiaison
768942
public void createGenerator (Connection conn, String tableName, String columnName, int initValue)
        throws SQLException
    {
        if (initValue == 1) {
            return; // that's the default! yay, do nothing
        }

        String seqname = "\"" + tableName + "_" + columnName + "_seq\"";
        Statement stmt = conn.createStatement();
        try {
            stmt.executeQuery("select setval('" + seqname + "', " + initValue + ", false)");
        } finally {
            JDBCUtil.close(stmt);
        }
        log("Initial value of " + seqname  + " set to " + initValue + ".");
    }
644898
public DatabaseInfo getDatabaseInfo(Connection connection) throws SQLException
    {
        PreparedStatement statement = connection.prepareStatement("select @@servername, db_name()");
        ResultSet results = null;
        DatabaseInfo info = null;

        try
        {
            results = statement.executeQuery();

            if (!results.next())
            {
                throw new SQLException("Query for database name and server name returned zero rows!");
            }

            info = new DatabaseInfo(results.getString(1), results.getString(2));
        }
        finally
        {
            closeResultSet(results, "Ignoring error whilst closing ResultSet that was used to query the DatabaseInfo");

            closeStatement(statement, "Ignoring error whilst closing PreparedStatement that was used to query the DatabaseInfo");
        }

        return info;
    }
280490
private void initFromDatabase() throws SQLException, BlockStoreException {
        PreparedStatement ps = conn.get().prepareStatement(getSelectSettingsSQL());
        ResultSet rs;
        ps.setString(1, CHAIN_HEAD_SETTING);
        rs = ps.executeQuery();
        if (!rs.next()) {
            throw new BlockStoreException("corrupt database block store - no chain head pointer");
        }
        Sha256Hash hash = Sha256Hash.wrap(rs.getBytes(1));
        rs.close();
        this.chainHeadBlock = get(hash);
        this.chainHeadHash = hash;
        if (this.chainHeadBlock == null) {
            throw new BlockStoreException("corrupt database block store - head block not found");
        }
        ps.setString(1, VERIFIED_CHAIN_HEAD_SETTING);
        rs = ps.executeQuery();
        if (!rs.next()) {
            throw new BlockStoreException("corrupt database block store - no verified chain head pointer");
        }
        hash = Sha256Hash.wrap(rs.getBytes(1));
        rs.close();
        ps.close();
        this.verifiedChainHeadBlock = get(hash);
        this.verifiedChainHeadHash = hash;
        if (this.verifiedChainHeadBlock == null) {
            throw new BlockStoreException("corrupt database block store - verified head block not found");
        }
    }
647453
private void executeJdbcStatements(Connection connection, String configName, String statements, String description) {
        Statement stmt = createStatement(configName, connection);
        try {
            log.debug("Executing statement [" + description + "]");
            
            List<String> stmtsToExecute = Stream.of(statements.split(";"))
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
            
            if ( log.isTraceEnabled()) {
                log.trace("These statements will be executed:");
                stmtsToExecute.forEach(s -> log.trace("Statement: [" + s + "]"));
            }
            
            for ( String currentStatement : stmtsToExecute) {
                stmt.execute(currentStatement);
                log.trace("Executing statement: " + currentStatement + " OK!");
            }
            
        } catch (SQLException e) {
            throw new ChorusException(
                    String.format("Failed while executing statement [%s] on database + %s [%s]", description, configName, e.toString(), e)
            );
        }
    }
479391
public void setDatabase(String databaseKey) {

        m_databaseKey = databaseKey;
        String vfsDriver;
        String userDriver;
        String projectDriver;
        String historyDriver;
        String subscriptionDriver;
        String sqlManager;
        vfsDriver = getDbProperty(m_databaseKey + ".vfs.driver");
        userDriver = getDbProperty(m_databaseKey + ".user.driver");
        projectDriver = getDbProperty(m_databaseKey + ".project.driver");
        historyDriver = getDbProperty(m_databaseKey + ".history.driver");
        subscriptionDriver = getDbProperty(m_databaseKey + ".subscription.driver");
        sqlManager = getDbProperty(m_databaseKey + ".sqlmanager");
        // set the db properties
        setExtProperty("db.name", m_databaseKey);
        setExtProperty("db.vfs.driver", vfsDriver);
        setExtProperty("db.vfs.sqlmanager", sqlManager);
        setExtProperty("db.user.driver", userDriver);
        setExtProperty("db.user.sqlmanager", sqlManager);
        setExtProperty("db.project.driver", projectDriver);
        setExtProperty("db.project.sqlmanager", sqlManager);
        setExtProperty("db.history.driver", historyDriver);
        setExtProperty("db.history.sqlmanager", sqlManager);
        setExtProperty("db.subscription.driver", subscriptionDriver);
        setExtProperty("db.subscription.sqlmanager", sqlManager);
        Properties dbProps = getDatabaseProperties().get(databaseKey);
        String prefix = "additional.";
        String dbPropBlock = "";
        for (Map.Entry<Object, Object> entry : dbProps.entrySet()) {
            if (entry.getKey() instanceof String) {
                String key = (String)entry.getKey();
                if (key.startsWith(prefix)) {
                    key = key.substring(prefix.length());
                    String val = (String)(entry.getValue());
                    setExtProperty(key, val);
                    dbPropBlock += key + "=" + val + "\n";
                }
            }

        }
        if (!CmsStringUtil.isEmptyOrWhitespaceOnly(dbPropBlock)) {
            m_additionalProperties.put("dbprops", dbPropBlock);
        }
    }
1163054
private DbDatum[] get_obj_property(Database database, String name, String type, String[] propnames)
            throws DevFailed {
        if (!database.isAccess_checked()) checkAccess(database);

        //	Format input parameters as string array
        //--------------------------------------------
        String[] array;
        array = new String[1 + propnames.length];
        array[0] = name;
        System.arraycopy(propnames, 0, array, 1, propnames.length);

        //	Buid command name (depends on object type)
        //---------------------------------------------------
        String cmd = "DbGet" + type + "Property";

        //	Read Database
        //---------------------
        DeviceData argIn = new DeviceData();
        argIn.insert(array);
        DeviceData argOut = command_inout(database, cmd, argIn);
        String[] result = argOut.extractStringArray();

        //	And convert to DbDatum array before returning
        //-------------------------------------------------
        return stringArray2DbDatum(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
    }
1146921
ThrowableInformation getException(Connection connection, long id)
      throws SQLException {

    PreparedStatement statement = null;

    try {
      statement = connection.prepareStatement(sqlException);
      statement.setLong(1, id);
      ResultSet rs = statement.executeQuery();

      Vector v = new Vector();

      while (rs.next()) {
        //int i = rs.getShort(1);
        v.add(rs.getString(1));
      }

      int len = v.size();
      String[] strRep = new String[len];
      for (int i = 0; i < len; i++) {
        strRep[i] = (String) v.get(i);
      }
      // we've filled strRep, we now attach it to the event
      return new ThrowableInformation(strRep);
    } finally {
      if (statement != null) {
        statement.close();
      }
    }
  }
250942
protected void readDatabaseConfig() {

        m_databaseKeys = new ArrayList<String>();
        m_databaseProperties = new HashMap<String, Properties>();

        FileInputStream input = null;
        File childResource = null;

        List<String> databaseKeys = new ArrayList<String>();
        Map<String, Properties> databaseProperties = new HashMap<String, Properties>();

        try {
            File databaseSetupFolder = new File(m_webAppRfsPath + FOLDER_SETUP + FOLDER_DATABASE);

            File[] childResources = databaseSetupFolder.listFiles();

            // collect all possible db configurations
            if (childResources != null) {
                for (int i = 0; i < childResources.length; i++) {
                    childResource = childResources[i];
                    if (childResource.exists() && childResource.isDirectory() && childResource.canRead()) {
                        databaseKeys.add(childResource.getName().trim());
                    }
                }
            }

            // create the properties with all possible configurations
            if (databaseSetupFolder.exists()) {
                for (String key : databaseKeys) {
                    String dbDir = m_webAppRfsPath + CmsSetupBean.FOLDER_SETUP + "database" + File.separatorChar + key;
                    String configPath = dbDir + File.separatorChar + "database.properties";
                    try {
                        input = new FileInputStream(new File(configPath));
                        Properties databaseProps = new Properties();
                        databaseProps.load(input);
                        databaseProperties.put(key, databaseProps);
                    } catch (Exception e) {
                        System.err.println(e.toString());
                        e.printStackTrace(System.err);
                        continue;
                    }
                }
            }

            // add the properties and the keys to the memeber variables if all needed files exist
            if (childResources != null) {
                for (int i = 0; i < childResources.length; i++) {
                    childResource = childResources[i];
                    if (childResource.exists() && childResource.isDirectory() && childResource.canRead()) {
                        String dataBasekey = childResource.getName().trim();
                        Properties props = databaseProperties.get(dataBasekey);
                        if (checkFilesExists(REQUIRED_SQL_DB_SETUP_FILES, childResource)) {
                            m_databaseKeys.add(childResource.getName().trim());
                            m_databaseProperties.put(dataBasekey, props);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.toString());
            e.printStackTrace(System.err);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                // noop
            }
        }
    }
1158913
@Override
    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,
            String inverseJoinColumnName, Object parentId, Class columnJavaType)
    {
        StringBuffer sqlQuery = new StringBuffer();
        sqlQuery.append("SELECT ").append(inverseJoinColumnName).append(" FROM ")
                .append(getFromClause(schemaName, joinTableName)).append(" WHERE ").append(joinColumnName).append("='")
                .append(parentId).append("'");

        Session s = getSession();

        SQLQuery query = s.createSQLQuery(sqlQuery.toString());

        List<E> foreignKeys = new ArrayList<E>();

        foreignKeys = query.list();

        return foreignKeys;
    }
1339806
public void initialiseDatabase() {
        if (!databaseInitialized) {
            sendConsoleMessage(Level.INFO, getLanguageManager().getString("loading_database_manager"));
            storageHandler = new StorageHandler();

            //TODO: Re-support that
            if (getMainConfig().getBoolean("System.Database.ConvertFromH2")) {
                convertDatabase();
            }

            databaseInitialized = true;
            sendConsoleMessage(Level.INFO, getLanguageManager().getString("database_manager_loaded"));
        }
    }
548537
private static void getForeignKeys(DatabaseMetaData md, DatabaseRelationDefinition relation, DBMetadata metadata) throws SQLException {

		QuotedIDFactory idfac = metadata.getQuotedIDFactory();

		RelationID relationId = relation.getID();
		try (ResultSet rs = md.getImportedKeys(null, relationId.getSchemaName(), relationId.getTableName())) {
            extractForeignKeys(relation, metadata, idfac, rs);
        }
        catch (Exception ex) {
            try (ResultSet rs = md.getImportedKeys(relationId.getSchemaName(),null, relationId.getTableName())) {
                extractForeignKeys(relation, metadata, idfac, rs);
            }
        }
	}
1223526
def from_database(cls, database):
        """"""
        if isinstance(database, PostgresqlDatabase):
            return PostgresqlMigrator(database)
        if isinstance(database, SqliteDatabase):
            return SqliteMigrator(database)
        if isinstance(database, MySQLDatabase):
            return MySQLMigrator(database)
        return super(SchemaMigrator, cls).from_database(database)
120686
def main():
    

    DATABASE.load_contents()

    continue_flag = False

    while not continue_flag:
        DATABASE.print_contents()
        try:
            command = raw_input(">>> ")
            for stmnt_unformated in sqlparse.parse(command):
                statement = sqlparse.parse(
                    sqlparse.format(
                        str(
                            stmnt_unformated
                        ),
                        reindent=True
                    )
                )[0]
                type = statement.tokens[0]

                if str(type).lower() == "drop":
                    if str(statement.tokens[2]).lower() == "table":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        table.rows = []
                        table.store_contents()
                        DATABASE.delete_table(tablename)
                        DATABASE.store_contents()
                    else:
                        raise Exception(
                            "Invalid Syntax of DROP TABLE t"
                        )
                elif str(type).lower() == "truncate":
                    if str(statement.tokens[2]).lower() == "table":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        table.rows = []
                        table.store_contents()
                    else:
                        raise Exception(
                            "Invalid Syntax of TRUNCATE TABLE t"
                        )
                elif str(type).lower() == "delete":
                    if str(statement.tokens[2]).lower() == "from":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        whereclause = statement.tokens[6]
                        if str(whereclause.tokens[0]).lower() == "where":
                            comparison = whereclause.tokens[2]
                            key = str(comparison.tokens[0])
                            value = int(str(comparison.tokens[4]))
                            table.delete_row(key, value)
                            table.store_contents()
                        else:
                            raise Exception(
                                "Invalid Syntax of DELETE FROM t where k = v"
                            )

                    else:
                        raise Exception(
                            "Invalid Syntax of DELETE FROM t WHERE k = v"
                        )
                elif str(type).lower() == "insert":
                    if str(statement.tokens[2]).lower() == "into":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        if str(statement.tokens[6]).lower() == "values":
                            parenthesis = statement.tokens[8]
                            idlist = parenthesis.tokens[1]
                            values_list = map(
                                lambda x: int(str(x)),
                                idlist.get_identifiers()
                            )
                            table.put_row_raw(values_list)
                            table.store_contents()
                        else:
                            raise Exception(
                                "Invalid Syntax of INSERT INTO t VALUES (v...)"
                            )
                    else:
                        raise Exception(
                            "Invalid Syntax of INSERT INTO t VALUES (v...)"
                        )
                elif str(type).lower() == "create":
                    if str(statement.tokens[2]).lower() == "table":
                        sublist = list(statement.tokens[4].get_sublists())
                        tablename = str(sublist[0])
                        garbage = str(sublist[1])
                        column_list = map(
                            lambda x: x.strip(" ()",).split()[0],
                            garbage.split(",")
                        )
                        DATABASE.create_table_raw(
                            tablename=tablename,
                            columns=column_list[:],
                        )
                        DATABASE.store_contents()
                elif str(type).lower() == "select":
                    col_list_or_single = statement.tokens[2]
                    if "," not in str(col_list_or_single):
                        if str(col_list_or_single) == "*":
                            column_list = ['*']
                        else:
                            column_list = [str(col_list_or_single)]
                    else:
                        column_list = map(
                            lambda x: str(x),
                            col_list_or_single.get_identifiers()
                        )
                    if str(statement.tokens[4]).lower() == "from":
                        tab_list_or_single = statement.tokens[6]
                        if "," not in str(tab_list_or_single):
                            table_list = [str(tab_list_or_single)]
                        else:
                            table_list = map(
                                lambda x: str(x),
                                tab_list_or_single.get_identifiers()
                            )
                        cross_columns = reduce(
                            lambda x, y: x + y,
                            map(
                                lambda x: DATABASE.get_table(
                                    x
                                ).get_column_list_prefixed(),
                                table_list
                            )
                        )
                        cross_table = parthsql.Table(
                            name="temp",
                            columns=cross_columns,
                            rows=[]
                        )
                        for i in itertools.product(
                            *map(
                                lambda x: DATABASE.get_table(x).get_all_rows(),
                                table_list
                            )
                        ):
                            cross_table.put_row_raw(
                                reduce(
                                    lambda x, y: x + y,
                                    i
                                )
                            )

                        if len(statement.tokens) >= 9:
                            whereclause = statement.tokens[8]
                            if str(whereclause.tokens[0]).lower() == "where":
                                comparison = whereclause.tokens[2]
                                key = str(comparison.tokens[0])
                                try:
                                    value = int(str(comparison.tokens[4]))
                                    cross_table.invert_delete_row(key, value)
                                except:
                                    value = str(comparison.tokens[4])
                                    cross_table.invert_delete_row2(key, value)
                            else:
                                raise Exception(
                                    "Invalid Syntax of DELETE FROM t where k = v"
                                )

                        if "*" in column_list:
                            cross_table.print_contents()
                        else:
                            temp_list = []
                            for i in column_list:
                                temp_list.append(cross_table.get_column(i))
                            print "\t\t\t".join(column_list)
                            for i in zip(*(temp_list)):
                                print "\t\t\t".join(map(str, i))
                    else:
                        raise Exception(
                            "Invalid Syntax of SELECT c... FROM t... WHERE k = v"
                        )
                else:
                    raise Exception(
                        "Unsupported Operation"
                    )
        except ValueError:
            print("¯\_(ツ)_/¯")
        except IOError:
            print("¯\_(ツ)_/¯")
        except IndexError:
            print("¯\_(ツ)_/¯")
        except AttributeError:
            print("¯\_(ツ)_/¯")
        except Exception, e:
            print e.message
818993
private void checkJdbcSupport(DatabaseMetaData metaData) throws SQLException {

        if (_getGeneratedKeys && !metaData.supportsGetGeneratedKeys()) {
            throw new ControlException("The database does not support getGeneratedKeys.");
        }

        if (_batchUpdate && !metaData.supportsBatchUpdates()) {
            throw new ControlException("The database does not support batchUpdates.");
        }

        if (_scrollType != JdbcControl.ScrollType.DRIVER_DEFAULT
                && !metaData.supportsResultSetConcurrency(_scrollType.getType(), _scrollType.getConcurrencyType())) {
            throw new ControlException("The database does not support the ResultSet concurrecy type: " + _scrollType.toString());
        }

        if (_holdability != JdbcControl.HoldabilityType.DRIVER_DEFAULT
                && !metaData.supportsResultSetHoldability(_holdability.getHoldability())) {
            throw new ControlException("The database does not support the ResultSet holdability type: " + _holdability.toString());
        }
    }
1330708
private synchronized void open() throws DatabaseException {
        try {
            if (!isOpen()) {
                connection = connectionFactory.getConnection();
                final String databaseProductName = determineDatabaseProductName(this.connection);
                statementBundle = databaseProductName != null
                        ? ResourceBundle.getBundle("data/dbStatements", new Locale(databaseProductName))
                        : ResourceBundle.getBundle("data/dbStatements");
                prepareStatements();
                databaseProperties = new DatabaseProperties(this);
            }
        } catch (DatabaseException e) {
            releaseResources();
            throw e;
        }
    }
874712
public DatabaseSession createDatabaseSession(BaseDatabase database, Map<String, Object> properties) throws RemoteException
    {
        DatabaseSession remoteDatabase = null;
        Map<String,Object> propOld = this.getProperties();
        this.setProperties(properties);
        DatabaseOwner databaseOwner = database.getDatabaseOwner();
        if (databaseOwner == null)
            databaseOwner = this.getDatabaseOwner();    // Never
        this.setProperties(propOld);
        if (databaseOwner instanceof Application)
            remoteDatabase = new DatabaseSession((Application)databaseOwner);   // Typical
        else
            remoteDatabase = new DatabaseSession((BaseSession)databaseOwner, null); // If AUTO_COMMIT if off, I need my own database
        database.setMasterSlave(RecordOwner.SLAVE);      // Don't create client behaviors
        remoteDatabase.setDatabase(database);
        return remoteDatabase;
    }