From e67e140554eafe2d9345ec8decc6ed3cd720e406 Mon Sep 17 00:00:00 2001
From: David Smith <david.smith@cern.ch>
Date: Tue, 13 Dec 2022 11:40:58 +0100
Subject: [PATCH] [Statistics] Avoid two concurrent queries using one db Conn
 in DatabaseStatisticsService

---
 ReleaseNotes.md                          | 1 +
 statistics/DatabaseStatisticsService.cpp | 9 ++++++++-
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/ReleaseNotes.md b/ReleaseNotes.md
index 821404fdfb..468882e3e4 100644
--- a/ReleaseNotes.md
+++ b/ReleaseNotes.md
@@ -12,6 +12,7 @@
 - cta/CTA#251 - Increase free drive STALE threshold to 4 hours
 - cta/CTA#218 - Do not retry during repack requests
 ### Bug Fixes
+- cta/CTA#181 - cta-statistics-update can fail for catalogues in postgres
 - cta/CTA#234 - Replace stoi with toUint64 in standalone cli tool
 - cta/CTA#238 - Compilation fails when using cta::common::Configuration::getConfEntInt(...)
 ### Continuous Integration
diff --git a/statistics/DatabaseStatisticsService.cpp b/statistics/DatabaseStatisticsService.cpp
index 662aed6b42..39c10c239a 100644
--- a/statistics/DatabaseStatisticsService.cpp
+++ b/statistics/DatabaseStatisticsService.cpp
@@ -16,6 +16,7 @@
  */
 
 #include <string>
+#include <vector>
 
 #include "DatabaseStatisticsService.hpp"
 
@@ -92,10 +93,16 @@ void DatabaseStatisticsService::updateStatisticsPerTape() {
   try {
     auto selectStmt = m_conn.createStmt(selectVids);
     auto rset = selectStmt.executeQuery();
+    // Make a list of all dirty vids. The memory required for the list is
+    // expected to be acceptable.
+    std::vector<std::string> dirtyVids;
     while (rset.next()) {
+      dirtyVids.push_back(rset.columnString("VID"));
+    }
+    for (const auto & vid : dirtyVids) {
       // For all DIRTY tapes, update its statistics
       auto updateStmt = m_conn.createStmt(updateSql);
-      updateStmt.bindString(":VID", rset.columnString("VID"));
+      updateStmt.bindString(":VID", vid);
       updateStmt.executeNonQuery();
       m_nbUpdatedTapes += updateStmt.getNbAffectedRows();
     }
-- 
GitLab