C
First follow the instructions to compile and install LiteSync from the source code or use the pre-compiled binaries for your platform. You can start with the free version.
Example code
The litesync module has the same API as the SQLite3 library
#include <sqlite3.h>
char *uri = "file:app.db?node=secondary&connect=tcp://server:port";
int main() {
sqlite3 *db;
sqlite3_open(uri, &db); /* open the database */
/* check if the db is ready */
while(1){
char *json_str = sqlite3_query_value_str(db, "PRAGMA sync_status", NULL);
bool db_is_ready = strstr(json_str, "\"db_is_ready\": true") > 0;
sqlite3_free(json_str);
if (db_is_ready) break;
sleep_ms(250);
}
/* now we can use the db connection */
...
}
char * sqlite3_query_value_str(sqlite3 *db, char *sql, char **ppErrMsg) {
char *ptr = NULL;
sqlite3_stmt *stmt;
int rc;
if (ppErrMsg) *ppErrMsg = NULL;
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
if (ppErrMsg) *ppErrMsg = sqlite3_strdup(sqlite3_errmsg(db));
return NULL;
}
if (sqlite3_step(stmt) == SQLITE_ROW) {
char *text = (char *)sqlite3_column_text(stmt, 0);
if (text) {
ptr = sqlite3_strdup(text);
}
}
sqlite3_finalize(stmt);
return ptr;
}
Update Notification
Your application can be notified when the local database is updated due to synchronization with remote nodes. The notification is done via a user-defined function.
static void on_db_update(sqlite3_context *context, int argc, sqlite3_value **argv){
char* changes = sqlite3_value_text(argv[0]);
printf("update received: %s\n", changes);
}
sqlite3_create_function(db, "update_notification", 1, SQLITE_UTF8, NULL, &on_db_update, NULL, NULL);
Transaction Notification
Your application can be notified when local transactions are synchronized with remote nodes. The notification is done via a user-defined function. If the value in the `result` argument is not "OK" then it contains the error message.
static void on_transaction_sync(sqlite3_context *context, int argc, sqlite3_value **argv){
char* sql = sqlite3_value_text(argv[0]);
char* result = sqlite3_value_text(argv[1]);
printf("Transaction synchronized (%s): %s\n", result, sql);
}
sqlite3_create_function(db, "transaction_notification", 2, SQLITE_UTF8, NULL, &on_transaction_sync, NULL, NULL);
Synchronization Status
Your application can check the synchronization status of the local database with the remote nodes.
char *json_str = sqlite3_query_value_str(db, "PRAGMA sync_status", NULL);
printf("sync status: %s\n", json_str);
sqlite3_free(json_str);
ATTENTION: The notification functions are called by the worker thread. The application should NOT use the db connection inside the notification functions and it must return as fast as possible! The application can transfer the notification to the main thread before returning.
Build
On Linux and macOS
gcc -o app app.c -llitesync
On Windows
gcc -o app app.c -L/path/to/litesync -llitesync