Reads an SQL-script and identifies individual statements.
The batch separator handling is dependent on the database manager
545267
public List<String> readFile(Reader reader) throws Exception {
        try {
            if (characteristics.doIgnoreCase()) {
                if (characteristics.aloneOnLine()) {
                    // Batch separator is located alone on a line
                    // beginning at first position. Ignore case.
                    //
                    // Example with separator "GO":
                    //
                    //   create index blipp ( blopp )
                    //   go
                    //
                    // -or-
                    //
                    //   CREATE INDEX blipp ( blopp )
                    //   GO
                    //
                    return readFileIgnoreCaseAloneOnLine(reader);
                } else {
                    // Batch separator may be located anywhere on a
                    // line. Ignore case.
                    //
                    // Example with separator ";":
                    //
                    //   CREATE INDEX blipp ( blopp );
                    //
                    // Beware of case (separator "GO"):
                    //
                    //   CREATE TABLE blipp (
                    //     pogopop INTEGER
                    //   )
                    //
                    // which will accept "go" in pogopop as separator.
                    //
                    // Since this is a "dangerous" case we do not support it!
                    throw new Exception("Batch separator detection scheme not implemented");
                }
            } else {
                if (characteristics.aloneOnLine()) {
                    // Batch separator is located alone on a line
                    // beginning at first position. Consider case.
                    //
                    // Example with separator "GO":
                    //
                    //   CREATE INDEX blipp ( blopp )
                    //   GO
                    //
                    // is handled while
                    //
                    //   create index blipp ( blopp )
                    //   go
                    //
                    // is not handled
                    //
                    return readFileConsiderCaseAloneOnLine(reader);
                } else {
                    // Batch separator may be located anywhere on a
                    // line. Consider case.
                    //
                    // Example with separator ";":
                    //
                    //   CREATE INDEX blipp ( blopp );
                    //
                    // If we follow our coding standards (keeping SQL uppercased
                    // and identifiers/names lowercased) the following
                    // is also handled correctly (separator "GO"):
                    //
                    //   CREATE TABLE blipp (
                    //     pogopop INTEGER
                    //   )
                    //   GO
                    //
                    // which will -NOT- accidentaly accept "go" in pogopop as separator.
                    // In the latter case it would be better still to use the alone-on-line
                    // model.
                    //
                    return readFileConsiderCase(reader);
                }
            }
        } catch (Exception e) {
            throw new Exception("Failed to read file: " + e.getMessage());

        } finally {
            if (options.debug) System.out.println("Done reading");
        }
    }
576130
static String getSQL(Token[] statement) {

        boolean      wasDelimiter = true;
        StringBuffer sb           = new StringBuffer();

        for (int i = 0; i < statement.length; i++) {
            // when the previous statement is ')', there should be a blank before the non-delimiter statement.
            if (!statement[i].isDelimiter &&
                    (!wasDelimiter
                            || (i > 0 && ")".equals(statement[i - 1].getSQL()))))
            {
                sb.append(' ');
            }

            sb.append(statement[i].getSQL());

            wasDelimiter = statement[i].isDelimiter;
        }

        return sb.toString();
    }
