Parse the sql and return an SqlStatement.

@param sql A String contianing the sql to parse.
@return A SqlStatement instance.
425305
public SqlStatement parse(String sql) {

        // does a cached parse result exist for this statement?
        if (_cachedSqlStatements.containsKey(sql)) {
            return _cachedSqlStatements.get(sql);
        }

        SqlGrammar _parser = new SqlGrammar(new StringReader(sql));
        SqlStatement parsed = null;
        try {
            parsed = _parser.parse();
        } catch (ParseException e) {
            throw new ControlException("Error parsing SQL statment." + e.getMessage(), e);
        } catch (TokenMgrError tme) {
            throw new ControlException("Error parsing SQL statment. " + tme.getMessage(), tme);
        }

        if (parsed.isCacheable()) {
            _cachedSqlStatements.put(sql, parsed);
        }
        return parsed;
    }
326157
public String subQuery(String sql) {
    if (options.maxQuerySizeToLog > 0 && sql.length() > options.maxQuerySizeToLog - 3) {
      return sql.substring(0, options.maxQuerySizeToLog - 3) + "...";
    }
    return sql;
  }
144128
protected PreparedStatement createStatment(Connection conn, Sql sql) throws SQLException {

		if (sql == null) {
			throw new NullPointerException("Sql Object is NULL");
		}
		String sqlBody = sql.getSql();

		if (StringUtils.isNotEmpty(sqlBody)) {
			PreparedStatement stmt = null;
			if (sql.isProcedure()) {
				stmt = conn.prepareCall("{" + sqlBody + "}");
			} else if (sql.isPreperStatement()) {
				stmt = conn.prepareStatement(sqlBody);
			}
			
			if (stmt != null) {
				Map<Integer, Object> prepareValues = sql.getPreperValues();
	
				Set<Integer> indexSet = prepareValues.keySet();
				for (Integer index : indexSet) {
					Object value = prepareValues.get(index);
					if (index != null && value != null) {
						if (value instanceof String) {
							stmt.setString(index, value.toString());
						} else if (value instanceof Integer) {
							stmt.setInt(index, ((Integer) value).intValue());
						} else if (value instanceof Long) {
							stmt.setLong(index, ((Long) value).longValue());
						} else if (value instanceof Double) {
							stmt.setDouble(index, ((Double) value).doubleValue());
						} else if (value instanceof Float) {
							stmt.setFloat(index, ((Float) value).floatValue());
						} else if (value instanceof Short) {
							stmt.setShort(index, ((Short) value).shortValue());
						} else if (value instanceof Byte) {
							stmt.setByte(index, ((Byte) value).byteValue());
						} else if (value instanceof Boolean) {
							stmt.setBoolean(index, ((Boolean) value).booleanValue());
						} else if (value instanceof Date) {
							stmt.setDate(index, (Date) value);
						} else if (value instanceof Time) {
							stmt.setTime(index, (Time) value, Calendar.getInstance());
						} else if (value instanceof Blob) {
							stmt.setBlob(index, (Blob) value);
						} else if (value instanceof Clob) {
							stmt.setClob(index, (Clob) value);
						} else if (value instanceof BigDecimal) {
							stmt.setBigDecimal(index, (BigDecimal) value);
						} else if (value instanceof byte[]) {
							stmt.setBytes(index, (byte[]) value);
						} else if (value instanceof Out) {
							if (stmt instanceof CallableStatement) {
								int outType = getProcedureOutType((Out)value);
								if (outType != -999) {
									((CallableStatement)stmt).registerOutParameter(index, outType);
								}
							}
						} else {
							stmt.setObject(index, value);
						}
					}
				}
				return stmt;
			} else {
				return conn.prepareStatement(sqlBody);
			}
		}
1185511
public Set<String> getTable(String sql) {
		Set<String> tableSet = new HashSet<String>();
		
		try {
			Statement statement = parserManager.parse(new StringReader(sql));
			
			if (statement instanceof Select) {
				tableSet = new SelectParser().parse((Select)statement);
			} else if (statement instanceof Delete) {
				tableSet = new DeleteParser().parse((Delete)statement);
			} else if (statement instanceof Insert) {
				tableSet = new InsertParser().parse((Insert)statement);
			} else if (statement instanceof Update) {
				tableSet = new UpdateParser().parse((Update)statement);
			} else if (statement instanceof CreateTable) {
				tableSet = new CreateTableParser().parse((CreateTable)statement);
			} else if (statement instanceof CreateView) {
				tableSet = new CreateViewParser().parse((CreateView)statement);
			} else if (statement instanceof Alter) {
				tableSet = new AlterParser().parse((Alter)statement);
			} else if (statement instanceof Drop) {
				tableSet = new DropParser().parse((Drop)statement);
			}
		} catch (Exception e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		} catch (Error e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		}
		
		Set<String> resultSet = new HashSet<String>();
		for (String tableName : tableSet) {
			if (StringUtils.isNotEmpty(tableName)) {
				if (tableName.startsWith("`")) {
					tableName = tableName.substring(1);
				}
				if (tableName.endsWith("`")) {
					tableName = tableName.substring(0, tableName.length() - 1);
				}
				resultSet.add(tableName.toUpperCase());
			}
		}
		
		return resultSet;
	}
561940
public ServerSidePreparedStatement serverPrepareStatement(final String sql)
      throws SQLException {
    return new ServerSidePreparedStatement(this,
        sql,
        ResultSet.TYPE_FORWARD_ONLY,
        ResultSet.CONCUR_READ_ONLY,
        Statement.RETURN_GENERATED_KEYS);
  }
970381
public boolean execute(Sql sql) throws SQLException {
		
		long start =  System.currentTimeMillis();
		
		if (sql.validate() == false) {
			return false;
		}
		
		boolean result = false;
		
		PreparedStatement stmt = null;
		try {
			stmt = this.createStatment(conn, sql);
			stmt.execute();
			
			result = true;
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
		logger.debug(String.format("Execute %s used %d ms", sql.getSql(), System.currentTimeMillis() - start));

		return result;
	}
988620
protected void executeSQL(String sql){
		Connection conn = null;
		Statement stmt = null;
		
		if (useAnt){
			try{
				AntSqlExec sqlExec = new AntSqlExec(dataSource, sql, delimiter, delimiterType);
				sqlExec.execute();
				log.info("SQL executed with Ant: " + sql);
			}catch(BuildException be){
				throw new RuntimeException("Failed to execute SQL with Ant (" + be.getMessage() + "): " + sql, be);
			}
		}else{
			try {
				conn = dataSource.getConnection();
				stmt = conn.createStatement();
				stmt.execute(sql);
				log.info("SQL executed: " + sql);
			}catch(SQLException sqle){
				throw new RuntimeException("Failed to execute SQL (" + sqle.getMessage() + "): " + sql, sqle);
			}finally{
				ConnectionUtility.closeConnection(conn, stmt);
			}
		}
	}
253947
public static String getWhereClause (String sql) {
        if (null == sql ) return null;

        String s = sql.trim();
        int len = s.length();
        int last = s.lastIndexOf("AND");
        if (len > 0 && (last == len -3)) {
            if (s.indexOf("WHERE") == -1) {
                s = "WHERE " + s.substring(0,len-3);
            } else {
                s = s.substring(0,len-3);
            }
        }
        return s;
    }
438629
public int queryForInt(String sql) throws SQLException {
		Number number = queryForObject(sql, Integer.class);
		return (number != null ? number.intValue() : 0);
	}
831235
@NotNull
    protected static String parse(@NotNull String sql, @NotNull Map<String, List<Integer>> paramMap) {
        int length = sql.length();
        StringBuilder parsedQuery = new StringBuilder(length);
        boolean inSingleQuote = false;
        boolean inDoubleQuote = false;
        int index = 1;

        for (int i = 0; i < length; i++) {
            char c = sql.charAt(i);
            if (inSingleQuote) {
                if (c == '\'') {
                    inSingleQuote = false;
                }
            } else if (inDoubleQuote) {
                if (c == '"') {
                    inDoubleQuote = false;
                }
            } else {
                if (c == '\'') {
                    inSingleQuote = true;
                } else {
                    if (c == '"') {
                        inDoubleQuote = true;
                    } else {
                        if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(sql.charAt(i + 1))) {
                            int j = i + 2;
                            while (j < length && Character.isJavaIdentifierPart(sql.charAt(j))) {
                                j++;
                            }
                            String name = sql.substring(i + 1, j);
                            c = '?'; // replace the parameter with a question mark
                            i += name.length(); // skip past the end if the parameter

                            List<Integer> indexList = paramMap.computeIfAbsent(name, k -> new ArrayList<>());
                            indexList.add(index);

                            index++;
                        }
                    }
                }
            }
            parsedQuery.append(c);
        }
        return parsedQuery.toString();
    }
959998
private SQLExpression parseExpression(final SQLStatement sqlStatement) {
        String literals = lexerEngine.getCurrentToken().getLiterals();
        final int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - literals.length();
        final SQLExpression expression = getExpression(literals, sqlStatement);
        lexerEngine.nextToken();
        if (lexerEngine.skipIfEqual(Symbol.DOT)) {
            String property = lexerEngine.getCurrentToken().getLiterals();
            lexerEngine.nextToken();
            return skipIfCompositeExpression(sqlStatement)
                    ? new SQLIgnoreExpression(lexerEngine.getInput().substring(beginPosition, lexerEngine.getCurrentToken().getEndPosition()))
                    : new SQLPropertyExpression(new SQLIdentifierExpression(literals), property);
        }
        if (lexerEngine.equalAny(Symbol.LEFT_PAREN)) {
            lexerEngine.skipParentheses(sqlStatement);
            skipRestCompositeExpression(sqlStatement);
            return new SQLIgnoreExpression(lexerEngine.getInput().substring(beginPosition,
                    lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length()).trim());
        }
        return skipIfCompositeExpression(sqlStatement)
                ? new SQLIgnoreExpression(lexerEngine.getInput().substring(beginPosition, lexerEngine.getCurrentToken().getEndPosition())) : expression;
    }
104823
public static QueryAction create(Client client, String sql) throws SqlParseException, SQLFeatureNotSupportedException {
		sql = sql.replaceAll("\n"," ");
        String firstWord = sql.substring(0, sql.indexOf(' '));
        switch (firstWord.toUpperCase()) {
			case "SELECT":
			    //zhongshu-comment 将sql字符串解析成AST，即SQLQueryExpr sqlExpr就是AST了，下面的代码就开始访问AST、从中获取token
				SQLQueryExpr sqlExpr = (SQLQueryExpr) toSqlExpr(sql);
                if(isMulti(sqlExpr)){//zhongshu-comment 判断是不是union查询，union查询两个select语句，btw：子查询也有多个select语句，至少2个
                    MultiQuerySelect multiSelect = new SqlParser().parseMultiSelect((SQLUnionQuery) sqlExpr.getSubQuery().getQuery());
                    handleSubQueries(client,multiSelect.getFirstSelect());
                    handleSubQueries(client,multiSelect.getSecondSelect());
                    return new MultiQueryAction(client, multiSelect);
                }
                else if(isJoin(sqlExpr,sql)){//zhongshu-comment join连接查询
                    JoinSelect joinSelect = new SqlParser().parseJoinSelect(sqlExpr);
                    handleSubQueries(client, joinSelect.getFirstTable());
                    handleSubQueries(client, joinSelect.getSecondTable());
                    return ESJoinQueryActionFactory.createJoinAction(client, joinSelect);
                }
                else {
                    //zhongshu-comment 大部分查询都是走这个分支，先看懂这个分支
                    Select select = new SqlParser().parseSelect(sqlExpr);
                    //todo 看不懂，测试了好几个常见的sql，都没有进去handleSubQueries该方法，那就先不理了，看别的
                    handleSubQueries(client, select);
                    return handleSelect(client, select);
                }
			case "DELETE":
                SQLStatementParser parser = createSqlStatementParser(sql);
				SQLDeleteStatement deleteStatement = parser.parseDeleteStatement();
				Delete delete = new SqlParser().parseDelete(deleteStatement);
				return new DeleteQueryAction(client, delete);
            case "SHOW":
                return new ShowQueryAction(client,sql);
			default:
				throw new SQLFeatureNotSupportedException(String.format("Unsupported query: %s", sql));
		}
	}
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]
1109901
public Map<String, Object> selectOne(String sql) {
        List<Map<String, Object>> list = selectList(sql);
        return getOne(list);
    }
650434
private void execute(String sql) throws SQLException {
        Statement statement = connection.createStatement();
        try {
            statement.executeUpdate(substitute(sql));
        } finally {
            DbUtils.closeQuietly(statement);
        }
    }
1094228
private void get(final StringBuilder sql) {
        sql.append("SELECT * FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = ?");
    }
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();
    }