Example usage for java.sql ResultSet setFetchSize

List of usage examples for java.sql ResultSet setFetchSize

Introduction

In this page you can find the example usage for java.sql ResultSet setFetchSize.

Prototype

void setFetchSize(int rows) throws SQLException;

Source Link

Document

Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for this ResultSet object.

Usage

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.DAMQueriesLevel2.java

private List<String> gatherHybridizationDataGroupNames(final int firstDataSetId) {
    final List<String> hybDataGroupNames = new ArrayList<String>();
    final String sqlHDG = HYB_DATA_GROUP_NAME_QUERY;

    getJdbcTemplate().query(sqlHDG, new Object[] { firstDataSetId }, new RowCallbackHandler() {
        public void processRow(final ResultSet resultSet) throws SQLException {
            resultSet.setFetchSize(DEFAULT_FETCHSIZE);
            //get GROUP_COLUMN_NAME that is 1
            hybDataGroupNames.add(resultSet.getString(1));
        }/* w  w w.  ja v  a  2 s .c  o  m*/
    });

    return hybDataGroupNames;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.DAMQueriesLevel2.java

private void generateFileInTransaction(final DataFileLevelTwoThree dataFile, final Writer writer)
        throws IOException {
    /*// w  ww  .jav a  2  s  .  c  o  m
    Set the variables for column names we'll need locally.  Local var is 6 times faster than a shared constant.
    If you change the select for HYBRIDIZATION_VALUE_QUERY please change these values and maintain column number order.
     */
    final Integer PROBE_NAME = 1;
    final Integer CHROMOSOME = 2;
    final Integer START_POSITION = 3;
    final Integer END_POSITION = 4;
    final Integer HYBRIDIZATION_REF_ID = 5;
    final Integer GROUP_COLUMN_NAME = 6;
    final Integer VALUE = 7;

    final String STRING = "-";
    // 1. gather barcodes and hyb_data_groups from database
    final List<String> hybDataGroupNames = gatherHybridizationDataGroupNames(
            dataFile.getDataSetsDP().iterator().next());
    final Map<String, Long> hybrefIdToBarcodeMap = getBarcodesForHybrefs(dataFile);

    // sort barcodes into the order we want to write them in the file (alphabetical)
    final String[] orderedBarcodes = new String[hybrefIdToBarcodeMap.size()];
    hybrefIdToBarcodeMap.keySet().toArray(orderedBarcodes);
    Arrays.sort(orderedBarcodes);

    int platformId = getPortalPlatformId(dataFile.getDataSetsDP().iterator().next());

    final boolean willHaveProbeConstants = getWillHaveProbeConstants(platformId);
    writeHeaders(writer, hybDataGroupNames, orderedBarcodes, willHaveProbeConstants);

    List<Object> queryBindValues = new ArrayList<Object>();
    String query = prepareQueryAndBindVariables(dataFile, queryBindValues, platformId);
    insertTempHybrefIds(dataFile.getHybRefIds());
    insertTempDataSetIds(dataFile.getDataSetsDP());
    final Map<String, String> currentRowValues = new HashMap<String, String>(); // keyed by "hybref_id.data_group_name"
    final String[] lastProbe = new String[] { null, null, null }; // done this way b/c used by inner class
    getJdbcTemplate().query(query, queryBindValues.toArray(), new RowCallbackHandler() {
        public void processRow(final ResultSet resultSet) throws SQLException {
            resultSet.setFetchSize(DEFAULT_FETCHSIZE);

            String currentProbe = resultSet.getString(PROBE_NAME);
            if (lastProbe[0] != null && !lastProbe[0].equals(currentProbe)) {
                // this result set is the start of a new row, so write the old one
                try {
                    writeDataRow(lastProbe, currentRowValues, orderedBarcodes, hybrefIdToBarcodeMap,
                            hybDataGroupNames, writer, willHaveProbeConstants);
                    currentRowValues.clear();
                } catch (IOException e) {
                    getLogger().logError(e);
                    throw new DataAccessException(e.getMessage(), e) {
                    };
                }
            }

            // store this value in the values map, keyed by combination of hybrefid and datagroup name
            final String key = resultSet.getLong(HYBRIDIZATION_REF_ID) + "."
                    + resultSet.getString(GROUP_COLUMN_NAME);
            currentRowValues.put(key, resultSet.getString(VALUE));
            lastProbe[0] = currentProbe;
            lastProbe[1] = resultSet.getString(CHROMOSOME);
            lastProbe[2] = resultSet.getString(START_POSITION) + STRING + resultSet.getString(END_POSITION);
        }
    });
    // write last row!
    if (lastProbe[0] != null) {
        writeDataRow(lastProbe, currentRowValues, orderedBarcodes, hybrefIdToBarcodeMap, hybDataGroupNames,
                writer, willHaveProbeConstants);
    }
}

From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java

/**
 * Calculate hash on DB//from  w ww .j a v a 2  s.com
 *
 * @return
 */
public String retrieveFullResultSet(ResultSet rs) {

    this.logger.info("Resulset row count: " + this.getResultSetRowCount(rs));

    String resultSetHash = "";
    String currentHash = "";
    String previousKey = "";
    String compositeHash = "";
    int hashCounter = 0;

    long startTime = System.currentTimeMillis();
    //int hashCounter =0;

    try {

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnsNumber = rsmd.getColumnCount();
        this.logger.info("There are " + columnsNumber + " columns in the result set");
        String newResultSetHash = null;
        long meanTimeStart = System.currentTimeMillis();

        rs.setFetchSize(1000);

        while (rs.next()) {
            hashCounter++;
            if (hashCounter % 1000 == 0) {
                long meanTimeStop = System.currentTimeMillis();

                this.logger.warning("Calculated " + hashCounter + " hashes so far. This batch took "
                        + (double) ((meanTimeStop - meanTimeStart) / 1000) + " seconds");

                meanTimeStart = System.currentTimeMillis();
            }
            for (int i = 1; i < columnsNumber; i++) {
                currentHash += rs.getString(i);
            }

            if (rs.isFirst()) {

                resultSetHash = this.calculateHashFromString(currentHash);

            } else {

                compositeHash = (resultSetHash + currentHash);

                // reset the variables in order to reduce overhead
                resultSetHash = null;
                currentHash = null;
                newResultSetHash = this.calculateHashFromString(compositeHash);
                //this.logger.info("[resultSetHash] "+resultSetHash + "[currentHash] " + currentHash +" ->
                // [newResultSetHash]" + newResultSetHash );
                resultSetHash = newResultSetHash;

            }
            System.gc();
        }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    double elapsedTime = (double) (totalTime / 1000);

    this.logger.info("Calculated " + hashCounter + " hash values in " + elapsedTime + " sec");
    this.logger.info("Hash is " + resultSetHash);
    return resultSetHash;

}

From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java

public String calculateResultSetHashShort(ResultSet rs, String concatenatedColumns) {

    //@todo hashing

    this.logger.info("Resulset row count: " + this.getResultSetRowCount(rs));

    String resultSetHash = concatenatedColumns;
    String concatenatedIdentifiers = "";

    String currentHash = "";
    String previousKey = "";
    String compositeHash = "";
    int hashCounter = 0;

    long startTime = System.currentTimeMillis();
    //int hashCounter =0;

    try {//from   ww w  . j a  v a  2 s  .c  o m

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnsNumber = rsmd.getColumnCount();
        this.logger.info("There are " + columnsNumber + " columns in the result set");

        long meanTimeStart = System.currentTimeMillis();

        rs.setFetchSize(10000);

        while (rs.next()) {
            hashCounter++;
            if (hashCounter % 1000 == 0) {
                long meanTimeStop = System.currentTimeMillis();

                this.logger.warning("Calculated " + hashCounter + " hashes so far. This batch took "
                        + (double) ((meanTimeStop - meanTimeStart) / 1000) + " seconds");

                meanTimeStart = System.currentTimeMillis();
            }

            concatenatedIdentifiers += rs.getString(1);
            //this.logger.info("At row " + hashCounter +" the hash currently has the length of: " + concatenatedIdentifiers.length());

            System.gc();
        }

        resultSetHash += concatenatedIdentifiers;
        this.logger.info("The hash has the length of: " + concatenatedIdentifiers.length());
        resultSetHash = this.calculateHashFromString(resultSetHash);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    double elapsedTime = (double) (totalTime / 1000);

    this.logger.info("Calculated " + hashCounter + " hash values in " + elapsedTime + " sec");
    this.logger.info("Hash is " + resultSetHash);
    return resultSetHash;

}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testFetchSize() throws SQLException {
    stat = conn.createStatement();/*www  . ja v a 2  s. co m*/
    ResultSet rs = stat.executeQuery("SELECT * FROM SYSTEM_RANGE(1, 100)");
    int a = stat.getFetchSize();
    int b = rs.getFetchSize();
    assertEquals(a, b);
    rs.setFetchSize(b + 1);
    b = rs.getFetchSize();
    assertEquals(a + 1, b);
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@Test
public void testResultSetOptions() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);

    assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection());
    rs.setFetchDirection(ResultSet.FETCH_FORWARD);
    assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection());

    try {/*from  w  ww. j a  v  a2  s . com*/
        rs.setFetchDirection(ResultSet.FETCH_REVERSE);
        fail();
    } catch (SQLException ignore) {
    }

    assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection());

    rs.setFetchSize(100);
    assertEquals(100, rs.getFetchSize());

    rs.close();
    statement.close();
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testInt() throws SQLException {
    trace("test INT");
    ResultSet rs;
    Object o;/*ww  w .  jav a 2s  .  c om*/
    stat = conn.createStatement();
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(31,-1, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(32,0, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(33,1, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(34," + Integer.MAX_VALUE + ", 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(35," + Integer.MIN_VALUE + ", 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(36,0, 'testInt')");
    stat.execute("INSERT INTO test (column1,column2,column3) VALUES(37,0, 'testInt')");
    // this should not be read - maxrows=6

    // MySQL compatibility (is this required?)
    rs = stat.executeQuery("SELECT column1,column2,column3 FROM test where column3='testInt' ORDER BY column1");
    // MySQL compatibility
    assertEquals(1, rs.findColumn("column1"));
    assertEquals(2, rs.findColumn("column2"));

    ResultSetMetaData meta = rs.getMetaData();
    assertEquals(3, meta.getColumnCount());

    assertTrue(rs.getRow() == 0);

    rs.next();
    trace("default fetch size=" + rs.getFetchSize());
    // 0 should be an allowed value (but it's not defined what is actually
    // means)
    rs.setFetchSize(1);
    assertThrows(SQLErrorCode.INVALID_VALUE_2, rs).setFetchSize(-1);
    // fetch size 100 is bigger than maxrows - not allowed
    rs.setFetchSize(6);

    assertTrue(rs.getRow() == 1);
    assertEquals(2, rs.findColumn("COLUMN2"));
    assertEquals(2, rs.findColumn("column2"));
    assertEquals(2, rs.findColumn("Column2"));
    assertEquals(1, rs.findColumn("COLUMN1"));
    assertEquals(1, rs.findColumn("column1"));
    assertEquals(1, rs.findColumn("Column1"));
    assertEquals(1, rs.findColumn("colUMN1"));
    assertTrue(rs.getInt(2) == -1 && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN2") == -1 && !rs.wasNull());
    assertTrue(rs.getInt("column2") == -1 && !rs.wasNull());
    assertTrue(rs.getInt("Column2") == -1 && !rs.wasNull());
    assertTrue(rs.getString("Column2").equals("-1") && !rs.wasNull());

    o = rs.getObject("column2");
    trace(o.getClass().getName());
    assertTrue(o instanceof Long);
    assertTrue(((Long) o).longValue() == -1);
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Long);
    assertTrue(((Long) o).longValue() == -1);
    assertTrue(rs.getBoolean("Column2"));
    assertTrue(rs.getByte("Column2") == (byte) -1);
    assertTrue(rs.getShort("Column2") == (short) -1);
    assertTrue(rs.getLong("Column2") == -1);
    assertTrue(rs.getFloat("Column2") == -1.0);
    assertTrue(rs.getDouble("Column2") == -1.0);

    assertTrue(rs.getString("Column2").equals("-1") && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN1") == 31 && !rs.wasNull());
    assertTrue(rs.getInt("column1") == 31 && !rs.wasNull());
    assertTrue(rs.getInt("Column1") == 31 && !rs.wasNull());
    assertTrue(rs.getInt(1) == 31 && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 2);
    assertTrue(rs.getInt(2) == 0 && !rs.wasNull());
    assertTrue(!rs.getBoolean(2));
    assertTrue(rs.getByte(2) == 0);
    assertTrue(rs.getShort(2) == 0);
    assertTrue(rs.getLong(2) == 0);
    assertTrue(rs.getFloat(2) == 0.0);
    assertTrue(rs.getDouble(2) == 0.0);
    assertTrue(rs.getString(2).equals("0") && !rs.wasNull());
    assertTrue(rs.getInt(1) == 32 && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 3);
    assertTrue(rs.getInt("COLUMN1") == 33 && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN2") == 1 && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 4);
    assertTrue(rs.getInt("COLUMN1") == 34 && !rs.wasNull());
    assertTrue(rs.getInt("COLUMN2") == Integer.MAX_VALUE && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 5);
    assertTrue(rs.getInt("column1") == 35 && !rs.wasNull());
    assertTrue(rs.getInt("column2") == Integer.MIN_VALUE && !rs.wasNull());
    assertTrue(rs.getString(1).equals("35") && !rs.wasNull());
    rs.next();
    assertTrue(rs.getRow() == 6);
    assertTrue(rs.getInt("column1") == 36 && !rs.wasNull());
    assertTrue(rs.getInt("column2") == 0 && !rs.wasNull());
    assertTrue(rs.getInt(2) == 0 && !rs.wasNull());
    assertTrue(rs.getInt(1) == 36 && !rs.wasNull());
    assertTrue(rs.getString(1).equals("36") && !rs.wasNull());
    assertTrue(rs.getString(2).equals("0") && !rs.wasNull());
    assertTrue(!rs.wasNull());
    // assertFalse(rs.next());
    // assertEquals(0, rs.getRow());
    // there is one more row, but because of setMaxRows we don't get it
}

From source file:com.amazon.carbonado.repo.jdbc.JDBCStorableIntrospector.java

/**
 * Uses the given database connection to query database metadata. This is
 * used to bind storables to tables, and properties to columns. Other
 * checks are performed to ensure that storable type matches well with the
 * definition in the database./*from ww  w  . ja  v  a2 s.  com*/
 */
private static <S extends Storable> JDBCStorableInfo<S> examine(StorableInfo<S> mainInfo, Connection con,
        final String searchCatalog, final String searchSchema, SchemaResolver resolver,
        boolean primaryKeyCheckDisabled) throws SQLException, SupportException {
    final DatabaseMetaData meta = con.getMetaData();

    final String databaseProductName = meta.getDatabaseProductName();
    final String userName = meta.getUserName();

    String[] tableAliases;
    if (mainInfo.getAliasCount() > 0) {
        tableAliases = mainInfo.getAliases();
    } else {
        String name = mainInfo.getStorableType().getSimpleName();
        tableAliases = generateAliases(name);
    }

    // Try to find matching table from aliases.
    String catalog = null, schema = null, tableName = null, tableType = null;
    findName: {
        // The call to getTables may return several matching tables. This
        // map defines the "best" table type we'd like to use. The higher
        // the number the better.
        Map<String, Integer> fitnessMap = new HashMap<String, Integer>();
        fitnessMap.put("LOCAL TEMPORARY", 1);
        fitnessMap.put("GLOBAL TEMPORARY", 2);
        fitnessMap.put("VIEW", 3);
        fitnessMap.put("SYSTEM TABLE", 4);
        fitnessMap.put("TABLE", 5);
        fitnessMap.put("ALIAS", 6);
        fitnessMap.put("SYNONYM", 7);

        for (int i = 0; i < tableAliases.length; i++) {
            ResultSet rs = meta.getTables(searchCatalog, searchSchema, tableAliases[i], null);
            try {
                int bestFitness = 0;
                while (rs.next()) {
                    String type = rs.getString("TABLE_TYPE");
                    Integer fitness = fitnessMap.get(type);
                    if (fitness != null) {
                        String rsSchema = rs.getString("TABLE_SCHEM");

                        if (searchSchema == null) {
                            if (userName != null && userName.equalsIgnoreCase(rsSchema)) {
                                // Favor entities whose schema name matches
                                // the user name.
                                fitness += 7;
                            }
                        }

                        if (fitness > bestFitness) {
                            bestFitness = fitness;
                            catalog = rs.getString("TABLE_CAT");
                            schema = rsSchema;
                            tableName = rs.getString("TABLE_NAME");
                            tableType = type;
                        }
                    }
                }
            } finally {
                rs.close();
            }

            if (tableName != null) {
                // Found a match, so stop checking aliases.
                break;
            }
        }
    }

    if (tableName == null && !mainInfo.isIndependent()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Unable to find matching table name for type \"");
        buf.append(mainInfo.getStorableType().getName());
        buf.append("\" by looking for ");
        appendToSentence(buf, tableAliases);
        buf.append(" with catalog " + searchCatalog + " and schema " + searchSchema);
        throw new MismatchException(buf.toString());
    }

    String qualifiedTableName = tableName;
    String resolvedTableName = tableName;

    // Oracle specific stuff...
    // TODO: Migrate this to OracleSupportStrategy.
    if (tableName != null && databaseProductName.toUpperCase().contains("ORACLE")) {
        if ("TABLE".equals(tableType) && searchSchema != null) {
            // Qualified table name references the schema. Used by SQL statements.
            qualifiedTableName = searchSchema + '.' + tableName;
        } else if ("SYNONYM".equals(tableType)) {
            // Try to get the real schema. This call is Oracle specific, however.
            String select = "SELECT TABLE_OWNER,TABLE_NAME " + "FROM ALL_SYNONYMS "
                    + "WHERE OWNER=? AND SYNONYM_NAME=?";
            PreparedStatement ps = con.prepareStatement(select);
            ps.setString(1, schema); // in Oracle, schema is the owner
            ps.setString(2, tableName);
            try {
                ResultSet rs = ps.executeQuery();
                try {
                    if (rs.next()) {
                        schema = rs.getString("TABLE_OWNER");
                        resolvedTableName = rs.getString("TABLE_NAME");
                    }
                } finally {
                    rs.close();
                }
            } finally {
                ps.close();
            }
        }
    }

    // Gather information on all columns such that metadata only needs to
    // be retrieved once.
    Map<String, ColumnInfo> columnMap = new TreeMap<String, ColumnInfo>(String.CASE_INSENSITIVE_ORDER);

    if (resolvedTableName != null) {
        ResultSet rs = meta.getColumns(catalog, schema, resolvedTableName, null);
        rs.setFetchSize(1000);
        try {
            while (rs.next()) {
                ColumnInfo info = new ColumnInfo(rs);
                columnMap.put(info.columnName, info);
            }
        } finally {
            rs.close();
        }
    }

    // Make sure that all properties have a corresponding column.
    Map<String, ? extends StorableProperty<S>> mainProperties = mainInfo.getAllProperties();
    Map<String, String> columnToProperty = new HashMap<String, String>();
    Map<String, JDBCStorableProperty<S>> jProperties = new LinkedHashMap<String, JDBCStorableProperty<S>>(
            mainProperties.size());

    ArrayList<String> errorMessages = new ArrayList<String>();

    for (StorableProperty<S> mainProperty : mainProperties.values()) {
        if (mainProperty.isDerived() || mainProperty.isJoin() || tableName == null) {
            jProperties.put(mainProperty.getName(), new JProperty<S>(mainProperty, primaryKeyCheckDisabled));
            continue;
        }

        String[] columnAliases;
        if (mainProperty.getAliasCount() > 0) {
            columnAliases = mainProperty.getAliases();
        } else {
            columnAliases = generateAliases(mainProperty.getName());
        }

        JDBCStorableProperty<S> jProperty = null;
        boolean addedError = false;

        findName: for (int i = 0; i < columnAliases.length; i++) {
            ColumnInfo columnInfo = columnMap.get(columnAliases[i]);
            if (columnInfo != null) {
                AccessInfo accessInfo = getAccessInfo(mainProperty, columnInfo.dataType,
                        columnInfo.dataTypeName, columnInfo.columnSize, columnInfo.decimalDigits);

                if (accessInfo == null) {
                    TypeDesc propertyType = TypeDesc.forClass(mainProperty.getType());
                    String message = "Property \"" + mainProperty.getName() + "\" has type \""
                            + propertyType.getFullName() + "\" which is incompatible with database type \""
                            + columnInfo.dataTypeName + '"';

                    if (columnInfo.decimalDigits > 0) {
                        message += " (decimal digits = " + columnInfo.decimalDigits + ')';
                    }

                    errorMessages.add(message);
                    addedError = true;
                    break findName;
                }

                if (columnInfo.nullable) {
                    if (!mainProperty.isNullable() && !mainProperty.isIndependent()) {
                        errorMessages.add(
                                "Property \"" + mainProperty.getName() + "\" must have a Nullable annotation");
                    }
                } else {
                    if (mainProperty.isNullable() && !mainProperty.isIndependent()) {
                        errorMessages.add("Property \"" + mainProperty.getName()
                                + "\" must not have a Nullable annotation");
                    }
                }

                boolean autoIncrement = mainProperty.isAutomatic();
                if (autoIncrement) {
                    // Need to execute a little query to check if column is
                    // auto-increment or not. This information is not available in
                    // the regular database metadata prior to jdk1.6.

                    PreparedStatement ps = con.prepareStatement(
                            "SELECT " + columnInfo.columnName + " FROM " + tableName + " WHERE 1=0");

                    try {
                        ResultSet rs = ps.executeQuery();
                        try {
                            autoIncrement = rs.getMetaData().isAutoIncrement(1);
                        } finally {
                            rs.close();
                        }
                    } finally {
                        ps.close();
                    }
                }

                jProperty = new JProperty<S>(mainProperty, columnInfo, autoIncrement, primaryKeyCheckDisabled,
                        accessInfo.mResultSetGet, accessInfo.mPreparedStatementSet, accessInfo.getAdapter());

                break findName;
            }
        }

        if (jProperty != null) {
            jProperties.put(mainProperty.getName(), jProperty);
            columnToProperty.put(jProperty.getColumnName(), jProperty.getName());
        } else {
            if (mainProperty.isIndependent()) {
                jProperties.put(mainProperty.getName(),
                        new JProperty<S>(mainProperty, primaryKeyCheckDisabled));
            } else if (!addedError) {
                StringBuilder buf = new StringBuilder();
                buf.append("Unable to find matching database column for property \"");
                buf.append(mainProperty.getName());
                buf.append("\" by looking for ");
                appendToSentence(buf, columnAliases);
                errorMessages.add(buf.toString());
            }
        }
    }

    if (errorMessages.size() > 0) {
        throw new MismatchException(mainInfo.getStorableType(), errorMessages);
    }

    // Now verify that primary or alternate keys match.

    if (resolvedTableName != null)
        checkPrimaryKey: {
            ResultSet rs;
            try {
                rs = meta.getPrimaryKeys(catalog, schema, resolvedTableName);
            } catch (SQLException e) {
                getLog().info("Unable to get primary keys for table \"" + resolvedTableName + "\" with catalog "
                        + catalog + " and schema " + schema + ": " + e);
                break checkPrimaryKey;
            }

            List<String> pkProps = new ArrayList<String>();

            try {
                while (rs.next()) {
                    String columnName = rs.getString("COLUMN_NAME");
                    String propertyName = columnToProperty.get(columnName);

                    if (propertyName == null) {
                        errorMessages
                                .add("Column \"" + columnName + "\" must be part of primary or alternate key");
                        continue;
                    }

                    pkProps.add(propertyName);
                }
            } finally {
                rs.close();
            }

            if (errorMessages.size() > 0) {
                // Skip any extra checks.
                break checkPrimaryKey;
            }

            if (pkProps.size() == 0) {
                // If no primary keys are reported, don't even bother checking.
                // There's no consistent way to get primary keys, and entities
                // like views and synonyms don't usually report primary keys.
                // A primary key might even be logically defined as a unique
                // constraint.
                break checkPrimaryKey;
            }

            if (matchesKey(pkProps, mainInfo.getPrimaryKey())) {
                // Good. Primary key in database is same as in Storable.
                break checkPrimaryKey;
            }

            // Check if Storable has an alternate key which matches the
            // database's primary key.
            boolean foundAnyAltKey = false;
            for (StorableKey<S> altKey : mainInfo.getAlternateKeys()) {
                if (matchesKey(pkProps, altKey)) {
                    // Okay. Primary key in database matches a Storable
                    // alternate key.
                    foundAnyAltKey = true;

                    // Also check that declared primary key is a strict subset
                    // of the alternate key. If not, keep checking alt keys.

                    if (matchesSubKey(pkProps, mainInfo.getPrimaryKey())) {
                        break checkPrimaryKey;
                    }
                }
            }

            if (foundAnyAltKey) {
                errorMessages.add("Actual primary key matches a declared alternate key, "
                        + "but declared primary key must be a strict subset. "
                        + mainInfo.getPrimaryKey().getProperties() + " is not a subset of " + pkProps);
            } else {
                errorMessages.add("Actual primary key does not match any "
                        + "declared primary or alternate key: " + pkProps);
            }
        }

    if (errorMessages.size() > 0) {
        if (primaryKeyCheckDisabled) {
            for (String errorMessage : errorMessages) {
                getLog().warn("Suppressed error: " + errorMessage);
            }
            errorMessages.clear();
        } else {
            throw new MismatchException(mainInfo.getStorableType(), errorMessages);
        }
    }

    // IndexInfo is empty, as querying for it tends to cause a table analyze to run.
    IndexInfo[] indexInfo = new IndexInfo[0];

    if (needsQuotes(tableName)) {
        String quote = meta.getIdentifierQuoteString();
        if (quote != null && !quote.equals(" ")) {
            tableName = quote + tableName + quote;
            qualifiedTableName = quote + qualifiedTableName + quote;
        }
    }

    return new JInfo<S>(mainInfo, catalog, schema, tableName, qualifiedTableName, indexInfo, jProperties);
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@SuppressWarnings("deprecation")
@Test//from   ww  w.  j ava2  s  . c o  m
public void testResultSetWhenClosed() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);

    rs.close();

    try {
        rs.isBeforeFirst();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.isAfterLast();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.isFirst();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.isLast();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.beforeFirst();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.afterLast();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.first();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.last();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.next();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getRow();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getType();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getConcurrency();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.rowUpdated();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.rowDeleted();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.rowInserted();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getStatement();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.wasNull();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getString(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getString("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getShort(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getShort("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(1, null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(1, null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(1, null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getUnicodeStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getUnicodeStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getMetaData();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.setFetchDirection(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFetchDirection();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.setFetchSize(100);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFetchSize();
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getHoldability();
        fail();
    } catch (SQLException ignore) {
    }

    statement.close();
}

From source file:org.apache.hive.jdbc.TestJdbcDriver2.java

/**
 * Validate error on closed resultset//from   w  ww. j a va2s  . c o m
 * @throws SQLException
 */
@Test
public void testPostClose() throws SQLException {
    Statement stmt = con.createStatement();
    ResultSet res = stmt.executeQuery("select * from " + tableName);
    assertNotNull("ResultSet is null", res);
    res.close();
    try {
        res.getInt(1);
        fail("Expected SQLException");
    } catch (SQLException e) {
    }
    try {
        res.getMetaData();
        fail("Expected SQLException");
    } catch (SQLException e) {
    }
    try {
        res.setFetchSize(10);
        fail("Expected SQLException");
    } catch (SQLException e) {
    }
}