buckelieg.fn.db.Select Maven / Gradle / Ivy
/*
* Copyright 2016- Anatoly Kutyakov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package buckelieg.fn.db;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static buckelieg.fn.db.Utils.*;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
/**
* An abstraction for SELECT statement
*/
@SuppressWarnings("unchecked")
@ParametersAreNonnullByDefault
public interface Select extends Query {
/**
* In cases when single result of SELECT statement is expected.
* Like SELECT COUNT(*) FROM TABLE_NAME etc...
*
* @param mapper ResultSet mapper function
* @throws NullPointerException if mapper is null
* @see #execute(TryFunction)
*/
@Nonnull
default Optional single(TryFunction mapper) {
T result;
try {
result = execute(mapper).iterator().next();
} catch (NoSuchElementException e) {
result = null;
} catch (Exception e) {
throw newSQLRuntimeException(e);
} finally {
close();
}
return ofNullable(result);
}
/**
* Executes SELECT statement for SINGLE result with default mapper applied
*
* @return a {@link Map} with key-value pairs
*/
@Nonnull
default Map single() {
return single(defaultMapper).orElse(Collections.emptyMap());
}
/**
* Stream abstraction over ResultSet.
* Note:
* Whenever we left stream without calling some 'reduction' (terminal) operation we left resource freeing to JDBC
* stream().iterator().next().get(...)
* Thus there could be none or some rows more, but result set (and a statement) would not be closed forcibly.
* In such cases we rely on JDBC resources auto closing mechanism.
* And it is strongly recommended to use single
method for the cases above.
*
* @return a {@link Stream} over {@link ResultSet}
* @see #single(TryFunction)
*/
@Nonnull
default Stream