execute mysql_check only if a query fails.
[NeonServV5.git] / mysqlConn.c
1
2 #include "mysqlConn.h"
3
4 struct used_result {
5     MYSQL_RES *result;
6     struct used_result *next;
7 };
8
9 struct escaped_string {
10     char *string;
11     struct escaped_string *next;
12 };
13
14 MYSQL *mysql_conn = NULL;
15 static struct used_result *used_results;
16 static struct escaped_string *escaped_strings;
17
18 void check_mysql() {
19     if(mysql_ping(mysql_conn)) {
20         //mysql error
21         show_mysql_error();
22     }
23 }
24
25 MYSQL_RES *mysql_use() {
26     MYSQL_RES *res = mysql_store_result(mysql_conn);
27     struct used_result *result = malloc(sizeof(*result));
28     if (!result) {
29         mysql_free_result(res);
30         return NULL;
31     }
32     result->result = res;
33     result->next = used_results;
34     used_results = result;
35     return res;
36 }
37
38 void mysql_free() {
39     struct used_result *result, *next_result;
40     for(result = used_results; result; result = next_result) {
41         next_result = result->next;
42         mysql_free_result(result->result);
43         free(result);
44     }
45     used_results = NULL;
46     struct escaped_string *escaped, *next_escaped;
47     for(escaped = escaped_strings; escaped; escaped = next_escaped) {
48         next_escaped = escaped->next;
49         free(escaped->string);
50         free(escaped);
51     }
52     escaped_strings = NULL;
53 }
54
55 void init_mysql() {
56     mysql_conn = mysql_init(NULL);
57     if (!mysql_real_connect(mysql_conn, MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_BASE, MYSQL_PORT, NULL, 0)) {
58         //error
59         show_mysql_error();
60     }
61 }
62
63 void free_mysql() {
64     mysql_close(mysql_conn);
65 }
66
67 void show_mysql_error() {
68     //show mysql_error()
69     printf("MySQL Error: %s\n", mysql_error(mysql_conn));
70 }
71
72 void printf_mysql_query(const char *text, ...) {
73     va_list arg_list;
74     char queryBuf[MYSQLMAXLEN];
75     int pos;
76     queryBuf[0] = '\0';
77     va_start(arg_list, text);
78     pos = vsnprintf(queryBuf, MYSQLMAXLEN - 2, text, arg_list);
79     va_end(arg_list);
80     if (pos < 0 || pos > (MYSQLMAXLEN - 2)) pos = MYSQLMAXLEN - 2;
81     queryBuf[pos] = '\0';
82     printf("MySQL: %s\n", queryBuf);
83     if(mysql_query(mysql_conn, queryBuf)) {
84         check_mysql();
85         if(mysql_query(mysql_conn, queryBuf)) {
86             show_mysql_error();
87         }
88     }
89 }
90
91 char* escape_string(const char *str) {
92     struct escaped_string *escapedstr = malloc(sizeof(*escapedstr));
93     if (!escapedstr) {
94         return NULL;
95     }
96     char escaped[strlen(str)*2+1];
97     mysql_real_escape_string(mysql_conn, escaped, str, strlen(str));
98     escapedstr->string = strdup(escaped);
99     escapedstr->next = escaped_strings;
100     escaped_strings = escapedstr;
101     return escapedstr->string;
102 }