Skip to content

Commit d96bfcb

Browse files
[MISC] Define charm constants (#774)
1 parent d65d531 commit d96bfcb

File tree

6 files changed

+36
-18
lines changed

6 files changed

+36
-18
lines changed

lib/charms/postgresql_k8s/v0/postgresql.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@
3535

3636
# Increment this PATCH version before using `charmcraft publish-lib` or reset
3737
# to 0 if you are raising the major API version
38-
LIBPATCH = 42
38+
LIBPATCH = 43
39+
40+
# Groups to distinguish database permissions
41+
PERMISSIONS_GROUP_ADMIN = "admin"
3942

4043
INVALID_EXTRA_USER_ROLE_BLOCKING_MESSAGE = "invalid role(s) for extra user roles"
4144

@@ -187,7 +190,7 @@ def create_database(
187190
Identifier(database)
188191
)
189192
)
190-
for user_to_grant_access in [user, "admin", *self.system_users]:
193+
for user_to_grant_access in [user, PERMISSIONS_GROUP_ADMIN, *self.system_users]:
191194
cursor.execute(
192195
SQL("GRANT ALL PRIVILEGES ON DATABASE {} TO {};").format(
193196
Identifier(database), Identifier(user_to_grant_access)
@@ -236,15 +239,17 @@ def create_user(
236239
roles = privileges = None
237240
if extra_user_roles:
238241
extra_user_roles = tuple(extra_user_roles.lower().split(","))
239-
admin_role = "admin" in extra_user_roles
242+
admin_role = PERMISSIONS_GROUP_ADMIN in extra_user_roles
240243
valid_privileges, valid_roles = self.list_valid_privileges_and_roles()
241244
roles = [
242-
role for role in extra_user_roles if role in valid_roles and role != "admin"
245+
role
246+
for role in extra_user_roles
247+
if role in valid_roles and role != PERMISSIONS_GROUP_ADMIN
243248
]
244249
privileges = {
245250
extra_user_role
246251
for extra_user_role in extra_user_roles
247-
if extra_user_role not in roles and extra_user_role != "admin"
252+
if extra_user_role not in roles and extra_user_role != PERMISSIONS_GROUP_ADMIN
248253
}
249254
invalid_privileges = [
250255
privilege for privilege in privileges if privilege not in valid_privileges
@@ -566,7 +571,7 @@ def set_up_database(self) -> None:
566571
)
567572
)
568573
self.create_user(
569-
"admin",
574+
PERMISSIONS_GROUP_ADMIN,
570575
extra_user_roles="pg_read_all_data,pg_write_all_data",
571576
)
572577
cursor.execute("GRANT CONNECT ON DATABASE postgres TO admin;")

src/charm.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
from constants import (
7272
APP_SCOPE,
7373
BACKUP_USER,
74+
DATABASE_DEFAULT_NAME,
7475
METRICS_PORT,
7576
MONITORING_PASSWORD_KEY,
7677
MONITORING_SNAP_SERVICE,
@@ -373,7 +374,7 @@ def postgresql(self) -> PostgreSQL:
373374
current_host=self._unit_ip,
374375
user=USER,
375376
password=self.get_secret(APP_SCOPE, f"{USER}-password"),
376-
database="postgres",
377+
database=DATABASE_DEFAULT_NAME,
377378
system_users=SYSTEM_USERS,
378379
)
379380

src/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
BACKUP_ID_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
77
PGBACKREST_BACKUP_ID_FORMAT = "%Y%m%d-%H%M%S"
88
DATABASE = "database"
9+
DATABASE_DEFAULT_NAME = "postgres"
910
DATABASE_PORT = "5432"
1011
LEGACY_DB = "db"
1112
LEGACY_DB_ADMIN = "db-admin"

tests/integration/helpers.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
wait_fixed,
3131
)
3232

33+
from constants import DATABASE_DEFAULT_NAME
34+
3335
CHARM_BASE = "ubuntu@22.04"
3436
METADATA = yaml.safe_load(Path("./metadata.yaml").read_text())
3537
DATABASE_APP_NAME = METADATA["name"]
@@ -497,7 +499,7 @@ async def execute_query_on_unit(
497499
unit_address: str,
498500
password: str,
499501
query: str,
500-
database: str = "postgres",
502+
database: str = DATABASE_DEFAULT_NAME,
501503
sslmode: str | None = None,
502504
):
503505
"""Execute given PostgreSQL query on a unit.

tests/integration/new_relations/test_new_relations_1.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
from pytest_operator.plugin import OpsTest
1313
from tenacity import Retrying, stop_after_attempt, wait_fixed
1414

15+
from constants import DATABASE_DEFAULT_NAME
16+
1517
from ..helpers import (
1618
CHARM_BASE,
1719
assert_sync_standbys,
@@ -277,7 +279,10 @@ async def test_two_applications_doesnt_share_the_same_relation_data(ops_test: Op
277279
(another_application_app_name, f"{APPLICATION_APP_NAME.replace('-', '_')}_database"),
278280
]:
279281
connection_string = await build_connection_string(
280-
ops_test, application, FIRST_DATABASE_RELATION_NAME, database="postgres"
282+
ops_test,
283+
application,
284+
FIRST_DATABASE_RELATION_NAME,
285+
database=DATABASE_DEFAULT_NAME,
281286
)
282287
with pytest.raises(psycopg2.Error):
283288
psycopg2.connect(connection_string)
@@ -487,7 +492,7 @@ async def test_admin_role(ops_test: OpsTest):
487492

488493
# Check that the user can access all the databases.
489494
for database in [
490-
"postgres",
495+
DATABASE_DEFAULT_NAME,
491496
f"{APPLICATION_APP_NAME.replace('-', '_')}_database",
492497
"another_application_database",
493498
]:
@@ -511,11 +516,11 @@ async def test_admin_role(ops_test: OpsTest):
511516
)
512517
assert version == data
513518

514-
# Write some data (it should fail in the "postgres" database).
519+
# Write some data (it should fail in the default database name).
515520
random_name = (
516521
f"test_{''.join(secrets.choice(string.ascii_lowercase) for _ in range(10))}"
517522
)
518-
should_fail = database == "postgres"
523+
should_fail = database == DATABASE_DEFAULT_NAME
519524
cursor.execute(f"CREATE TABLE {random_name}(data TEXT);")
520525
if should_fail:
521526
assert False, (
@@ -533,7 +538,7 @@ async def test_admin_role(ops_test: OpsTest):
533538

534539
# Test the creation and deletion of databases.
535540
connection_string = await build_connection_string(
536-
ops_test, DATA_INTEGRATOR_APP_NAME, "postgresql", database="postgres"
541+
ops_test, DATA_INTEGRATOR_APP_NAME, "postgresql", database=DATABASE_DEFAULT_NAME
537542
)
538543
connection = psycopg2.connect(connection_string)
539544
connection.autocommit = True
@@ -542,8 +547,10 @@ async def test_admin_role(ops_test: OpsTest):
542547
cursor.execute(f"CREATE DATABASE {random_name};")
543548
cursor.execute(f"DROP DATABASE {random_name};")
544549
try:
545-
cursor.execute("DROP DATABASE postgres;")
546-
assert False, "the admin extra user role was able to drop the `postgres` system database"
550+
cursor.execute(f"DROP DATABASE {DATABASE_DEFAULT_NAME};")
551+
assert False, (
552+
f"the admin extra user role was able to drop the `{DATABASE_DEFAULT_NAME}` system database"
553+
)
547554
except psycopg2.errors.InsufficientPrivilege:
548555
# Ignore the error, as the admin extra user role mustn't be able to drop
549556
# the "postgres" system database.

tests/integration/new_relations/test_relations_coherence.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import pytest
1010
from pytest_operator.plugin import OpsTest
1111

12+
from constants import DATABASE_DEFAULT_NAME
13+
1214
from ..helpers import CHARM_BASE, DATABASE_APP_NAME
1315
from .helpers import build_connection_string
1416
from .test_new_relations_1 import DATA_INTEGRATOR_APP_NAME
@@ -125,14 +127,14 @@ async def test_relations(ops_test: OpsTest, charm):
125127

126128
for database in [
127129
DATA_INTEGRATOR_APP_NAME.replace("-", "_"),
128-
"postgres",
130+
DATABASE_DEFAULT_NAME,
129131
]:
130132
logger.info(f"connecting to the following database: {database}")
131133
connection_string = await build_connection_string(
132134
ops_test, DATA_INTEGRATOR_APP_NAME, "postgresql", database=database
133135
)
134136
connection = None
135-
should_fail = database == "postgres"
137+
should_fail = database == DATABASE_DEFAULT_NAME
136138
try:
137139
with (
138140
psycopg2.connect(connection_string) as connection,
@@ -142,7 +144,7 @@ async def test_relations(ops_test: OpsTest, charm):
142144
data = cursor.fetchone()
143145
assert data[0] == "some data"
144146

145-
# Write some data (it should fail in the "postgres" database).
147+
# Write some data (it should fail in the default database name).
146148
random_name = f"test_{''.join(secrets.choice(string.ascii_lowercase) for _ in range(10))}"
147149
cursor.execute(f"CREATE TABLE {random_name}(data TEXT);")
148150
if should_fail:

0 commit comments

Comments
 (0)