Skip to content

Commit 53b928d

Browse files
committed
Made db ref_count atomic and fixed related error handling bug
1 parent 2602248 commit 53b928d

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

lib/sqlite3_stubs.c

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ static inline value safe_copy_header_strings(const char **strs, int len) {
360360
/* Databases */
361361

362362
static inline void ref_count_finalize_dbw(db_wrap *dbw) {
363-
if (--dbw->ref_count == 0) {
363+
if (atomic_fetch_sub(&dbw->ref_count, 1) == 1) {
364364
user_function *link, *next;
365365
for (link = dbw->user_functions; link != NULL; link = next) {
366366
caml_remove_generational_global_root(&link->v_fun);
@@ -856,7 +856,6 @@ static inline value prepare_it(db_wrap *dbw, const char *sql, int sql_len,
856856
int rc;
857857
stmt_wrap *stmtw = caml_stat_alloc(sizeof(stmt_wrap));
858858
stmtw->db_wrap = dbw;
859-
dbw->ref_count++;
860859
stmtw->sql = caml_stat_alloc(sql_len + 1);
861860
memcpy(stmtw->sql, sql, sql_len);
862861
stmtw->sql[sql_len] = '\0';
@@ -869,19 +868,19 @@ static inline value prepare_it(db_wrap *dbw, const char *sql, int sql_len,
869868
if (rc != SQLITE_OK)
870869
raise_sqlite3_current(dbw->db, loc);
871870
raise_sqlite3_Error("No code compiled from %s", sql);
872-
} else {
871+
}
872+
atomic_fetch_add(&dbw->ref_count, 1);
873873
#if SQLITE_STMTSTATUS_MEMUSED
874-
size_t mem = sizeof(stmt_wrap) + sql_len + 1 +
875-
sqlite3_stmt_status(stmtw->stmt, SQLITE_STMTSTATUS_MEMUSED, 0);
876-
value v_stmt =
877-
caml_alloc_custom_mem(&stmt_wrap_ops, sizeof(stmt_wrap *), mem);
874+
size_t mem = sizeof(stmt_wrap) + sql_len + 1 +
875+
sqlite3_stmt_status(stmtw->stmt, SQLITE_STMTSTATUS_MEMUSED, 0);
876+
value v_stmt =
877+
caml_alloc_custom_mem(&stmt_wrap_ops, sizeof(stmt_wrap *), mem);
878878
#else
879-
value v_stmt =
880-
caml_alloc_custom(&stmt_wrap_ops, sizeof(stmt_wrap *), 1, 1000);
879+
value v_stmt =
880+
caml_alloc_custom(&stmt_wrap_ops, sizeof(stmt_wrap *), 1, 1000);
881881
#endif
882-
Sqlite3_stmtw_val(v_stmt) = stmtw;
883-
return v_stmt;
884-
}
882+
Sqlite3_stmtw_val(v_stmt) = stmtw;
883+
return v_stmt;
885884
}
886885

887886
CAMLprim value caml_sqlite3_stmt_finalize(value v_stmt) {

0 commit comments

Comments
 (0)