Skip to content

Commit 9e8929e

Browse files
committed
Separate connections
1 parent 80ab30b commit 9e8929e

File tree

1 file changed

+53
-38
lines changed

1 file changed

+53
-38
lines changed

lib/charms/postgresql_k8s/v1/postgresql.py

Lines changed: 53 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -816,28 +816,27 @@ def set_up_database(self, temp_location: Optional[str] = None) -> None:
816816
connection.close()
817817
connection = None
818818

819-
for database in self._get_existing_databases():
820-
with self._connect_to_database(
821-
database=database
822-
) as connection, connection.cursor() as cursor:
823-
cursor.execute(
824-
"SELECT TRUE FROM pg_roles WHERE rolname='charmed_databases_owner';"
819+
with self._connect_to_database(
820+
database="template1"
821+
) as connection, connection.cursor() as cursor:
822+
cursor.execute(
823+
"SELECT TRUE FROM pg_roles WHERE rolname='charmed_databases_owner';"
824+
)
825+
if cursor.fetchone() is None:
826+
self.create_user(
827+
"charmed_databases_owner",
828+
can_create_database=True,
825829
)
826-
if cursor.fetchone() is None:
827-
self.create_user(
828-
"charmed_databases_owner",
829-
can_create_database=True,
830-
)
831830

832-
self.set_up_login_hook_function(cursor)
833-
self.set_up_predefined_catalog_roles_function(cursor)
831+
self.set_up_login_hook_function()
832+
self.set_up_predefined_catalog_roles_function()
834833

835-
# Create database function and event trigger to identify users created by PgBouncer.
836-
cursor.execute(
837-
"SELECT TRUE FROM pg_event_trigger WHERE evtname = 'update_pg_hba_on_create_schema';"
838-
)
839-
if cursor.fetchone() is None:
840-
cursor.execute("""
834+
# Create database function and event trigger to identify users created by PgBouncer.
835+
cursor.execute(
836+
"SELECT TRUE FROM pg_event_trigger WHERE evtname = 'update_pg_hba_on_create_schema';"
837+
)
838+
if cursor.fetchone() is None:
839+
cursor.execute("""
841840
CREATE OR REPLACE FUNCTION update_pg_hba()
842841
RETURNS event_trigger
843842
LANGUAGE plpgsql
@@ -894,21 +893,21 @@ def set_up_database(self, temp_location: Optional[str] = None) -> None:
894893
END;
895894
$$;
896895
""")
897-
cursor.execute("""
896+
cursor.execute("""
898897
CREATE EVENT TRIGGER update_pg_hba_on_create_schema
899898
ON ddl_command_end
900899
WHEN TAG IN ('CREATE SCHEMA')
901900
EXECUTE FUNCTION update_pg_hba();
902901
""")
903-
cursor.execute("""
902+
cursor.execute("""
904903
CREATE EVENT TRIGGER update_pg_hba_on_drop_schema
905904
ON ddl_command_end
906905
WHEN TAG IN ('DROP SCHEMA')
907906
EXECUTE FUNCTION update_pg_hba();
908907
""")
909908

910-
connection.close()
911-
connection = None
909+
connection.close()
910+
connection = None
912911

913912
with self._connect_to_database() as connection, connection.cursor() as cursor:
914913
cursor.execute("REVOKE ALL PRIVILEGES ON DATABASE postgres FROM PUBLIC;")
@@ -928,7 +927,7 @@ def set_up_database(self, temp_location: Optional[str] = None) -> None:
928927
if connection is not None:
929928
connection.close()
930929

931-
def set_up_login_hook_function(self, cursor) -> None:
930+
def set_up_login_hook_function(self) -> None:
932931
"""Create a login hook function to set the user for the current session."""
933932
function_creation_statement = """CREATE OR REPLACE FUNCTION login_hook.login() RETURNS VOID AS $$
934933
DECLARE
@@ -974,16 +973,24 @@ def set_up_login_hook_function(self, cursor) -> None:
974973
END;
975974
END;
976975
$$ LANGUAGE plpgsql;"""
976+
connection = None
977977
try:
978-
cursor.execute(SQL("CREATE EXTENSION IF NOT EXISTS login_hook;"))
979-
cursor.execute(SQL("CREATE SCHEMA IF NOT EXISTS login_hook;"))
980-
cursor.execute(SQL(function_creation_statement))
981-
cursor.execute(SQL("GRANT EXECUTE ON FUNCTION login_hook.login() TO PUBLIC;"))
978+
for database in self._get_existing_databases():
979+
with self._connect_to_database(
980+
database=database
981+
) as connection, connection.cursor() as cursor:
982+
cursor.execute(SQL("CREATE EXTENSION IF NOT EXISTS login_hook;"))
983+
cursor.execute(SQL("CREATE SCHEMA IF NOT EXISTS login_hook;"))
984+
cursor.execute(SQL(function_creation_statement))
985+
cursor.execute(SQL("GRANT EXECUTE ON FUNCTION login_hook.login() TO PUBLIC;"))
982986
except psycopg2.Error as e:
983987
logger.error(f"Failed to create login hook function: {e}")
984988
raise e
989+
finally:
990+
if connection:
991+
connection.close()
985992

986-
def set_up_predefined_catalog_roles_function(self, cursor) -> None:
993+
def set_up_predefined_catalog_roles_function(self) -> None:
987994
"""Create predefined catalog roles function."""
988995
function_creation_statement = """CREATE OR REPLACE FUNCTION set_up_predefined_catalog_roles() RETURNS VOID AS $$
989996
DECLARE
@@ -1053,19 +1060,27 @@ def set_up_predefined_catalog_roles_function(self, cursor) -> None:
10531060
END LOOP;
10541061
END;
10551062
$$ LANGUAGE plpgsql security definer;"""
1063+
connection = None
10561064
try:
1057-
cursor.execute(SQL(function_creation_statement))
1058-
cursor.execute(
1059-
SQL("ALTER FUNCTION set_up_predefined_catalog_roles OWNER TO operator;")
1060-
)
1061-
cursor.execute(
1062-
SQL(
1063-
"GRANT execute ON FUNCTION set_up_predefined_catalog_roles TO charmed_databases_owner;"
1064-
)
1065-
)
1065+
for database in self._get_existing_databases():
1066+
with self._connect_to_database(
1067+
database=database
1068+
) as connection, connection.cursor() as cursor:
1069+
cursor.execute(SQL(function_creation_statement))
1070+
cursor.execute(
1071+
SQL("ALTER FUNCTION set_up_predefined_catalog_roles OWNER TO operator;")
1072+
)
1073+
cursor.execute(
1074+
SQL(
1075+
"GRANT execute ON FUNCTION set_up_predefined_catalog_roles TO charmed_databases_owner;"
1076+
)
1077+
)
10661078
except psycopg2.Error as e:
10671079
logger.error(f"Failed to set up predefined catalog roles function: {e}")
10681080
raise PostgreSQLCreatePredefinedRolesError() from e
1081+
finally:
1082+
if connection:
1083+
connection.close()
10691084

10701085
def update_user_password(
10711086
self, username: str, password: str, database_host: Optional[str] = None

0 commit comments

Comments
 (0)