84 lines
2.3 KiB
C
84 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_run_script(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 run_script(const char *db_name, const char *script_filename) {
|
|
int j, rc;
|
|
char *copy_statements, *orig_statements, *saveptr1, *str1, *token, *zErrMsg;
|
|
sqlite3 *db;
|
|
|
|
zErrMsg = 0;
|
|
orig_statements = file_read(script_filename);
|
|
if (orig_statements) {
|
|
copy_statements = strndup(orig_statements, 4096);
|
|
} else {
|
|
fprintf(stderr, "Error reading file: %s\n", script_filename);
|
|
return -1;
|
|
}
|
|
|
|
rc = sqlite3_open(db_name, &db);
|
|
if (rc) {
|
|
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
|
|
return -1;
|
|
} else {
|
|
fprintf(stderr, "Open database successfully\n");
|
|
}
|
|
|
|
for (j = 1, str1 = copy_statements;; j++, str1 = NULL) {
|
|
token = strtok_r(str1, "\n", &saveptr1);
|
|
if (token == NULL)
|
|
break;
|
|
if (strlen(token) > 2 && token[0] == '-' && token[1] == '-')
|
|
continue; /* Comment line; TODO multiline comment */
|
|
printf("%d: %s\n", j, token);
|
|
rc = sqlite3_exec(db, token, callback_run_script, 0, &zErrMsg);
|
|
if (rc != SQLITE_OK) {
|
|
fprintf(stderr, " !! SQL error: %s\n", sqlite3_errmsg(db));
|
|
sqlite3_free(zErrMsg);
|
|
break;
|
|
}
|
|
}
|
|
|
|
free(copy_statements);
|
|
free(orig_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 run_script("familyGuy.sqlite3", script_filename);
|
|
}
|
|
#endif
|