/*
** CBLM v3
** $Id: db.c,v 1.3 2006/05/17 04:41:31 sella Exp $
** Copyright (c) 2004 James M. Sella. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
** 
** Cheap Bastard Latency Monitor v3
*/

#include "db.h"
#include "prefs.h"
#include "cblm.h"

/* Global Variables */
MYSQL mysql;
int connected = 1;

/* External Global Variables */
extern struct args_t args;
extern struct prefs_t prefs;
extern int running, restart;

int db_connect() {
	unsigned int timeout = DEF_DBTIMO;

	mysql_init(&mysql);
	mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, PROGRAM_NAME);
	mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (const char *) &timeout);

	if (!mysql_real_connect(&mysql, args.db_host, args.db_user, args.db_pass, args.db_name, args.db_port, args.db_sock, args.db_comp)) {
		syslog(LOG_CRIT, "MySQL Error(%d): %s", mysql_errno(&mysql), mysql_error(&mysql));
		return 1;
	}

	connected = 1;

	return 0;
}

void db_disconnect() {
	if (connected == 1) {
		connected = 0;
		mysql_close(&mysql);
	}
}

int db_query(MYSQL_RES** res, char* sql) {
	int len;

	assert(res != NULL);
	assert(sql != NULL);
	assert(connected == 1);

	len = strlen(sql);

	if (args.debug >= DEBUG_SQL) {
		syslog(LOG_DEBUG, "SQL: %s", sql);
	}

	if (mysql_real_query(&mysql, sql, len) != 0) {
		syslog(LOG_CRIT, "MySQL Error(%d): %s", mysql_errno(&mysql), mysql_error(&mysql));

		running = 0;
		restart = 1;

		return 1;
	}

	*res = mysql_store_result(&mysql);
	if (mysql_errno(&mysql) != 0) {
		syslog(LOG_CRIT, "MySQL Error(%d): %s", mysql_errno(&mysql), mysql_error(&mysql));

		running = 0;
		restart = 1;

		return 1;
	}

	return 0;
}

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim: noet ts=3 sw=3
*/
