From f841bb887bf9b05da8ad4c05f34ab6001573b412 Mon Sep 17 00:00:00 2001
From: Marco Hald <marco.hald@usu.com>
Date: Thu, 28 Sep 2023 09:55:55 +0200
Subject: [PATCH] Fix get_bloat for Windows and use PGPASSFILE

This commit fixes two issue.
1. The get_bloat executes psql for each database.
This is necessary because otherwise it exceeds the maximum 8191 characters limit of windows https://learn.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/command-line-string-limitation
Which triggers the error "The command line is too long."
I observed it with 3 databases

2. The PGPASSFILE Env varaible is only overwritten by the instance pg_passfile when it is not empty.
In this way it is possible to use a system wide PGPASSFILE evnironment variable.
---
 agents/plugins/mk_postgres.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/agents/plugins/mk_postgres.py b/agents/plugins/mk_postgres.py
index ae174167774..88186e83845 100755
--- a/agents/plugins/mk_postgres.py
+++ b/agents/plugins/mk_postgres.py
@@ -125,7 +125,8 @@ def __init__(self, db_user, instance, process_match_patterns):
         self.pg_passfile = instance.get("pg_passfile", "")
         self.pg_version = instance.get("pg_version")
         self.my_env = os.environ.copy()
-        self.my_env["PGPASSFILE"] = instance.get("pg_passfile", "")
+        if instance.get("pg_passfile", ""):
+            self.my_env["PGPASSFILE"] = instance.get("pg_passfile", "")
         self.sep = os.sep
         self.psql_binary_name = "psql"
         self.psql_binary_path = self.get_psql_binary_path()
@@ -720,13 +721,16 @@ def get_bloat(self, databases, numeric_version):
         query = "\\pset footer off \\\\"
 
         cur_rows_only = False
+        output = ""
         for idx, database in enumerate(databases):
 
             query = "%s \\c %s \\\\ %s" % (query, database, bloat_query)
             if idx == 0:
                 query = "%s \\pset tuples_only on" % query
-
-        return self.run_sql_as_db_user(query, mixed_cmd=True, rows_only=cur_rows_only)
+            output += self.run_sql_as_db_user(query, mixed_cmd=True, rows_only=cur_rows_only)
+            cur_rows_only = True
+            query = "\\pset footer off \\\\"
+        return output
 
 
 class PostgresLinux(PostgresBase):