Skip to content

Commit

Permalink
Create config for database name (#27)
Browse files Browse the repository at this point in the history
* Create config for database name

* Address lint warnings
  • Loading branch information
shayancanonical authored Mar 31, 2024
1 parent 406fe93 commit 13d4dc9
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 9 deletions.
4 changes: 4 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ options:
description: "Whether to auto start continuous writes on relation events."
type: boolean
default: true
database_name:
description: "Name of database to direct continuous writes to"
type: string
default: "continuous_writes_database"
23 changes: 18 additions & 5 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing import Dict, Optional

from charms.data_platform_libs.v0.data_interfaces import DatabaseRequires
from ops import EventBase
from ops.charm import ActionEvent, CharmBase
from ops.main import main
from ops.model import ActiveStatus, Relation, WaitingStatus
Expand All @@ -24,7 +25,6 @@
from connector import MySQLConnector # isort: skip
from literals import (
CONTINUOUS_WRITE_TABLE_NAME,
DATABASE_NAME,
DATABASE_RELATION,
LEGACY_MYSQL_RELATION,
PEER,
Expand All @@ -45,6 +45,7 @@ def __init__(self, *args):

# Charm events
self.framework.observe(self.on.start, self._on_start)
self.framework.observe(self.on.config_changed, self._on_config_changed)
self.framework.observe(self.on[PEER].relation_changed, self._on_peer_relation_changed)
self.framework.observe(self.on.update_status, self._on_update_status)

Expand Down Expand Up @@ -75,7 +76,9 @@ def __init__(self, *args):
)

# Database related events
self.database = DatabaseRequires(self, "database", DATABASE_NAME)
self.database = DatabaseRequires(
self, relation_name="database", database_name=self.database_name
)
self.framework.observe(
getattr(self.database.on, "database_created"), self._on_database_created
)
Expand Down Expand Up @@ -119,6 +122,11 @@ def unit_peer_data(self) -> Dict:

return self._peers.data[self.unit]

@property
def database_name(self) -> str:
"""Returns the database name for the continuous writes."""
return self.config["database_name"]

@property
def _database_config(self):
"""Returns the database config to use to connect to the MySQL cluster."""
Expand All @@ -144,7 +152,7 @@ def _database_config(self):
config = {
"user": username,
"password": password,
"database": DATABASE_NAME,
"database": self.database_name,
}
if endpoints.startswith("file://"):
config["unix_socket"] = endpoints[7:]
Expand Down Expand Up @@ -221,7 +229,7 @@ def _max_written_value(self) -> int:

with MySQLConnector(self._database_config) as cursor:
cursor.execute(
f"SELECT MAX(number) FROM `{DATABASE_NAME}`.`{CONTINUOUS_WRITE_TABLE_NAME}`;"
f"SELECT MAX(number) FROM `{self.database_name}`.`{CONTINUOUS_WRITE_TABLE_NAME}`;"
)
return cursor.fetchone()[0]

Expand Down Expand Up @@ -268,13 +276,18 @@ def _write_random_value(self) -> str:
# ==============
# Handlers
# ==============
def _on_config_changed(self, event: EventBase) -> None:
"""Handle config changes, especially database_name."""
logger.warning("Please unrelate and re-relate after updating the database_name config")

def _on_start(self, _) -> None:
"""Handle the start event."""
self.unit.set_workload_version("0.0.2")
if self._database_config:
self.unit.status = ActiveStatus()
else:
self.unit.status = WaitingStatus()
self.app_peer_data["initialized"] = "true"

def _on_clear_continuous_writes_action(self, _) -> None:
"""Handle the clear continuous writes action event."""
Expand All @@ -284,7 +297,7 @@ def _on_clear_continuous_writes_action(self, _) -> None:
self._stop_continuous_writes()
with MySQLConnector(self._database_config) as cursor:
cursor.execute(
f"DROP TABLE IF EXISTS `{DATABASE_NAME}`.`{CONTINUOUS_WRITE_TABLE_NAME}`;"
f"DROP TABLE IF EXISTS `{self.database_name}`.`{CONTINUOUS_WRITE_TABLE_NAME}`;"
)

def _on_start_continuous_writes_action(self, _) -> None:
Expand Down
1 change: 0 additions & 1 deletion src/literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"""Test application literals."""

CONTINUOUS_WRITE_TABLE_NAME = "data"
DATABASE_NAME = "continuous_writes_database"
DATABASE_RELATION = "database"
LEGACY_MYSQL_RELATION = "mysql" # MariaDB legacy relation
PEER = "application-peers"
Expand Down
8 changes: 5 additions & 3 deletions src/relations/legacy_mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import logging

from literals import DATABASE_NAME, LEGACY_MYSQL_RELATION
from literals import LEGACY_MYSQL_RELATION
from ops import Object, RelationChangedEvent
from ops.model import BlockedStatus

Expand Down Expand Up @@ -59,8 +59,10 @@ def _on_relation_joined(self, event):
return

database_name = relation_data["database"]
if database_name != DATABASE_NAME:
logger.error(f"Database name must be set to `{DATABASE_NAME}`. Modify the test.")
if database_name != self.charm.database_name:
logger.error(
f"Database name must be set to `{self.charm.database_name}`. Modify the test."
)
self.charm.unit.status = BlockedStatus("Wrong database name")
return

Expand Down

0 comments on commit 13d4dc9

Please sign in to comment.