Compile a batch of one or more SQL statements into a set of plans.
Parameters are valid iff there is exactly one DML/DQL statement.
352377
public static AdHocPlannedStatement compileAdHocSQL(PlannerTool plannerTool,
                                                        String sqlStatement,
                                                        boolean inferPartitioning,
                                                        Object userPartitionKey,
                                                        ExplainMode explainMode,
                                                        boolean isLargeQuery,
                                                        boolean isSwapTables,
                                                        Object[] userParamSet)
                                                                throws AdHocPlanningException
    {
        assert(plannerTool != null);
        assert(sqlStatement != null);
        final PlannerTool ptool = plannerTool;

        // Take advantage of the planner optimization for inferring single partition work
        // when the batch has one statement.
        StatementPartitioning partitioning = null;

        if (inferPartitioning) {
            partitioning = StatementPartitioning.inferPartitioning();
        }
        else if (userPartitionKey == null) {
            partitioning = StatementPartitioning.forceMP();
        }
        else {
            partitioning = StatementPartitioning.forceSP();
        }

        try {
            return ptool.planSql(sqlStatement,
                                 partitioning,
                                 explainMode != ExplainMode.NONE,
                                 userParamSet,
                                 isSwapTables,
                                 isLargeQuery);
        }
        catch (Exception e) {
            throw new AdHocPlanningException(e.getMessage());
        }
        catch (StackOverflowError error) {
            // Overly long predicate expressions can cause a
            // StackOverflowError in various code paths that may be
            // covered by different StackOverflowError/Error/Throwable
            // catch blocks. The factors that determine which code path
            // and catch block get activated appears to be platform
            // sensitive for reasons we do not entirely understand.
            // To generate a deterministic error message regardless of
            // these factors, purposely defer StackOverflowError handling
            // for as long as possible, so that it can be handled
            // consistently by a minimum number of high level callers like
            // this one.
            // This eliminates the need to synchronize error message text
            // in multiple catch blocks, which becomes a problem when some
            // catch blocks lead to re-wrapping of exceptions which tends
            // to adorn the final error text in ways that are hard to track
            // and replicate.
            // Deferring StackOverflowError handling MAY mean ADDING
            // explicit StackOverflowError catch blocks that re-throw
            // the error to bypass more generic catch blocks
            // for Error or Throwable on the same try block.
            throw new AdHocPlanningException("Encountered stack overflow error. " +
                    "Try reducing the number of predicate expressions in the query.");
        }
        catch (AssertionError ae) {
            String msg = "An unexpected internal error occurred when planning a statement issued via @AdHoc.  "
                    + "Please contact VoltDB at support@voltdb.com with your log files.";
            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);
            ae.printStackTrace(writer);
            String stackTrace = stringWriter.toString();

            adhocLog.error(msg + "\n" + stackTrace);
            throw new AdHocPlanningException(msg);
        }
    }
447699
def __build_query(self, routine, parameters):
        """"""

        parameter_names = []
        replacements = {}
        for i, value in enumerate(parameters):
            name = 'arg' + str(i)

            parameter_names.append(name)
            replacements[name] = value

        parameter_pieces = []
        for i, name in enumerate(parameter_names):
            if i > 0:
                parameter_pieces.append(', ')

            # Embed encoded blobs directly.
            if issubclass(replacements[name].__class__, _BlobArgumentWrapper) is True:
                parameter_pieces.append(replacements[name].encoded)
                del replacements[name]
            else:
                parameter_pieces.append(':' + name)

        query = "CALL " + routine + "(" + ''.join(parameter_pieces) + ")"

        return (query, replacements)
791485
def _executing(self, sql, params=[]):
        
        with self.connection() as connection:
            for row in connection.execute(sql, params):
                yield row
                if not self._db:
                    return
1142935
public int[] executeBatchPreparedStatement(String statement, Collection inParamsBatch) throws SQLException {
		return executeBatchPreparedStatement(statement, inParamsBatch, true);
	}
