from DatabaseLiaison
495528
public void deleteGenerator (Connection conn, String table, String column)
        throws SQLException
    {
        executeQuery(conn, "drop sequence if exists \"" + table + "_" + column + "_seq\"");
    }
978619
public static String execSqlQueryTabular(@NotNull final SQLInputs sqlInputs) throws Exception {
        ConnectionService connectionService = new ConnectionService();
        try (final Connection connection = connectionService.setUpConnection(sqlInputs)){
            connection.setReadOnly(true);

            final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
            statement.setQueryTimeout(sqlInputs.getTimeout());

            final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());

            final String resultSetToTable = Format.resultSetToTable(resultSet, sqlInputs.isNetcool());
            resultSet.close();
            return resultSetToTable;
        }
    }
1051049
private boolean query()
		throws SQLException
	{
		statement = this.connection.createStatement();

		String query = "SELECT PrimaryKey, RevisionCounter,"
				+ " RevisionID, ArticleID, Timestamp, FullRevisionID "
				+ "FROM revisions";

		if (primaryKey > 0) {
			query += " WHERE PrimaryKey > " + primaryKey;
		}

		if (MAX_NUMBER_RESULTS > 0) {
			query += " LIMIT " + MAX_NUMBER_RESULTS;
		}

		result = statement.executeQuery(query);
		return result.next();
	}
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);
    }
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");
        }
    }
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
1057540
private boolean verify() throws SQLException {
    //check total num pageview
    String countAccessQuery = "SELECT COUNT(*) FROM Access";
    String sumPageviewQuery = "SELECT SUM(pageview) FROM Pageview";
    Statement st = null;
    ResultSet rs = null;
    try {
      st = connection.createStatement();
      rs = st.executeQuery(countAccessQuery);
      rs.next();
      long totalPageview = rs.getLong(1);

      rs = st.executeQuery(sumPageviewQuery);
      rs.next();
      long sumPageview = rs.getLong(1);

      LOG.info("totalPageview=" + totalPageview);
      LOG.info("sumPageview=" + sumPageview);

      return totalPageview == sumPageview && totalPageview != 0;
    }finally {
      if(st != null)
        st.close();
      if(rs != null)
        rs.close();
    }
  }
148990
public void init(DatabaseOwner databaseOwner, String strDbName, int iDatabaseType, Map<String, Object> properties)
    {
        super.init(databaseOwner, strDbName, iDatabaseType, properties);
        m_pDatabase = null;
    }
339742
def database(connection_string, db_class=SimplDB):
    
    if not hasattr(database, "singletons"):
        database.singletons = {}
    if connection_string not in database.singletons:
        instance = db_class(connection_string)
        database.singletons[connection_string] = instance
    return database.singletons[connection_string]
597605
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);
        
        m_databaseFake = m_database;
        m_database = this.getSharedTable().getDatabase();  // Return the correct database
    }
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);
            }
        }
	}
1197032
private static boolean getAccessSetFromDB(final String _sql,
                                              final Object _criteria)
        throws CacheReloadException
    {
        boolean ret = false;
        Connection con = null;
        try {
            AccessSet accessSet = null;
            con = Context.getConnection();
            PreparedStatement stmt = null;
            try {
                stmt = con.prepareStatement(_sql);
                stmt.setObject(1, _criteria);
                final ResultSet rs = stmt.executeQuery();

                if (rs.next()) {
                    final long id = rs.getLong(1);
                    final String uuid = rs.getString(2);
                    final String name = rs.getString(3);
                    AccessSet.LOG.debug("read AccessSet '{}' (id = {}, uuid ={})", name, id, uuid);
                    accessSet = new AccessSet(id, uuid, name);
                }
                ret = true;
                rs.close();
            } finally {
                if (stmt != null) {
                    stmt.close();
                }
            }
            con.commit();
            if (accessSet != null) {
                accessSet.readLinks2AccessTypes();
                accessSet.readLinks2DMTypes();
                accessSet.readLinks2Status();
                accessSet.readLinks2Person();
                // needed due to cluster serialization that does not update automatically
                AccessSet.cacheAccessSet(accessSet);
            }
        } catch (final SQLException e) {
            throw new CacheReloadException("could not read roles", e);
        } catch (final EFapsException e) {
            throw new CacheReloadException("could not read roles", e);
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (final SQLException e) {
                throw new CacheReloadException("could not read child type ids", e);
            }
        }
        return ret;
    }
