Skip to content

bpo-45089: raise exceptions on error in sqlite3 trace callback #28133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/sqlite3/test/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,15 @@ def trace(statement):
con2.close()
self.assertEqual(traced_statements, queries)

@with_tracebacks(["ZeroDivisionError", "division by zero"])
def test_trace_bad_handler(self):
cx = sqlite.connect(":memory:")
cx.set_trace_callback(lambda stmt: 5/0)
self.assertRaisesRegex(
sqlite.OperationalError, "trace callback raised an exception",
cx.execute, "select 1"
)


def suite():
tests = [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
The :mod:`sqlite3` trace callback now raise :exc:`~sqlite3.DataError` or
:exc:`~sqlite3.OperationalError` on error. Patch by Erlend E. Aasland.
30 changes: 18 additions & 12 deletions Modules/_sqlite/connection.c
Original file line number Diff line number Diff line change
Expand Up @@ -1011,27 +1011,33 @@ trace_callback(void *ctx, const char *statement_string)

PyGILState_STATE gilstate = PyGILState_Ensure();

PyObject *py_statement = NULL;
PyObject *ret = NULL;
py_statement = PyUnicode_DecodeUTF8(statement_string,
PyObject *py_statement = PyUnicode_DecodeUTF8(statement_string,
strlen(statement_string), "replace");
if (py_statement) {
ret = PyObject_CallOneArg((PyObject*)ctx, py_statement);
Py_DECREF(py_statement);
if (py_statement == NULL) {
pysqlite_state *state = pysqlite_get_state(NULL);
if (state->enable_callback_tracebacks) {
PyErr_Print();
}
PyErr_SetString(state->DataError,
"trace callback unable to fetch statement string");
goto exit;
}

if (ret) {
Py_DECREF(ret);
} else {
PyObject *ret = PyObject_CallOneArg((PyObject *)ctx, py_statement);
Py_DECREF(py_statement);
if (ret == NULL) {
pysqlite_state *state = pysqlite_get_state(NULL);
if (state->enable_callback_tracebacks) {
PyErr_Print();
}
else {
PyErr_Clear();
}
PyErr_SetString(state->OperationalError,
"trace callback raised an exception");
}
else {
Py_DECREF(ret);
}

exit:
PyGILState_Release(gilstate);
#ifdef HAVE_TRACE_V2
return 0;
Expand Down