quote-bot/db.c
2021-03-08 23:16:14 -05:00

90 lines
2.3 KiB
C

/* <https://gist.github.com/enile8/2424514> */
#define _POSIX_C_SOURCE 200809L /* strtok_r, strndup */
#include <string.h>
#include <assert.h> /* assert */
#include <sqlite3.h>
#include <stdio.h> /* size_t */
#include <stdlib.h> /* malloc */
/* TODO: libircclient for basic IRC functionality.
* Perhaps a database backend and a client frontend that's separate. */
#ifndef UNUSED
#define UNUSED(x) (void)(x)
#endif
#include "io.h"
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
UNUSED(NotUsed);
for (i = 0; i < argc; i++) {
printf(" => %s = %s\n", azColName[i], (argv[i] ? argv[i] : "NULL"));
}
return 0;
}
int test_db(char *script_filename) {
char *orig_statements;
char *saveptr1;
char *statements;
char *str1, *token;
char *zErrMsg;
const char *db_name;
int j;
int rc;
sqlite3 *db;
zErrMsg = 0;
orig_statements = file_read(script_filename);
if (orig_statements) {
statements = strndup(orig_statements, 4096);
} else {
fprintf(stderr, "Error reading file: %s\n", script_filename);
return -1;
}
db_name = "familyGuy.db";
rc = sqlite3_open(db_name, &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
} else {
fprintf(stderr, "Open database successfully\n");
}
for (j = 1, str1 = statements;; j++, str1 = NULL) {
token = strtok_r(str1, "\n", &saveptr1);
if (token == NULL)
break;
if (strlen(token) > 2 && token[0] == '-' && token[1] == '-')
continue;
printf("%d: %s\n", j, token);
rc = sqlite3_exec(db, token, callback, 0, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
sqlite3_free(zErrMsg);
break;
}
}
free(orig_statements);
free(statements);
sqlite3_close(db);
fprintf(stderr, "Bye!\n");
return 0;
}
#ifdef TEST_DB
int main(int argc, char **argv) {
char *script_filename;
if (argc > 1) {
script_filename = argv[1];
} else {
fprintf(stderr, "Usage: %s <script>\n", argv[0]);
return -1;
}
return test_db(script_filename);
}
#endif