908113
@Override
  public Map<String, JdbcType> retrieveDateColumns(String database, String table)
      throws SQLException {
    Map<String, JdbcType> targetDataTypes =
        ImmutableMap.<String, JdbcType>builder().put("DATE", JdbcType.DATE).put("TIME WITH TIME ZONE", JdbcType.TIME)
            .put("TIME WITHOUT TIME ZONE", JdbcType.TIME).put("TIMESTAMP WITH TIME ZONE", JdbcType.TIMESTAMP)
            .put("TIMESTAMP WITHOUT TIME ZONE", JdbcType.TIMESTAMP).build();

    ImmutableMap.Builder<String, JdbcType> dateColumnsBuilder = ImmutableMap.builder();

    try (PreparedStatement pstmt = this.conn
        .prepareStatement(INFORMATION_SCHEMA_SELECT_SQL_PSTMT, ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY)) {
      pstmt.setString(1, database);
      pstmt.setString(2, table);
      log.info("Retrieving column type information from SQL: " + pstmt);
      try (ResultSet rs = pstmt.executeQuery()) {
        if (!rs.first()) {
          throw new IllegalArgumentException("No result from information_schema.columns");
        }
        do {
          String type = rs.getString("data_type").toUpperCase();
          JdbcType convertedType = targetDataTypes.get(type);
          if (convertedType != null) {
            dateColumnsBuilder.put(rs.getString("column_name"), convertedType);
          }
        } while (rs.next());
      }
    }
    return dateColumnsBuilder.build();
  }
962915
static void initializeDatabaseDriver(String databaseType) {
    String driverClass = System.getProperty(JDBC_DRIVER_CLASS_KEY_PREFIX + databaseType);
    if (driverClass != null) {
      Log.debug("Loading " + driverClass + " to initialize database of type " + databaseType);
      try {
        Class.forName(driverClass);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException("Connection to '" + databaseType + "' database is not possible due to missing JDBC driver. " +
                "User specified driver class: " + driverClass, e);
      }
      return;
    }
    // use built-in defaults
    switch (databaseType) {
      case HIVE_DB_TYPE:
        try {
          Class.forName(HIVE_JDBC_DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException("Connection to HIVE database is not possible due to missing JDBC driver.", e);
        }
        break;
      case NETEZZA_DB_TYPE:
        try {
          Class.forName(NETEZZA_JDBC_DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException("Connection to Netezza database is not possible due to missing JDBC driver.", e);
        }
        break;
      default:
        //nothing to do
    }
  }
215096
protected String checkForMariaDb(DatabaseMetaData databaseMetaData, String databaseName) {
    try {
      String databaseProductVersion = databaseMetaData.getDatabaseProductVersion();
      if (databaseProductVersion != null && databaseProductVersion.toLowerCase().contains("mariadb")) {
        return MARIA_DB_PRODUCT_NAME;
      }
    } catch (SQLException ignore) {
    }

    try {
      String driverName = databaseMetaData.getDriverName();
      if (driverName != null && driverName.toLowerCase().contains("mariadb")) {
        return MARIA_DB_PRODUCT_NAME;
      }
    } catch (SQLException ignore) {
    }

    String metaDataClassName = databaseMetaData.getClass().getName();
    if (metaDataClassName != null && metaDataClassName.toLowerCase().contains("mariadb")) {
      return MARIA_DB_PRODUCT_NAME;
    }

    return databaseName;
  }
1225753
private String determineDatabaseProductName(Connection conn) {
        try {
            final String databaseProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
            LOGGER.debug("Database product: {}", databaseProductName);
            return databaseProductName;
        } catch (SQLException se) {
            LOGGER.warn("Problem determining database product!", se);
            return null;
        }
    }
285971
public Database getDatabase(String strDBName, int iDatabaseType, Map<String, Object> properties)
    {
        if ((strDBName == null) || (strDBName.length() == 0))
            return null;
        Database database = this.getDatabaseList(iDatabaseType).get(strDBName);
        if (database == null)
        {
            if ((properties != null)
            	&& (DBConstants.FALSE.equals(properties.get(DBConstants.CREATE_DB_IF_NOT_FOUND)))
            	&& (Environment.DATABASE_DOESNT_EXIST == ((Environment)m_databaseOwner.getEnvironment()).getCachedDatabaseProperties(strDBName)))
            		return null;	// Hey, if the database doesn't exist, don't try again.
            if (iDatabaseType != DBConstants.SCREEN)
                database = this.makeDatabase(iDatabaseType);    // BaseDatabase not found, open it!
            else
                database = new BaseDatabase();                  // Special case: A screen database
            if (database != null)
                database.init(m_databaseOwner, strDBName, iDatabaseType & DBConstants.TABLE_MASK, properties); // init it!
            if (database != null)
            {
                try   {
                    ((BaseDatabase)database).open();    // open it!
                } catch (DBException ex) {
                    database.free();
                    database = null;    // Failure on db open
                    if ((ex.getErrorCode() == DBConstants.DB_NOT_FOUND)
                		&& (properties != null)
                        && (DBConstants.FALSE.equals(properties.get(DBConstants.CREATE_DB_IF_NOT_FOUND))))
                    {	// If the db doesn't exist, cache the name so I won't try this (expensive) operation again
                        ((Environment)m_databaseOwner.getEnvironment()).cacheDatabaseProperties(strDBName, Environment.DATABASE_DOESNT_EXIST);
                    }
                }
            }
        }
        return database;
    }