From 364981e072039de1322a72c936e3747c462e57d4 Mon Sep 17 00:00:00 2001
From: Matthew White <mehw.is.me@inventati.org>
Date: Fri, 5 May 2023 11:46:27 +0000
Subject: [PATCH] Plugins: fix compiling with Python 3.11

Python 3.11 removed PyThreadState()->frame, but since Python 3.9
PyThreadState_GetFrame() can be used to get the frame.

To get the frame's f_locals and f_globals use PyFrame_GetLocals()
and PyFrame_GetGlobals() when compiling with Python 3.11.

Merged here is also 'Fixed compilation for Python < 3.11':
https://github.com/pawelsalawa/sqlitestudio/commit/30ad718415ffe78a5ac0ff9cf12cff2bd01e9810

References:
https://docs.python.org/3/c-api/frame.html
---
 Plugins/ScriptingPython/scriptingpython.cpp | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/Plugins/ScriptingPython/scriptingpython.cpp b/Plugins/ScriptingPython/scriptingpython.cpp
index 1dedb5c106..663c55b7d7 100644
--- a/Plugins/ScriptingPython/scriptingpython.cpp
+++ b/Plugins/ScriptingPython/scriptingpython.cpp
@@ -582,15 +582,25 @@ SqlQueryPtr ScriptingPython::dbCommonEval(PyObject* sqlArg, const char* fnName)
 QVariant ScriptingPython::getVariable(const QString& name)
 {
     PyThreadState* state = PyThreadState_Get();
-    if (!state->frame)
+#if PY_VERSION_HEX < 0x03090000
+    PyFrameObject* frame = state->frame;
+#else
+    PyFrameObject* frame = PyThreadState_GetFrame(state);
+#endif
+    if (!frame)
         return QVariant();
 
     const char* varName = name.toUtf8().constData();
     PyObject* obj = nullptr;
 
-    PyFrame_FastToLocals(state->frame);
-    PyObject* locals = state->frame->f_locals;
-    PyObject* globals = state->frame->f_globals;
+    PyFrame_FastToLocals(frame);
+#if PY_VERSION_HEX < 0x030b0000
+    PyObject* locals = frame->f_locals;
+    PyObject* globals = frame->f_globals;
+#else
+    PyObject* locals = PyFrame_GetLocals(frame);
+    PyObject* globals = PyFrame_GetGlobals(frame);
+#endif
     if (PyMapping_Check(locals))
         obj = PyMapping_GetItemString(locals, varName);
     else if (PyDict_Check(globals))
