Example usage for java.sql Connection hashCode

List of usage examples for java.sql Connection hashCode

Introduction

In this page you can find the example usage for java.sql Connection hashCode.

Prototype

@HotSpotIntrinsicCandidate
public native int hashCode();

Source Link

Document

Returns a hash code value for the object.

Usage

From source file:com.vertica.hadoop.VerticaOutputFormat.java

/**
  * Optionally called at the end of a job to optimize any newly created and
  * loaded tables. Useful for new tables with more than 100k records.
  * /*from w w  w .  j a v  a2 s.c o m*/
  * @param conf
  * @throws Exception
  */
public static void optimize(Configuration conf) throws Exception {
    VerticaConfiguration vtconfig = new VerticaConfiguration(conf);
    Connection conn = vtconfig.getConnection(true);

    // TODO: consider more tables and skip tables with non-temp projections 
    Relation vTable = new Relation(vtconfig.getOutputTableName());
    Statement stmt = conn.createStatement();
    ResultSet rs = null;
    HashSet<String> tablesWithTemp = new HashSet<String>();

    //for now just add the single output table
    tablesWithTemp.add(vTable.getQualifiedName().toString());

    // map from table name to set of projection names
    HashMap<String, Collection<String>> tableProj = new HashMap<String, Collection<String>>();
    rs = stmt.executeQuery("select projection_schema, anchor_table_name, projection_name from projections;");
    while (rs.next()) {
        String ptable = rs.getString(1) + "." + rs.getString(2);
        if (!tableProj.containsKey(ptable)) {
            tableProj.put(ptable, new HashSet<String>());
        }

        tableProj.get(ptable).add(rs.getString(3));
    }

    for (String table : tablesWithTemp) {
        if (!tableProj.containsKey(table)) {
            throw new RuntimeException("Cannot optimize table with no data: " + table);
        }
    }

    String designName = (new Integer(conn.hashCode())).toString();
    stmt.execute("select dbd_create_workspace('" + designName + "')");
    stmt.execute("select dbd_create_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_design_tables('" + designName + "', '" + vTable.getQualifiedName().toString()
            + "')");
    stmt.execute("select dbd_populate_design('" + designName + "', '" + designName + "')");

    //Execute
    stmt.execute("select dbd_create_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_deployment_design('" + designName + "', '" + designName + "', '" + designName
            + "')");
    stmt.execute("select dbd_add_deployment_drop('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_execute_deployment('" + designName + "', '" + designName + "')");

    //Cleanup
    stmt.execute("select dbd_drop_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_remove_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_workspace('" + designName + "')");
}

From source file:com.vertica.hivestoragehandler.VerticaOutputFormat.java

/**
  * Optionally called at the end of a job to optimize any newly created and
  * loaded tables. Useful for new tables with more than 100k records.
  * /*  w  w  w . j a va  2 s  .c  om*/
  * @param conf
  * @throws Exception
  */
public static void optimize(Configuration conf) throws Exception {
    VerticaConfiguration vtconfig = new VerticaConfiguration(conf);
    Connection conn = vtconfig.getConnection(true);

    // TODO: consider more tables and skip tables with non-temp projections 
    VerticaRelation vTable = new VerticaRelation(vtconfig.getOutputTableName());
    Statement stmt = conn.createStatement();
    ResultSet rs = null;
    HashSet<String> tablesWithTemp = new HashSet<String>();

    //for now just add the single output table
    tablesWithTemp.add(vTable.getQualifiedName().toString());

    // map from table name to set of projection names
    HashMap<String, Collection<String>> tableProj = new HashMap<String, Collection<String>>();
    rs = stmt.executeQuery("select projection_schema, anchor_table_name, projection_name from projections;");
    while (rs.next()) {
        String ptable = rs.getString(1) + "." + rs.getString(2);
        if (!tableProj.containsKey(ptable)) {
            tableProj.put(ptable, new HashSet<String>());
        }

        tableProj.get(ptable).add(rs.getString(3));
    }

    for (String table : tablesWithTemp) {
        if (!tableProj.containsKey(table)) {
            throw new RuntimeException("Cannot optimize table with no data: " + table);
        }
    }

    String designName = (new Integer(conn.hashCode())).toString();
    stmt.execute("select dbd_create_workspace('" + designName + "')");
    stmt.execute("select dbd_create_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_design_tables('" + designName + "', '" + vTable.getQualifiedName().toString()
            + "')");
    stmt.execute("select dbd_populate_design('" + designName + "', '" + designName + "')");

    //Execute
    stmt.execute("select dbd_create_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_deployment_design('" + designName + "', '" + designName + "', '" + designName
            + "')");
    stmt.execute("select dbd_add_deployment_drop('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_execute_deployment('" + designName + "', '" + designName + "')");

    //Cleanup
    stmt.execute("select dbd_drop_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_remove_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_workspace('" + designName + "')");
}

From source file:com.draagon.meta.manager.db.ObjectManagerDB.java

