Skip to content

Commit 57b8b7a

Browse files
suketaotegami
authored andcommitted
fix the DuckDB::PreparedStatement initialize function.
1 parent 807d3f7 commit 57b8b7a

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

ext/duckdb/prepared_statement.c

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ VALUE rbduckdb_prepared_statement_new(duckdb_connection con, duckdb_extracted_st
8181
static VALUE duckdb_prepared_statement_initialize(VALUE self, VALUE con, VALUE query) {
8282
rubyDuckDBConnection *ctxcon;
8383
rubyDuckDBPreparedStatement *ctx;
84+
duckdb_state state;
85+
const char *error;
8486

8587
if (!rb_obj_is_kind_of(con, cDuckDBConnection)) {
8688
rb_raise(rb_eTypeError, "1st argument should be instance of DackDB::Connection");
@@ -89,10 +91,20 @@ static VALUE duckdb_prepared_statement_initialize(VALUE self, VALUE con, VALUE q
8991
TypedData_Get_Struct(self, rubyDuckDBPreparedStatement, &prepared_statement_data_type, ctx);
9092
ctxcon = get_struct_connection(con);
9193

92-
if (duckdb_prepare(ctxcon->con, StringValuePtr(query), &(ctx->prepared_statement)) == DuckDBError) {
93-
const char *error = duckdb_prepare_error(ctx->prepared_statement);
94+
// Initialize to NULL before preparing
95+
ctx->prepared_statement = NULL;
96+
97+
// Try to prepare the statement and get the state
98+
state = duckdb_prepare(ctxcon->con, StringValuePtr(query), &(ctx->prepared_statement));
99+
100+
// Get error message before any exception might be thrown
101+
error = duckdb_prepare_error(ctx->prepared_statement);
102+
103+
// If preparation failed, raise Ruby exception with the error message
104+
if (state == DuckDBError) {
94105
rb_raise(eDuckDBError, "%s", error ? error : "Failed to prepare statement(Database connection closed?).");
95106
}
107+
96108
return self;
97109
}
98110

0 commit comments

Comments
 (0)