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

org.fluentjdbc.DatabaseWhereBuilder Maven / Gradle / Ivy

There is a newer version: 0.5.3
Show newest version
package org.fluentjdbc;

import javax.annotation.CheckReturnValue;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Used to build the WHERE ... clause of SQL statements such as SELECT, UPDATE and DELETE.
 * Add clauses with {@link #where(String, Object)}, {@link #whereIn(String, Collection)} etc. Then
 * get the string for the WHERE clause with {@link #whereClause()} and the parameters with {@link #getParameters()}
 */
@ParametersAreNonnullByDefault
public class DatabaseWhereBuilder implements DatabaseQueryable {

    private final List conditions = new ArrayList<>();
    private final List parameters = new ArrayList<>();

    /**
     * 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 DatabaseWhereBuilder whereExpressionWithParameterList(String expression, Collection parameters) {
        this.conditions.add("(" + expression + ")");
        this.parameters.addAll(parameters);
        return this;
    }

    /**
     * Implemented as return this for compatibility purposes
     */
    @Override
    public DatabaseWhereBuilder query() {
        return this;
    }

    /**
     * If any conditions were added, returns WHERE condition1 AND condition2 AND condition2 ....
     * If no conditions were added, returns the empty string
     */
    @CheckReturnValue
    public String whereClause() {
        return conditions.isEmpty() ? "" : " WHERE " + String.join(" AND ", conditions);
    }

    /**
     * Returns all parameters added with .whereXXX() method calls
     */
    @CheckReturnValue
    public List getParameters() {
        return parameters;
    }
}