performs a SQL UPDTE, INSERT or DELETE statement against RDBMS.
@param sqlStatement the query string.
@param cld ClassDescriptor providing meta-information.
@return int returncode
518821
public int executeUpdateSQL(
        String sqlStatement,
        ClassDescriptor cld,
        ValueContainer[] values1,
        ValueContainer[] values2)
        throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
            logger.debug("executeUpdateSQL: " + sqlStatement);

        int result;
        int index;
        PreparedStatement stmt = null;
        final StatementManagerIF sm = broker.serviceStatementManager();
        try
        {
            stmt = sm.getPreparedStatement(cld, sqlStatement,
                    Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));
            index = sm.bindValues(stmt, values1, 1);
            sm.bindValues(stmt, values2, index);
            result = stmt.executeUpdate();
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the Update SQL query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            ValueContainer[] tmp = addValues(values1, values2);
            throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
        return result;
    }
1185445
private static String stmtAssignSqlParams(PreparedStatement stmt, List<SqlParam> sqlParams) throws SQLException {
		String cursorParam = null;
		if (sqlParams == null)
			return null;

		CallableStatement cstmt = null;
		if (stmt instanceof CallableStatement) {
			cstmt = (CallableStatement) stmt;
		}

		int pos = 0;
		for (SqlParam param : sqlParams) {
			pos++;
			boolean isPositionalParam = (param.code == null); // named vs positional param
			if (param.type == null)
				throw new SQLDataException("Please provide parameter type for param.code='" + param.code + "' pos=" + pos);
			if (isPositionalParam == false && cstmt == null)
				throw new SQLDataException("To use named params, need to use CallableStatement (param.code='" + param.code + "' pos=" + pos + ")");

			switch (param.type) {
				case CURSOR:
					if (cstmt == null)
						throw new SQLDataException("Param type CURSOR is not allowed for preparedStatement");
					cursorParam = param.code;
					if (param.code == null)
						cstmt.registerOutParameter(pos, JetJdbcParamType.CURSOR.oracleId);
					else
						cstmt.registerOutParameter(param.code, JetJdbcParamType.CURSOR.oracleId);
					break;
				case STRING:
					if (isPositionalParam)
						stmt.setString(pos, param.value == null ? null : param.value.toString());
					else
						cstmt.setString(param.code, param.value == null ? null : param.value.toString());
					break;
				case INTEGER: case LONG:
					if (param.value == null) {
						if (isPositionalParam)
							stmt.setNull(pos, Types.BIGINT);
						else
							cstmt.setNull(param.code, Types.BIGINT);
					} else {
						long val = 0;
						if (param.value.getClass().isAssignableFrom(Integer.class)) {
							val = (Integer) param.value;
						} else {
							val = (Long) param.value;
						}
						if (isPositionalParam)
							stmt.setLong(pos, val);
						else
							cstmt.setLong(param.code, val);
					}
					break;
				case TIMESTAMP:
					Date date1 = (Date) param.value;
					if (isPositionalParam)
						stmt.setTimestamp(pos, param.value == null ? null : new Timestamp(date1.getTime()));
					else
						cstmt.setTimestamp(param.code, param.value == null ? null : new Timestamp(date1.getTime()));
					break;
				case DATE:
					Date date2 = (Date) param.value;
					if (isPositionalParam)
						stmt.setDate(pos, param.value == null ? null : new java.sql.Date(date2.getTime()));
					else
						cstmt.setDate(param.code, param.value == null ? null : new java.sql.Date(date2.getTime()));
					break;
				case BLOB:
					if (param.value == null) {
						if (isPositionalParam)
							stmt.setBlob(pos, new ByteArrayInputStream(new byte[0]));
						else
							cstmt.setBlob(param.code, new ByteArrayInputStream(new byte[0]));
					} else {
						byte[] bytes = (byte[]) param.value;
						if (isPositionalParam)
							stmt.setBlob(pos, new ByteArrayInputStream(bytes), (int) bytes.length);
						else
							cstmt.setBlob(param.code, new ByteArrayInputStream(bytes), (int) bytes.length);
					}
					break;
				default:
					throw new IllegalStateException("Data type '" + param.type.toString() + "' is not supported yet");
			}
		}
		return cursorParam;
	}
