Last active
August 8, 2021 17:45
-
-
Save little-brother/f669509e71b321a9abf0553ac41563b0 to your computer and use it in GitHub Desktop.
SQLite query watcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Build | |
gcc.exe -Wall -O2 -c main.c -o obj\main.o | |
gcc.exe -Wall -O2 -c sqlite3.c -o obj\sqlite3.o | |
gcc.exe -o watcher.exe obj\main.o obj\sqlite3.o -s | |
Usage example | |
watcher -d "D:/my.sqlite" -q "select * from t order by 1 desc limit 10" - t 2 | |
*/ | |
#include <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include "sqlite3.h" | |
int main(int argc, char *argv[]) { | |
int opt; | |
char* query = 0, *dbpath = 0; | |
int timer = 5; | |
while ((opt = getopt(argc, argv, "t:q:d:")) != -1) { | |
switch (opt) { | |
case 'q': query = optarg; break; | |
case 'd': dbpath = optarg; break; | |
case 't': timer = atoi(optarg); break; | |
} | |
} | |
if (!dbpath || !strlen(dbpath) || !query || !strlen(query)) { | |
fprintf(stderr, | |
"Usage: %s -d dbpath -q query -t timer\n" \ | |
"Example: %s -d \"D:/my.db\" -q \"select * from t order by 1 desc limit 10\" -t 1\n" \ | |
"By default timer is 5 sec\n", argv[0], argv[0]); | |
exit(EXIT_FAILURE); | |
} | |
sqlite3 *db; | |
if (SQLITE_OK != sqlite3_open(dbpath, &db)) { | |
printf("Can't open database: %s\n", dbpath); | |
exit(EXIT_FAILURE); | |
} | |
char createSql[strlen(query) + 200]; | |
sprintf(createSql, "create table temp.dataset as %s", query); | |
while (true) { | |
sqlite3_exec(db, "begin", 0, 0, 0); | |
if (SQLITE_OK != sqlite3_exec(db, createSql, 0, 0, 0)) { | |
printf ("Can't fetch data: %s\n", sqlite3_errmsg(db)); | |
break; | |
} | |
sqlite3_exec(db, "create table temp.dataset_old as select * from temp.dataset where 1 = 2", 0, 0, 0); | |
sqlite3_stmt* stmt; | |
if (SQLITE_OK == sqlite3_prepare_v2(db, "select * from temp.dataset except select * from temp.dataset_old", -1, &stmt, 0)) { | |
while (SQLITE_ROW == sqlite3_step(stmt)) { | |
int colCount = sqlite3_column_count(stmt); | |
for (int colNo = 0; colNo < colCount; colNo++) { | |
printf((const char*)sqlite3_column_text(stmt, colNo)); | |
printf(colNo != colCount - 1 ? " | " : "\n"); | |
} | |
} | |
} | |
sqlite3_finalize(stmt); | |
sqlite3_exec(db, "drop table temp.dataset_old", 0, 0, 0); | |
sqlite3_exec(db, "alter table temp.dataset rename to dataset_old", 0, 0, 0); | |
sqlite3_exec(db, "commit", 0, 0, 0); | |
sleep(timer); | |
} | |
sqlite3_close(db); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Windows 32-bit binary - https://sgeproject.narod.ru/watcher.zip