Skip to content

Commit 4c2717f

Browse files
committed
Payload is now applied inside a transaction
1 parent 5990ea9 commit 4c2717f

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/cloudsync.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1514,6 +1514,7 @@ void *cloudsync_context_create (void) {
15141514
DEBUG_SETTINGS("cloudsync_context_create %p", data);
15151515

15161516
data->libversion = CLOUDSYNC_VERSION;
1517+
data->pending_db_version = CLOUDSYNC_VALUE_NOTSET;
15171518
#if CLOUDSYNC_DEBUG
15181519
data->debug = 1;
15191520
#endif
@@ -2150,11 +2151,19 @@ int cloudsync_payload_apply (sqlite3_context *context, const char *payload, int
21502151
buffer = (const char *)clone;
21512152
}
21522153

2154+
// apply payload inside a transaction
2155+
sqlite3 *db = sqlite3_context_db_handle(context);
2156+
int rc = sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
2157+
if (rc != SQLITE_OK) {
2158+
dbutils_context_result_error(context, "Error on cloudsync_payload_apply: unable to start a transaction (%s).", sqlite3_errmsg(db));
2159+
if (clone) cloudsync_memory_free(clone);
2160+
return -1;
2161+
}
2162+
21532163
// precompile the insert statement
21542164
sqlite3_stmt *vm = NULL;
2155-
sqlite3 *db = sqlite3_context_db_handle(context);
21562165
const char *sql = "INSERT INTO cloudsync_changes(tbl, pk, col_name, col_value, col_version, db_version, site_id, cl, seq) VALUES (?,?,?,?,?,?,?,?,?);";
2157-
int rc = sqlite3_prepare(db, sql, -1, &vm, NULL);
2166+
rc = sqlite3_prepare(db, sql, -1, &vm, NULL);
21582167
if (rc != SQLITE_OK) {
21592168
dbutils_context_result_error(context, "Error on cloudsync_payload_apply: error while compiling SQL statement (%s).", sqlite3_errmsg(db));
21602169
if (clone) cloudsync_memory_free(clone);
@@ -2197,8 +2206,11 @@ int cloudsync_payload_apply (sqlite3_context *context, const char *payload, int
21972206

21982207
char *lasterr = NULL;
21992208
if (rc != SQLITE_OK && rc != SQLITE_DONE) lasterr = cloudsync_string_dup(sqlite3_errmsg(db), false);
2209+
(lasterr) ? sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL) : sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL);
22002210

2201-
if (payload_apply_callback) payload_apply_callback(&payload_apply_xdata, &decoded_context, db, data, CLOUDSYNC_PAYLOAD_APPLY_CLEANUP, rc);
2211+
if (payload_apply_callback) {
2212+
payload_apply_callback(&payload_apply_xdata, &decoded_context, db, data, CLOUDSYNC_PAYLOAD_APPLY_CLEANUP, rc);
2213+
}
22022214

22032215
if (rc == SQLITE_DONE) rc = SQLITE_OK;
22042216
if (rc == SQLITE_OK) {

0 commit comments

Comments
 (0)