import com.mysql.jdbc.exceptions.MySQLSyntaxErrorException;

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

/**
 * Created by dachaoli on 1/9/15.
 */
public class BitColumnBugReport extends com.mysql.jdbc.util.BaseBugReport {

	@Override
	public String getUrl() {
		return "jdbc:mysql://localhost:3306/test?user=testuser&password=test";
	}
	/**
	 * Override this method with code that sets up the testcase for
	 * demonstrating your bug (creating tables, populating data, etc).
	 *
	 * @throws Exception if an error occurs during the 'setUp' phase.
	 */
	@Override
	public void setUp() throws Exception {
		Connection con = getConnection();
		Statement stmt = con.createStatement();

		String createTableQuery = "CREATE TABLE `bug_report` (\n" +
			"  `id` mediumint(8),\n" +
			"  `deleted` bit(1) NOT NULL DEFAULT b'0',\n" +
			"  PRIMARY KEY (`id`)" +
			")";
		stmt.executeUpdate(createTableQuery);

		String insertQuery = "INSERT INTO bug_report (id, deleted) VALUES (1, 1)";
		stmt.executeUpdate(insertQuery);
	}

	/**
	 * Override this method with code that cleans up anything created in the
	 * setUp() method.
	 *
	 * @throws Exception if an error occurs during the 'tearDown' phase.
	 */
	@Override
	public void tearDown() throws Exception {
		Statement stmt = getConnection().createStatement();
		stmt.executeUpdate("DROP TABLE bug_report");
	}

	/**
	 * Override this method with code that demonstrates the bug. This method
	 * will be called after setUp(), and before tearDown().
	 *
	 * @throws Exception if an error occurs during your test run.
	 */
	@Override
	public void runTest() throws Exception {
		Statement stmt = getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
		ResultSet result = stmt.executeQuery("SELECT * FROM bug_report");

		SQLException exception = null;
		while (result.next()) {
			result.updateInt("id", result.getInt("id")+1);
			try {
				result.updateRow();
			} catch (SQLException errorException) {
				errorException.printStackTrace();
				exception = errorException;
			}
		}

		assertTrue(exception != null);
		System.out.println("Test finished");
	}

	public static void main(String[] args) throws Exception {
		new BitColumnBugReport().run();
	}
}
