C

먼저 소스 코드에서 LiteSync를 컴파일하고 설치하거나 사용 중인 플랫폼에 맞는 미리 컴파일된 바이너리를 사용하세요. 무료 버전으로 시작할 수 있습니다.


예제 코드

litesync 모듈은 SQLite3 라이브러리와 동일한 API를 가지고 있습니다

#include <sqlite3.h>

char *uri = "file:app.db?node=secondary&connect=tcp://server:port";

int main() {
  sqlite3 *db;
  sqlite3_open(uri, &db);  /* 데이터베이스 열기 */

  /* db가 준비되었는지 확인 */
  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);
  }

  /* 이제 db 연결을 사용할 수 있습니다 */
  ...
}

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;
}


업데이트 알림

원격 노드와의 동기화로 인해 로컬 데이터베이스가 업데이트될 때 애플리케이션에 알림을 받을 수 있습니다. 알림은 사용자 정의 함수를 통해 이루어집니다.

static void on_db_update(sqlite3_context *context, int argc, sqlite3_value **argv){
  char* changes = sqlite3_value_text(argv[0]);
  printf("업데이트 수신됨: %s\n", changes);
}

sqlite3_create_function(db, "update_notification", 1, SQLITE_UTF8, NULL, &on_db_update, NULL, NULL);


트랜잭션 알림

로컬 트랜잭션이 원격 노드와 동기화될 때 애플리케이션에 알림을 받을 수 있습니다. 알림은 사용자 정의 함수를 통해 이루어집니다. `result` 인수의 값이 "OK"가 아닌 경우 오류 메시지를 포함합니다.

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("트랜잭션 동기화됨 (%s): %s\n", result, sql);
}

sqlite3_create_function(db, "transaction_notification", 2, SQLITE_UTF8, NULL, &on_transaction_sync, NULL, NULL);


동기화 상태

원격 노드와의 로컬 데이터베이스 동기화 상태를 확인할 수 있습니다.

char *json_str = sqlite3_query_value_str(db, "PRAGMA sync_status", NULL);
printf("동기화 상태: %s\n", json_str);
sqlite3_free(json_str);


주의: 알림 함수는 작업자 스레드에 의해 호출됩니다. 애플리케이션은 알림 함수 내에서 db 연결을 사용해서는 안 되며 가능한 한 빨리 반환해야 합니다! 애플리케이션은 반환하기 전에 알림을 메인 스레드로 전달할 수 있습니다.




빌드

gcc -o app app.c -llitesync