com.datastax.data.dataset.provider.sql.AbstractSqlCommand Maven / Gradle / Ivy
The newest version!
package com.datastax.data.dataset.provider.sql;
import com.datastax.data.dataset.DataCommand;
import com.datastax.data.dataset.DataRow;
import java.sql.PreparedStatement;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractSqlCommand extends DataCommand {
private static final Logger LOG = Logger.getLogger(AbstractSqlCommand.class.getName());
protected abstract PreparedStatement getSelectStatement(JDBCDataConnection conn) throws Exception;
protected abstract PreparedStatement getInsertStatement(JDBCDataConnection conn, DataRow row) throws Exception;
protected abstract PreparedStatement getUpdateStatement(JDBCDataConnection conn, DataRow row) throws Exception;
protected abstract PreparedStatement getDeleteStatement(JDBCDataConnection conn, DataRow row) throws Exception;
protected String constructSql(String sql, Map> indexes) {
StringBuilder buffer = new StringBuilder(sql);
int paramIndex = 0;
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
for (int i=0; i= buffer.length()) {
found = true;
} else {
char next = buffer.charAt(i);
if (next == ' ' || next == '\n' || next == '\t' || next == '\r' || next == ',' || next == ')') {
found = true;
}
}
i++;
}
String paramName = buffer.substring(firstCharIndex+1, i-1);
buffer.replace(firstCharIndex, i-1, "?");
if (!indexes.containsKey(paramName)) {
indexes.put(paramName, new ArrayList());
}
List list = indexes.get(paramName);
list.add(paramIndex++);
i = firstCharIndex + 1;
}
}
return buffer.toString();
}
protected PreparedStatement prepareStatement(String sql, Map values, JDBCDataConnection conn) throws Exception {
Map> indexes = new HashMap>();
PreparedStatement ps = conn.prepareStatement(constructSql(sql, indexes));
for (String paramName : getParameterNames()) {
values.put(paramName, super.getParameter(paramName));
}
for (String paramName : getParameterNames(new String[]{sql})) {
List list = indexes.get(paramName);
if (list != null) {
for (int index : list) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Index: {0}, ParamName: {1}, ParamValue: {2}",
new Object[]{index + 1, paramName, values.get(paramName)});
}
ps.setObject(index + 1, values.get(paramName));
}
}
}
return ps;
}
public String[] getParameterNames(String[] statements) {
StringBuilder buffer = new StringBuilder();
for (String s : statements) {
buffer.append(s);
buffer.append("\n");
}
Set names = new HashSet();
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
for (int i=0; i= buffer.length()) {
found = true;
} else {
char next = buffer.charAt(i);
if (next == ' ' || next == '\n' || next == '\t' || next == '\r' || next == ',' || next == ')') {
found = true;
}
}
i++;
}
String paramName = buffer.substring(firstCharIndex+1, i-1);
names.add(paramName);
}
}
String[] results = new String[names.size()];
return names.toArray(results);
}
}