SqlInsert.java

package space.sunqian.fs.utils.jdbc;

import space.sunqian.annotation.Immutable;
import space.sunqian.annotation.Nonnull;
import space.sunqian.fs.Fs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * This interface represents the insert operation of a SQL statement.
 *
 * @author sunqian
 */
public interface SqlInsert extends SqlOperation {

    /**
     * Returns the auto-generated keys of this operation.
     *
     * @return the auto-generated keys of this operation
     * @throws SqlRuntimeException if any error occurs
     * @implNote The default implementation closes the result set by {@link ResultSet#close()}.
     */
    default @Nonnull @Immutable List<@Nonnull Object> autoGeneratedKeys() throws SqlRuntimeException {
        return Fs.uncheck(() -> {
            PreparedStatement statement = preparedStatement();
            // Get auto-generated keys
            ResultSet generatedKeys = statement.getGeneratedKeys();
            List<Object> keys = new ArrayList<>();
            while (generatedKeys.next()) {
                keys.add(generatedKeys.getObject(1));
            }
            generatedKeys.close();
            return keys;
        }, SqlRuntimeException::new);
    }

    /**
     * Executes this insert operation and returns the number of rows inserted by this operation.
     *
     * @return the number of rows inserted by this operation
     * @throws SqlRuntimeException if any error occurs
     * @implNote The default implementation commits the connection by {@link Connection#commit()}.
     */
    @SuppressWarnings("resource")
    default long execute() throws SqlRuntimeException {
        return Fs.uncheck(() -> {
            PreparedStatement statement = preparedStatement();
            long count = statement.executeLargeUpdate();
            statement.getConnection().commit();
            return count;
        }, SqlRuntimeException::new);
    }
}