public int execute(ObjectConnection c, String query, Collection<?> arguments) throws MetaException {
    Connection conn = (Connection) c.getDatastoreConnection();

    // Check for a valid transaction if enforced
    checkTransaction(conn, true);//  w  w  w  .j a  v a  2  s  .co m

    try {
        PreparedStatement s = getPreparedStatement(conn, query, arguments);

        try {
            if (log.isDebugEnabled()) {
                log.debug("SQL (" + conn.hashCode() + ") - execute: [" + query + " " + arguments + "]");
            }

            return s.executeUpdate();
        } finally {
            s.close();
        }
    } catch (SQLException e) {
        log.error("Unable to execute object query [" + query + "]: " + e.getMessage());
        throw new MetaException("Unable to execute object query [" + query + "]", e);
    }
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Gets the delete statement for a specific id
 *//*from  w ww  .  ja  v a2 s  .co  m*/
protected PreparedStatement getDeleteStatement(Connection c, MetaObject mc, ObjectMappingDB omdb,
        Collection<MetaField> keys, Object obj) throws SQLException, MetaException {

    // Get the components of the SELECT query
    String tableStr = getProperName(omdb.getDBDef().getNameDef());

    String whereStr = null;//getWhereStringForKeys(keys);

    // Construct the SELECT query
    String query = "DELETE FROM " + tableStr + " WHERE " + whereStr;

    PreparedStatement s = c.prepareStatement(query);

    // ystem.out.println( ">>> QUERY: " + query );

    StringBuilder valStr = new StringBuilder(" ");

    try {
        // Set the key values
        int j = 1;
        for (Iterator<MetaField> i = keys.iterator(); i.hasNext(); j++) {
            MetaField f = i.next();
            setStatementValue(s, f, j, f.getObject(obj));

            valStr.append("(" + f.getString(obj) + ")");
        }

        if (log.isDebugEnabled()) {
            log.debug("SQL (" + c.hashCode() + ") - getDeleteStatement: [" + query + valStr + "]");
        }

        // Return the prepared statement
        return s;
    } catch (SQLException e) {
        s.close();
        throw e;
    }
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Gets the id clause for a unique transaction
 *///from   w w w. jav a 2s.  c o  m
protected PreparedStatement getDeleteStatementWhere(Connection c, MetaObject mc, ObjectMappingDB omdb,
        Expression where) throws SQLException, MetaException {

    // Get the components of the SELECT query
    String tableStr = getProperName(omdb.getDBDef().getNameDef());

    // Construct the SELECT query
    StringBuilder query = new StringBuilder("DELETE FROM ");
    query.append(tableStr); //.append( " A");

    ArrayList<SQLArg> args = new ArrayList<SQLArg>();

    if (where != null) {
        query.append(" WHERE ");
        query.append(getExpressionString(mc, omdb, where, args, null));
    }

    PreparedStatement s = c.prepareStatement(query.toString());

    int index = 1;

    StringBuilder valStr = new StringBuilder(" ");

    if (where != null) {
        for (SQLArg arg : args) {

            MetaField f = arg.getMetaField();
            Object value = arg.getValue();

            if (index > 1) {
                valStr.append(", ");
            }

            setStatementValue(s, f, index++, value);

            valStr.append("(" + value + ")");
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("SQL (" + c.hashCode() + ") - getDeleteStatementWhere: [ " + query.toString()
                + valStr.toString() + " ]");
    }

    // ystem.out.println( ">>> QUERY: " + query.toString() + " " +
    // valStr.toString() );

    return s;
}

From source file:com.draagon.meta.manager.db.ObjectManagerDB.java

/**
 * Executes the specified query and maps it to the given object.
 *
 * String oql = "[" + Product.CLASSNAME + "]" + " SELECT {P.*}, {M.name} AS
 * manuName" + " FROM [" + Product.CLASSNAME + "=P]," + " [" +
 * Manufacturer.CLASSNAME + "=M]" + " WHERE {M.id}={P.manuId} AND {M.id} >
 * ?";/*from  w ww.ja v a 2s.  c  o m*/
 *
 * String oql = "[{min:int,max:int,num:int}]" + " SELECT MIN({extra2}) AS
 * min, MAX({extra2}) AS max, COUNT(1) AS num" + " FROM [" +
 * Product.CLASSNAME + "]";
 */
public Collection<?> executeQuery(ObjectConnection c, String query, Collection<?> arguments)
        throws MetaException {
    Connection conn = (Connection) c.getDatastoreConnection();

    // Check for a valid transaction if enforced
    checkTransaction(conn, false);

    try {
        MetaObject resultClass = null;

        query = query.trim();
        if (query.startsWith("[{")) {
            int i = query.indexOf("}]");
            if (i <= 0) {
                throw new MetaException("OQL does not contain a closing '}]': [" + query + "]");
            }

            String classTemplate = query.substring(2, i).trim();
            query = query.substring(i + 2).trim();
            String templateClassname = "draagon::meta::manager::db::OQL" + classTemplate.hashCode();

            // Get the result class, try it from the cache first
            resultClass = templateCache.get(templateClassname);
            if (resultClass == null) {
                resultClass = ValueMetaObject.createFromTemplate(templateClassname, classTemplate);
                templateCache.put(templateClassname, resultClass);
            }
        } else if (query.startsWith("[")) {
            int i = query.indexOf("]");
            if (i <= 0) {
                throw new MetaException("OQL does not contain a closing ']': [" + query + "]");
            }

            String className = query.substring(1, i).trim();
            query = query.substring(i + 1).trim();

            resultClass = MetaObject.forName(className);
        } else {
            throw new MetaException(
                    "OQL does not contain a result set definition using []'s or {}'s: [" + query + "]");
        }

        PreparedStatement s = getPreparedStatement(conn, query, arguments);

        try {
            if (log.isDebugEnabled()) {
                log.debug("SQL (" + conn.hashCode() + ") - executeQuery: [" + query + " " + arguments + "]");
            }

            ResultSet rs = s.executeQuery();

            LinkedList<Object> data = new LinkedList<Object>();
            try {
                ObjectMappingDB mapping = (ObjectMappingDB) getReadMapping(resultClass);

                while (rs.next()) {
                    Object o = resultClass.newInstance();

                    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                        String col = rs.getMetaData().getColumnName(i);

                        MetaField mf = getFieldForColumn(resultClass, mapping, col);

                        if (mf != null) {
                            parseField(o, mf, rs, i);
                        }
                    }

                    data.add(o);
                }

                return data;
            } finally {
                rs.close();
            }
        } finally {
            s.close();
        }
    } catch (SQLException e) {
        log.error("Unable to execute object query [" + query + " (" + arguments + ")]: " + e.getMessage());
        throw new MetaException(
                "Unable to execute object query [" + query + " (" + arguments + ")]: " + e.getMessage(), e);
    }
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Gets the id clause for a unique transaction
 *//*from w w  w  .j  a v  a 2  s  .co  m*/
protected PreparedStatement getInsertStatement(Connection c, MetaObject mc, ObjectMappingDB omdb, Object o)
        throws SQLException, MetaException {

    Collection<MetaField> fields = omdb.getMetaFields();

    // Get the components of the SELECT query
    String tableStr = getProperName(omdb.getDBDef().getNameDef());

    String fieldStr = getFieldString(omdb, fields, false, null);
    String valueStr = getValueStringForFields(omdb, fields);

    // Construct the SELECT query
    String query = "INSERT INTO " + tableStr + " (" + fieldStr + ")" + " VALUES (" + valueStr + ")";

    PreparedStatement s = null;

    // Tack on any needed queries to get the keys
    // if ( getDatabaseDriver().getAutoType() == AUTO_DURING )
    // {
    // String add = getDatabaseDriver().getInsertAppendString( mc );
    // if ( add != null && add.length() > 0 ) query += add;

    // s = c.prepareCall( query );
    // }
    // else
    // {
    s = c.prepareStatement(query);
    // }

    StringBuilder valStr = new StringBuilder(" ");

    try {
        int j = 1;
        for (MetaField f : fields) {

            ColumnDef colDef = (ColumnDef) omdb.getArgDef(f);

            // Do not use the field if it's an auto id that is set after
            // after creation/update -- only valid on some drivers (MSSQL)
            //if ( colDef.isAutoIncrementor() )
            //   continue;

            // Set the statement id value
            if (colDef.getAutoType() == ColumnDef.AUTO_ID) {
                f.setString(o, getNextAutoId(c, colDef));
            } else if (colDef.getAutoType() == ColumnDef.AUTO_LAST_ID) {
                continue;
            }
            // Set the create date (if auto)
            //else if ( colDef.getAutoType() == ColumnDef.AUTO_DATE_CREATE ) {
            //   f.setDate( o, new Date() );
            //}

            setStatementValue(s, f, j, f.getObject(o));

            valStr.append("(" + f.getString(o) + ")");

            j++;
        }

        if (log.isDebugEnabled()) {
            log.debug("SQL (" + c.hashCode() + ") - getInsertStatement: [" + query + valStr.toString() + "]");
        }

        // ystem.out.println( ">>> QUERY: [" + query + "] [" +
        // valStr.toString() + "]" );

        // Return the prepared statement
        return s;
    } catch (SQLException e) {
        s.close();
        throw e;
    }
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Gets the id clause for a unique transaction
 *//*www .  ja v  a2 s  .  co m*/
protected PreparedStatement getCountStatementWhere(Connection c, MetaObject mc, ObjectMappingDB omdb,
        Expression where) throws SQLException, MetaException {

    // Construct the SELECT query
    StringBuilder query = new StringBuilder();
    query.append("SELECT COUNT(*) FROM ");

    char prefix = 'A';
    BaseTableDef base = (BaseTableDef) omdb.getDBDef();
    while (base != null) {
        // Get the components of the SELECT query
        String tableStr = getProperName(base.getNameDef());
        query.append(tableStr).append(' ').append(prefix);

        if (base instanceof TableDef) {

            TableDef table = (TableDef) base;
            base = null;

            InheritenceDef idef = table.getInheritence();
            if (idef != null) {
                base = idef.getRefTable();
                prefix++;

                query.append(" LEFT JOIN ");
                tableStr = getProperName(base.getNameDef());
                query.append(tableStr).append(' ').append(prefix);
                query.append(" ON ");
                query.append(prefix--).append(idef.getColumnName()).append("=").append(prefix)
                        .append(idef.getRefColumn().getName());
            }
        } else {
            break;
        }
    }

    ArrayList<SQLArg> args = new ArrayList<SQLArg>();

    if (where != null) {
        query.append(" WHERE ").append(getExpressionString(mc, omdb, where, args, "A"));
    }

    PreparedStatement s = c.prepareStatement(query.toString());

    int index = 1;

    StringBuilder valStr = null;
    if (log.isDebugEnabled()) {
        valStr = new StringBuilder(" ");
    }

    if (where != null) {
        for (SQLArg arg : args) {

            MetaField f = arg.getMetaField();
            Object value = arg.getValue();

            if (log.isDebugEnabled() && index > 1) {
                valStr.append(", ");
            }

            setStatementValue(s, f, index++, value);

            if (log.isDebugEnabled()) {
                valStr.append("(" + value + ")");
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("SQL (" + c.hashCode() + ") - getCountStatementWhere: [ " + query.toString()
                + valStr.toString() + " ]");
    }

    // ystem.out.println( ">>> QUERY: " + query.toString() + " " +
    // valStr.toString() );

    return s;
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Gets the update statement for a unique object
 *//*  ww  w  .java2 s  .c o  m*/
protected PreparedStatement getUpdateStatement(Connection c, ObjectMappingDB omdb, Collection<MetaField> fields,
        MetaObject mc, Object o, Expression exp) throws SQLException {

    // WARNING: The query construction should be cached for each MetaClass &
    // field combo

    // validateMetaClass( c, mc );

    // String id = pmc.getId( o );
    //Collection<MetaField> keys = getPrimaryKeys(mc);

    // Get the components of the SELECT query
    String tableStr = getProperName(omdb.getDBDef().getNameDef());

    ArrayList<SQLArg> args = new ArrayList<SQLArg>();

    String setStr = getSetString(omdb, fields);
    String whereStr = getExpressionString(mc, omdb, exp, args, null);

    // Construct the SELECT query
    String query = "UPDATE " + tableStr + " SET " + setStr + " WHERE " + whereStr;

    // Used to prevent dirty writes
    //if (dirtyField != null) {
    //   query += " AND ( " + dirtyField.getAttribute(COL_REF) + "=? )";
    //}

    PreparedStatement s = c.prepareStatement(query);

    // ystem.out.println( ">>> QUERY: " + query );

    StringBuilder valStr = new StringBuilder(" ");

    try {
        // Set the update values
        int j = 1;
        for (MetaField f : fields) {

            ColumnDef colDef = (ColumnDef) omdb.getArgDef(f);

            if (colDef.isAutoIncrementor()) {
                continue;
            }

            // Set the create date (if auto)
            //if ( colDef.getAutoType() == ColumnDef.AUTO_DATE_CREATE ||
            //      colDef.getAutoType() == ColumnDef.AUTO_DATE_UPDATE ) {
            //   f.setDate( o, new Date() );
            //}

            setStatementValue(s, f, j++, f.getObject(o));

            valStr.append("(" + f.getString(o) + ")");
        }

        // Set the WHERE clause arguments
        for (SQLArg arg : args) {

            MetaField f = arg.getMetaField();
            Object value = arg.getValue();

            if (j > 1) {
                valStr.append(", ");
            }

            setStatementValue(s, f, j++, value);

            // If we're logging, then get the values to log
            if (log.isDebugEnabled()) {

                String v = null;
                if (value != null && value instanceof Date) {
                    v = "" + ((Date) value).getTime();
                } else {
                    v = "" + value;
                }
                valStr.append("(" + v + ")");
            }
        }

        // Set the key values - replaced by WHERE clause
        //for (MetaField f : keys) {
        //   setStatementValue(s, f, j++, f.getObject(o));
        //   valStr.append("{" + f.getString(o) + "}");
        //}

        // Used to prevent dirty writes
        //if (dirtyField != null)
        //   setStatementValue(s, dirtyField, j, dirtyFieldValue);

        if (log.isDebugEnabled()) {
            log.debug("SQL (" + c.hashCode() + ") - getUpdateStatement: [" + query + valStr + "]");
        }

        // Return the prepared statement
        return s;
    } catch (SQLException e) {
        s.close();
        throw e;
    }
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Gets the id clause for a unique transaction
 *///from  w w  w  .  j  a  v  a2s.  co m
protected PreparedStatement getSelectStatementWhere(Connection c, MetaObject mc, ObjectMappingDB omdb,
        Collection<MetaField> fields, QueryOptions options) throws SQLException, MetaException {

    Expression where = options.getExpression();
    SortOrder order = options.getSortOrder();

    // Construct the SELECT query
    StringBuilder query = new StringBuilder();
    query.append("SELECT ");
    if (options.isDistinct()) {
        query.append("DISTINCT ");
    }
    if (options.getRange() != null) {
        // TODO: Make this a little smarter for christ's sake!
        // Recommendation: Have the driver form the final SELECT call, then
        // it can insert the limit where needed
        //if (getDatabaseDriver() instanceof MSSQLDriver) {
        //   query.append("TOP ").append(options.getRange().getEnd())
        //         .append(' ');
        //}
    }

    String fieldStr = getFieldString(omdb, fields, "A");

    query.append(fieldStr);

    query.append(" FROM ");

    char prefix = 'A';
    BaseTableDef base = (BaseTableDef) omdb.getDBDef();
    while (base != null) {
        // Get the components of the SELECT query
        String tableStr = getProperName(base.getNameDef());
        query.append(tableStr).append(' ').append(prefix);

        if (base instanceof TableDef) {

            TableDef table = (TableDef) base;
            base = null;

            InheritenceDef idef = table.getInheritence();
            if (idef != null) {
                base = idef.getRefTable();
                prefix++;

                query.append(" LEFT JOIN ");
                tableStr = getProperName(base.getNameDef());
                query.append(tableStr).append(' ').append(prefix);
                query.append(" ON ");
                query.append(prefix--).append(idef.getColumnName()).append("=").append(prefix)
                        .append(idef.getRefColumn().getName());
            }
        } else {
            break;
        }
    }

    ArrayList<SQLArg> args = new ArrayList<SQLArg>();

    if (where != null) {
        query.append(" WHERE ").append(getExpressionString(mc, omdb, where, args, "A"));
    }

    if (order != null) {
        query.append(" ORDER BY ").append(getOrderString(mc, omdb, order));
    }

    if (options.withLock()) {
        query.append(" ").append(getLockString());
    }

    // Add on the range
    Range range = options.getRange();
    if (supportsRangeInQuery() && options.getRange() != null && range.getStart() > 0 && range.getEnd() > 0) {

        if (range.getStart() > range.getEnd()) {
            throw new IllegalArgumentException("The range end (" + range.getEnd()
                    + ") cannot be greater than the start value (" + range.getStart() + ")");
        }

        query.append(" ").append(getRangeString(range));
    }

    PreparedStatement s = c.prepareStatement(query.toString());

    int index = 1;

    StringBuilder valStr = null;
    if (log.isDebugEnabled()) {
        valStr = new StringBuilder(" ");
    }

    if (where != null) {
        for (SQLArg arg : args) {

            MetaField f = arg.getMetaField();
            Object value = arg.getValue();

            if (log.isDebugEnabled() && index > 1) {
                valStr.append(", ");
            }

            setStatementValue(s, f, index++, value);

            if (log.isDebugEnabled()) {
                valStr.append("(" + value + ")");
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("SQL (" + c.hashCode() + ") - getSelectStatementWhere: [ " + query.toString()
                + valStr.toString() + " ]");
    }

    // ystem.out.println( ">>> QUERY: " + query.toString() + " " +
    // valStr.toString() );

    return s;
}