Checks if original SQL string valid.
If string contains some unnamed "?" parameters - it is considered unvalid

@param originalSql Original SQL String
3977
protected void validateSqlString(String originalSql) {
        if (originalSql == null) {
            throw new IllegalArgumentException(ERROR_SQL_QUERY_NULL);
        }
        if (processor.hasUnnamedParameters(originalSql) == true) {
            throw new IllegalArgumentException(ERROR_FOUND_UNNAMED_PARAMETER);
        }
    }
28236
public boolean execUpdateByRawSQL(String updateRawSQL) {

    boolean retVal = false;

    log("#execUpdateByRawSQL updateRawSQL=" + updateRawSQL);

    final Connection conn = createConnection();

    try {

      Statement stmt = null;

      // There is a possibility that the error occurs in one single update
      // statement.
      // Therefore, turn the auto commit off.
      conn.setAutoCommit(false);

      stmt = conn.createStatement();
      stmt.executeUpdate(updateRawSQL);

      // finally,commit
      conn.commit();

      retVal = true;

    } catch (SQLException e) {

      loge("#execUpdateByRawSQL", e);
      retVal = false;

    } finally {

      try {
        conn.close();
      } catch (SQLException e) {
        retVal = false;
        loge("#execUpdateByRawSQL", e);
      }
    }
    return retVal;

  }
286446
public static void checkQuery(SpiQuery<?> query, Set<String> whitelist,
                                  Set<String> blacklist, boolean ignoreUnknown) {
        checkQuery(
                query,
                new ListExpressionValidation(
                        query.getBeanDescriptor(), whitelist, blacklist
                ),
                ignoreUnknown
        );
    }
21250
private void sanityCheckQuery(String sql) throws SQLException
  {
    if (sql == null || sql.isEmpty())
    {
      throw new SnowflakeSQLException(SqlState.SQL_STATEMENT_NOT_YET_COMPLETE,
                                      ErrorCode.INVALID_SQL.getMessageCode(), sql);

    }
  }
852074
@Override public void validate() { 
    if (id == null || id.isEmpty()) {
      throw new IllegalArgumentException("missing or empty id");
    }
    Query.validateId(id);
  }
203624
public static boolean isSqlStateDuplicateValueInUniqueIndex(SQLException se) {
        String sqlState = se.getSQLState();
        return sqlState != null && (sqlState.equals("23505") || se.getMessage().contains("duplicate value in unique index"));
    }
924685
private static boolean isValidBrace(String url) {
        if (null == url || url.trim().length() == 0) {
            return false;
        }

        boolean isInsideVariable = false;
        StringTokenizer tokenizer = new StringTokenizer(url, "{}", true);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (token.equals("{")) {
                // { is not allowed inside of a variable specification
                if (isInsideVariable) {
                    return false;
                }
                isInsideVariable = true;
            } else if (token.equals("}")) {
                // } must be preceded by {;
                if (!isInsideVariable) {
                    return false;
                }
                isInsideVariable = false;
            }
        }
        return true;
    }
1172090
public static boolean restrictQueryExecution(String sql) {
		String[] restrictions = { "delete", "truncate", "update", "drop", "alter" };
		if (sql != null) {
			sql = sql.toLowerCase();
			for (String restriction : restrictions) {
				if (sql.startsWith(restriction)) {
					return true;
				}
				String regex = "\\s+" + restriction + "\\s+";
				Pattern pattern = Pattern.compile(regex);
				Matcher matcher = pattern.matcher(sql);
				if (matcher.find()) {
					return true;
				}
			}
		}
		return false;
	}
1364392
def sql_dequote_string(s: str) -> str:
    
    if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE:
        raise ValueError("Not an SQL string literal")
    s = s[1:-1]  # strip off the surrounding quotes
    return s.replace(DOUBLE_SQUOTE, SQUOTE)
248966
def validate(self, value):
        

        query = Query(sql=value)

        passes_blacklist, failing_words = query.passes_blacklist()

        error = MSG_FAILED_BLACKLIST % ', '.join(failing_words) if not passes_blacklist else None

        if error:
            raise ValidationError(
                error,
                code="InvalidSql"
            )
927530
private static function isValidUriQuery(?string $query): bool
    {
        if ($query === null || $query === '') {
            return true;
        }

        // http://tools.ietf.org/html/rfc3986#section-3.4
        // query = *( pchar / "/" / "?" )
        // pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
        $pattern = sprintf(
            '/\A(?:[%s%s\/?:@]|(?:%s))*\z/i',
            'a-z0-9\-._~',
            '!$&\'()*+,;=',
            '%[a-f0-9]{2}'
        );

        return !!preg_match($pattern, $query);
    }
