构建SQL对象

@param query 原SQL语句
@param parameters 参数表

@return SQL对象
338892
public static Sql getSql(String query, Map<String, Object> parameters) {
		SqlBuilder builder = new SqlBuilder();
		String sql = builder.replaceVariables(query, parameters);
		return new Sql(sql, parameters);
	}
195543
public int countBySQL(String sql, List<?> params) {
        Object[] args = null;
        if (params == null) {
            args = new Object[0];
        } else {
            args = params.toArray(new Object[params.size()]);
        }
        return jdbcTemplate.queryForObject(sql, Integer.class, args);
    }
981533
public static Query setParameter(Query query, QueryParameterWrap parameterWrap){
		setBasicParameter(query, parameterWrap);
		setPageParameter(query, parameterWrap.getPageable());
		setResultTransformerType(query, parameterWrap.getResultTransformerType());
		return query;
	}
169999
public static String formatQuery(Map<String, String> params) {
        StringBuilder query = new StringBuilder();
        for (Entry<String, String> entry : params.entrySet()) {
            try {
                query.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                .append("&");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return query.deleteCharAt(query.length() - 1).toString();
    }
659234
public function fetchCol($query, array $parameters = array())
    {
        $parameters = $this->parameterTransformer->transform($parameters);
        return $this->db->fetchCol($query, $parameters);
    }
932873
@Override
    public Map<String, Object> getQueryParameters() {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("userId", this.userId.toString());
        params.put("itemId", this.itemId.toString());
        if (this.timestamp!=null) {
            params.put("timestamp", Double.toString(this.timestamp.getTime()/1000.0));
        }
        return params;
    }
540915
public <T>
    Query<T> build(
                    final Query<T> query,
                    final QueryParams params
                    )
    {
//        query.disableValidation();

        for (String  key : params.keys()) {
            Handler  handler = _getHandler( key );
            String  field = _getField( key );
            String  value = params.get( key );

            if (CommonQueryParams.Key.ORDER.equalsIgnoreCase( key )) {
                value = _convertOrderingFields( value );
            }

            handler.build( query, field, value );
        }

        return query;
    }
125385
public static List<String> findParamsInQuery(String query, boolean changeToLower) {
		List<String> result = new ArrayList<>();

		Matcher matcher = PARAM_PATTERN.matcher(query);

		while (matcher.find()) {
			if (matcher.group("PARAM") != null) {
				String param;
				if (changeToLower) {
					param = matcher.group("PARAM").toLowerCase();
				} else {
					param = matcher.group("PARAM");
				}

				if (!result.contains(param)) {
					result.add(param);
				}
			}
		}

		return result;
	}
897197
private String replaceVariables(String query, Map<String, Object> parameters) {
		if (StringUtils.isNotEmpty(query)) {
			try {
				if (parameters != null) {
					// 执行变量替换, 变量格式为:var
					Set<String> keySet = parameters.keySet();
					for (String key : keySet) {
						Object value = parameters.get(key);

						if (value instanceof String) {
							value = String.format("'%s'", value);
						} else if (value instanceof List) {
							StringBuffer valueBuffer = new StringBuffer();

							List<?> list = (List<?>) value;
							for (Object item : list) {
								if (item instanceof String) {
									valueBuffer.append(String.format("'%s'", item) + ",");
								} else {
									valueBuffer.append(item.toString() + ",");
								}
							}
							value = StringUtils.removeEnd(valueBuffer.toString(), ",");
						} else if (value == null) {
							continue;
						} else if (value instanceof Date) {
							value = String.format("'%s'", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value));
						} else {
							value = value.toString();
						}

						key = ":" + key;
						query = StringUtils.replace(query, key, (String) value);
					}
				}

				// 多个空格替换为单个空格
				if (query != null) {
					query = query.replaceAll(" +", " ");
				}
			} catch (Exception e) {
				return null;
			}
		}

		return query;
	}
94683
public String toSql(boolean showParameters) {
        String sql;
        if(forPaginator){
            sql = metaModel.getDialect().formSelect(null, null, fullQuery, orderBys, limit, offset);
        }else{
            sql = fullQuery != null ? fullQuery
                    : metaModel.getDialect().formSelect(metaModel.getTableName(), null, subQuery, orderBys, limit, offset);
        }
        if (showParameters) {
            StringBuilder sb = new StringBuilder(sql).append(", with parameters: ");
            join(sb, params, ", ");
            sql = sb.toString();
        }
        return sql;
    }
364822
public Sql getSQLByNameWithParameters(String name, Object parameters) {
		if (name == null) {
			return null;
		}

		Map<String, Object> parameterMap = buildParameters(parameters);

		SqlObject sqlObj = this.sqlMap.get(name);
		if (sqlObj != null) {

			if (sqlObj.isPrepare() == false || (this.varMap.containsKey("prepare") == false && "false".equalsIgnoreCase(this.varMap.get("prepare")))) {
				String sql = replaceSQL(sqlObj, parameterMap);
				return new Sql(sql, parameterMap);
			} else {
				String sql = replaceChoose(sqlObj, parameterMap);
				if (sqlObj instanceof ProcedureObject) {
					ProcedureObject procedureObj = (ProcedureObject)sqlObj;
					List<Out> outList = procedureObj.getOut();
					for (Out out : outList) {
						parameterMap.put(out.getName(), out);
					}
				}
				return getPreperSQLWithParameters(sql, parameterMap);
			}
		} else {
			return null;
		}
	}
1094398
public String getQuery(boolean withParams) {
        if (withParams) {
            StringBuffer sql = new StringBuffer(query);
            for (Object param : params) {
                int index = sql.indexOf("?");

                // 日期
                StringBuffer str;
                if (param instanceof Time) {
                    str = new StringBuffer(new SimpleDateFormat("HH:mm:ss").format(param));
                } else if (param instanceof Date || param instanceof java.sql.Date) {
                    str = new StringBuffer(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(param));
                } else {
                    str = new StringBuffer(param.toString());
                }

                // 非数字
                if (!(param instanceof Number)) {
                    str.insert(0, "'");
                    str.append("'");
                }
                sql.replace(index, index + 1, str.toString());
            }
            return sql.toString();
        } else {
            return getQuery();
        }
    }
1183551
public static HashMap<String, String> getParameters(String query) {
        HashMap<String, String> params = new HashMap<String, String>();
        if (query == null || query.length() == 0) {
            return params;
        }

        String[] splitQuery = query.split("&");
        for (String splitItem : splitQuery) {
            String[] items = splitItem.split("=");

            if (items.length == 1) {
                params.put(items[0], "");
            } else {
                params.put(items[0], items[1]);
            }
        }

        return params;
    }
106302
public static Map<String, String> parseQuery(String query) {
		Map<String, String> result = new LinkedHashMap<String, String>();
		
		if (query != null) {
			for (String keyValue: query.split("&")) {
				String[] pair = keyValue.split("=");
				result.put(StringUtils.urlDecode(pair[0]), StringUtils.urlDecode(pair[1]));
			}
		}
		
		return result;
	}
1290479
public static Map<String, String> queryToParams(String query) throws UnsupportedEncodingException {
		Map<String, String> query_pairs = new HashMap<String, String>();
		String[] pairs = query.split("&");
		for (String pair : pairs) {
			int idx = pair.indexOf("=");
			query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
					URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
		}
		return query_pairs;
	}
1257278
public QueryFilter withQuery(String query) {
        try {
            String encodedQuery = urlEncode(query);
            parameters.put(KEY_QUERY, encodedQuery);
            return this;
        } catch (UnsupportedEncodingException ex) {
            //"Every implementation of the Java platform is required to support the following standard charsets [...]: UTF-8"
            //cf. https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html
            throw new IllegalStateException("UTF-8 encoding not supported by current Java platform implementation.", ex);
        }
    }
265313
public SqlPara getSqlPara(String key, Object... paras) {
		Template template = getSqlTemplate(key);
		if (template == null) {
			return null;
		}
		
		SqlPara sqlPara = new SqlPara();
		Map data = new HashMap();
		data.put(SQL_PARA_KEY, sqlPara);
		data.put(PARA_ARRAY_KEY, paras);
		sqlPara.setSql(template.renderToString(data));
		// data 为本方法中创建，不会污染用户数据，无需移除 SQL_PARA_KEY、PARA_ARRAY_KEY
		return sqlPara;
	}