#include "sqlite3_util.h"

/**
 * execute sql on sqlite3 db using sqlite3_exec().
 *
 * Returns: TRUE on success, FALSE otherwise. if FALSE, errmsg will be printed
 * with g_warning().
 */
gboolean
sqlite3_exec_simple (sqlite3 *db, const char *sql)
{
	if (! db) {
		g_warning ("trying to execute sql %s on NULL db handler", sql);
		g_assert_not_reached ();
		return FALSE;
	}
	char *errmsg = NULL;
	if (sqlite3_exec (db, sql, NULL, NULL, &errmsg) != SQLITE_OK) {
		g_warning ("execute sql failed: sql=%s error=%s", sql, errmsg);
		sqlite3_free (errmsg);
		return FALSE;
	}
	g_assert_null (errmsg);
	return TRUE;
}

/**
 * copy all data from src db to dest db.
 *
 * it's a wrapper for sqlite3_backup_init(), sqlite3_backup_step(),
 * sqlite3_backup_finish().
 *
 * TODO probably should add glib based error handling instead of print via
 * g_warning and return gboolean for real world use.
 *
 * @dest: dest db handler
 * @dest_dbname: dest db name
 * @src: src db handler
 * @src_dbname: src db name
 */
gboolean
sqlite3_copy_db (sqlite3 *dest, const char* dest_dbname,
		 sqlite3 *src, const char* src_dbname)
{
	gboolean copy_done = FALSE;
        sqlite3_backup *backup = sqlite3_backup_init (
		dest, dest_dbname, src, src_dbname);
        if (backup) {
            int r = sqlite3_backup_step (backup, -1);
	    if (r == SQLITE_DONE) {
		    copy_done = TRUE;
	    } else {
		    g_warning ("sqlite3_backup_step() failed: %d (%s)",
			       r, sqlite3_errmsg (dest));
	    }
            r = sqlite3_backup_finish (backup);
	    if (r != SQLITE_OK) {
		    g_warning ("sqlite3_backup_finish() failed: %d (%s)",
			       r, sqlite3_errmsg (dest));
	    }
        } else {
		g_warning ("sqlite3_backup_init() failed: %d (%s)",
			   sqlite3_errcode (dest), sqlite3_errmsg (dest));
	}
	return copy_done;
}
