99 lines
2.7 KiB
Java
99 lines
2.7 KiB
Java
package com.cubetiqs.sql;
|
|
|
|
import java.util.*;
|
|
|
|
public class SqlMapParameter implements ISqlMapParameter {
|
|
private final String sql;
|
|
private final Map<String, Object> params = new HashMap<>();
|
|
|
|
// Replace all ":variableName" with "?"
|
|
private String formatSql;
|
|
|
|
// Allow ignoring validate the missing key, when the params doesn't exist in sql statement
|
|
private final boolean ignoreMissingKey;
|
|
|
|
public SqlMapParameter(final String sql) {
|
|
this.sql = sql;
|
|
this.ignoreMissingKey = false;
|
|
}
|
|
|
|
public SqlMapParameter(final String sql, final boolean ignoreMissingKey) {
|
|
this.sql = sql;
|
|
this.ignoreMissingKey = ignoreMissingKey;
|
|
}
|
|
|
|
public SqlMapParameter addParam(final String key, final Object value) {
|
|
params.put(key, value);
|
|
return this;
|
|
}
|
|
|
|
public SqlMapParameter addParams(final Map<String, Object> values) {
|
|
params.putAll(values);
|
|
return this;
|
|
}
|
|
|
|
@Override
|
|
public Map<String, Object> getParams() {
|
|
return params;
|
|
}
|
|
|
|
@Override
|
|
public String getSql() {
|
|
return sql;
|
|
}
|
|
|
|
@Override
|
|
public String getFormatSql() {
|
|
return formatSql;
|
|
}
|
|
|
|
@Override
|
|
public Object[] getSqlArgs() {
|
|
if (sql == null || sql.equals("")) {
|
|
return null;
|
|
}
|
|
|
|
if (params.size() == 0) {
|
|
return null;
|
|
}
|
|
|
|
List<String> keys = ResultSetUtil.findValues(sql, ":", null, false);
|
|
Set<String> keySet = new HashSet<>(keys);
|
|
if (keySet.size() > 0 && keySet.size() > params.size()) {
|
|
System.out.println("Found Keys = " + keys + ", KeySet = " + keySet + ", Params = " + params);
|
|
throw new IllegalArgumentException("Parameter not matched with keys size!");
|
|
} else {
|
|
if (!ignoreMissingKey) {
|
|
// validate the keys
|
|
keys.forEach(key -> {
|
|
if (!params.containsKey(key)) {
|
|
throw new IllegalArgumentException("Missing key '" + key + "' in args!");
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
Object[] args = new Object[keys.size()];
|
|
|
|
for (int i = 0; i < args.length; i++) {
|
|
args[i] = params.get(keys.get(i));
|
|
}
|
|
|
|
Map<String, Object> replacement = new HashMap<>();
|
|
for (String key : keys) {
|
|
replacement.put(key, "?");
|
|
}
|
|
|
|
formatSql = ResultSetUtil.replacerPrefix(sql, replacement, ":");
|
|
return args;
|
|
}
|
|
|
|
public static SqlMapParameter create(final String sql) {
|
|
return new SqlMapParameter(sql);
|
|
}
|
|
|
|
public static SqlMapParameter create(final String sql, final boolean ignoreMissingKey) {
|
|
return new SqlMapParameter(sql, ignoreMissingKey);
|
|
}
|
|
}
|