#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;
	if(gda_sql_identifier_needs_quotes(table_name))
		quoted = gda_sql_identifier_add_quotes(table_name);
	else
		quoted = g_strdup(table_name);

	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",
    "HOST=localhost;PORT=5434;DB_NAME=glom_example_smallbusiness_v2",
    "USERNAME=test;PASSWORD=test",
    GDA_CONNECTION_OPTIONS_NONE,
    NULL);
  if(error)
	{
	  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(error)
	{
	  g_warning("create_operation(CREATE_TABLE) failed: %s\n", error->message);
	  g_clear_error(&error);
	}

	gda_server_operation_set_value_at(operation, table_name, NULL, "/TABLE_DEF_P/TABLE_NAME");
	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?
  gda_server_operation_set_value_at(operation, table_name, NULL, "/COLUMN_DEF_P/TABLE_NAME");
  gda_server_operation_set_value_at(operation, "NewField", NULL, "/COLUMN_DEF_P/COLUMN_NAME");
  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);
	}
}
