/*
(non-Javadoc)

@see com.stratio.deep.commons.querybuilder.QueryBuilder#prepareBatchQuery()
501809
@Override
    public String prepareBatchQuery(List<String> statements) {

        StringBuilder sb = new StringBuilder("BEGIN BATCH \n");

        for (String statement : statements) {
            sb.append(statement).append("\n");
        }

        sb.append(" APPLY BATCH;");

        return sb.toString();
    }
878501
@Override
    public String prepareQuery(Cells keys, Cells values) {

        StringBuilder sb = new StringBuilder("UPDATE ").append(quote(getCatalogName())).append(".")
                .append(quote(getTableName()))
                .append(" SET ");

        boolean isFirst = true;
        StringBuilder keyClause = new StringBuilder(" WHERE ");

        for (Cell cell : keys.getCells()) {
            if (!isFirst) {
                keyClause.append(" AND ");
            } else {
                isFirst = false;
            }
            keyClause.append(String.format("%s = ?", quote(cell.getCellName())));
        }

        isFirst = true;

        for (Cell cell : values.getCells()) {
            if (!isFirst) {
                sb.append(", ");
            } else {
                isFirst = false;
            }
            sb.append(String.format("%s = ?", quote(cell.getCellName())));

        }

        sb.append(keyClause).append(";");

        return sb.toString();
    }
754278
function(callback){

    output("Initializing queries...");

    if(program.keyspace){
        batchQueries.unshift("USE " + program.keyspace + ";");
    }

    if(batchQueries && batchQueries.length > 0){
        output("Running queries...");
        executeQuery(batchQueries.shift(), callback);
    }else{
        callback("No queries to run.", null);
    }
}
602728
private void prepareQuery()
        throws EFapsException
    {
        for (final QueryBuilder queryBldr : this.attrQueryBldrs.values()) {
            final AttributeQuery attrQuery = queryBldr.getAttributeQuery();
            this.addWhereAttrInQuery(queryBldr.getLinkAttributeName(), attrQuery);
        }

        if (!this.types.isEmpty()) {
            // force the include
            this.query.setIncludeChildTypes(true);
            final Type baseType = Type.get(this.typeUUID);
            final QEqual eqPart = new QEqual(new QAttribute(baseType.getTypeAttribute()));

            for (final UUID type : this.types) {
                eqPart.addValue(new QNumberValue(Type.get(type).getId()));
            }
            this.compares.add(eqPart);
        }

        if (!this.compares.isEmpty()) {
            final QAnd and = this.or ? new QOr() : new QAnd();
            for (final AbstractQAttrCompare compare : this.compares) {
                and.addPart(compare);
            }
            this.query.setWhere(new QWhereSection(and));
        }
        if (!this.orders.isEmpty()) {
            final QOrderBySection orderBy = new QOrderBySection(
                            this.orders.toArray(new AbstractQPart[this.orders.size()]));
            this.query.setOrderBy(orderBy);
        }
        if (this.limit > 0) {
            this.query.setLimit(this.limit);
        }
    }
1368057
public static void updateBatch(String sql, Object[][] arg) {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < arg.length; i++) {
                for (int j = 0; j < arg[i].length; j++) {
                    ps.setObject(j + 1, arg[i][j]);
                }
                ps.addBatch();
            }
            ps.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        JDBCUtils.release(ps, connection);
    }
437605
protected PreparedStatement statement(Connection connection, String query)
            throws SQLException {
        return connection.prepareStatement(query);
    }
427443
protected void writeBatchEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
        sb.append("\"batch\":");
        sb.append(execInfo.isBatch() ? "true" : "false");
        sb.append(", ");
    }
1003935
@Override
    public int[] executeBatch() throws SQLException
    {
        checkClosed();
        closeCurrentResult();
        if (batch == null || batch.size() == 0) {
            return new int[0];
        }

        int[] updateCounts = new int[batch.size()];
        // keep a running total of update counts
        int runningUpdateCount = 0;

        int i = 0;
        try {
            for (; i < batch.size(); i++) {

                setCurrentResult(
                        null,
                        (int) batch.get(i).execute(
                                sourceConnection.NativeConnection,
                                this.m_timeout,
                                sourceConnection.queryTimeOutUnit)[0].fetchRow(
                                0).getLong(0));
                updateCounts[i] = this.lastUpdateCount;
                runningUpdateCount += this.lastUpdateCount;
            }
        } catch (SQLException x) {
            updateCounts[i] = EXECUTE_FAILED;
            throw new BatchUpdateException(Arrays.copyOf(updateCounts, i + 1),
                    x);
        } finally {
            clearBatch();
        }
        // replace the update count from the last statement with the update count
        // from the last batch.
        this.lastUpdateCount = runningUpdateCount;

        return updateCounts;
    }
518701
public void executeBatch() throws OJBBatchUpdateException
    {
        if (batchCon != null)
        {
            try
            {
                batchCon.executeBatch();
            }
            catch (Throwable th)
            {
                throw new OJBBatchUpdateException(th);
            }
        }
    }
1361190
PreparedStatement getPreparedStatement(final SqlContext sqlContext) throws SQLException {
		Connection conn = null;
		if (sqlContext.getDbAlias() != null) {
			conn = getConnection(sqlContext.getDbAlias());
		} else {
			conn = getConnection();
		}

		if (conn == null) {
			throw new IllegalArgumentException(sqlContext.getDbAlias());
		}

		PreparedStatement stmt = null;
		switch (sqlContext.getSqlKind()) {
		case INSERT:
		case BULK_INSERT:
		case BATCH_INSERT:
			if (sqlContext.hasGeneratedKeyColumns()) {
				stmt = conn.prepareStatement(sqlContext.getExecutableSql(), sqlContext.getGeneratedKeyColumns());
			} else {
				stmt = conn.prepareStatement(sqlContext.getExecutableSql(), Statement.RETURN_GENERATED_KEYS);
			}
			break;
		case SELECT:
			stmt = conn.prepareStatement(sqlContext.getExecutableSql(),
					sqlContext.getResultSetType(),
					sqlContext.getResultSetConcurrency());
			break;
		default:
			stmt = conn.prepareStatement(sqlContext.getExecutableSql());
			break;
		}
		return sqlFilterManager.doPreparedStatement(sqlContext, stmt);
	}
1070205
@Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
1004721
@Override
    public int executeBatch()
    {
        Map<HTableInterface, List<HBaseDataWrapper>> data = new HashMap<HTableInterface, List<HBaseDataWrapper>>();

        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    node.handlePreEvent();
                    HTableInterface hTable = null;
                    Object rowKey = node.getEntityId();
                    Object entity = node.getData();
                    if (node.isInState(RemovedState.class))
                    {
                        delete(entity, rowKey);
                    }
                    else
                    {
                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                node.getDataClass());

                        HBaseDataWrapper columnWrapper = new HBaseDataHandler.HBaseDataWrapper(rowKey,
                                new java.util.HashMap<String, Attribute>(), entity, metadata.getTableName());

                        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                                .getMetamodel(metadata.getPersistenceUnit());

                        EntityType entityType = metaModel.entity(node.getDataClass());

                        List<HBaseDataWrapper> embeddableData = new ArrayList<HBaseDataHandler.HBaseDataWrapper>();

                        hTable = ((HBaseDataHandler) handler).gethTable(metadata.getSchema());
                        ((HBaseDataHandler) handler).preparePersistentData(metadata.getSchema(),
                                metadata.getTableName(), entity, rowKey, metaModel, entityType.getAttributes(),
                                columnWrapper, embeddableData, showQuery);

                        List<HBaseDataWrapper> dataSet = null;
                        if (data.containsKey(hTable))
                        {
                            dataSet = data.get(metadata.getTableName());
                            addRecords(columnWrapper, embeddableData, dataSet);
                        }
                        else
                        {
                            dataSet = new ArrayList<HBaseDataHandler.HBaseDataWrapper>();
                            addRecords(columnWrapper, embeddableData, dataSet);
                            data.put(hTable, dataSet);
                        }
                    }
                    node.handlePostEvent();
                }
            }

            if (!data.isEmpty())
            {
                ((HBaseDataHandler) handler).batch_insert(data);
            }
            return data.size();
        }
        catch (IOException ioex)
        {
            log.error("Error while executing batch insert/update, Caused by: .", ioex);
            throw new KunderaException(ioex);
        }

    }
1221578
@Override
    public int executeBatch()
    {

        Map<Key, List<TableOperation>> operations = new HashMap<Key, List<TableOperation>>();
        for (Node node : nodes)
        {
            if (node.isDirty())
            {
                node.handlePreEvent();
                // delete can not be executed in batch
                if (node.isInState(RemovedState.class))
                {
                    delete(node.getData(), node.getEntityId());
                }
                else
                {
                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            node.getDataClass());
                    List<RelationHolder> relationHolders = getRelationHolders(node);
                    // KunderaCoreUtils.showQuery("Execute batch for" +
                    // metadata.getSchema() + "." + metadata.getTableName(),
                    // showQuery);
                    Row row = createRow(metadata, node.getData(), node.getEntityId(), relationHolders);

                    Table schemaTable = tableAPI.getTable(metadata.getTableName());

                    addOps(operations, schemaTable, row);
                }
                node.handlePostEvent();
            }
        }

        execute(operations);
        return nodes.size();
    }
308893
public function prepareQuery()
    {
        $query = $this->model->newQuery();
        $primaryTable = $this->model->getTable();
        $selects = [$primaryTable.'.*'];
        $joins = [];
        $withs = [];

        /**
         * @event backend.list.extendQueryBefore
         * Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQueryBefore', function($listWidget, $query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        $this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);

        /*
         * Prepare searchable column names
         */
        $primarySearchable = [];
        $relationSearchable = [];

        $columnsToSearch = [];
        if (!empty($this->searchTerm) && ($searchableColumns = $this->getSearchableColumns())) {
            foreach ($searchableColumns as $column) {
                /*
                 * Related
                 */
                if ($this->isColumnRelated($column)) {
                    $table = $this->model->makeRelation($column->relation)->getTable();
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
                        : $table . '.' . $column->valueFrom;

                    $relationSearchable[$column->relation][] = $columnName;
                }
                /*
                 * Primary
                 */
                else {
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
                        : DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');

                    $primarySearchable[] = $columnName;
                }
            }
        }

        /*
         * Prepare related eager loads (withs) and custom selects (joins)
         */
        foreach ($this->getVisibleColumns() as $column) {

            // If useRelationCount is enabled, eager load the count of the relation into $relation_count
            if ($column->relation && @$column->config['useRelationCount']) {
                $query->withCount($column->relation);
            }

            if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
                continue;
            }

            if (isset($column->valueFrom)) {
                $withs[] = $column->relation;
            }

            $joins[] = $column->relation;
        }

        /*
         * Add eager loads to the query
         */
        if ($withs) {
            $query->with(array_unique($withs));
        }

        /*
         * Apply search term
         */
        $query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {

            /*
             * Search primary columns
             */
            if (count($primarySearchable) > 0) {
                $this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
            }

            /*
             * Search relation columns
             */
            if ($joins) {
                foreach (array_unique($joins) as $join) {
                    /*
                     * Apply a supplied search term for relation columns and
                     * constrain the query only if there is something to search for
                     */
                    $columnsToSearch = array_get($relationSearchable, $join, []);

                    if (count($columnsToSearch) > 0) {
                        $innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
                            $this->applySearchToQuery($_query, $columnsToSearch);
                        });
                    }
                }
            }

        });

        /*
         * Custom select queries
         */
        foreach ($this->getVisibleColumns() as $column) {
            if (!isset($column->sqlSelect)) {
                continue;
            }

            $alias = $query->getQuery()->getGrammar()->wrap($column->columnName);

            /*
             * Relation column
             */
            if (isset($column->relation)) {

                // @todo Find a way...
                $relationType = $this->model->getRelationType($column->relation);
                if ($relationType == 'morphTo') {
                    throw new ApplicationException('The relationship morphTo is not supported for list columns.');
                }

                $table =  $this->model->makeRelation($column->relation)->getTable();
                $sqlSelect = $this->parseTableName($column->sqlSelect, $table);

                /*
                 * Manipulate a count query for the sub query
                 */
                $relationObj = $this->model->{$column->relation}();
                $countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);

                $joinSql = $this->isColumnRelated($column, true)
                    ? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
                    : DbDongle::raw($sqlSelect);

                $joinSql = $countQuery->select($joinSql)->toSql();

                $selects[] = Db::raw("(".$joinSql.") as ".$alias);
            }
            /*
             * Primary column
             */
            else {
                $sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
                $selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
            }
        }

        /*
         * Apply sorting
         */
        if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
            if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
                $sortColumn = $this->isColumnPivot($column)
                    ? 'pivot_' . $column->valueFrom
                    : $column->valueFrom;
            }

            // Set the sorting column to $relation_count if useRelationCount enabled
            if (isset($column->relation) && @$column->config['useRelationCount']) {
                $sortColumn = $column->relation . '_count';
            }

            $query->orderBy($sortColumn, $this->sortDirection);
        }

        /*
         * Apply filters
         */
        foreach ($this->filterCallbacks as $callback) {
            $callback($query);
        }

        /*
         * Add custom selects
         */
        $query->addSelect($selects);

        /**
         * @event backend.list.extendQuery
         * Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQuery', function($listWidget, $query) {
         *         $newQuery = MyModel::newQuery();
         *         return $newQuery;
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQuery', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
            return $event;
        }

        return $query;
    }
355212
public List<T> query(ConnectionSource connectionSource, PreparedStmt<T> preparedStmt, ObjectCache objectCache)
			throws SQLException {
		SelectIterator<T, ID> iterator = buildIterator(/* no dao specified because no removes */null, connectionSource,
				preparedStmt, objectCache, DatabaseConnection.DEFAULT_RESULT_FLAGS);
		try {
			List<T> results = new ArrayList<T>();
			while (iterator.hasNextThrow()) {
				results.add(iterator.nextThrow());
			}
			logger.debug("query of '{}' returned {} results", preparedStmt.getStatement(), results.size());
			return results;
		} finally {
			IOUtils.closeThrowSqlException(iterator, "iterator");
		}
	}
