001// Licensed under the MIT license. See LICENSE file in the project root for full license information.
002
003package de.bytefish.pgbulkinsert.bulkprocessor.handler;
004
005import de.bytefish.pgbulkinsert.IPgBulkInsert;
006import de.bytefish.pgbulkinsert.util.PostgreSqlUtils;
007import org.postgresql.PGConnection;
008
009import java.sql.Connection;
010import java.util.List;
011import java.util.function.Supplier;
012
013public class BulkWriteHandler<TEntity> implements IBulkWriteHandler<TEntity> {
014
015    private final IPgBulkInsert<TEntity> client;
016
017    private final Supplier<Connection> connectionFactory;
018
019    public BulkWriteHandler(IPgBulkInsert<TEntity> client, Supplier<Connection> connectionFactory) {
020        this.client = client;
021        this.connectionFactory = connectionFactory;
022    }
023
024    @Override
025    public void write(List<TEntity> entities) throws Exception {
026        // Obtain a new Connection and execute it in a try with resources block, so it gets closed properly:
027        try(Connection connection = connectionFactory.get()) {
028            // Now get the underlying PGConnection for the COPY API wrapping:
029            final PGConnection pgConnection = PostgreSqlUtils.getPGConnection(connection);
030            // And finally save all entities by using the COPY API:
031            client.saveAll(pgConnection, entities.stream());
032        }
033    }
034}