263356
private String exWithQuery(String message, PrepareResult serverPrepareResult,
      ParameterHolder[] parameters) {
    if (options.dumpQueriesOnException) {
      StringBuilder sql = new StringBuilder(serverPrepareResult.getSql());
      if (serverPrepareResult.getParamCount() > 0) {
        sql.append(", parameters [");
        if (parameters.length > 0) {
          for (int i = 0; i < Math.min(parameters.length, serverPrepareResult.getParamCount());
              i++) {
            sql.append(parameters[i].toString()).append(",");
          }
          sql = new StringBuilder(sql.substring(0, sql.length() - 1));
        }
        sql.append("]");
      }

      if (options.maxQuerySizeToLog != 0 && sql.length() > options.maxQuerySizeToLog - 3) {
        return message
            + "\nQuery is: " + sql.substring(0, options.maxQuerySizeToLog - 3) + "..."
            + "\njava thread: " + Thread.currentThread().getName();
      } else {
        return message
            + "\nQuery is: " + sql
            + "\njava thread: " + Thread.currentThread().getName();
      }
    }
    return message;
  }
1318209
public boolean execUpdateByRawSQL(String preparedSQL, Object[] preparedValues) {

    boolean retVal = false;

    final Connection conn = createConnection();

    try {

      PreparedStatement preparedStmt = null;

      // There is a possibility that the error occurs in one single update
      // statement.
      // Therefore, turn the auto commit off.
      conn.setAutoCommit(false);

      preparedStmt = conn.prepareStatement(preparedSQL);

      final StringBuilder logSb = new StringBuilder();

      if (preparedValues != null) {
        logSb.append("/ ");
        for (int i = 0; i < preparedValues.length; i++) {

          setObject((i + 1), preparedStmt, preparedValues[i]);

          logSb.append("key(" + (i + 1) + ")=" + preparedValues[i]);
          logSb.append(" ");
        }
      }

      log("#execUpdateWithRawSQL SQL=" + preparedSQL + " " + logSb.toString());

      // execute SQL
      preparedStmt.executeUpdate();

      // finally commit
      conn.commit();

      retVal = true;

    } catch (SQLException e) {

      loge("#execUpdate", e);
      retVal = false;

    } finally {
      try {
        conn.close();
      } catch (SQLException e) {
        retVal = false;
        loge("#execUpdate", e);
      }
    }
    return retVal;

  }
674950
private <L extends Collection<JQLPlaceHolder>> L extractPlaceHoldersFromVariableStatement(final JQLContext jqlContext, String jql, final L result) {
		final One<Boolean> valid = new One<>();

		if (!StringUtils.hasText(jql))
			return result;

		valid.value0 = false;

		analyzeVariableStatementInternal(jqlContext, jql, new JqlBaseListener() {

			@Override
			public void enterBind_parameter(Bind_parameterContext ctx) {
				String parameter;
				if (ctx.bind_parameter_name() != null) {
					parameter = ctx.bind_parameter_name().getText();
				} else {
					parameter = ctx.getText();
				}
				result.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, parameter));
			}

			@Override
			public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
				result.add(new JQLPlaceHolder(JQLPlaceHolderType.DYNAMIC_SQL, ctx.bind_parameter_name().getText()));
			}

		});
		return result;
	}
758225
public static void checkQuery(SpiQuery<?> query, ListExpressionValidation validation, boolean ignoreUnknown) {
        if (query != null) {
            validate(query.getWhereExpressions(), validation, ignoreUnknown);
            validate(query.getHavingExpressions(), validation, ignoreUnknown);
            validate(query.getOrderBy(), validation, ignoreUnknown);

            Set<String> invalid = validation.getUnknownProperties();

            if (!ignoreUnknown && !invalid.isEmpty()) {
                UnprocessableEntityException.throwQuery(invalid);
            }
        }
    }
530878
public boolean is(String query) {
        Evaluator eval = QueryParser.parse(query);
        for (Element e : this) {
            if (e.is(eval))
                return true;
        }
        return false;
    }
546744
public static String checkPermitted(String sql)
    {
        /*
         *  IMPORTANT: Black-lists are checked first because they know more about
         * what they don't like about a statement and can provide a better message.
         * It requires that black-lists patterns be very selective and that they
         * don't mind seeing statements that wouldn't pass the white-lists.
         */

        //=== Check against blacklists, must not be rejected by any.

        for (CheckedPattern cp : BLACKLISTS) {
            CheckedPattern.Result result = cp.check(sql);
            if (result.matcher != null) {
                return String.format("%s, in statement: %s", result.explanation, sql);
            }
        }

        //=== Check against whitelists, must be accepted by at least one.

        boolean hadWLMatch = false;
        for (CheckedPattern cp : WHITELISTS) {
            if (cp.matches(sql)) {
                hadWLMatch = true;
                break;
            }
        }
        if (!hadWLMatch) {
            return String.format("AdHoc DDL contains an unsupported statement: %s", sql);
        }

        // The statement is permitted.
        return null;
    }