Split *sql* into single statements.

    :param sql: A string containing one or more SQL statements.
    :param encoding: The encoding of the statement (optional).
    :returns: A list of strings.
189517
def split(sql, encoding=None):
    
    stack = engine.FilterStack()
    return [text_type(stmt).strip() for stmt in stack.run(sql, encoding)]
609968
public static final String sqlEscape(final String sql) {
        if (sql == null) {
            return "";
        }

        int primePos = sql.indexOf("'");

        if (primePos == -1) {
            return sql;
        }

        final StringBuffer sb = new StringBuffer(sql.length() + 4);
        int startPos = 0;

        do {
            sb.append(sql.substring(startPos, primePos + 1));
            sb.append("'");
            startPos = primePos + 1;
            primePos = sql.indexOf("'", startPos);
        } while (primePos != -1);

        sb.append(sql.substring(startPos));
        return sb.toString();
    }
446533
def execute_sql(
    host,
    username,
    password,
    sql,
    schema=None,
    param=None,
    kwargs=None
):
    """"""
    kwargs.schema = coalesce(kwargs.schema, kwargs.database)

    if param:
        with MySQL(kwargs) as temp:
            sql = expand_template(sql, quote_param(param))

    # We have no way to execute an entire SQL file in bulk, so we
    # have to shell out to the commandline client.
    args = [
        "mysql",
        "-h{0}".format(host),
        "-u{0}".format(username),
        "-p{0}".format(password)
    ]
    if schema:
        args.append("{0}".format(schema))

    try:
        proc = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            bufsize=-1
        )
        if is_text(sql):
            sql = sql.encode("utf8")
        (output, _) = proc.communicate(sql)
    except Exception as e:
        raise Log.error("Can not call \"mysql\"", e)

    if proc.returncode:
        if len(sql) > 10000:
            sql = "<" + text_type(len(sql)) + " bytes of sql>"
        Log.error(
            "Unable to execute sql: return code {{return_code}}, {{output}}:\n {{sql}}\n",
            sql=indent(sql),
            return_code=proc.returncode,
            output=output
        )
1097597
public static function splitSql($sql)
	{
		$start   = 0;
		$length  = strlen($sql);
		$queries = [];

		foreach (Str::findLiteral(';', $sql) as $queryEndPosition)
		{
			$queries[] = trim(substr($sql, $start, $queryEndPosition - $start + 1));
			$start     = $queryEndPosition + 1;
		}

		// Grab the last query in case it doesn't end with a ';'
		if ($end = trim(substr($sql, $start)))
		{
			$queries[] = $end;
		}

		return $queries;
	}
397436
def delete_sql(table, filter):
    '''
    
    '''
    keys, values = _split_dict(filter)
    where = _pairs(keys)
    sql = 'DELETE FROM {} WHERE {}'.format(table, where)
    return sql, values
1166855
public static function splitSql($sql)
  {
    $start = 0;
    $open = false;
    $char = '';
    $end = strlen($sql);
    $queries = [];

    for($i=0; $i<$end; $i++){
      $current = substr($sql, $i, 1);
      if ( $current == '"' || $current == '\'' ){
        $n = 2;

        while(substr($sql, $i - $n + 1, 1) == '\\' && $n < $i){
          $n++;
        }

        if ( $n % 2 == 0 ){
          if ( $open ){
            if ( $current == $char ){
              $open = false;
              $char = '';
            }
          }
          else {
            $open = true;
            $char = $current;
          }
        }
      }

      if ( ($current == ';' && !$open) || $i == $end - 1 ){
        $queries[] = substr($sql, $start, ($i - $start + 1));
        $start = $i + 1;
      }
    }

    return $queries;
  }
1287425
public Selects parse(String sql) throws SQLParserException {
	columnIndex = 0;
	ParserString raw = new ParserString(sql.trim());
	Selects selects = new Selects();
	Select select = new Select();

	boolean runAgain = false;
	do {

	    // select
	    if (!raw.forwardIfCurrentAndNoWordNumberAfter("select")) throw new SQLParserException("missing select");
	    raw.removeSpace();

	    // top
	    if (raw.forwardIfCurrentAndNoWordNumberAfter("top")) {
		raw.removeSpace();
		ValueNumber number = number(raw);
		if (number == null) throw new SQLParserException("missing top number");
		select.setTop(number);
		raw.removeSpace();
	    }

	    // distinct
	    if (raw.forwardIfCurrentAndNoWordNumberAfter("distinct")) {
		select.setDistinct(true);
		raw.removeSpace();
	    }

	    // all
	    if (raw.forwardIfCurrentAndNoWordNumberAfter("all")) {
		select.setDistinct(false);
		raw.removeSpace();
	    }

	    // select expression
	    selectExpressions(raw, select);
	    raw.removeSpace();

	    // from
	    if (!raw.forwardIfCurrentAndNoWordNumberAfter("from")) throw new SQLParserException("missing from");
	    tableList(raw, select);
	    raw.removeSpace();

	    // where
	    if (raw.forwardIfCurrentAndNoWordNumberAfter("where")) whereExpressions(raw, select);
	    raw.removeSpace();

	    // group by
	    if (raw.forwardIfCurrentAndNoWordNumberAfter("group by")) {
		groupByExpressions(raw, select);
		raw.removeSpace();

		// having
		if (raw.forwardIfCurrentAndNoWordNumberAfter("having")) havingExpressions(raw, select);
		raw.removeSpace();
	    }
	    selects.addSelect(select);

	    runAgain = false;
	    // union
	    if (raw.forwardIfCurrentAndNoWordNumberAfter("union")) {
		select = new Select();
		raw.removeSpace();
		if (raw.forwardIfCurrentAndNoWordNumberAfter("all")) {
		    raw.removeSpace();
		    select.setUnionDistinct(false);
		}
		else if (raw.forwardIfCurrentAndNoWordNumberAfter("distinct")) {
		    raw.removeSpace();
		    select.setUnionDistinct(true);
		}
		else select.setDistinct(true);
		raw.removeSpace();
		runAgain = true;
	    }

	}
	while (runAgain);

	// order by
	if (raw.forwardIfCurrentAndNoWordNumberAfter("order by")) orderByExpressions(raw, selects);
	raw.removeSpace();

	if (raw.forwardIfCurrent(';')) raw.removeSpace();

	if (!raw.isAfterLast()) throw new SQLParserException("can not read the full sql statement (stop at:" + raw.getCurrent() + ")");
	return selects;
    }
200835
private function split_sql_file($sql, $delimiter) {
        // Split up our string into "possible" SQL statements.
        $tokens = explode($delimiter, $sql);

        // try to save mem.
        $sql = "";
        $output = array();

        // we don't actually care about the matches preg gives us.
        $matches = array();

        // this is faster than calling count($oktens) every time thru the loop.
        $token_count = count($tokens);
        for ($i = 0; $i < $token_count; $i++) {
            // Don't wanna add an empty string as the last thing in the array.
            if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) {
                // This is the total number of single quotes in the token.
                $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
                // Counts single quotes that are preceded by an odd number of backslashes,
                // which means they're escaped quotes.
                $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

                $unescaped_quotes = $total_quotes - $escaped_quotes;

                // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
                if (($unescaped_quotes % 2) == 0) {
                    // It's a complete sql statement.
                    $output[] = $tokens[$i];
                    // save memory.
                    $tokens[$i] = "";
                } else {
                    // incomplete sql statement. keep adding tokens until we have a complete one.
                    // $temp will hold what we have so far.
                    $temp = $tokens[$i] . $delimiter;
                    // save memory..
                    $tokens[$i] = "";

                    // Do we have a complete statement yet?
                    $complete_stmt = false;

                    for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++) {
                        // This is the total number of single quotes in the token.
                        $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
                        // Counts single quotes that are preceded by an odd number of backslashes,
                        // which means they're escaped quotes.
                        $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

                        $unescaped_quotes = $total_quotes - $escaped_quotes;

                        if (($unescaped_quotes % 2) == 1) {
                            // odd number of unescaped quotes. In combination with the previous incomplete
                            // statement(s), we now have a complete statement. (2 odds always make an even)
                            $output[] = $temp . $tokens[$j];

                            // save memory.
                            $tokens[$j] = "";
                            $temp = "";

                            // exit the loop.
                            $complete_stmt = true;
                            // make sure the outer loop continues at the right point.
                            $i = $j;
                        } else {
                            // even number of unescaped quotes. We still don't have a complete statement.
                            // (1 odd and 1 even always make an odd)
                            $temp .= $tokens[$j] . $delimiter;
                            // save memory.
                            $tokens[$j] = "";
                        }
                    } // for..
                } // else
            }
        }

        return $output;
    }