629842
protected void executeQueryPrologue(boolean isBatch) throws SQLException {
    executing = true;
    if (closed) {
      throw new SQLException("execute() is called on closed statement");
    }
    protocol.prolog(maxRows, protocol.getProxy() != null, connection, this);
    if (queryTimeout != 0 && (!canUseServerTimeout || isBatch)) {
      setTimerTask(isBatch);
    }
  }
751130
private void executeBatchStatements(Connection conn) throws SQLException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "executeBatchStatements", new java.lang.Object[] { conn, this });

        PreparedStatement insertStatement = null;
        PreparedStatement updateStatement = null;
        PreparedStatement removeStatement = null;

        try {
            // Prepare the statements
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Prepare the INSERT statement for " + _inserts + " inserts");

            if (_inserts > 0) {
                String insertString = "INSERT INTO " + _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix +
                                      " (SERVER_NAME, SERVICE_ID, RU_ID, RUSECTION_ID, RUSECTION_DATA_INDEX, DATA)" +
                                      " VALUES (?,?,?,?,?,?)";
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "INSERT string - " + insertString);
                insertStatement = conn.prepareStatement(insertString);
                insertStatement.setString(1, _serverName);
                insertStatement.setShort(2, (short) _recoveryAgent.clientIdentifier());
            }

            if (tc.isDebugEnabled())
                Tr.debug(tc, "Prepare the UPDATE statement for " + _updates + " updates");

            if (_updates > 0) {
                String updateString = "UPDATE " + _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix +
                                      " SET DATA = ? WHERE " +
                                      "SERVER_NAME = ? AND SERVICE_ID = ? AND RU_ID = ? AND RUSECTION_ID = ? AND RUSECTION_DATA_INDEX = 0";
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "UPDATE string - " + updateString);
                updateStatement = conn.prepareStatement(updateString);
                updateStatement.setString(2, _serverName);
                updateStatement.setShort(3, (short) _recoveryAgent.clientIdentifier());
            }

            if (tc.isDebugEnabled())
                Tr.debug(tc, "Prepare the DELETE statement for " + _removes + " removes");

            if (_removes > 0) {
                String removeString = "DELETE FROM " + _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix + " WHERE " +
                                      "SERVER_NAME = ? AND SERVICE_ID = ? AND RU_ID = ? ";
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "DELETE string - " + removeString);
                removeStatement = conn.prepareStatement(removeString);
                removeStatement.setString(1, _serverName);
                removeStatement.setShort(2, (short) _recoveryAgent.clientIdentifier());
            }

            // Batch the INSERT statements
            if (_inserts > 0) {
                for (ruForReplay element : _cachedInserts) {
                    insertStatement.setLong(3, element.getRuId());
                    insertStatement.setLong(4, element.getSectionId());
                    insertStatement.setShort(5, (short) element.getIndex());
                    insertStatement.setBytes(6, element.getData());

                    insertStatement.addBatch();
                }
            }

            // Batch the UPDATE statements
            if (_updates > 0) {
                for (ruForReplay element : _cachedUpdates) {
                    updateStatement.setLong(4, element.getRuId());
                    updateStatement.setLong(5, element.getSectionId());
                    updateStatement.setBytes(1, element.getData());

                    updateStatement.addBatch();
                }
            }

            // Batch the DELETE statements
            if (_removes > 0) {
                for (ruForReplay element : _cachedRemoves) {
                    removeStatement.setLong(3, element.getRuId());
                    removeStatement.addBatch();
                }
            }

            // Execute the statements
            if (_inserts > 0) {
                int[] numUpdates = insertStatement.executeBatch();
                if (tc.isDebugEnabled()) {
                    for (int i = 0; i < numUpdates.length; i++) {
                        if (numUpdates[i] == Statement.SUCCESS_NO_INFO)
                            Tr.debug(tc, "Execution " + i + ": unknown number of rows updated");
                        else
                            Tr.debug(tc, "Execution " + i + "successful: " + numUpdates[i] + " rows updated");
                    }
                }
            }
            if (tc.isEventEnabled())
                Tr.event(tc, "sql tranlog: batch inserts: " + _inserts);

            if (_updates > 0) {
                int[] numUpdates = updateStatement.executeBatch();
                if (tc.isDebugEnabled()) {
                    for (int i = 0; i < numUpdates.length; i++) {
                        if (numUpdates[i] == Statement.SUCCESS_NO_INFO)
                            Tr.debug(tc, "Execution " + i + ": unknown number of rows updated");
                        else
                            Tr.debug(tc, "Execution " + i + "successful: " + numUpdates[i] + " rows updated");
                    }
                }
            }
            if (tc.isEventEnabled())
                Tr.event(tc, "sql tranlog: batch updates: " + _updates);

            if (_removes > 0) {
                int[] numUpdates = removeStatement.executeBatch();
                if (tc.isDebugEnabled()) {
                    for (int i = 0; i < numUpdates.length; i++) {
                        if (numUpdates[i] == Statement.SUCCESS_NO_INFO)
                            Tr.debug(tc, "Execution " + i + ": unknown number of rows updated");
                        else
                            Tr.debug(tc, "Execution " + i + "successful: " + numUpdates[i] + " rows updated");
                    }
                }
            }
            if (tc.isEventEnabled())
                Tr.event(tc, "sql tranlog: batch deletes: " + _removes + ", for obj: " + this);
        } finally {
            if (insertStatement != null && !insertStatement.isClosed())
                insertStatement.close();
            if (updateStatement != null && !updateStatement.isClosed())
                updateStatement.close();
            if (removeStatement != null && !removeStatement.isClosed())
                removeStatement.close();
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "executeBatchStatements");
    }