bpo-43505: Explicitly initialize and shutdown sqlite3 (GH-25404)
diff --git a/Modules/_sqlite/module.c b/Modules/_sqlite/module.c
index 6bfb1b7..8dbfa7b 100644
--- a/Modules/_sqlite/module.c
+++ b/Modules/_sqlite/module.c
@@ -343,8 +343,7 @@ static struct PyModuleDef _sqlite3module = {
#define ADD_TYPE(module, type) \
do { \
if (PyModule_AddType(module, &type) < 0) { \
- Py_DECREF(module); \
- return NULL; \
+ goto error; \
} \
} while (0)
@@ -370,6 +369,12 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
return NULL;
}
+ int rc = sqlite3_initialize();
+ if (rc != SQLITE_OK) {
+ PyErr_SetString(PyExc_ImportError, sqlite3_errstr(rc));
+ return NULL;
+ }
+
module = PyModule_Create(&_sqlite3module);
if (!module ||
@@ -380,8 +385,7 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
(pysqlite_statement_setup_types(module) < 0) ||
(pysqlite_prepare_protocol_setup_types(module) < 0)
) {
- Py_XDECREF(module);
- return NULL;
+ goto error;
}
ADD_TYPE(module, *pysqlite_ConnectionType);
@@ -428,12 +432,11 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
goto error;
}
-error:
- if (PyErr_Occurred())
- {
- PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
- Py_DECREF(module);
- module = NULL;
- }
return module;
+
+error:
+ sqlite3_shutdown();
+ PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
+ Py_XDECREF(module);
+ return NULL;
}