Skip to content

Instantly share code, notes, and snippets.

@sitano
Created January 16, 2023 16:30
Show Gist options
  • Save sitano/7873b9836f00e80ad737b67ec0eb1842 to your computer and use it in GitHub Desktop.
Save sitano/7873b9836f00e80ad737b67ec0eb1842 to your computer and use it in GitHub Desktop.
test_sqlite3_int_vs_stmt.cc
#define _MULTI_THREADED
#include <sqlite3.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <cstring>
#define SQLOK(line) do { \
int rc = line; \
if (rc != SQLITE_OK) { \
fprintf(stderr, "[%d] %s: err=%d\n", gettid(), sqlite3_errstr(rc), rc); \
exit(1); \
}; \
} while (0)
int exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**)) {
char *err_msg = 0;
int rc = sqlite3_exec(db, sql, callback, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "[%d] SQL %s error: %s\n", gettid(), sql, err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
return 0;
}
extern int sqlite3_is_interrupted(sqlite3*);
// clang -O3 -lsqlite3 ./1.cc && /usr/bin/time ./a.out
// clang -O3 -L ~/sqlite/.libs -I ~/sqlite -lsqlite3 ./1.cc && LD_LIBRARY_PATH=~/sqlite/.libs /usr/bin/time ./a.out
int main(void) {
sqlite3 *db;
SQLOK(sqlite3_open(":memory:", &db));
exec(db, "CREATE TABLE t (id INT, t TEXT)", NULL);
sqlite3_interrupt(db);
fprintf(stderr, "[%d] interrupt status = %d : %d\n", gettid(), sqlite3_is_interrupted(db) ? 1 : 0, __LINE__);
exec(db, "INSERT INTO t VALUES (1, 't'), (2, 't'), (3, 'f')", NULL);
fprintf(stderr, "[%d] interrupt status = %d : %d\n", gettid(), sqlite3_is_interrupted(db) ? 1 : 0, __LINE__);
sqlite3_interrupt(db);
fprintf(stderr, "[%d] interrupt status = %d : %d\n", gettid(), sqlite3_is_interrupted(db) ? 1 : 0, __LINE__);
exec(db, "SELECT * FROM t WHERE id = 1", NULL);
fprintf(stderr, "[%d] interrupt status = %d : %d\n", gettid(), sqlite3_is_interrupted(db) ? 1 : 0, __LINE__);
const char *sql = "SELECT * FROM t";
sqlite3_stmt *s = NULL;
SQLOK(sqlite3_prepare_v2(db, sql, strlen(sql), &s, NULL));
while (s) {
int a = 0;
const unsigned char *b = NULL;
const int rc = sqlite3_step(s);
switch (rc) {
case SQLITE_ROW:
a = sqlite3_column_int64(s, 0);
b = sqlite3_column_text(s, 1);
printf(" %d, %s\n", a, b);
fprintf(stderr, "[%d] interrupt status = %d : %d\n", gettid(), sqlite3_is_interrupted(db) ? 1 : 0, __LINE__);
sqlite3_interrupt(db);
fprintf(stderr, "[%d] interrupt status = %d : %d\n", gettid(), sqlite3_is_interrupted(db) ? 1 : 0, __LINE__);
break;
case SQLITE_DONE:
sqlite3_finalize(s);
s = NULL;
break;
default:
fprintf(stderr, "Invalid return code for sqlite3_step: %d", rc);
sqlite3_finalize(s);
s = NULL;
break;
}
}
sqlite3_close(db);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment