18 #define ESC_BUFSIZE (8192 * 2)
20 #define ESC_BUFS 8 /* must be a power of 2 */
21 #define MAX_ESC_STRING ((ESC_BUFSIZE * 2) + 1)
23 #define esc(s) sql_escape(s)
24 char *sql_escape(const char *str
)
27 static char buf_ary
[ESC_BUFS
][ESC_BUFSIZE
];
36 if (len
>= MAX_ESC_STRING
) {
37 lerr("len > MAX_ESC_STRING in sql_escape (%d > %d)", len
, MAX_ESC_STRING
);
41 buf
= buf_ary
[idx
++ & (ESC_BUFS
- 1)];
43 mysql_real_escape_string(db
.link
, buf
, str
, len
);
49 * these two functions are only here to allow callers
50 * access to error reporting without having to expose
51 * the db-link to theh callers. It's also nifty as we
52 * want to remain database layer agnostic
54 const char *sql_error()
56 return mysql_error(db
.link
);
61 return mysql_errno(db
.link
);
64 SQL_RESULT
*sql_get_result(void)
66 return mysql_use_result(db
.link
);
69 SQL_ROW
sql_fetch_row(MYSQL_RES
*result
)
71 return mysql_fetch_row(result
);
74 void sql_free_result(SQL_RESULT
*result
)
76 mysql_free_result(result
);
79 int sql_query(const char *fmt
, ...)
86 len
= vasprintf(&query
, fmt
, ap
);
89 if (len
== -1 || !query
) {
90 linfo("sql_query: Failed to build query from format-string '%s'", fmt
);
93 if ((result
= mysql_real_query(db
.link
, query
, len
)))
94 linfo("mysql_query(): Failed to run [%s]: %s",
95 query
, mysql_error(db
.link
));
104 if (!(db
.link
= mysql_init(NULL
)))
112 if (!(mysql_real_connect(db
.link
, db
.host
, db
.user
, db
.pass
,
113 db
.name
, db
.port
, NULL
, 0)))
115 lerr("Failed to connect to '%s' at '%s':'%d' using %s:%s as credentials: %s",
116 db
.name
, db
.host
, db
.port
, db
.user
, db
.pass
, mysql_error(db
.link
));
127 mysql_close(db
.link
);
131 const char *sql_table_name(void)
134 return "report_data";
139 int sql_config(const char *key
, const char *value
)
141 if (!prefixcmp(key
, "db_database"))
142 db
.name
= strdup(value
);
143 else if (!prefixcmp(key
, "db_user"))
144 db
.user
= strdup(value
);
145 else if (!prefixcmp(key
, "db_pass"))
146 db
.pass
= strdup(value
);
147 else if (!prefixcmp(key
, "db_host"))
148 db
.host
= strdup(value
);
149 else if (!prefixcmp(key
, "db_table")) {
150 db
.table
= strdup(value
);
152 else if (!prefixcmp(key
, "db_port")) {
155 db
.port
= (unsigned int)strtoul(value
, &endp
, 0);
157 if (endp
== value
|| *endp
!= 0)
161 return -1; /* config error */