|
| 1 | +import logging |
| 2 | +from typing import Any, Optional |
| 3 | +from urllib.parse import quote, urlencode |
| 4 | + |
| 5 | +from testcontainers.core.container import DockerContainer |
| 6 | +from testcontainers.core.exceptions import ContainerStartException |
| 7 | +from testcontainers.core.waiting_utils import WaitStrategy |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class SqlContainer(DockerContainer): |
| 13 | + """ |
| 14 | + Generic SQL database container providing common functionality. |
| 15 | +
|
| 16 | + This class can serve as a base for database-specific container implementations. |
| 17 | + It provides connection management, URL construction, and basic lifecycle methods. |
| 18 | + Database connection readiness is automatically handled by the provided wait strategy. |
| 19 | +
|
| 20 | + Note: `SqlAlchemyConnectWaitStrategy` from `sql_connection_wait_strategy` is a provided wait strategy for SQL databases. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, image: str, wait_strategy: WaitStrategy, **kwargs): |
| 24 | + """ |
| 25 | + Initialize SqlContainer with optional wait strategy. |
| 26 | +
|
| 27 | + Args: |
| 28 | + image: Docker image name |
| 29 | + wait_strategy: Wait strategy for SQL database connectivity |
| 30 | + **kwargs: Additional arguments passed to DockerContainer |
| 31 | + """ |
| 32 | + super().__init__(image, **kwargs) |
| 33 | + self.wait_strategy = wait_strategy |
| 34 | + |
| 35 | + def _create_connection_url( |
| 36 | + self, |
| 37 | + dialect: str, |
| 38 | + username: str, |
| 39 | + password: str, |
| 40 | + host: Optional[str] = None, |
| 41 | + port: Optional[int] = None, |
| 42 | + dbname: Optional[str] = None, |
| 43 | + query_params: Optional[dict[str, str]] = None, |
| 44 | + **kwargs: Any, |
| 45 | + ) -> str: |
| 46 | + """ |
| 47 | + Create a database connection URL. |
| 48 | +
|
| 49 | + Args: |
| 50 | + dialect: Database dialect (e.g., 'postgresql', 'mysql') |
| 51 | + username: Database username |
| 52 | + password: Database password |
| 53 | + host: Database host (defaults to container host) |
| 54 | + port: Database port |
| 55 | + dbname: Database name |
| 56 | + query_params: Additional query parameters for the URL |
| 57 | + **kwargs: Additional parameters (checked for deprecated usage) |
| 58 | +
|
| 59 | + Returns: |
| 60 | + str: Formatted database connection URL |
| 61 | +
|
| 62 | + Raises: |
| 63 | + ValueError: If unexpected arguments are provided or required parameters are missing |
| 64 | + ContainerStartException: If container is not started |
| 65 | + """ |
| 66 | + |
| 67 | + if self._container is None: |
| 68 | + raise ContainerStartException("Container has not been started") |
| 69 | + |
| 70 | + host = host or self.get_container_host_ip() |
| 71 | + exposed_port = self.get_exposed_port(port) |
| 72 | + quoted_password = quote(password, safe="") |
| 73 | + quoted_username = quote(username, safe="") |
| 74 | + url = f"{dialect}://{quoted_username}:{quoted_password}@{host}:{exposed_port}" |
| 75 | + |
| 76 | + if dbname: |
| 77 | + quoted_dbname = quote(dbname, safe="") |
| 78 | + url = f"{url}/{quoted_dbname}" |
| 79 | + |
| 80 | + if query_params: |
| 81 | + query_string = urlencode(query_params) |
| 82 | + url = f"{url}?{query_string}" |
| 83 | + |
| 84 | + return url |
| 85 | + |
| 86 | + def start(self) -> "SqlContainer": |
| 87 | + """ |
| 88 | + Start the database container and perform initialization. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + SqlContainer: Self for method chaining |
| 92 | +
|
| 93 | + Raises: |
| 94 | + ContainerStartException: If container fails to start |
| 95 | + Exception: If configuration, seed transfer, or connection fails |
| 96 | + """ |
| 97 | + logger.info(f"Starting database container: {self.image}") |
| 98 | + |
| 99 | + try: |
| 100 | + self._configure() |
| 101 | + self.waiting_for(self.wait_strategy) |
| 102 | + super().start() |
| 103 | + self._transfer_seed() |
| 104 | + logger.info("Database container started successfully") |
| 105 | + except Exception as e: |
| 106 | + logger.error(f"Failed to start database container: {e}") |
| 107 | + raise |
| 108 | + |
| 109 | + return self |
| 110 | + |
| 111 | + def _configure(self) -> None: |
| 112 | + """ |
| 113 | + Configure the database container before starting. |
| 114 | +
|
| 115 | + Raises: |
| 116 | + NotImplementedError: Must be implemented by subclasses |
| 117 | + """ |
| 118 | + raise NotImplementedError("Subclasses must implement _configure()") |
| 119 | + |
| 120 | + def _transfer_seed(self) -> None: |
| 121 | + """ |
| 122 | + Transfer seed data to the database container. |
| 123 | +
|
| 124 | + This method can be overridden by subclasses to provide |
| 125 | + database-specific seeding functionality. |
| 126 | + """ |
| 127 | + logger.debug("No seed data to transfer") |
| 128 | + |
| 129 | + def get_connection_url(self) -> str: |
| 130 | + """ |
| 131 | + Get the database connection URL. |
| 132 | +
|
| 133 | + Returns: |
| 134 | + str: Database connection URL |
| 135 | +
|
| 136 | + Raises: |
| 137 | + NotImplementedError: Must be implemented by subclasses |
| 138 | + """ |
| 139 | + raise NotImplementedError("Subclasses must implement get_connection_url()") |
0 commit comments