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

buckelieg.fn.db.Update 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.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;

import static buckelieg.fn.db.Utils.toOptional;

/**
 * An abstraction for INSERT/UPDATE/DELETE statements.
 * Returns affected rows by this query.
 * If this is a batch query then affected rows are summarized.
 */
@SuppressWarnings("unchecked")
@ParametersAreNonnullByDefault
public interface Update extends Query {

    /**
     * Executes this DML query returning affected row count.
     * If this query represents a batch then affected rows are summarized for all batches.
     *
     * @return affected rows count
     */
    @Nonnull
    Long execute();

    /**
     * Executes an update query providing generated results
     * Autogenerated keys columns are accessible via their indices inside generatedValuesHandler
     * Example:
     * {@code
     * stream(
     * stream -> stream.map(rs -> new Object[] {
     * rs.getLong(1),
     * rs.getString(2),
     * rs.getObject(3)
     * }).collect(Collectors.toList()),
     * )}
     *
     * @param generatedValuesHandler handler which operates on {@link ResultSet} with generated values
     * @return affected rows count
     * @throws NullPointerException if generatedValuesHandler is null
     * @see java.sql.Connection#prepareStatement(String, int) (where int is of Statement.RETURN_GENERATED_KEYS)
     */
    @Nonnull
    Long execute(TryConsumer, SQLException> generatedValuesHandler);

    /**
     * Executes an update query providing generated results.
     * Autogenerated keys columns are accessible via their names inside generatedValuesHandler
     * Example:
     * {@code
     * stream(
     * stream -> stream.map(rs -> new Object[] {
     * rs.getLong("id"),
     * rs.getString("hash"),
     * rs.getObject("myGeneratedValueColumn")
     * }).collect(Collectors.toList()),
     * "id", "hash", "myGeneratedValueColumn"
     * )}
     *
     * @param generatedValuesHandler handler which operates on {@link ResultSet} with generated values
     * @param colNames               column names with generated keys
     * @return affected rows count
     * @throws NullPointerException     if colNames or generatedValuesHandler is null
     * @throws IllegalArgumentException if colNames is empty
     * @see java.sql.Connection#prepareStatement(String, String[])
     */
    @Nonnull
    Long execute(TryConsumer, SQLException> generatedValuesHandler, String... colNames);

    /**
     * Executes an update query providing generated results
     * Autogenerated keys columns are accessible via their indices inside generatedValuesHandler
     * Example:
     * {@code
     * stream(
     * stream -> stream.map(rs -> new Object[] {
     * rs.getLong(1),
     * rs.getString(2),
     * rs.getObject(5)
     * }).collect(Collectors.toList()),
     * 1, 2, 5
     * )}
     *
     * @param generatedValuesHandler handler which operates on {@link ResultSet} with generated values
     * @param colIndices             indices of the columns with generated keys
     * @return affected rows count
     * @throws NullPointerException     if colIndices or generatedValuesHandler is null
     * @throws IllegalArgumentException if colIndices is empty
     * @see java.sql.Connection#prepareStatement(String, int[])
     */
    @Nonnull
    Long execute(TryConsumer, SQLException> generatedValuesHandler, int... colIndices);

    /**
     * Tells this update will be a large update
     *
     * @return update query abstraction
     * @see PreparedStatement#executeLargeUpdate()
     */
    Update large(boolean isLarge);

    /**
     * Tells DB to use batch (if possible)
     *
     * @return update query abstraction
     * @see DatabaseMetaData#supportsBatchUpdates()
     */
    Update batched(boolean isBatch);

    /**
     * {@inheritDoc}
     */
    @Override
    @Nonnull
    Update timeout(int timeout);

    /**
     * Sets query execution timeout
     *
     * @param supplier timeout value supplier
     * @return update query abstraction
     * @throws NullPointerException if supplier is null
     * @see #timeout(int)
     */
    @Nonnull
    default Update timeout(Supplier supplier) {
        return timeout(toOptional(supplier).orElse(0));
    }


    /**
     * {@inheritDoc}
     */
    @Override
    @Nonnull
    Update poolable(boolean poolable);

    /**
     * Sets this query poolable.
     *
     * @param supplier poolable value supplier
     * @return update query abstraction
     * @throws NullPointerException if supplier is null
     * @see #poolable(boolean)
     */
    @Nonnull
    default Update poolable(Supplier supplier) {
        return poolable(toOptional(supplier).orElse(false));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Nonnull
    Update escaped(boolean escapeProcessing);

    /**
     * Set escape processing for this query.
     *
     * @param supplier escaped processing value supplier
     * @return update query abstraction
     * @throws NullPointerException if supplier is null
     * @see #escaped(boolean)
     */
    @Nonnull
    default Update escaped(Supplier supplier) {
        return escaped(toOptional(supplier).orElse(true));
    }

    /**
     * {@inheritDoc}
     */
    @Nonnull
    @Override
    Update skipWarnings(boolean skipWarnings);

    /**
     * Sets flag whether to skip on warnings or not.
     *
     * @param supplier skipWarning processing value supplier
     * @return update query abstraction
     * @throws NullPointerException if supplier is null
     * @see #skipWarnings(boolean)
     */
    default Update skipWarnings(Supplier supplier) {
        return skipWarnings(toOptional(supplier).orElse(true));
    }

    /**
     * Sets the transaction isolation level for this query.
     * These are:
     * {@code
     * TransactionIsolation.READ_UNCOMMITTED
     * TransactionIsolation.READ_COMMITTED
     * TransactionIsolation.REPEATABLE_READ
     * TransactionIsolation.SERIALIZABLE
     * }
     *
     * @param isolationLevel desired transaction isolation level
     * @return an update query abstraction
     * @throws NullPointerException if level is null
     * @see TransactionIsolation
     */
    @Nonnull
    Update transacted(TransactionIsolation isolationLevel);

    /**
     * Sets the transaction isolation level for this query.
     *
     * @param supplier transaction isolation level value supplier
     * @return an update query abstraction
     * @throws NullPointerException if supplier is null
     * @see #transacted(TransactionIsolation)
     */
    @Nonnull
    default Update transacted(Supplier supplier) {
        return transacted(toOptional(supplier).orElse(TransactionIsolation.SERIALIZABLE));
    }

    /**
     * Prints this query string (as SQL) to provided logger.
     *
     * @param printer query string consumer
     * @return update query abstraction
     */
    @Nonnull
    Update print(Consumer printer);

    /**
     * Prints this query string (as SQL) to standard output.
     *
     * @return update query abstraction
     * @see System#out
     * @see PrintStream#println
     */
    @Nonnull
    default Update print() {
        return print(System.out::println);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy