Skip to content

Commit 8d8c9c7

Browse files
committed
Track connection with the statement resource
We don't want the sqlite3 connection getting garbage collected before the statement is finalized.
1 parent 25abead commit 8d8c9c7

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

c_src/sqlite3_nif.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ typedef struct connection
2626

2727
typedef struct statement
2828
{
29+
connection_t* conn;
2930
sqlite3_stmt* statement;
3031
} statement_t;
3132

@@ -354,6 +355,9 @@ exqlite_prepare(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
354355
return make_error_tuple(env, "out_of_memory");
355356
}
356357

358+
enif_keep_resource(conn);
359+
statement->conn = conn;
360+
357361
rc = sqlite3_prepare_v3(conn->db, (char*)bin.data, bin.size, 0, &statement->statement, NULL);
358362
if (rc != SQLITE_OK) {
359363
enif_release_resource(statement);
@@ -865,6 +869,11 @@ statement_type_destructor(ErlNifEnv* env, void* arg)
865869
sqlite3_finalize(statement->statement);
866870
statement->statement = NULL;
867871
}
872+
873+
if (statement->conn) {
874+
enif_release_resource(statement->conn);
875+
statement->conn = NULL;
876+
}
868877
}
869878

870879
static int

0 commit comments

Comments
 (0)