import java.io.*;
import java.sql.*;

public class TestCase2
{
	public static void main(String[] args)
	{
		try
		{
			runTest(args[0]);
		}
		catch(Exception exception)
		{
			exception.printStackTrace();
			System.exit(1);
		}
	}

	private static void runTest(String url) throws Exception
	{
		// Connect to the database
		Class.forName("com.mysql.jdbc.Driver");
		Connection connection = DriverManager.getConnection(url);

		// Print connection meta-data
		DatabaseMetaData meta = connection.getMetaData();
		System.out.println("product=" + meta.getDatabaseProductName() + " (" + meta.getDatabaseProductVersion() + ")");
		System.out.println("driver=" + meta.getDriverName() + " (" + meta.getDriverVersion() + ")");

		// Create test tables and function
		Statement statement = connection.createStatement();
		statement.executeUpdate("DROP TABLE IF EXISTS test_table_2");
		statement.executeUpdate("DROP TABLE IF EXISTS test_table_1");
		statement.executeUpdate("CREATE TABLE test_table_1 (value_1 BIGINT PRIMARY KEY) ENGINE=InnoDB");
		statement.executeUpdate("INSERT INTO test_table_1 VALUES (1)");
		statement.executeUpdate("CREATE TABLE test_table_2 (value_2 BIGINT PRIMARY KEY) ENGINE=InnoDB");
		statement.executeUpdate("DROP FUNCTION IF EXISTS test_function");
		System.out.println("creating function ...");
		statement.executeUpdate("CREATE FUNCTION test_function() RETURNS BIGINT " +
				"DETERMINISTIC MODIFIES SQL DATA BEGIN " +
				"DECLARE max_value BIGINT; " +
				"SELECT MAX(value_1) INTO max_value FROM test_table_2; " +
				"RETURN max_value; END;");

		// Prepare the function call
		System.out.println("preparing function call ...");
		CallableStatement callable = connection.prepareCall("{? = call test_function()}");
		callable.registerOutParameter(1,Types.BIGINT);

		System.out.println("calling function with invalid embedded column reference; this should throw an exception ...");
		callable.executeUpdate();
		System.out.println("impossible; we should never get here.");

		// Cleanup test objects
		statement.executeUpdate("DROP TABLE test_table_2");
		statement.executeUpdate("DROP TABLE test_table_1");
		statement.executeUpdate("DROP FUNCTION test_function");

		// Free resources
		statement.close();
		connection.close();
	}
}
