chiark / gitweb /
WIP routesearch; before try not using interior point
[ypp-sc-tools.db-test.git] / yarrg / rssql.c
1
2 #include "rscommon.h"
3
4 sqlite3 *db;
5 sqlite3_stmt *ss_ipair;
6
7 DEBUG_DEFINE_DEBUGF(sql);
8
9 static int busy_handler(void *u, int previous) {
10   debugf("[[DB BUSY %d]]",previous);
11   sysassert(! usleep(5000) );
12   return 1;
13 }
14
15 void setup(void) {
16   sqlite3_stmt *sst;
17   
18   SQL_MUST( sqlite3_open("OCEAN-Midnight.db", &db) );
19   SQL_MUST( sqlite3_busy_handler(db, busy_handler, 0) );
20
21   sst= sql_prepare("BEGIN","(begin)");
22   assert( !SQL_STEP(sst) );
23   sqlite3_finalize(sst);
24
25   setup_value();
26 }
27
28 int sql_single_int(const char *stmt) {
29   sqlite3_stmt *sst;
30   sst= sql_prepare(stmt,"(single int)");
31   assert( SQL_STEP(sst) );
32   int rv= sqlite3_column_int(sst,0);
33   sqlite3_finalize(sst);
34   return rv;
35 }
36
37 void sql_fatal(const char *stmt_what, int sqr, const char *act_what) {
38   fatal("SQL call failed, stmt %s code %d: %s: %s",
39         stmt_what, sqr, sqlite3_errmsg(db), act_what);
40 }
41
42 void sql_bind(sqlite3_stmt *ss, int index, int value,
43               const char *ss_what, const char *val_what) {
44   debugf("SQL BIND %s #%d = %d = %s\n", ss_what, index, value, val_what);
45   int sqr= sqlite3_bind_int(ss, index, value);
46   if (sqr) sql_fatal(ss_what, sqr,
47                      masprintf("bind #%d (%s)", index, val_what));
48 }
49   
50 sqlite3_stmt *sql_prepare(const char *stmt, const char *what) {
51   sqlite3_stmt *ssr;
52   debugf("SQL PREPARE %s [[\n%s\n]]\n", what, stmt);
53   SQL_MUST( sqlite3_prepare(db, stmt, -1, &ssr, 0) );
54   return ssr;
55 }
56
57 int sql_step_wrap(sqlite3_stmt *ssh, const char *ssh_string,
58                   const char *file, int line) {
59   for (;;) {
60     int sqr;
61     sqr= sqlite3_step((ssh));
62     switch (sqr) {
63     case SQLITE_DONE:
64       debugf("SQL %s DONE\n",ssh_string);
65       return 0;
66     case SQLITE_ROW:
67       if (DEBUGP(sql)) {
68         int i;
69         fprintf(debug,"SQL %s R",ssh_string);
70         for (i=0; i<sqlite3_column_count(ssh); i++) {
71           fputc('\t',debug);
72           const char *txt= (const char*)sqlite3_column_text(ssh,i);
73           fputs(txt ? txt : "<null>", debug);
74         }
75         fputs("\n",debug);
76       }
77       return 1;
78     default: fatal("SQL step failed at %s:%d: code %d: %s: %s",
79                    file, line, sqr, sqlite3_errmsg(db), ssh_string);
80     }
81   }
82 }