The size of a statement inside a batch query is different from the size of a complete
Statement. The inner batch statements only include the query or prepared ID, and the values of
the statement.
191456
public static Integer sizeOfInnerBatchStatementInBytes(
      BatchableStatement statement, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
    int size = 0;

    size +=
        PrimitiveSizes
            .BYTE; // for each inner statement, there is one byte for the "kind": prepared or string

    if (statement instanceof SimpleStatement) {
      size += PrimitiveSizes.sizeOfLongString(((SimpleStatement) statement).getQuery());
      size +=
          sizeOfSimpleStatementValues(
              ((SimpleStatement) statement), protocolVersion, codecRegistry);
    } else if (statement instanceof BoundStatement) {
      size +=
          PrimitiveSizes.sizeOfShortBytes(
              ((BoundStatement) statement).getPreparedStatement().getId().array());
      size += sizeOfBoundStatementValues(((BoundStatement) statement));
    }
    return size;
  }
275942
@Override
    public int executeBatch()
    {
        Map<String, BulkWriteOperation> bulkWriteOperationMap = new HashMap<String, BulkWriteOperation>();
        int size = 0;
        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
                {
                    List<RelationHolder> relationHolders = getRelationHolders(node);
                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            node.getDataClass());
                    Map<String, DBObject> documents = handler.getDocumentFromEntity(metadata, node.getData(),
                            relationHolders, kunderaMetadata);
                    for (String tableName : documents.keySet())
                    {
                        if (!bulkWriteOperationMap.containsKey(tableName))
                        {
                            DBCollection collection = mongoDb.getCollection(tableName);
                            BulkWriteOperation builder = null;
                            if (isOrderedBulkOperation())
                            {
                                builder = collection.initializeOrderedBulkOperation();
                            }
                            else
                            {
                                builder = collection.initializeUnorderedBulkOperation();
                            }
                            bulkWriteOperationMap.put(tableName, builder);
                        }

                        if (!node.isUpdate())
                        {
                            bulkWriteOperationMap.get(tableName).insert(documents.get(tableName));
                        }

                        else
                        {
                            bulkWriteOperationMap.get(tableName).find(new BasicDBObject("_id", node.getEntityId()))
                                    .upsert().replaceOne(documents.get(tableName));
                        }
                        size++;
                    }
                    indexNode(node, metadata);
                }
                node.handlePostEvent();
            }
        }
        onFlushBatch(bulkWriteOperationMap);
        return size;
    }
894189
def size(self, value):
		
		
		if self._combining:  # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
			return reduce(self._combining, (q.size(value) for q in self._field))
		
		# Optimize this away in production; diagnosic aide.
		if __debug__ and _complex_safety_check(self._field, {'$size', '#array'}):  # pragma: no cover
			raise NotImplementedError("{self!r} does not allow $size comparison.".format(self=self))
		
		return Filter({self._name: {'$size': int(value)}})
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;
    }
806765
@NonNull
  public BatchStatementBuilder addStatement(@NonNull BatchableStatement<?> statement) {
    if (statementsCount >= 0xFFFF) {
      throw new IllegalStateException(
          "Batch statement cannot contain more than " + 0xFFFF + " statements.");
    }
    statementsCount += 1;
    statementsBuilder.add(statement);
    return this;
  }
554829
@Override
  public long[] executeLargeBatch() throws SQLException {
    checkClose();
    int size;
    if (batchQueries == null || (size = batchQueries.size()) == 0) {
      return new long[0];
    }

    lock.lock();
    try {
      internalBatchExecution(size);
      return results.getCmdInformation().getLargeUpdateCounts();

    } catch (SQLException initialSqlEx) {
      throw executeBatchExceptionEpilogue(initialSqlEx, size);
    } finally {
      executeBatchEpilogue();
      lock.unlock();
    }
  }
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);
    }
}
162023
private PreparedStatement prepareBatchStatement(String sql)
    {
        String sqlCmd = sql.substring(0, 7);

        if (sqlCmd.equals("UPDATE ") || sqlCmd.equals("DELETE ") || (_useBatchInserts && sqlCmd.equals("INSERT ")))
        {
            PreparedStatement stmt = (PreparedStatement) _statements.get(sql);
            if (stmt == null)
            {
                // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement
                // interfaces, otherwise proxy.jar works incorrectly
                stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{
                        PreparedStatement.class, Statement.class, BatchPreparedStatement.class},
                        new PreparedStatementInvocationHandler(this, sql, m_jcd));
                _statements.put(sql, stmt);
            }
            return stmt;
        }
        else
        {
            return null;
        }
    }