604604
def executemany(self, statement, parameters):
        
        # First try safer hana-style parameter expansion:
        try:
            statement_id = self.prepare(statement)
        except DatabaseError as msg:
            # Hana expansion failed, check message to be sure of reason:
            if 'incorrect syntax near "%"' not in str(msg):
                # Probably some other error than related to string expansion -> raise an error
                raise
            # Statement contained percentage char, so perform Python style parameter expansion:
            for row_params in parameters:
                operation = format_operation(statement, row_params)
                self._execute_direct(operation)
        else:
            # Continue with Hana style statement execution:
            prepared_statement = self.get_prepared_statement(statement_id)
            self.execute_prepared(prepared_statement, parameters)
        # Return cursor object:
        return self
647453
private void executeJdbcStatements(Connection connection, String configName, String statements, String description) {
        Statement stmt = createStatement(configName, connection);
        try {
            log.debug("Executing statement [" + description + "]");
            
            List<String> stmtsToExecute = Stream.of(statements.split(";"))
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
            
            if ( log.isTraceEnabled()) {
                log.trace("These statements will be executed:");
                stmtsToExecute.forEach(s -> log.trace("Statement: [" + s + "]"));
            }
            
            for ( String currentStatement : stmtsToExecute) {
                stmt.execute(currentStatement);
                log.trace("Executing statement: " + currentStatement + " OK!");
            }
            
        } catch (SQLException e) {
            throw new ChorusException(
                    String.format("Failed while executing statement [%s] on database + %s [%s]", description, configName, e.toString(), e)
            );
        }
    }
662029
protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException {
		List<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();
		String statement = buildStatementString(argList);
		ArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]);
		FieldType[] resultFieldTypes = getResultFieldTypes();
		FieldType[] argFieldTypes = new FieldType[argList.size()];
		for (int selectC = 0; selectC < selectArgs.length; selectC++) {
			argFieldTypes[selectC] = selectArgs[selectC].getFieldType();
		}
		if (!type.isOkForStatementBuilder()) {
			throw new IllegalStateException("Building a statement from a " + type + " statement is not allowed");
		}
		return new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs,
				(databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore);
	}
679487
protected void buildSQLStatements() {
        // prepare statements
        if (getStorageModel() == SM_BINARY_KEYS) {
            bundleInsertSQL = "insert into " + schemaObjectPrefix + "BUNDLE (BUNDLE_DATA, NODE_ID) values (?, ?)";
            bundleUpdateSQL = "update " + schemaObjectPrefix + "BUNDLE set BUNDLE_DATA = ? where NODE_ID = ?";
            bundleSelectSQL = "select BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE where NODE_ID = ?";
            bundleDeleteSQL = "delete from " + schemaObjectPrefix + "BUNDLE where NODE_ID = ?";

            nodeReferenceInsertSQL = "insert into " + schemaObjectPrefix + "REFS (REFS_DATA, NODE_ID) values (?, ?)";
            nodeReferenceUpdateSQL = "update " + schemaObjectPrefix + "REFS set REFS_DATA = ? where NODE_ID = ?";
            nodeReferenceSelectSQL = "select REFS_DATA from " + schemaObjectPrefix + "REFS where NODE_ID = ?";
            nodeReferenceDeleteSQL = "delete from " + schemaObjectPrefix + "REFS where NODE_ID = ?";

            bundleSelectAllIdsSQL = "select NODE_ID from " + schemaObjectPrefix + "BUNDLE ORDER BY NODE_ID";
            bundleSelectAllIdsFromSQL = "select NODE_ID from " + schemaObjectPrefix + "BUNDLE WHERE NODE_ID > ? ORDER BY NODE_ID";
            bundleSelectAllBundlesSQL = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE ORDER BY NODE_ID";
            bundleSelectAllBundlesFromSQL = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE WHERE NODE_ID > ? ORDER BY NODE_ID";
        } else {
            bundleInsertSQL = "insert into " + schemaObjectPrefix + "BUNDLE (BUNDLE_DATA, NODE_ID_HI, NODE_ID_LO) values (?, ?, ?)";
            bundleUpdateSQL = "update " + schemaObjectPrefix + "BUNDLE set BUNDLE_DATA = ? where NODE_ID_HI = ? and NODE_ID_LO = ?";
            bundleSelectSQL = "select BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE where NODE_ID_HI = ? and NODE_ID_LO = ?";
            bundleDeleteSQL = "delete from " + schemaObjectPrefix + "BUNDLE where NODE_ID_HI = ? and NODE_ID_LO = ?";

            nodeReferenceInsertSQL =
                "insert into " + schemaObjectPrefix + "REFS"
                + " (REFS_DATA, NODE_ID_HI, NODE_ID_LO) values (?, ?, ?)";
            nodeReferenceUpdateSQL =
                "update " + schemaObjectPrefix + "REFS"
                + " set REFS_DATA = ? where NODE_ID_HI = ? and NODE_ID_LO = ?";
            nodeReferenceSelectSQL = "select REFS_DATA from " + schemaObjectPrefix + "REFS where NODE_ID_HI = ? and NODE_ID_LO = ?";
            nodeReferenceDeleteSQL = "delete from " + schemaObjectPrefix + "REFS where NODE_ID_HI = ? and NODE_ID_LO = ?";

            bundleSelectAllIdsSQL = "select NODE_ID_HI, NODE_ID_LO from " + schemaObjectPrefix 
                + "BUNDLE ORDER BY NODE_ID_HI, NODE_ID_LO";
            // need to use HI and LO parameters
            // this is not the exact statement, but not all databases support WHERE (NODE_ID_HI, NODE_ID_LOW) >= (?, ?)
            bundleSelectAllIdsFromSQL =
                "select NODE_ID_HI, NODE_ID_LO from " + schemaObjectPrefix + "BUNDLE"
                + " WHERE (NODE_ID_HI >= ?) AND (? IS NOT NULL)"
                + " ORDER BY NODE_ID_HI, NODE_ID_LO";

            bundleSelectAllBundlesSQL = "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix
                    + "BUNDLE ORDER BY NODE_ID_HI, NODE_ID_LO";
            // need to use HI and LO parameters
            // this is not the exact statement, but not all databases support WHERE (NODE_ID_HI, NODE_ID_LOW) >= (?, ?)
            bundleSelectAllBundlesFromSQL =
                    "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE"
                            + " WHERE (NODE_ID_HI >= ?) AND (? IS NOT NULL)"
                            + " ORDER BY NODE_ID_HI, NODE_ID_LO";

        }

    }
1009936
def _processDDL(self):
        """"""
        sql_statements = self._generateDDL()

        logging.info('Generating sqllite tables')
        for stmt in sql_statements:
            c = self.conn.cursor()
            c.execute(stmt)
            self.conn.commit()
507778
public static String batchQueryGenerator(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();
    }
155193
def _sqlfile_to_statements(sql):
    
    statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql))
    return [stmt for stmt in statements if stmt]
30419
StatementDMQL compileCursorSpecification() {

        QueryExpression queryExpression = XreadQueryExpression();

        queryExpression.setAsTopLevel();
        queryExpression.resolve(session);
        if (token.tokenType == Tokens.FOR) {
            read();

            if (token.tokenType == Tokens.READ) {
                read();
                readThis(Tokens.ONLY);
            } else {
                readThis(Tokens.UPDATE);

                if (token.tokenType == Tokens.OF) {
                    readThis(Tokens.OF);

                    OrderedHashSet colNames = readColumnNameList(null, false);
                }
            }
        }

        StatementDMQL cs = new StatementQuery(session, queryExpression,
                                              compileContext);

        return cs;
    }
