From dd56ba5f9b3f9308df6b07bb287f97789c3aca10 Mon Sep 17 00:00:00 2001
From: Bastien Abadie <abadie@teklia.com>
Date: Wed, 27 Mar 2024 14:18:55 +0000
Subject: [PATCH] Ensure django database wrappers always have a connection
 before creating a cursor

---
 arkindex/documents/export/__init__.py | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/arkindex/documents/export/__init__.py b/arkindex/documents/export/__init__.py
index a1c633e3af..df872fcbc3 100644
--- a/arkindex/documents/export/__init__.py
+++ b/arkindex/documents/export/__init__.py
@@ -51,7 +51,13 @@ def run_pg_query(query, source_db):
     Run a single Postgresql query and split the results into chunks.
     When a name is given to a cursor, psycopg2 uses a server-side cursor; we just use a random string as a name.
     """
-    with connections[source_db].create_cursor(name=str(uuid.uuid4())) as pg_cursor:
+    db = connections[source_db]
+
+    # Make sure a connection is open and available for export databases
+    if source_db != "default" and db.connection is None:
+        db.connect()
+
+    with db.create_cursor(name=str(uuid.uuid4())) as pg_cursor:
         pg_cursor.itersize = BATCH_SIZE
         pg_cursor.execute(query)
 
-- 
GitLab