// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package tx.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLTransientException;
import java.sql.Statement;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.PoolingDriver;
import org.apache.commons.pool2.impl.GenericObjectPool;

public class PerfTest2 {
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:apache:commons:dbcp:mypool");
    }
    private static Random rng = new Random();
    private static void test(boolean conflict, int delay) {
        try {
            try(Connection con = getConnection()) {
                con.setAutoCommit(false);
                con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                try(PreparedStatement sel = con.prepareStatement("SELECT val FROM concdata WHERE id = ?");
                    PreparedStatement upd = con.prepareStatement("UPDATE concdata SET val = ? WHERE id = ?")) {
                    int ix;
                    if(conflict) {
                        ix = 1;
                    } else {
                        synchronized(rng) {
                            ix = rng.nextInt(1000) + 1;
                        }
                    }
                    boolean done;
                    do {
                        try {
                            sel.setInt(1,  ix);
                            ResultSet rs = sel.executeQuery();
                            rs.next();
                            int val = rs.getInt(1);
                            val = val + 1;
                            Thread.sleep(delay);
                            upd.setInt(1,  val);
                            upd.setInt(2,  ix);
                            upd.executeUpdate();
                            con.commit();
                            done = true;
                        } catch(SQLException ex) {
                            if(ex instanceof SQLTransientException ||
                               ex.getSQLState().equals("40001")) {
                                con.rollback();
                                done = false;
                            } else {
                                throw ex;
                            }
                        }
                    } while(!done);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private static final int N = 500;
    private static void test(boolean conflict, int nthreads, int delay) throws SQLException, InterruptedException {
        try(Connection con = getConnection()) {
            try(Statement stmt = con.createStatement()) {
                try {
                    stmt.executeUpdate("DROP TABLE concdata");
                } catch(SQLException ex) { }
                stmt.executeUpdate("CREATE TABLE concdata (id INTEGER NOT NULL, val INTEGER, PRIMARY KEY(id))");
                for(int i = 0; i < 1000; i++) {
                    stmt.executeUpdate("INSERT INTO concdata VALUES(" + (i + 1) + ", 0)");
                }
            }
            long t1 = System.currentTimeMillis();
            ExecutorService es = Executors.newFixedThreadPool(nthreads);
            for(int i = 0; i < N; i++) {
                es.submit(() -> { test(conflict, delay); });
            }
            es.shutdown();
            es.awaitTermination(1, TimeUnit.HOURS);
            long t2 = System.currentTimeMillis();
            System.out.printf("%s - %d threads and %d ms delay : %d ms (%.1f ops/sec)\n", conflict ? "Conflict" : "No conflict",
                                                                                          nthreads, delay,
                                                                                          t2 - t1,
                                                                                          N * 1000.0 / (t2 - t1));
            try(Statement stmt = con.createStatement()) {
                stmt.executeUpdate("DROP TABLE concdata");
            }
        }
    }
    private static void test(String db) throws SQLException, InterruptedException {
        System.out.printf("%s:\n", db);
        for(boolean conflict : new boolean[] { false, true } ) {
            for(int nthread : new int[] { 1, 5, 10, 25, 50, 100 }) {
                for(int delay : new int[] { 0, 10, 25, 50, 100 }) {
                    test(conflict, nthread, delay);
                }
            }
        }
    }
    public static void test(String db, String url, String usr, String pwd) throws Exception {
        Class.forName("org.apache.commons.dbcp2.PoolingDriver");
        PoolingDriver driver = (PoolingDriver)DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(new DriverManagerConnectionFactory(url, usr, pwd), null);
        GenericObjectPool<PoolableConnection> cp = new GenericObjectPool<>(pcf);
        cp.setMinIdle(105);
        cp.setMaxTotal(105);
        pcf.setPool(cp);
        driver.registerPool("mypool", cp);
        test(db);
        driver.closePool("mypool");
    }
    public static void main(String[] args) throws Exception {
        test("MySQL", "jdbc:mysql://localhost/Test", "root", "hemmeligt");
        //test("PostgreSQL", "jdbc:postgresql://localhost/Test" , "postgres", "hemmeligt");
        //test("IBM DB2", "jdbc:db2://localhost:50000/Test", "arne", "hemmeligt");
        //test("MS SQLServer", "jdbc:sqlserver://localhost;database=Test;integratedSecurity=true;", null, null);
    }
}