197275
def batch_find(self, *dbqueries):
        
        if len(dbqueries) < 1:
            raise Exception('Must have at least one query.')

        data = json.dumps(dbqueries)

        return json.loads(self._post('batch_find', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
367061
@Override
  public void addBatch(String sql) throws SQLException {
    checkClosed();

    if (batchStatements == null) {
      batchStatements = new ArrayList<Query>();
      batchParameters = new ArrayList<ParameterList>();
    }

    // Simple statements should not replace ?, ? with $1, $2
    boolean shouldUseParameterized = false;
    CachedQuery cachedQuery = connection.createQuery(sql, replaceProcessingEnabled, shouldUseParameterized);
    batchStatements.add(cachedQuery.query);
    batchParameters.add(null);
  }
828595
def _read_sql_with_offset_pandas_on_ray(
    partition_column,
    start,
    end,
    num_splits,
    sql,
    con,
    index_col=None,
    coerce_float=True,
    params=None,
    parse_dates=None,
    columns=None,
    chunksize=None,
):  # pragma: no cover
    

    from .sql import query_put_bounders

    query_with_bounders = query_put_bounders(sql, partition_column, start, end)
    pandas_df = pandas.read_sql(
        query_with_bounders,
        con,
        index_col=index_col,
        coerce_float=coerce_float,
        params=params,
        parse_dates=parse_dates,
        columns=columns,
        chunksize=chunksize,
    )
    index = len(pandas_df)
    return _split_result_for_readers(1, num_splits, pandas_df) + [index]
1000068
def sql(self, sql: str, *qmark_params, **named_params):
        
        statement = SingleSqlStatement(sql)
        return self.statement(statement).execute(*qmark_params, **named_params)
987762
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True):
        """"""
        return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
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;
}
333859
def execute_sql_statement(sql_statement, query, user_name, session, cursor):
    """"""
    database = query.database
    db_engine_spec = database.db_engine_spec
    parsed_query = ParsedQuery(sql_statement)
    sql = parsed_query.stripped()
    SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW')

    if not parsed_query.is_readonly() and not database.allow_dml:
        raise SqlLabSecurityException(
            _('Only `SELECT` statements are allowed against this database'))
    if query.select_as_cta:
        if not parsed_query.is_select():
            raise SqlLabException(_(
                'Only `SELECT` statements can be used with the CREATE TABLE '
                'feature.'))
        if not query.tmp_table_name:
            start_dttm = datetime.fromtimestamp(query.start_time)
            query.tmp_table_name = 'tmp_{}_table_{}'.format(
                query.user_id, start_dttm.strftime('%Y_%m_%d_%H_%M_%S'))
        sql = parsed_query.as_create_table(query.tmp_table_name)
        query.select_as_cta_used = True
    if parsed_query.is_select():
        if SQL_MAX_ROWS and (not query.limit or query.limit > SQL_MAX_ROWS):
            query.limit = SQL_MAX_ROWS
        if query.limit:
            sql = database.apply_limit_to_sql(sql, query.limit)

    # Hook to allow environment-specific mutation (usually comments) to the SQL
    SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
    if SQL_QUERY_MUTATOR:
        sql = SQL_QUERY_MUTATOR(sql, user_name, security_manager, database)

    try:
        if log_query:
            log_query(
                query.database.sqlalchemy_uri,
                query.executed_sql,
                query.schema,
                user_name,
                __name__,
                security_manager,
            )
        query.executed_sql = sql
        with stats_timing('sqllab.query.time_executing_query', stats_logger):
            logging.info('Running query: \n{}'.format(sql))
            db_engine_spec.execute(cursor, sql, async_=True)
            logging.info('Handling cursor')
            db_engine_spec.handle_cursor(cursor, query, session)

        with stats_timing('sqllab.query.time_fetching_results', stats_logger):
            logging.debug('Fetching data for query object: {}'.format(query.to_dict()))
            data = db_engine_spec.fetch_data(cursor, query.limit)

    except SoftTimeLimitExceeded as e:
        logging.exception(e)
        raise SqlLabTimeoutException(
            "SQL Lab timeout. This environment's policy is to kill queries "
            'after {} seconds.'.format(SQLLAB_TIMEOUT))
    except Exception as e:
        logging.exception(e)
        raise SqlLabException(db_engine_spec.extract_error_message(e))

    logging.debug('Fetching cursor description')
    cursor_description = cursor.description
    return dataframe.SupersetDataFrame(data, cursor_description, db_engine_spec)
378397
def _split_queries(cls, sql):
        ""

        sql_s = dbt.compat.to_string(sql)
        sql_buf = StringIO(sql_s)
        split_query = snowflake.connector.util_text.split_statements(sql_buf)
        return [part[0] for part in split_query]
917691
private String readProgram( String script) {
        String program = null;
        
        if ( script != null) {
            Pattern pattern = Pattern.compile( "^#!(/.*)");
            Matcher matcher = pattern.matcher( script);
            if ( matcher.find()) {
                program = matcher.group( 1);
            }            
        }
                
        return program;
    }
212411
public static boolean containsSqlScriptDelimiters(String script, String delim) {
        boolean inLiteral = false;
        char[] content = script.toCharArray();
        for (int i = 0; i < script.length(); i++) {
            if (content[i] == '\'') {
                inLiteral = !inLiteral;
            }
            if (!inLiteral && script.startsWith(delim, i)) {
                return true;
            }
        }
        return false;
    }
901934
def commands(self):
        
        # Retrieve all commands via split function or splitting on ';'
        print('\tRetrieving commands from', self.sql_script)
        print('\tUsing command splitter algorithm {0}'.format(self.split_algo))

        with Timer('\tRetrieved commands in'):
            # Split commands
            # sqlparse packages split function combined with sql_split function
            if self.split_algo is 'sql_parse':
                commands = SplitCommands(self.sql_script).sql_parse

            # Split on every ';' (unreliable)
            elif self.split_algo is 'simple_split':
                commands = SplitCommands(self.sql_script).simple_split()

            # sqlparse package without additional splitting
            elif self.split_algo is 'sql_parse_nosplit':
                commands = SplitCommands(self.sql_script).sql_parse_nosplit

            # Parse every char of the SQL commands and determine breakpoints
            elif self.split_algo is 'sql_split':
                commands = SplitCommands(self.sql_script).sql_split(disable_tqdm=False)
            else:
                commands = SplitCommands(self.sql_script).sql_split(disable_tqdm=False)

            # remove dbo. prefixes from table names
            cleaned_commands = [com.replace("dbo.", '') for com in commands]
        return cleaned_commands
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();
    }
1248398
static String choppedStatementNoLineChange(String statement) {
    // \r\n needs to be the first element in the pipe.
    statement = statement.replaceAll("\\r\\n|\\r|\\n", " ");
    if (statement.length() <= MAX_OUTPUT_STMT_LENGTH) {
      return statement;
    }
    return statement.substring(0, MAX_OUTPUT_STMT_LENGTH) + "...... (" + (statement.length() - MAX_OUTPUT_STMT_LENGTH)
        + " characters omitted)";
  }
903682
def parse_sql(self, asql):
        
        import sqlparse

        statements = sqlparse.parse(sqlparse.format(asql, strip_comments=True))
        parsed_statements = []
        for statement in statements:

            statement_str = statement.to_unicode().strip()

            for preprocessor in self._backend.sql_processors():
                statement_str = preprocessor(statement_str, self._library, self._backend, self.connection)

            parsed_statements.append(statement_str)

        return parsed_statements