998863
private String getDataInsertStatement(String table) throws SQLException {

        StringBuilder sql = new StringBuilder();

        ResultSet rs = stmt.executeQuery("SELECT * FROM " + "`" + table + "`;");

        //move to the last row to get max rows returned
        rs.last();
        int rowCount = rs.getRow();

        //there are no records just return empty string
        if(rowCount <= 0) {
            return sql.toString();
        }

        sql.append("\n--").append("\n-- Inserts of ").append(table).append("\n--\n\n");

        //temporarily disable foreign key constraint
        sql.append("\n/*!40000 ALTER TABLE `").append(table).append("` DISABLE KEYS */;\n");

        sql.append("\n--\n")
                .append(MysqlBaseService.SQL_START_PATTERN).append(" table insert : ").append(table)
                .append("\n--\n");

        sql.append("INSERT INTO `").append(table).append("`(");

        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        //generate the column names that are present
        //in the returned result set
        //at this point the insert is INSERT INTO (`col1`, `col2`, ...)
        for(int i = 0; i < columnCount; i++) {
            sql.append("`")
                    .append(metaData.getColumnName( i + 1))
                    .append("`, ");
        }

        //remove the last whitespace and comma
        sql.deleteCharAt(sql.length() - 1).deleteCharAt(sql.length() - 1).append(") VALUES \n");

        //now we're going to build the values for data insertion
        rs.beforeFirst();
        while(rs.next()) {
            sql.append("(");
            for(int i = 0; i < columnCount; i++) {

                int columnType = metaData.getColumnType(i + 1);
                int columnIndex = i + 1;

                //this is the part where the values are processed based on their type
                if(Objects.isNull(rs.getObject(columnIndex))) {
                    sql.append("").append(rs.getObject(columnIndex)).append(", ");
                }
                else if( columnType == Types.INTEGER || columnType == Types.TINYINT || columnType == Types.BIT) {
                    sql.append(rs.getInt(columnIndex)).append(", ");
                }
                else {

                    String val = rs.getString(columnIndex);
                   //escape the single quotes that might be in the value
                    val = val.replace("'", "\\'");

                    sql.append("'").append(val).append("', ");
                }
            }

            //now that we're done with a row
            //let's remove the last whitespace and comma
            sql.deleteCharAt(sql.length() - 1).deleteCharAt(sql.length() - 1);

            //if this is the last row, just append a closing
            //parenthesis otherwise append a closing parenthesis and a comma
            //for the next set of values
            if(rs.isLast()) {
                sql.append(")");
            } else {
                sql.append("),\n");
            }
        }

        //now that we are done processing the entire row
        //let's add the terminator
        sql.append(";");

        sql.append("\n--\n")
                .append(MysqlBaseService.SQL_END_PATTERN).append(" table insert : ").append(table)
                .append("\n--\n");

        //enable FK constraint
        sql.append("\n/*!40000 ALTER TABLE `").append(table).append("` ENABLE KEYS */;\n");

        return sql.toString();
    }
353502
public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) {
		List<T> result = new ArrayList<T>();
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = getconnnection();
			ps = con.prepareStatement(sql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					ps.setObject((i + 1), args[i]);
				}
			}
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			while (rs.next()) {
				T obj = clz.newInstance();
				for (int i = 1; i <= columnCount; i++) {
					String columnName = rsmd.getColumnName(i);
					String methodName = "set" + columnName.substring(0, 1).toUpperCase()
							+ columnName.substring(1, columnName.length());
					Method method[] = clz.getMethods();
					for (Method meth : method) {
						if (methodName.equals(meth.getName())) {
							meth.invoke(obj, rs.getObject(i));
						}
					}
				}
				result.add(obj);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} finally {
			close(rs, ps, con);
		}
		return result;
	}
1143862
@Override
  public OperationHandle executeStatement(SessionHandle sessionHandle, String statement,
      Map<String, String> confOverlay) throws HiveSQLException {
    return cliService.executeStatement(sessionHandle, statement, confOverlay);
  }
