import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import net.jaekl.cfb.db.Column;
import net.jaekl.cfb.db.Column.Type;
+import net.jaekl.cfb.db.Condition;
+import net.jaekl.cfb.db.Row;
+import net.jaekl.cfb.db.Sequence;
import net.jaekl.cfb.db.Table;
public abstract class DbDriver {
return true;
}
- public abstract ResultSet selectColumnsFromWhere(Column[] columns, Table[] tables, String where);
+ public boolean createSequence(Connection con, Sequence seq) throws SQLException
+ {
+ String sql = createSequenceSql(seq);
+ try (PreparedStatement ps = con.prepareStatement(sql)) {
+ ps.executeUpdate();
+ }
+ catch (SQLException exc) {
+ throw new SQLException("Failed to executeUpdate: " + sql, exc);
+ }
+
+ return true;
+ }
+
+ public List<Row> select(Connection con, Column[] columns, Table[] tables, Condition[] conditions)
+ throws SQLException
+ {
+ String sql = selectSql(columns, tables, conditions);
+ ArrayList<Row> result = new ArrayList<Row>();
+
+ try (PreparedStatement ps = con.prepareStatement(sql)) {
+ int index = 0;
+ for (Condition condition : conditions) {
+ if (condition.getOperation().hasParam()) {
+ index++;
+ ps.setObject(index, condition.getValue());
+ }
+ }
+
+ try (ResultSet rs = ps.executeQuery()) {
+ while (rs.next()) {
+ Object[] values = new Object[columns.length];
+ for (index = 0; index < columns.length; ++index) {
+ values[index] = rs.getObject(index);
+ }
+ Row row = new Row(columns, values);
+ result.add(row);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ protected String selectSql(Column[] columns, Table[] tables, Condition[] conditions)
+ {
+ StringBuilder sb = new StringBuilder("SELECT ");
+
+ boolean firstColumn = true;
+ for (Column column : columns) {
+ if (firstColumn) {
+ firstColumn = false;
+ }
+ else {
+ sb.append(", ");
+ }
+ sb.append(column.getName());
+ }
+
+ sb.append(" FROM ");
+
+ boolean firstTable = true;
+ for (Table table : tables) {
+ if (firstTable) {
+ firstTable = false;
+ }
+ else {
+ sb.append(", ");
+ }
+ sb.append(table.getName());
+ }
+
+ if (null != conditions && conditions.length > 0) {
+ sb.append(" WHERE ");
+
+ boolean firstCondition = true;
+
+ for (Condition condition : conditions) {
+ if (firstCondition) {
+ firstCondition = false;
+ }
+ else {
+ sb.append(" AND ");
+ }
+
+ sb.append(condition.getColumn().getName())
+ .append(condition.getOperation().getSql());
+ }
+ }
+
+ return sb.toString();
+ }
protected String typeName(Type type) {
return type.toString();
return sb.toString();
}
+
+ protected String createSequenceSql(Sequence seq) {
+ assert(null != seq);
+ assert(null != seq.getName());
+
+ return "CREATE SEQUENCE " + seq.getName();
+ }
}