package com.tunz.mysql;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class BigIntTests {

	private Connection conn;

	@Before
	public void setUp() throws SQLException, ClassNotFoundException {
		Class.forName("org.mariadb.jdbc.Driver"); // Be sure the mariadb client is

		this.conn = (Connection) DriverManager.getConnection("jdbc:mariadb://<SETUP YOUR CONNECTION HERE>", "<USER>", "<PASSWORD>");

		Statement setup = this.conn.createStatement();
		setup.executeQuery("DROP TABLE IF EXISTS `testBigintTable`;");
		setup.executeQuery("CREATE TABLE `testBigintTable` (`id` bigint(11) unsigned NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
		setup.executeQuery("INSERT INTO `testBigintTable` (`id`) VALUES (0)");
	}

	@After
	public void tearDown() throws SQLException, ClassNotFoundException {

		Statement stop = this.conn.createStatement();
		stop.executeQuery("DROP TABLE IF EXISTS `testBigintTable`;");
		stop.close();
		conn.close();
	}

	@Test
	public void testBigInt() throws SQLException {
		PreparedStatement stmt = this.conn.prepareStatement("UPDATE `testBigintTable` SET `id` =?");
		stmt.setBigDecimal(1, new BigDecimal(BigInteger.valueOf(System.currentTimeMillis())));
		stmt.executeUpdate();

		long t = System.currentTimeMillis();
		BigInteger bigT = BigInteger.valueOf(t);
		stmt = this.conn.prepareStatement("UPDATE `testBigintTable` SET `id` =?");
		stmt.setObject(1, bigT);
		stmt.executeUpdate();

		stmt = this.conn.prepareStatement("SELECT `id` FROM `testBigintTable` WHERE `id` =?");
		stmt.setObject(1, BigInteger.valueOf(t));
		ResultSet res = stmt.executeQuery();
		if (res.next()) {
			Assert.assertEquals(0, res.getBigDecimal(1).toBigInteger().compareTo(bigT));
		}
	}
}
