package postgres;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class ExecutePostgresIntegerOverflow {

	static String statements = 	"DROP TABLE IF EXISTS t1;\n" +
								"CREATE TABLE t1(c0 int);\n" +
								"INSERT INTO t1(c0) VALUES(2147483647);\n" +
								"UPDATE t1 SET c0 = 0;\n" +
								"CREATE INDEX i0 ON t1((1 + t1.c0));\n" +
								"VACUUM FULL;";

	private static final String USER_NAME = "";
	private static final String PASSWORD = "";

	
	private static void dropCreateDatabase(String db) {
		Connection con;
		try {
			con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", USER_NAME, PASSWORD);
			con.createStatement().execute(String.format("DROP DATABASE IF EXISTS %s;CREATE DATABASE %s;", db, db));
		} catch (SQLException e) {
			throw new AssertionError(e);
		}
	}

	public static void main(String[] args) {
		Runnable r1 = new Runnable() {

			@Override
			public void run() {
				while (true) {
					dropCreateDatabase("db1");
				}
			}
		};
		new Thread(r1).start();
		Runnable r2 = new Runnable() {

			@Override
			public void run() {
				dropCreateDatabase("db2");
				try {
					while (true) {
						try (Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db2",
								USER_NAME, PASSWORD)) {
							for (String statement : statements.split("\n")) {
								try (Statement s = con.createStatement()) {
									s.execute(statement);
								} catch (SQLException e) {
									System.err.println("statement causing exception : " + statement);
									e.printStackTrace();
									System.exit(-1);
								}
							}
						}
					}
				} catch (SQLException e) {
					throw new AssertionError(e);
				}

			}
		};
		new Thread(r2).start();
	}

}
