2025-02-09 20:01:22 +01:00
|
|
|
from psycopg import connect
|
2025-02-09 19:48:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
def create_db(
|
|
|
|
hostname="localhost", username=None, password=None, dbname=None, port=None
|
|
|
|
):
|
|
|
|
"""Create test database.
|
|
|
|
|
|
|
|
:param hostname: string
|
|
|
|
:param username: string
|
|
|
|
:param password: string
|
|
|
|
:param dbname: string
|
|
|
|
:param port: int
|
|
|
|
:return:
|
|
|
|
|
|
|
|
"""
|
|
|
|
cn = create_cn(hostname, password, username, "postgres", port)
|
|
|
|
|
2025-02-09 20:01:22 +01:00
|
|
|
cn.autocommit = True
|
2025-02-09 19:48:22 +01:00
|
|
|
with cn.cursor() as cr:
|
2025-02-09 20:01:22 +01:00
|
|
|
cr.execute(f"drop database if exists {dbname}")
|
|
|
|
cr.execute(f"create database {dbname}")
|
2025-02-09 19:48:22 +01:00
|
|
|
|
|
|
|
cn.close()
|
|
|
|
|
|
|
|
cn = create_cn(hostname, password, username, dbname, port)
|
|
|
|
return cn
|
|
|
|
|
|
|
|
|
|
|
|
def create_cn(hostname, password, username, dbname, port):
|
|
|
|
"""
|
|
|
|
Open connection to database.
|
|
|
|
:param hostname:
|
|
|
|
:param password:
|
|
|
|
:param username:
|
|
|
|
:param dbname: string
|
|
|
|
:return: psycopg2.connection
|
|
|
|
"""
|
|
|
|
cn = connect(
|
2025-02-09 20:01:22 +01:00
|
|
|
host=hostname, user=username, dbname=dbname, password=password, port=port
|
2025-02-09 19:48:22 +01:00
|
|
|
)
|
|
|
|
|
2025-02-09 20:01:22 +01:00
|
|
|
print(f"Created connection: {cn.info.get_parameters()}.")
|
2025-02-09 19:48:22 +01:00
|
|
|
return cn
|
|
|
|
|
|
|
|
|
2025-02-09 20:01:22 +01:00
|
|
|
def pgbouncer_available(hostname="localhost", password=None, username="postgres"):
|
|
|
|
cn = None
|
|
|
|
try:
|
|
|
|
cn = create_cn(hostname, password, username, "pgbouncer", 6432)
|
|
|
|
return True
|
|
|
|
except:
|
|
|
|
print("Pgbouncer is not available.")
|
|
|
|
finally:
|
|
|
|
if cn:
|
|
|
|
cn.close()
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2025-02-09 19:48:22 +01:00
|
|
|
def drop_db(hostname="localhost", username=None, password=None, dbname=None, port=None):
|
|
|
|
"""
|
|
|
|
Drop database.
|
|
|
|
:param hostname: string
|
|
|
|
:param username: string
|
|
|
|
:param password: string
|
|
|
|
:param dbname: string
|
|
|
|
"""
|
|
|
|
cn = create_cn(hostname, password, username, "postgres", port)
|
|
|
|
|
|
|
|
# Needed for DB drop.
|
2025-02-09 20:01:22 +01:00
|
|
|
cn.autocommit = True
|
2025-02-09 19:48:22 +01:00
|
|
|
|
|
|
|
with cn.cursor() as cr:
|
2025-02-09 20:01:22 +01:00
|
|
|
cr.execute(f"drop database if exists {dbname}")
|
2025-02-09 19:48:22 +01:00
|
|
|
|
|
|
|
close_cn(cn)
|
|
|
|
|
|
|
|
|
|
|
|
def close_cn(cn=None):
|
|
|
|
"""
|
|
|
|
Close connection.
|
|
|
|
:param connection: psycopg2.connection
|
|
|
|
"""
|
|
|
|
if cn:
|
2025-02-09 20:01:22 +01:00
|
|
|
cn_params = cn.info.get_parameters()
|
2025-02-09 19:48:22 +01:00
|
|
|
cn.close()
|
2025-02-09 20:01:22 +01:00
|
|
|
print(f"Closed connection: {cn_params}.")
|