1271446
public function count() {
        $sql    = $this->getSQL();
        $values = $this->values;
        if ($sql) {
            try {
                $ids = array_keys($this->datas);
                if ($this->batch && count($this->datas) > 1) {
                    unset($ids[0]);
                    $sqlValues = [];
                    foreach ($ids as $idx) {
                        $d       = $this->datas[ $idx ];
                        $vstring = [];
                        foreach ($d as $ff => $vv) {
                            if ($vv instanceof ImmutableValue) { // a immutable value
                                $vv->setDialect($this->dialect);
                                $vstring [] = $this->sanitize($vv->__toString());
                            } else if ($vv instanceof Query) { // a sub-select SQL as a value
                                $vv->setBindValues($values);
                                $vv->setDialect($this->dialect);
                                $vstring [] = '(' . $vv->__toString() . ')';
                            } else {
                                $vstring [] = $values->addValue($ff, $vv);
                            }
                        }
                        $sqlValues[] = '(' . implode(' , ', $vstring) . ')';
                    }
                    $this->sql = $sql = $sql . ',' . implode(' , ', $sqlValues);
                }

                $statement = $this->dialect->prepare($sql);

                foreach ($values as $value) {
                    list ($name, $val, $type) = $value;
                    if (!$statement->bindValue($name, $val, $type)) {
                        $this->errorSQL    = $sql;
                        $this->errorValues = $values->__toString();
                        $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name;

                        return false;
                    }
                }

                $rst = $statement->execute();
                if ($rst) {
                    if ($this->keySet) {
                        $this->fillAutoIds();
                    } else {
                        $this->ids [] = $this->dialect->lastInsertId($this->keyField);
                    }

                    return $statement->rowCount();
                } else {
                    $this->dumpSQL($statement);
                }

                if ($statement) {
                    $statement->closeCursor();
                    $statement = null;
                }
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $sql;
                $this->errorValues = $values->__toString();

                return false;
            }
        } else {
            $this->error       = 'Can not generate the insert SQL';
            $this->errorSQL    = '';
            $this->errorValues = $values->__toString();
        }

        return false;
    }
1280376
static int parametersCount(Query query) {
        if (query.names().isEmpty())
            return countQuestionMarkParameters(query.sql());
        else
            return query.names().size();
    }
1140093
void setBatchSize(String batch_Size) {
        if (!StringUtils.isBlank(batch_Size)) {
            batchSize = Integer.valueOf(batch_Size);
            if (batchSize == 0) {
                throw new IllegalArgumentException("kundera.batch.size property must be numeric and > 0.");
            }
        }
    }
1214170
@NonNull
  public BatchStatementBuilder addStatements(@NonNull Iterable<BatchableStatement<?>> statements) {
    int delta = Iterables.size(statements);
    if (statementsCount + delta > 0xFFFF) {
      throw new IllegalStateException(
          "Batch statement cannot contain more than " + 0xFFFF + " statements.");
    }
    statementsCount += delta;
    statementsBuilder.addAll(statements);
    return this;
  }
107498
protected void incrementBatchCount() throws SQLException {
        batchCount++;
        if (batchCount == batchSize /* never true for batchSize of 0 */) {
            int[] result = delegate.executeBatch();
            processResult(result);
            batchCount = 0;
        }
    }
