#include <libgda/libgda.h>
#include <sql-parser/gda-sql-parser.h>

int main()
{
	//const char* table_name = "\"CapitalTest8\"";
	/* This creates a "capitaltest8" table instead of a "CapitalTest8" table: */
	   const char* table_name = "CapitalTest8";

  
	gchar* quoted;

	gda_init();

	GError* error = NULL;
  
#if 0
	GdaConnection* conn = gda_connection_open_from_string("SQLite", g_strdup_printf("DB_DIR=.;DB_NAME=%s", table_name), "", GDA_CONNECTION_OPTIONS_NONE, NULL);
#endif
	GdaConnection* conn = gda_connection_open_from_string("PostgreSQL",
							      "DB_NAME=glom_example_smallbusiness_v2",
							      NULL,
							      GDA_CONNECTION_OPTIONS_NONE,
							      NULL);
	if(!conn)
		{
			g_warning("gda_connection_open_from_string() failed: %s\n", error->message);
			g_clear_error(&error);
		}

	GdaServerProvider* provider = gda_connection_get_provider(conn);

	/* Create the table: */
	GdaServerOperation* operation = gda_server_provider_create_operation(provider, conn, GDA_SERVER_OPERATION_CREATE_TABLE, NULL, &error);
	if(!operation)
		{
			g_warning("create_operation(CREATE_TABLE) failed: %s\n", error->message);
			g_clear_error(&error);
		}

	quoted = gda_sql_identifier_quote (table_name, conn, NULL, FALSE, TRUE);
	gda_server_operation_set_value_at(operation, quoted, NULL, "/TABLE_DEF_P/TABLE_NAME");
	g_free (quoted);
	gda_server_operation_set_value_at(operation, "id", NULL, "/FIELDS_A/@COLUMN_NAME/0");
	gda_server_operation_set_value_at(operation, "int", NULL, "/FIELDS_A/@COLUMN_TYPE/0");
	gda_server_operation_set_value_at(operation, "TRUE", NULL, "/FIELDS_A/@COLUMN_PKEY/0");

	gda_server_provider_perform_operation(provider, conn, operation, &error);
	if(error)
		{
			g_warning("perform_operation(CREATE_TABLE) failed: %s\n", error->message);
			g_clear_error(&error);
		}

	/* Add a column (field): */
	operation = gda_server_provider_create_operation(provider, conn, GDA_SERVER_OPERATION_ADD_COLUMN, NULL, &error);
	if(error)
		{
			g_warning("create_operation(ADD_COLUMN) failed: %s\n", error->message);
			g_clear_error(&error);
		}


	//TODO: Quote table_name and field_name?
	quoted = gda_sql_identifier_quote (table_name, conn, NULL, FALSE, TRUE);
	gda_server_operation_set_value_at(operation, quoted, NULL, "/COLUMN_DEF_P/TABLE_NAME");
	g_free (quoted);
	quoted = gda_sql_identifier_quote ("NewField", conn, NULL, FALSE, TRUE);
	gda_server_operation_set_value_at(operation, quoted, NULL, "/COLUMN_DEF_P/COLUMN_NAME");
	g_free (quoted);
	gda_server_operation_set_value_at(operation, "int", NULL, "/COLUMN_DEF_P/COLUMN_TYPE");
	gda_server_operation_set_value_at(operation, "FALSE", NULL, "/COLUMN_DEF_P/COLUMN_PKEY");
	gda_server_operation_set_value_at(operation, "FALSE", NULL, "/COLUMN_DEF_P/COLUMN_UNIQUE");
  
	gda_server_provider_perform_operation(provider, conn, operation, &error);
	if(error)
		{
			g_warning("perform_operation(ADD_COLUMN) failed: %s\n", error->message);
			g_clear_error(&error);
		}
	return 0;
}