212659
public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeQuery: " + query);
        }
        /*
		 * MBAIRD: we should create a scrollable resultset if the start at
		 * index or end at index is set
		 */
        boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));
        /*
		 * OR if the prefetching of relationships is being used.
		 */
        if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())
        {
            scrollable = true;
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try
        {
            final int queryFetchSize = query.getFetchSize();
            final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());
            stmt = sm.getPreparedStatement(cld, sql.getStatement() ,
                    scrollable, queryFetchSize, isStoredProcedure);
            if (isStoredProcedure)
            {
                // Query implemented as a stored procedure, which must return a result set.
                // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
                getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
                sm.bindStatement(stmt, query, cld, 2);

                if (logger.isDebugEnabled())
                    logger.debug("executeQuery: " + stmt);

                stmt.execute();
                rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
            }
            else
            {
                sm.bindStatement(stmt, query, cld, 1);

                if (logger.isDebugEnabled())
                    logger.debug("executeQuery: " + stmt);

                rs = stmt.executeQuery();
            }

            return new ResultSetAndStatement(sm, stmt, rs, sql);
        }
        catch (PersistenceBrokerException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            logger.error("PersistenceBrokerException during the execution of the query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);
        }
    }
818760
private static Query buildQuery(ClassDescriptor cld)
    {
        FieldDescriptor[] pkFields = cld.getPkFields();
        Criteria crit = new Criteria();

        for(int i = 0; i < pkFields.length; i++)
        {
            crit.addEqualTo(pkFields[i].getAttributeName(), null);
        }
        return new QueryByCriteria(cld.getClassOfObject(), crit);
    }
62552
public static long getMaxIdForClass(
            PersistenceBroker brokerForClass, ClassDescriptor cldForOriginalOrExtent, FieldDescriptor original)
            throws PersistenceBrokerException
    {
        FieldDescriptor field = null;
        if (!original.getClassDescriptor().equals(cldForOriginalOrExtent))
        {
            // check if extent match not the same table
            if (!original.getClassDescriptor().getFullTableName().equals(
                    cldForOriginalOrExtent.getFullTableName()))
            {
                // we have to look for id's in extent class table
                field = cldForOriginalOrExtent.getFieldDescriptorByName(original.getAttributeName());
            }
        }
        else
        {
            field = original;
        }
        if (field == null)
        {
            // if null skip this call
            return 0;
        }

        String column = field.getColumnName();
        long result = 0;
        ResultSet rs = null;
        Statement stmt = null;
        StatementManagerIF sm = brokerForClass.serviceStatementManager();
        String table = cldForOriginalOrExtent.getFullTableName();
        // String column = cld.getFieldDescriptorByName(fieldName).getColumnName();
        String sql = SM_SELECT_MAX + column + SM_FROM + table;
        try
        {
            //lookup max id for the current class
            stmt = sm.getGenericStatement(cldForOriginalOrExtent, Query.NOT_SCROLLABLE);
            rs = stmt.executeQuery(sql);
            rs.next();
            result = rs.getLong(1);
        }
        catch (Exception e)
        {
            log.warn("Cannot lookup max value from table " + table + " for column " + column +
                    ", PB was " + brokerForClass + ", using jdbc-descriptor " +
                    brokerForClass.serviceConnectionManager().getConnectionDescriptor(), e);
        }
        finally
        {
            try
            {
                sm.closeResources(stmt, rs);
            }
            catch (Exception ignore)
            {
                // ignore it
           }
        }
        return result;
    }
510122
private void executeStatement(String statement) throws SQLException {
		logger.entering(CLASSNAME, "executeStatement", statement);

		Connection conn = getConnection();
		PreparedStatement ps = null;

		ps = conn.prepareStatement(statement);
		ps.executeUpdate();

		cleanupConnection(conn, ps);
		logger.exiting(CLASSNAME, "executeStatement");
	}
