Skip to content

Commit

Permalink
Merge branch 'StanAccy-feature-query-unique'
Browse files Browse the repository at this point in the history
  • Loading branch information
aaberg committed Apr 13, 2024
2 parents f274552 + 36c8706 commit a568c5f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
20 changes: 20 additions & 0 deletions core/src/main/java/org/sql2o/Query.java
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,26 @@ public ResultSetHandler<T> newResultSetHandler(ResultSetMetaData resultSetMetaDa
};
}

public <T> T executeAndFetchUnique(Class<T> returnType){
return executeAndFetchUnique( newResultSetHandlerFactory( returnType ) );
}

public <T> T executeAndFetchUnique(ResultSetHandler<T> resultSetHandler){
return executeAndFetchUnique( newResultSetHandlerFactory( resultSetHandler ) );
}

public <T> T executeAndFetchUnique(ResultSetHandlerFactory<T> factory) {
List<T> list = executeAndFetch( factory );
int size = list.size();
if( size > 1 ) {
throw new Sql2oException( "Expected 0..1 results, found: " + list.size() );
}
if( size == 0 ){
return null;
}
return list.get( 0 );
}

public <T> List<T> executeAndFetch(Class<T> returnType){
if (returnType.isPrimitive() || Arrays.stream(primitives).anyMatch(n -> returnType.equals(n)))
{
Expand Down
27 changes: 27 additions & 0 deletions core/src/test/java/org/sql2o/Sql2oTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,33 @@ public void testExecuteAndFetch(){
deleteUserTable();
}

@Test
public void testExecuteAndFetchUniqueWhenUnique(){
createAndFillUserTable();

try (Connection con = sql2o.open()) {

User user = con.createQuery("select * from user_table u where u.id = 1").executeAndFetchUnique(User.class);

assertNotNull(user);
}

deleteUserTable();
}

@Test(expected = Sql2oException.class)
public void testExecuteAndFetchUniqueWhenNotUnique(){
createAndFillUserTable();

try (Connection con = sql2o.open()) {

User user = con.createQuery("select * from user_table u where u.id > 0").executeAndFetchUnique(User.class);
}
finally {
deleteUserTable();
}
}

@Test
public void testExecuteAndFetchWithNulls(){
String sql =
Expand Down

0 comments on commit a568c5f

Please sign in to comment.