56337
def execute_sql_statements(
    ctask, query_id, rendered_query, return_results=True, store_results=False,
    user_name=None, session=None, start_time=None,
):
    """"""
    if store_results and start_time:
        # only asynchronous queries
        stats_logger.timing(
            'sqllab.query.time_pending', now_as_float() - start_time)

    query = get_query(query_id, session)
    payload = dict(query_id=query_id)
    database = query.database
    db_engine_spec = database.db_engine_spec
    db_engine_spec.patch()

    if store_results and not results_backend:
        raise SqlLabException("Results backend isn't configured.")

    # Breaking down into multiple statements
    parsed_query = ParsedQuery(rendered_query)
    statements = parsed_query.get_statements()
    logging.info(f'Executing {len(statements)} statement(s)')

    logging.info("Set query to 'running'")
    query.status = QueryStatus.RUNNING
    query.start_running_time = now_as_float()

    engine = database.get_sqla_engine(
        schema=query.schema,
        nullpool=True,
        user_name=user_name,
        source=sources.get('sql_lab', None),
    )
    # Sharing a single connection and cursor across the
    # execution of all statements (if many)
    with closing(engine.raw_connection()) as conn:
        with closing(conn.cursor()) as cursor:
            statement_count = len(statements)
            for i, statement in enumerate(statements):
                # TODO CHECK IF STOPPED
                msg = f'Running statement {i+1} out of {statement_count}'
                logging.info(msg)
                query.set_extra_json_key('progress', msg)
                session.commit()
                try:
                    cdf = execute_sql_statement(
                        statement, query, user_name, session, cursor)
                    msg = f'Running statement {i+1} out of {statement_count}'
                except Exception as e:
                    msg = str(e)
                    if statement_count > 1:
                        msg = f'[Statement {i+1} out of {statement_count}] ' + msg
                    payload = handle_query_error(msg, query, session, payload)
                    return payload

    # Success, updating the query entry in database
    query.rows = cdf.size
    query.progress = 100
    query.set_extra_json_key('progress', None)
    query.status = QueryStatus.SUCCESS
    if query.select_as_cta:
        query.select_sql = database.select_star(
            query.tmp_table_name,
            limit=query.limit,
            schema=database.force_ctas_schema,
            show_cols=False,
            latest_partition=False)
    query.end_time = now_as_float()

    payload.update({
        'status': query.status,
        'data': cdf.data if cdf.data else [],
        'columns': cdf.columns if cdf.columns else [],
        'query': query.to_dict(),
    })

    if store_results:
        key = str(uuid.uuid4())
        logging.info(f'Storing results in results backend, key: {key}')
        with stats_timing('sqllab.query.results_backend_write', stats_logger):
            json_payload = json.dumps(
                payload, default=json_iso_dttm_ser, ignore_nan=True)
            cache_timeout = database.cache_timeout
            if cache_timeout is None:
                cache_timeout = config.get('CACHE_DEFAULT_TIMEOUT', 0)
            results_backend.set(key, zlib_compress(json_payload), cache_timeout)
        query.results_key = key
    session.commit()

    if return_results:
        return payload
171270
private static void generateSQLBuild(SQLiteModelMethod method, MethodSpec.Builder methodBuilder, SplittedSql splittedSql, boolean countQuery) {
		methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
		methodBuilder.addStatement("_sqlBuilder.append($S)", splittedSql.sqlBasic.trim());

		SqlModifyBuilder.generateInitForDynamicWhereVariables(method, methodBuilder, method.dynamicWhereParameterName, method.dynamicWhereArgsParameterName);

		if (method.jql.isOrderBy()) {
			methodBuilder.addStatement("String _sortOrder=$L", method.jql.paramOrderBy);
		}

		SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);
		SqlSelectBuilder.generateDynamicPartOfQuery(method, methodBuilder, splittedSql, countQuery);
	}
1186059
WrappedStatement compile(String sql) throws SQLException {
    WrappedStatement ws;
    if (! isEnabled(Option.REUSE_STATEMENTS)) {
      ws = new WrappedStatement(connection.prepareStatement(sql), false);
    }
    else {
      if (pool == null) {
        pool = new IdentityHashMap<>();
      }
      String sqlI = sql.intern();
      ws = pool.get(sqlI);
      if (ws == null) {
        ws =  new WrappedStatement(connection.prepareStatement(sql), true);
        pool.put(sqlI, ws);
      }
    }
    return ws;
  }
716239
def batch(self, queries):
        
        with self.connection() as cur:
            for sql, vars in queries:

                if self.debug:
                    print(cur.mogrify(query, vars))
                cur.execute(sql, vars)
1269659
function Batch(db, options) {
  this.options = options || {};
  this.ops = [];
  this.db = db;
  this.written = false;
}