/*
 * Copyright (c) 2004-2009, Luiz Otavio O Souza <loos.br@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * $Id: mysql.h 112 2009-03-15 17:30:28Z loos-br $
 */

#ifndef MYSQL_H
#define MYSQL_H

#ifndef MYSQLCONFDIR
#define MYSQLCONFDIR		"/usr/local/etc/msn-proxy/mysql"
#endif
#ifndef MYSQLCONF
#define MYSQLCONF       	"conf"
#endif
#ifndef MYSQLTABLE
#define MYSQLTABLE      	"tables"
#endif
#ifndef DEFAULT_MYSQL_HOST
#define DEFAULT_MYSQL_HOST	"/tmp/mysql.sock"
#endif
#ifndef DEFAULT_MYSQL_PORT
#define DEFAULT_MYSQL_PORT	3306
#endif
#ifndef DEFAULT_MYSQL_USER
#define DEFAULT_MYSQL_USER	"maildir-index"
#endif
#ifndef DEFAULT_MYSQL_PASS
#define DEFAULT_MYSQL_PASS	"secret"
#endif
#ifndef DEFAULT_MYSQL_DB
#define DEFAULT_MYSQL_DB	"maildir-index"
#endif

#include "tree.h"
#include "string.h"
#include <mysql/mysql.h>

struct table__ {
    RB_ENTRY(table__)	table_;
    string		name;
    string		sql;
    size_t		size;
    int			exist;
};

struct tables {
    struct table__	*rbh_root; /* root of the tree */
};

typedef struct {
    struct tables	table_head;	/* sql to create table */
    MYSQL		mysql;          /* mysql internal data */
    string		user;           /* mysql user */
    string		pass;           /* mysql pass */
    string		db;             /* mysql db */
    string		host;           /* mysql host */
    unsigned int	port;           /* mysql port */
    int			connected;      /* is mysql connected ? */
    void		(*info)(const char *, ...);
    void		(*debug)(const char *, ...);
} mysql_;

MYSQL_ROW	db_fetch_row(MYSQL_RES *res);
u_int64_t	db_count(MYSQL_RES *res);
u_int64_t	db_affected_rows(MYSQL *mysql);
u_int64_t	db_last_id(MYSQL *mysql);
MYSQL_RES	*db_free(MYSQL_RES *res);
char		*db_escape(mysql_ *mysql, char *from);
MYSQL_RES	*db_query(mysql_ *mysql, string *query);
int		db_query2(mysql_ *mysql, string *query);
int		db_create_all(mysql_ *mysql);
int		db_check(mysql_ *mysql);
char		*db_error(mysql_ *mysql);
int		db_init(mysql_ *mysql,
			void (*debug)(const char *, ...),
			void (*sql)(const char *,...));
void		db_close(mysql_ *mysql);
int		db_read_conf(mysql_ *mysql, const char *configdir);

void free_sqltable_tree(mysql_ *mysql);

#endif
