|
| 1 | +from os import environ |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +from testcontainers.core.generic import DbContainer |
| 5 | +from testcontainers.core.waiting_utils import wait_container_is_ready, wait_for_logs |
| 6 | + |
| 7 | + |
| 8 | +class Db2Container(DbContainer): |
| 9 | + """ |
| 10 | + IBM Db2 database container. |
| 11 | +
|
| 12 | + Example: |
| 13 | +
|
| 14 | + .. doctest:: |
| 15 | +
|
| 16 | + >>> import sqlalchemy |
| 17 | + >>> from testcontainers.db2 import Db2Container |
| 18 | +
|
| 19 | + >>> with Db2Container("icr.io/db2_community/db2:latest") as db2: |
| 20 | + ... engine = sqlalchemy.create_engine(db2.get_connection_url()) |
| 21 | + ... with engine.begin() as connection: |
| 22 | + ... result = connection.execute(sqlalchemy.text("select service_level from sysibmadm.env_inst_info")) |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + image: str = "icr.io/db2_community/db2:latest", |
| 28 | + username: str = "db2inst1", |
| 29 | + password: Optional[str] = None, |
| 30 | + port: int = 50000, |
| 31 | + dbname: str = "testdb", |
| 32 | + dialect: str = "db2+ibm_db", |
| 33 | + **kwargs, |
| 34 | + ) -> None: |
| 35 | + super().__init__(image, **kwargs) |
| 36 | + |
| 37 | + self.port = port |
| 38 | + self.with_exposed_ports(self.port) |
| 39 | + |
| 40 | + self.password = password or environ.get("DB2_PASSWORD", "password") |
| 41 | + self.username = username |
| 42 | + self.dbname = dbname |
| 43 | + self.dialect = dialect |
| 44 | + |
| 45 | + def _configure(self) -> None: |
| 46 | + self.with_env("LICENSE", "accept") |
| 47 | + self.with_env("DB2INSTANCE", self.username) |
| 48 | + self.with_env("DB2INST1_PASSWORD", self.password) |
| 49 | + self.with_env("DBNAME", self.dbname) |
| 50 | + self.with_env("ARCHIVE_LOGS", "false") |
| 51 | + self.with_env("AUTOCONFIG", "false") |
| 52 | + self.with_kwargs(privileged=True) |
| 53 | + |
| 54 | + @wait_container_is_ready() |
| 55 | + def _connect(self) -> None: |
| 56 | + wait_for_logs(self, predicate="Setup has completed") |
| 57 | + |
| 58 | + def get_connection_url(self) -> str: |
| 59 | + return super()._create_connection_url( |
| 60 | + dialect=self.dialect, username=self.username, password=self.password, dbname=self.dbname, port=self.port |
| 61 | + ) |
0 commit comments