Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Methods on Query

  • Loading branch information...
commit 15f99e2c376223121c6a16085a1c3f84c6198a57 1 parent 77c6961
@poetix poetix authored
View
6 src/main/java/com/youdevise/hsd/Query.java
@@ -1,6 +1,9 @@
package com.youdevise.hsd;
import java.sql.Connection;
+import java.util.List;
+
+import com.google.common.collect.Lists;
public class Query {
@@ -15,4 +18,7 @@ public Query(String sql, Object[] parameters) {
public QueryResult execute(Connection connection) {
return new QueryResult(sql, parameters, connection);
}
+
+ public String sql() { return sql; }
+ public List<Object> parameters() { return Lists.newArrayList(parameters); }
}
View
26 src/main/java/com/youdevise/hsd/QueryType.java
@@ -0,0 +1,26 @@
+package com.youdevise.hsd;
+
+public enum QueryType {
+ SELECT("select"),
+ INSERT("insert"),
+ UPDATE("update"),
+ DELETE("delete");
+
+ private String keyword;
+ private QueryType(String keyword) {
+ this.keyword = keyword;
+ }
+
+ public boolean matches(String sql) {
+ return sql.trim().toLowerCase().startsWith(keyword);
+ }
+
+ public static QueryType forSql(String sql) {
+ for (QueryType queryType : QueryType.values()) {
+ if (queryType.matches(sql)) {
+ return queryType;
+ }
+ }
+ throw new IllegalArgumentException("Query type not recognised for query: " + sql);
+ }
+}
View
28 src/test/java/com/youdevise/hsd/QueryTest.java
@@ -58,4 +58,32 @@
assertThat(result, is(true));
}
+ @Test public void
+ insert_statement_returns_generated_keys() throws SQLException {
+ final String sql = "INSERT INTO xyzzy (foo, bar) VALUES (?, ?)";
+ final Object[] parameters = new Object[] { "foo", 12 };
+ Query query = new Query(sql, parameters);
+
+ context.checking(new Expectations() {{
+ oneOf(connection).prepareStatement(sql); will(returnValue(statement));
+ oneOf(statement).setObject(1, "foo");
+ oneOf(statement).setObject(2, 12);
+
+ allowing(statement).execute(); will(returnValue(false));
+ allowing(statement).getGeneratedKeys(); will(returnValue(resultSet));
+
+ final Sequence recordIteration = context.sequence("recordIteration");
+ oneOf(resultSet).next(); will(returnValue(true)); inSequence(recordIteration);
+ oneOf(handler).handle(resultSet); will(returnValue(true)); inSequence(recordIteration);
+ oneOf(resultSet).next(); will(returnValue(false)); inSequence(recordIteration);
+
+ oneOf(resultSet).close();
+ oneOf(statement).close();
+ }});
+
+ boolean result = query.execute(connection).traverse(handler);
+ context.assertIsSatisfied();
+ assertThat(result, is(true));
+ }
+
}
Please sign in to comment.
Something went wrong with that request. Please try again.