1023843
private void storeToDb(Object obj, ClassDescriptor cld, Identity oid, boolean insert, boolean ignoreReferences)
    {
        // 1. link and store 1:1 references
        storeReferences(obj, cld, insert, ignoreReferences);

        Object[] pkValues = oid.getPrimaryKeyValues();
        if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))
        {
            // BRJ: fk values may be part of pk, but the are not known during
            // creation of Identity. so we have to get them here
            pkValues = serviceBrokerHelper().getKeyValues(cld, obj);
            if (!serviceBrokerHelper().assertValidPksForStore(cld.getPkFields(), pkValues))
            {
                String append = insert ? " on insert" : " on update" ;
                throw new PersistenceBrokerException("assertValidPkFields failed for Object of type: " + cld.getClassNameOfObject() + append);
            }
        }

        // get super class cld then store it with the object
        /*
        now for multiple table inheritance
        1. store super classes, topmost parent first
        2. go down through heirarchy until current class
        3. todo: store to full extent?

// arminw: TODO: The extend-attribute feature dosn't work, should we remove this stuff?
        This if-clause will go up the inheritance heirarchy to store all the super classes.
        The id for the top most super class will be the id for all the subclasses too
         */
        if(cld.getSuperClass() != null)
        {

            ClassDescriptor superCld = getDescriptorRepository().getDescriptorFor(cld.getSuperClass());
            storeToDb(obj, superCld, oid, insert);
            // arminw: why this?? I comment out this section
            // storeCollections(obj, cld.getCollectionDescriptors(), insert);
        }

        // 2. store primitive typed attributes (Or is THIS step 3 ?)
        // if obj not present in db use INSERT
        if (insert)
        {
            dbAccess.executeInsert(cld, obj);
            if(oid.isTransient())
            {
                // Create a new Identity based on the current set of primary key values.
                oid = serviceIdentity().buildIdentity(cld, obj);
            }
        }
        // else use UPDATE
        else
        {
            try
            {
                dbAccess.executeUpdate(cld, obj);
            }
            catch(OptimisticLockException e)
            {
                // ensure that the outdated object be removed from cache
                objectCache.remove(oid);
                throw e;
            }
        }
        // cache object for symmetry with getObjectByXXX()
        // Add the object to the cache.
        objectCache.doInternalCache(oid, obj, ObjectCacheInternal.TYPE_WRITE);
        // 3. store 1:n and m:n associations
        if(!ignoreReferences) storeCollections(obj, cld, insert);
    }
1178267
public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
        ResultSet rs = null;
        int id = 0;
        try {
            rs = statement.getGeneratedKeys();
            if (!rs.next()) {
                throw new DatabaseException("Unable to get primary key for inserted row");
            }
            id = rs.getInt(1);
        } catch (SQLException ex) {
            throw new DatabaseException("Unable to get primary key for inserted row");
        } finally {
            closeResultSet(rs);
        }
        return id;
    }
521411
private String toSQLClause(ExistsCriteria c, ClassDescriptor cld)
    {
        StringBuffer buf = new StringBuffer();
        Query subQuery = (Query) c.getValue();

        buf.append(c.getClause());
        buf.append(" (");

        // If it's a proper call
        if (cld != null)
        {
            buf.append(
                getPreparedSelectStatement(
                    subQuery,
                    cld.getRepository().getDescriptorFor(subQuery.getSearchClass())));

            // Otherwise it's most likely a call to toString()
        }
        else
        {
            buf.append(subQuery);
        }

        buf.append(")");
        return buf.toString();
    }
683704
public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException
    {
        try
        {
            return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());
        }
        catch (SQLException e)
        {
            throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
        }
        catch (LookupException e)
        {
            throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
        }
    }
314652
private String toSQLClause(SelectionCriteria c, ClassDescriptor cld)
    {
        String colName = toSqlClause(c.getAttribute(), cld);
        return colName + c.getClause() + " ? ";
    }
1276179
public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException
    {
        try
        {
            return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection());
        }
        catch (SQLException e)
        {
            throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
        }
        catch (LookupException e)
        {
            throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
        }
    }
886275
public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeInsert: " + obj);
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        PreparedStatement stmt = null;
        try
        {
            stmt = sm.getInsertStatement(cld);
            if (stmt == null)
            {
                logger.error("getInsertStatement returned a null statement");
                throw new PersistenceBrokerException("getInsertStatement returned a null statement");
            }
            // before bind values perform autoincrement sequence columns
            assignAutoincrementSequences(cld, obj);
            sm.bindInsert(stmt, cld, obj);
            if (logger.isDebugEnabled())
                logger.debug("executeInsert: " + stmt);
            stmt.executeUpdate();
            // after insert read and assign identity columns
            assignAutoincrementIdentityColumns(cld, obj);

            // Harvest any return values.
            harvestReturnValues(cld.getInsertProcedure(), obj, stmt);
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the insert: " + e.getMessage(), e);
            throw e;
        }
        catch(SequenceManagerException e)
        {
            throw new PersistenceBrokerException("Error while try to assign identity value", e);
        }
        catch (SQLException e)
        {
            final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();
            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
    }
320369
private static void setBlob(PreparedStatement ps, int i, Object o, Class<?> cls)
            throws SQLException {
        final InputStream is;
        if (o instanceof byte[]) {
            is = new ByteArrayInputStream((byte[]) o);
        }