584712
def convert_to_ascii(statement):
    
    import unicodedata

    text = unicodedata.normalize('NFKD', statement.text)
    text = text.encode('ascii', 'ignore').decode('utf-8')

    statement.text = str(text)
    return statement
1284121
private static ProcessedInput processSqlStatement(final String sql) {
        Map<String, String> parsedSqlResult = new HashMap<String, String>();

        Set<String> namedParameters = new HashSet<String>();
        String sqlToUse = sql;
        List<ParameterHolder> parameterList = new ArrayList<ParameterHolder>();

        char[] statement = sql.toCharArray();
        int namedParameterCount = 0;
        int unnamedParameterCount = 0;
        int totalParameterCount = 0;

        int escapes = 0;
        int i = 0;
        while (i < statement.length) {
            int skipToPosition = i;
            while (i < statement.length) {
                skipToPosition = skipCommentsAndQuotes(statement, i);
                if (i == skipToPosition) {
                    break;
                } else {
                    i = skipToPosition;
                }
            }
            if (i >= statement.length) {
                break;
            }
            char c = statement[i];
            if (c == ':' || c == '&') {
                int j = i + 1;
                if (j < statement.length && statement[j] == ':' && c == ':') {
                    // Postgres-style "::" casting operator - to be skipped.
                    i = i + 2;
                    continue;
                }
                String parameter = null;
                if (j < statement.length && c == ':' && statement[j] == '{') {
                    // :{x} style parameter
                    while (j < statement.length && !('}' == statement[j])) {
                        j++;
                        if (':' == statement[j] || '{' == statement[j]) {
                            throw new IllegalArgumentException("Parameter name contains invalid character '"
                                    + statement[j] + "' at position " + i + " in statement " + sql);
                        }
                    }
                    if (j >= statement.length) {
                        throw new IllegalArgumentException("Non-terminated named parameter declaration at position "
                                + i + " in statement " + sql);
                    }
                    if (j - i > 3) {
                        parameter = sql.substring(i + 2, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
                    }
                    j++;
                } else {
                    while (j < statement.length && !isParameterSeparator(statement[j])) {
                        j++;
                    }
                    if (j - i > 1) {
                        parameter = sql.substring(i + 1, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
                    }
                }
                i = j - 1;
            } else {
                if (c == '\\') {
                    int j = i + 1;
                    if (j < statement.length && statement[j] == ':') {
                        // this is an escaped : and should be skipped
                        sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
                        escapes++;
                        i = i + 2;
                        continue;
                    }
                }
                if (c == '?') {
                    unnamedParameterCount++;
                    totalParameterCount++;
                }
            }
            i++;
        }
        ProcessedInput processedInput = new ProcessedInput(sql);

        for (ParameterHolder ph : parameterList) {
            processedInput.addParameter(ph.getParameterName(), ph.getStartIndex(), ph.getEndIndex());
        }

        return processedInput;
    }
826131
def sql(self):
        
        clone = self.query.clone()
        sql, params = clone.get_compiler(using=self.db).as_sql()
        return sql % params
1220619
private Split prepare() {
		if (sql != null && !sql.equals("")) {
			sqlNormalizer = new SqlNormalizer(sql);
			sqlCmdLabel = prefix + ".sql." + sqlNormalizer.getType();
			return startSplit();
		} else {
			return null;
		}
	}
923871
public static ParsedSql parseSqlStatement(final String sql) {
        Assert.notNull(sql, "SQL must not be null");

        Set<String> namedParameters = new HashSet<>();
        String sqlToUse = sql;
        List<ParameterHolder> parameterList = new ArrayList<>();

        char[] statement = sql.toCharArray();
        int namedParameterCount = 0;
        int unnamedParameterCount = 0;
        int totalParameterCount = 0;

        int escapes = 0;
        int i = 0;
        while (i < statement.length) {
            int skipToPosition;
            while (i < statement.length) {
                skipToPosition = skipCommentsAndQuotes(statement, i);
                if (i == skipToPosition) {
                    break;
                } else {
                    i = skipToPosition;
                }
            }
            if (i >= statement.length) {
                break;
            }
            char c = statement[i];
            if (c == ':' || c == '&') {
                int j = i + 1;
                if (j < statement.length && statement[j] == ':' && c == ':') {
                    // Postgres-style "::" casting operator should be skipped
                    i = i + 2;
                    continue;
                }
                String parameter;
                if (j < statement.length && c == ':' && statement[j] == '{') {
                    // :{x} style parameter
                    while (j < statement.length && !('}' == statement[j])) {
                        j++;
                        if (':' == statement[j] || '{' == statement[j]) {
                            throw new CommonRuntimeException("Parameter name contains invalid character '" +
                                    statement[j] + "' at position " + i + " in statement: " + sql);
                        }
                    }
                    if (j >= statement.length) {
                        throw new CommonRuntimeException(
                                "Non-terminated named parameter declaration at position " + i + " in statement: " + sql);
                    }
                    if (j - i > 3) {
                        parameter = sql.substring(i + 2, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
                    }
                    j++;
                } else {
                    while (j < statement.length && !isParameterSeparator(statement[j])) {
                        j++;
                    }
                    if (j - i > 1) {
                        parameter = sql.substring(i + 1, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
                    }
                }
                i = j - 1;
            } else {
                if (c == '\\') {
                    int j = i + 1;
                    if (j < statement.length && statement[j] == ':') {
                        // escaped ":" should be skipped
                        sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
                        escapes++;
                        i = i + 2;
                        continue;
                    }
                }
                if (c == '?') {
                    int j = i + 1;
                    if (j < statement.length && (statement[j] == '?' || statement[j] == '|' || statement[j] == '&')) {
                        // Postgres-style "??", "?|", "?&" operator should be skipped
                        i = i + 2;
                        continue;
                    }
                    unnamedParameterCount++;
                    totalParameterCount++;
                }
            }
            i++;
        }

        ParsedSql parsedSql = new ParsedSql(sqlToUse);
        parsedSql.setParameterList(parameterList);
        parsedSql.setNamedParameterCount(namedParameterCount);
        parsedSql.setUnnamedParameterCount(unnamedParameterCount);
        parsedSql.setTotalParameterCount(totalParameterCount);
        return parsedSql;
    }
1296537
def _raw_sql(self, values):
        """"""
        if isinstance(self.model._meta.pk, CharField):
            when_clauses = " ".join(
                [self._when("'{}'".format(x), y) for (x, y) in values]
            )
        else:
            when_clauses = " ".join([self._when(x, y) for (x, y) in values])
        table_name = self.model._meta.db_table
        primary_key = self.model._meta.pk.column
        return 'SELECT CASE {}."{}" {} ELSE 0 END'.format(
            table_name, primary_key, when_clauses
        )
665165
private function tokenizeSQL($sql): array
    {
        $token = '\\(|\\)|\[|\]|[\']|"|\140|<>|<=|>=|:=|[*\/<>,+=-]';
        $terminal = $token.'|;| |\\n';
        $result = [];
        $string = $sql;
        $string = ltrim($string);
        $string = rtrim($string, ';').';'; // always ends with a terminal
        $string = preg_replace("/[\n\r]/s", ' ', $string);
        while (
            preg_match("/^($token)($terminal)/s", $string, $matches) ||
            preg_match("/^({$token})./s", $string, $matches) ||
            preg_match("/^(@?[a-zA-Z0-9_.]+?)($terminal)/s", $string, $matches)
        ) {
            $t = $matches[1];
            if ($t == '\'') {
                // it's a string
                $t = $this->tokSingleQuoteString($string);
                array_push($result, $t);
            }
            elseif ($t == "\140") {
                // it's a backtick string (a name)
                $t = $this->tokBackQuoteString($string);
                array_push($result, $t);
            }
            elseif ($t == '"') {
                // it's a double quoted string (a name in normal sql)
                $t = $this->tokDoubleQuoteString($string);
                array_push($result, $t);
            }
            else {
                array_push($result, $t);
            }
            $string = substr($string, strlen($t));
            $string = ltrim($string);
        }
        return $result;
    }
1221001
function formatSql(sqlText, options = {}) {
    let command = buildCommand(options);
    // Pass sqlText in as stdin and run pgFormatter
    let formatted = child_process_1.execSync(command, {
        encoding: "utf8",
        input: sqlText
    });
    return formatted;
}
91981
def _split_sql(self, sql):
        
        bookends = ("\n", ";", "--", "/*", "*/")
        last_bookend_found = None
        start = 0

        while start <= len(sql):
            results = self._get_next_occurrence(sql, start, bookends)
            if results is None:
                yield (last_bookend_found, None, sql[start:])
                start = len(sql) + 1
            else:
                (end, bookend) = results
                yield (last_bookend_found, bookend, sql[start:end])
                start = end + len(bookend)
                last_bookend_found = bookend