midgard_hello_world

/* compile: gcc -v  -I `pkg-config --cflags midgard-2.0` `pkg-config --libs midgard-2.0` hello-world.c -o midgard-hello-world */

#include <midgard/midgard.h>

int 
main (int argc, char **argv)
{
	/* Initialize Midgard and GType system */
	midgard_init();


	/* Create default Midgard configuration */
	MidgardConfig *config = midgard_config_new();
	g_object_set(config, 
			"dbtype", "SQLite",
			"database", "MidgardHelloWorld",
			"dbuser", "midgard",
			"dbpass", "midgard", NULL);

	/* Save configuration */
	if (!midgard_config_save_file(config, "midgard_hello_world", TRUE, NULL)) {

		g_warning("Failed to save configuration");
		return 1;
	}

	GError *error = NULL;
	/* Re open configuration */
	if (!midgard_config_read_file(config, "midgard", TRUE, &error)) {

		g_warning("Failed to open default configuration. %s", 
				error && error->message ? error->message : "Unknown reason");
		return 1;
	}

	/* Open connection using given config */
	MidgardConnection *mgd = midgard_connection_new();

	if (!midgard_connection_open_config(mgd, config)) {

		g_warning("Failed to open database connection. %s",
				midgard_connection_get_error_string(mgd));
		return 1;
	}
	
	/* Set 'message' loglevel */
	midgard_connection_set_loglevel(mgd, "loglevel", NULL);

	/* Create default tables in database */
	midgard_storage_create_base_storage(mgd);

	/* Create tables for user defined classes */
	guint n_types, i;
	GType *all_types = g_type_children(MIDGARD_TYPE_OBJECT, &n_types);
	const gchar *typename;

	for (i = 0; i < n_types; i++) {

		typename = g_type_name(all_types[i]);
		MidgardObjectClass *klass = MIDGARD_OBJECT_GET_CLASS_BY_NAME(typename);

		midgard_storage_create_class_storage(klass, mgd);
	}

	/* Tables are created, set warning loglevel */
	midgard_connection_set_loglevel(mgd, "warn", NULL);

	/* Create new object (record) */
	MgdObject *person = midgard_object_new(mgd, "midgard_person", NULL);
	
	/* Set properties */
	g_object_set(person, 
			"username", "John",
			"firstname", "Hello",
			"lastname", "World", NULL);

	if (!midgard_object_create(person)) {

		g_warning("Failed to create new person. %s",
				midgard_connection_get_error_string(mgd));
		return 1;
	}

	g_print("\n Hello World! John object has been created! \n\n");	

	/* Unref config and connection */
	g_object_unref(config);
	g_object_unref(mgd);
	
	midgard_close();

	return 0;
}