934376
def each
      # Need to close the connection, teh result_set, AND the result_set.getStatement when
      # we're done.
      connection = open_connection!

      # We're going to need to ask for item/copy info while in the
      # middle of streaming our results. JDBC is happier and more performant
      # if we use a seperate connection for this.
      extra_connection = open_connection! if include_some_holdings?

      # We're going to make our marc records in batches, and only yield
      # them to caller in batches, so we can fetch copy/item info in batches
      # for efficiency.
      batch_size = settings["horizon.batch_size"].to_i
      record_batch = []

      exclude_tags = (settings["horizon.exclude_tags"] || "").split(",")


      rs = self.fetch_result_set!(connection)

      current_bib_id = nil
      record = nil
      record_count = 0

      error_handler = org.marc4j.ErrorHandler.new

      while(rs.next)
        bib_id      = rs.getInt("bib#");

        if bib_id != current_bib_id
          record_count += 1

          if settings["debug_ascii_progress"] &&  (record_count % settings["solrj_writer.batch_size"] == 0)
            $stderr.write ","
          end

          # new record! Put old one on batch queue.
          record_batch << record if record

          # prepare and yield batch?
          if (record_count % batch_size == 0)
            enhance_batch!(extra_connection, record_batch)
            record_batch.each do |r|
              # set current_bib_id for error logging
              current_bib_id = r['001'].value
              yield r
            end
            record_batch.clear
          end

          # And start new record we've encountered.
          error_handler = org.marc4j.ErrorHandler.new
          current_bib_id = bib_id
          record = MARC::Record.new
          record.append MARC::ControlField.new("001", bib_id.to_s)
        end

        tagord      = rs.getInt("tagord");
        tag         = rs.getString("tag")

        # just silently skip it, some weird row in the horizon db, it happens.
        # plus any of our exclude_tags.
        next if tag.nil? || tag == "" || exclude_tags.include?(tag)

        indicators = rs.getString("indicators")

        # a packed byte array could be in various columns, in order of preference...
        # the xref stuff is joined in from the auth table
        # Have to get it as bytes and then convert it to String to avoid JDBC messing
        # up the encoding marc8 grr
        authtext = rs.getBytes("xref_longtext") || rs.getBytes("xref_text")
        text     = rs.getBytes("longtext") || rs.getBytes("text")


        if tag == "000"
          # Horizon puts a \x1E marc field terminator on the end of hte
          # leader in the db too, but that's not really part of it.
          record.leader =  String.from_java_bytes(text).chomp("\x1E")

          fix_leader!(record.leader)
        elsif tag != "001"
          # we add an 001 ourselves with bib id in another part of code.
          field = build_marc_field!(error_handler, tag, indicators, text, authtext)
          record.append field unless field.nil?
        end
      end

      # last one
      record_batch << record if record

      # yield last batch
      enhance_batch!(extra_connection, record_batch)

      record_batch.each do |r|
        yield r
      end
      record_batch.clear

    rescue Exception => e
      logger.fatal "HorizonReader, unexpected exception at bib id:#{current_bib_id}: #{e}"    
      raise e
    ensure
      logger.info("HorizonReader: Closing all JDBC objects...")

      # have to cancel the statement to keep us from waiting on entire
      # result set when exception is raised in the middle of stream.
      statement = rs && rs.getStatement
      if statement
        statement.cancel
        statement.close
      end

      rs.close if rs

      # shouldn't actually need to close the resultset and statement if we cancel, I think.
      connection.close if connection

      extra_connection.close if extra_connection

      logger.info("HorizonReader: Closed JDBC objects")
    end
1181230
private static void runCopy(final long start, final long len, final int keySize, final int batchSize, final long otmp[][], final byte xtmp[][], final long o[][], final byte x[][]) {
    // now copy _otmp and _xtmp back over _o and _x from the start position, allowing for boundaries
    // _o, _x, _otmp and _xtmp all have the same _batchsize
    // Would be really nice if Java had 64bit indexing to save programmer time.
    long numRowsToCopy = len;
    int sourceBatch = 0, sourceOffset = 0;
    int targetBatch = (int)(start / batchSize), targetOffset = (int)(start % batchSize);
    int targetBatchRemaining = batchSize - targetOffset;  // 'remaining' means of the the full batch, not of the numRowsToCopy
    int sourceBatchRemaining = batchSize - sourceOffset;  // at most batchSize remaining.  No need to actually put the number of rows left in here
    while (numRowsToCopy > 0) {   // TO DO: put this into class as well, to ArrayCopy into batched
      final int thisCopy = (int)Math.min(numRowsToCopy, Math.min(sourceBatchRemaining, targetBatchRemaining));
      System.arraycopy(otmp[sourceBatch], sourceOffset,         o[targetBatch], targetOffset,         thisCopy);
      System.arraycopy(xtmp[sourceBatch], sourceOffset*keySize, x[targetBatch], targetOffset*keySize, thisCopy*keySize);
      numRowsToCopy -= thisCopy;
      sourceOffset += thisCopy; sourceBatchRemaining -= thisCopy;
      targetOffset += thisCopy; targetBatchRemaining -= thisCopy;
      if (sourceBatchRemaining == 0) { sourceBatch++; sourceOffset = 0; sourceBatchRemaining = batchSize; }
      if (targetBatchRemaining == 0) { targetBatch++; targetOffset = 0; targetBatchRemaining = batchSize; }
      // 'source' and 'target' deliberately the same length variable names and long lines deliberately used so we
      // can easy match them up vertically to ensure they are the same
    }
  }
1051049
private boolean query()
		throws SQLException
	{
		statement = this.connection.createStatement();

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

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

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

		result = statement.executeQuery(query);
		return result.next();
	}
94738
@Override
	public int[] executeBatch() throws SQLException {
		Split s = prepare(batchSql);
		try {
			return stmt.executeBatch();
		} finally {
			finish(s);
		}
	}