/* Build like so:
 * gcc test_libgda_unquoted_as.c `pkg-config libgda-5.0 --cflags --libs`
 */

#include <libgda/libgda.h>

GdaConnection* conn = NULL;


int main()
{
	gda_init();

	GError* error = NULL;
	conn = gda_connection_open_from_string("PostgreSQL",
		"HOST=localhost;PORT=5434;DB_NAME=glom_musiccollection211",
		"USERNAME=glom_default_developer_user;PASSWORD=glom_default_developer_password",
		GDA_CONNECTION_OPTIONS_SQL_IDENTIFIERS_CASE_SENSITIVE,
		&error);
	
	if (error) {
		g_warning("gda_connection_open_from_string() failed: %s\n", error->message);
		g_clear_error(&error);
		return 0;
	}

/* Generate SQL like this:	
  SELECT "songs"."songs_id", "songs"."album_id",
  "ALBUMS"."name" FROM "songs" LEFT JOIN
  "albums" AS "ALBUMS" ON (("songs"."album_id" =
  "ALBUMS"."album_id"))  WHERE ("songs"."songs_id" = 0)
*/

  GdaSqlBuilder* builder = gda_sql_builder_new(GDA_SQL_STATEMENT_SELECT);
  const guint target_songs = gda_sql_builder_select_add_target(builder, "songs", NULL);
  
  
  const char* alias_name = "ALBUMS";

  const guint to_target_id = gda_sql_builder_select_add_target(builder, "albums", alias_name);

  gda_sql_builder_select_join_targets(
    builder,
    target_songs,
    to_target_id,
    GDA_SQL_SELECT_JOIN_LEFT,
    gda_sql_builder_add_cond(
      builder,
      GDA_SQL_OPERATOR_TYPE_EQ,
      gda_sql_builder_add_field_id(builder, "album_id", "songs"),
      gda_sql_builder_add_field_id(builder, "album_id", alias_name),
      0));;
  
  gda_sql_builder_select_add_field(builder, "songs_id", "songs", NULL);
  gda_sql_builder_select_add_field(builder, "album_id", "songs", NULL);
  gda_sql_builder_select_add_field(builder, "name", alias_name, NULL);
  
  GdaStatement* stmt = gda_sql_builder_get_statement(builder, &error);
  if (error) {
		g_warning("gda_sql_builder_get_statement() failed: %s\n", error->message);
		g_clear_error(&error);
		return 0;
	}

  GdaDataModel* model = gda_connection_statement_execute_select(
    conn, stmt, NULL, &error);
  if (error) {
		g_warning("gda_connection_statement_execute_select() failed: %s\n", error->message);
		g_clear_error(&error);
		return 0;
	}
 
  

	return 0;
}
