All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.fluentjdbc.DbContextSqlBuilder Maven / Gradle / Ivy

package org.fluentjdbc;

import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import java.sql.Connection;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Used to construct SQL SELECT statements in a flexible way with {@link #where(String, Object)}
 * clauses, {@link #select(String...)} column names, {@link #from(String)} table statement,
 * {@link #groupBy(String...)}, {@link #orderBy(String)} and {@link #skipAndLimit(int, int)}.
 *
 * Example:
 *
 * 
 * new DbContextSqlBuilder(dbContext)
 *      .select("first_name", "last_name")
 *      .select("p.id")
 *      .from("person p full join organizations o")
 *      .where("organization_sector", sector)
 *      .limit(100)
 *      .list(row -> List.of(row.getString("first_name"), row.getString("last_name"), row.getUUID("p.id"));
 * 
* */ public class DbContextSqlBuilder implements DbContextListableSelect { private final DatabaseSqlBuilder builder; private final DbContext dbContext; public DbContextSqlBuilder(DbContext dbContext) { this.dbContext = dbContext; builder = new DatabaseSqlBuilder(dbContext.getStatementFactory()); } /** * Implemented as return this for compatibility purposes */ @Override public DbContextSqlBuilder query() { return this; } /** * Add the arguments to the column list for the SELECT column, column... statement */ @CheckReturnValue public DbContextSqlBuilder select(String... columns) { return query(builder.select(columns)); } /** * Replace the from part of the SELECT ... FROM fromStatement in the select statement */ @CheckReturnValue public DbContextSqlBuilder from(String fromStatement) { return query(builder.from(fromStatement)); } /** * Adds the expression to the WHERE-clause and all the values to the parameter list. * E.g. whereExpressionWithParameterList("created_at between ? and ?", List.of(earliestDate, latestDate)) */ @Override public DbContextSqlBuilder whereExpressionWithParameterList(String expression, Collection parameters) { return query(builder.whereExpressionWithParameterList(expression, parameters)); } /** * Add the arguments to the column list for the SELECT ... FROM ... ... GROUP BY groupByStatement statement */ @CheckReturnValue public DbContextSqlBuilder groupBy(String... groupByStatement) { return query(builder.groupBy(groupByStatement)); } /** * Adds ORDER BY ... clause to the SELECT statement */ @Override public DbContextSqlBuilder orderBy(String orderByClause) { return query(builder.orderBy(orderByClause)); } /** * If you haven't called {@link #orderBy}, the results of {@link DatabaseListableQueryBuilder#list} * will be unpredictable. Call unordered() if you are okay with this. */ @CheckReturnValue public DbContextSqlBuilder unordered() { return query(builder.unordered()); } /** * Adds OFFSET ... ROWS FETCH ... ROWS ONLY clause to the SELECT * statement. FETCH FIRST was introduced in * SQL:2008 * and is supported by Postgresql 8.4, Oracle 12c, IBM DB2, HSQLDB, H2, and SQL Server 2012. */ @Override public DbContextSqlBuilder skipAndLimit(int offset, int rowCount) { return query(builder.skipAndLimit(offset, rowCount)); } /** * Execute the query and map each return value over the {@link DatabaseResult.RowMapper} function to return a stream. Example: *
     *     table.where("status", status).stream(row -> row.getInstant("created_at"))
     * 
*/ @Override public Stream stream(DatabaseResult.RowMapper mapper) { return builder.stream(getConnection(), mapper); } /** * Execute the query and map each return value over the {@link DatabaseResult.RowMapper} function to return a list. Example: *
     *     List<Instant> creationTimes = table.where("status", status).list(row -> row.getInstant("created_at"))
     * 
*/ @Override public List list(DatabaseResult.RowMapper mapper) { return builder.list(getConnection(), mapper); } /** * Executes SELECT count(*) FROM ... on the query and returns the result */ @Override public int getCount() { return builder.getCount(getConnection()); } /** * If the query returns no rows, returns {@link Optional#empty()}, if exactly one row is returned, maps it and return it, * if more than one is returned, throws `IllegalStateException` * * @param mapper Function object to map a single returned row to a object * @return the mapped row if one row is returned, Optional.empty otherwise * @throws IllegalStateException if more than one row was matched the the query */ @Nonnull @Override public Optional singleObject(DatabaseResult.RowMapper mapper) { return builder.singleObject(getConnection(), mapper); } /** * Executes the SELECT * FROM ... statement and calls back to * {@link DatabaseResult.RowConsumer} for each returned row */ @Override public void forEach(DatabaseResult.RowConsumer consumer) { builder.forEach(getConnection(), consumer); } @SuppressWarnings("unused") private DbContextSqlBuilder query(DatabaseSqlBuilder builder) { return this; } @Nonnull private Connection getConnection() { return dbContext.getThreadConnection(); } }