Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,12 @@ You can define settings via fixture factory arguments, command line options, or
- --postgresql-load-autocommit
- postgresql_load_autocommit
- False
* - Test database cloning strategy
- create_strategy
- create_strategy
- --postgresql-create-strategy
- postgresql_create_strategy
- PostgreSQL's default
* - PostgreSQL connection options
- options
- options
Expand Down Expand Up @@ -500,6 +506,61 @@ This example shows how to create an SQLAlchemy session fixture:
SessionLocal.close()
Base.metadata.drop_all(engine)

Advanced Usage: Test database cloning
-------------------------------------

Use ``create_strategy`` on ``postgresql_proc`` or ``postgresql_noproc`` to choose
how synchronous and asynchronous client fixtures clone the template database
for each test. Initial and layered template creation keep the server default.

.. code-block:: python

postgresql_my_proc = factories.postgresql_proc(create_strategy="clone")
postgresql_my = factories.postgresql("postgresql_my_proc")

For an existing server, including PostgreSQL in Docker, configure the noproc
factory instead:

.. code-block:: python

postgresql_external = factories.postgresql_noproc(create_strategy="clone")
postgresql_my = factories.postgresql("postgresql_external")
postgresql_my_async = factories.postgresql_async("postgresql_external")

The same setting is available on the command line and in ``pytest.ini``:

.. code-block:: sh

pytest --postgresql-create-strategy=clone

.. code-block:: ini

[pytest]
postgresql_create_strategy = clone

The available values are:

* Unset (the default): no ``STRATEGY`` clause or session setting is sent.
* ``wal_log``: ``CREATE DATABASE ... STRATEGY WAL_LOG`` (PostgreSQL 15+).
* ``file_copy``: ``SET file_copy_method = copy``, then
``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+).
* ``clone``: ``SET file_copy_method = clone``, then
``CREATE DATABASE ... STRATEGY FILE_COPY`` (PostgreSQL 18+).

The session setting and database creation use the same connection; no server
restart is needed. PostgreSQL reports unsupported settings or strategies directly.
Factory arguments take precedence over command line and ini options. Chained
fixtures use the client-facing noproc factory's argument or global configuration,
not the strategy of its ``depends_on`` fixture.

``clone`` needs operating-system support, and sharing disk blocks depends on the
server's filesystem supporting reflinks. It is not guaranteed to improve
performance; compare the full test suite at its usual worker count. For strategy,
checkpoint and filesystem details, see PostgreSQL's `CREATE DATABASE documentation
<https://www.postgresql.org/docs/18/sql-createdatabase.html>`_ and
`file_copy_method documentation
<https://www.postgresql.org/docs/18/runtime-config-resource.html#GUC-FILE-COPY-METHOD>`_.

Advanced Usage: DatabaseJanitor
-------------------------------

Expand Down
4 changes: 4 additions & 0 deletions newsfragments/1260.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Add ``create_strategy`` to the process and noproc factories, with matching CLI
and ini options, to select PostgreSQL's default, ``wal_log``, ``file_copy``, or
the operating-system ``clone`` method when client fixtures copy the template
database. The default remains unchanged; cloning does not guarantee reflinks.
18 changes: 18 additions & 0 deletions pytest_postgresql/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@
import pytest
from _pytest._py.path import LocalPath

CREATE_STRATEGIES = ("wal_log", "file_copy", "clone")


def validate_create_strategy(create_strategy: str | None) -> str | None:
"""Validate the optional database cloning strategy."""
if create_strategy is not None and create_strategy not in CREATE_STRATEGIES:
raise ValueError(
f"Invalid PostgreSQL create_strategy {create_strategy!r}; "
f"expected one of {', '.join(CREATE_STRATEGIES)} or None"
)
return create_strategy


@dataclass(frozen=True)
class PostgreSQLConfig:
Expand All @@ -27,6 +39,7 @@ class PostgreSQLConfig:
load_autocommit: bool
postgres_options: str
drop_test_database: bool
create_strategy: str | None = None


def get_config(request: pytest.FixtureRequest) -> PostgreSQLConfig:
Expand All @@ -37,6 +50,10 @@ def get_postgresql_option(option: str) -> Any:
return request.config.getoption(name) or request.config.getini(name)

load_paths: list[Path | str] = detect_paths(get_postgresql_option("load"))
try:
create_strategy = validate_create_strategy(get_postgresql_option("create_strategy"))
except ValueError as exc:
raise pytest.UsageError(str(exc)) from exc

cfg = PostgreSQLConfig(
exec=get_postgresql_option("exec"),
Expand All @@ -54,6 +71,7 @@ def get_postgresql_option(option: str) -> Any:
load=load_paths,
load_autocommit=bool(get_postgresql_option("load_autocommit")),
postgres_options=get_postgresql_option("postgres_options"),
create_strategy=create_strategy,
drop_test_database=request.config.getoption("postgresql_drop_test_database"),
)
return cfg
Expand Down
3 changes: 3 additions & 0 deletions pytest_postgresql/executors/noop.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def __init__(
dbname: str,
password: str | None = None,
maintenance_dbname: str = "postgres",
create_strategy: str | None = None,
):
"""Initialize nooperator executor mock.

Expand All @@ -52,6 +53,7 @@ def __init__(
:param maintenance_dbname: database to connect to for server-level work,
i.e. reading the server version. Defaults to ``postgres``. Point it at
a database the user can reach when ``postgres`` is unavailable.
:param create_strategy: strategy used by client fixtures to clone databases
"""
self.host = host
self.port = int(port)
Expand All @@ -60,6 +62,7 @@ def __init__(
self.password = password
self.dbname = dbname
self.maintenance_dbname = maintenance_dbname
self.create_strategy = create_strategy
self._version: Any = None

@property
Expand Down
3 changes: 3 additions & 0 deletions pytest_postgresql/executors/proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def __init__(
password: str | None = None,
options: str = "",
postgres_options: str = "",
create_strategy: str | None = None,
):
"""Initialize PostgreSQLExecutor executor.

Expand All @@ -127,6 +128,7 @@ def __init__(
:param dbname: database name (might not yet exist)
:param options:
:param postgres_options: extra arguments to `postgres start`
:param create_strategy: strategy used by client fixtures to clone databases
"""
self._directory_initialised = False
self.executable = executable
Expand All @@ -139,6 +141,7 @@ def __init__(
self.logfile = logfile
self.startparams = startparams
self.postgres_options = postgres_options
self.create_strategy = create_strategy
if platform.system() == "Windows":
command = self.WINDOWS_PROC_START_COMMAND.format(
executable=self.executable,
Expand Down
15 changes: 14 additions & 1 deletion pytest_postgresql/factories/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@
from pytest_postgresql._asyncio_compat import mark_postgresql_async_fixture, supports_loop_factories
from pytest_postgresql.config import get_config
from pytest_postgresql.executors import NoopExecutor, PostgreSQLExecutor
from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseJanitor
from pytest_postgresql.janitor import AsyncDatabaseJanitor, DatabaseCreationStrategy, DatabaseJanitor, FileCopyMethod

_CREATE_STRATEGY_OPTIONS: dict[str | None, tuple[DatabaseCreationStrategy | None, FileCopyMethod | None]] = {
None: (None, None),
"wal_log": ("WAL_LOG", None),
"file_copy": ("FILE_COPY", "copy"),
"clone": ("FILE_COPY", "clone"),
}

try:
import pytest_asyncio as _pytest_asyncio
Expand Down Expand Up @@ -85,6 +92,7 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]:
pg_password = proc_fixture.password
pg_options = proc_fixture.options
pg_db = dbname or proc_fixture.dbname
strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
janitor = DatabaseJanitor(
user=pg_user,
host=pg_host,
Expand All @@ -94,6 +102,8 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]:
maintenance_dbname=proc_fixture.maintenance_dbname,
password=pg_password,
isolation_level=isolation_level,
strategy=strategy,
copy_method=copy_method,
)
if config.drop_test_database:
janitor.drop()
Expand Down Expand Up @@ -150,6 +160,7 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera
pg_password = proc_fixture.password
pg_options = proc_fixture.options
pg_db = dbname or proc_fixture.dbname
strategy, copy_method = _CREATE_STRATEGY_OPTIONS[proc_fixture.create_strategy]
janitor = AsyncDatabaseJanitor(
user=pg_user,
host=pg_host,
Expand All @@ -159,6 +170,8 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera
maintenance_dbname=proc_fixture.maintenance_dbname,
password=pg_password,
isolation_level=isolation_level,
strategy=strategy,
copy_method=copy_method,
)
if config.drop_test_database:
await janitor.drop()
Expand Down
7 changes: 6 additions & 1 deletion pytest_postgresql/factories/noprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

import pytest

from pytest_postgresql.config import get_config
from pytest_postgresql.config import get_config, validate_create_strategy
from pytest_postgresql.executors import NoopExecutor
from pytest_postgresql.janitor import DatabaseJanitor

Expand All @@ -48,6 +48,7 @@ def postgresql_noproc(
load: list[Callable | str | Path] | None = None,
load_autocommit: bool | None = None,
depends_on: str | None = None,
create_strategy: str | None = None,
) -> Callable[[pytest.FixtureRequest], Iterator[NoopExecutor]]:
"""Postgresql noprocess factory.

Expand All @@ -67,8 +68,11 @@ def postgresql_noproc(
Required for statements that cannot run inside a transaction block,
e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
:param depends_on: Optional name of the fixture to depend on.
:param create_strategy: strategy used by client fixtures to clone the template:
``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
:returns: function which makes a postgresql process
"""
validate_create_strategy(create_strategy)

@pytest.fixture(scope="session")
def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopExecutor]:
Expand Down Expand Up @@ -120,6 +124,7 @@ def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopEx
dbname=noop_exec_dbname,
options=pg_options,
maintenance_dbname=pg_maintenance_dbname,
create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
)
janitor = DatabaseJanitor(
user=noop_exec.user,
Expand Down
7 changes: 6 additions & 1 deletion pytest_postgresql/factories/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import pytest
from port_for import PortForException, get_port

from pytest_postgresql.config import PostgreSQLConfig, get_config
from pytest_postgresql.config import PostgreSQLConfig, get_config, validate_create_strategy
from pytest_postgresql.executors import PostgreSQLExecutor
from pytest_postgresql.factories._pg import _pg_exe
from pytest_postgresql.janitor import DatabaseJanitor
Expand Down Expand Up @@ -80,6 +80,7 @@ def postgresql_proc(
postgres_options: str | None = None,
load: list[Callable | str | Path] | None = None,
load_autocommit: bool | None = None,
create_strategy: str | None = None,
) -> Callable[[pytest.FixtureRequest, pytest.TempPathFactory], Iterator[PostgreSQLExecutor]]:
"""Postgresql process factory.

Expand All @@ -103,8 +104,11 @@ def postgresql_proc(
:param load_autocommit: run the SQL loader connection with autocommit on.
Required for statements that cannot run inside a transaction block,
e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
:param create_strategy: strategy used by client fixtures to clone the template:
``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
:returns: function which makes a postgresql process
"""
validate_create_strategy(create_strategy)

@pytest.fixture(scope="session")
def postgresql_proc_fixture(
Expand Down Expand Up @@ -201,6 +205,7 @@ def _cleanup_executor_resources() -> None:
logfile=str(logfile_path.resolve()),
startparams=startparams or config.startparams,
postgres_options=postgres_options or config.postgres_options,
create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
)
postgresql_executor.start()
postgresql_executor.wait_for_postgres()
Expand Down
31 changes: 30 additions & 1 deletion pytest_postgresql/janitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from contextlib import asynccontextmanager, contextmanager
from pathlib import Path
from types import TracebackType
from typing import Self, TypeVar
from typing import Literal, Self, TypeVar

import psycopg
import psycopg.sql as sql
Expand All @@ -19,6 +19,8 @@

DatabaseJanitorType = TypeVar("DatabaseJanitorType", bound="DatabaseJanitor")
AsyncDatabaseJanitorType = TypeVar("AsyncDatabaseJanitorType", bound="AsyncDatabaseJanitor")
DatabaseCreationStrategy = Literal["WAL_LOG", "FILE_COPY"]
FileCopyMethod = Literal["copy", "clone"]


class BaseDatabaseJanitor:
Expand All @@ -36,6 +38,8 @@ class BaseDatabaseJanitor:
isolation_level: "psycopg.IsolationLevel | None"
autocommit: bool
version: Version | None
strategy: DatabaseCreationStrategy | None
copy_method: FileCopyMethod | None

def __init__(
self,
Expand All @@ -52,6 +56,8 @@ def __init__(
isolation_level: "psycopg.IsolationLevel | None" = None,
autocommit: bool = False,
connection_timeout: int = 60,
strategy: DatabaseCreationStrategy | None = None,
copy_method: FileCopyMethod | None = None,
) -> None:
"""Initialize janitor.

Expand All @@ -75,6 +81,11 @@ def __init__(
affects the loader connection, not the janitor's admin cursor.
:param connection_timeout: how long to retry connection before
raising a TimeoutError
:param strategy: PostgreSQL creation strategy for client template clones:
``WAL_LOG`` or ``FILE_COPY``. None leaves the server default unchanged.
:param copy_method: PostgreSQL ``file_copy_method`` value, ``copy`` or
``clone``. Required with ``FILE_COPY`` and otherwise must be None.
Neither option affects template creation.
"""
self.user = user
self.password = password
Expand All @@ -87,6 +98,10 @@ def __init__(
self._connection_timeout = connection_timeout
self.isolation_level = isolation_level
self.autocommit = autocommit
if (strategy == "FILE_COPY") != (copy_method is not None):
raise ValueError("copy_method must be set exactly when strategy is FILE_COPY")
self.strategy = strategy
self.copy_method = copy_method
if version is not None:
warnings.warn(
"version argument is deprecated and will be removed in a future release",
Expand All @@ -109,8 +124,16 @@ def _build_create_database_sql(self) -> sql.Composed:
query = query + sql.SQL(" TEMPLATE {}").format(sql.Identifier(self.template_dbname))
if self.is_template():
query = query + sql.SQL(" IS_TEMPLATE = true")
elif self.template_dbname and self.strategy is not None:
query = query + sql.SQL(" STRATEGY {}").format(sql.Literal(self.strategy))
return query

def _build_file_copy_method_sql(self) -> sql.Composed | None:
"""Build a session setting for the explicit file-copy methods."""
if self.template_dbname and not self.is_template() and self.copy_method is not None:
return sql.SQL("SET file_copy_method = {}").format(sql.Literal(self.copy_method))
return None


class DatabaseJanitor(BaseDatabaseJanitor):
"""Manage database state for specific tasks."""
Expand All @@ -123,6 +146,9 @@ def init(self) -> None:
# Otherwise, Creating database from template will fail
self._terminate_connection(cur, self.template_dbname)
query = self._build_create_database_sql()
file_copy_method_sql = self._build_file_copy_method_sql()
if file_copy_method_sql is not None:
cur.execute(file_copy_method_sql)
cur.execute(query)

@staticmethod
Expand Down Expand Up @@ -231,6 +257,9 @@ async def init(self) -> None:
# Otherwise, Creating database from template will fail
await self._terminate_connection(cur, self.template_dbname)
query = self._build_create_database_sql()
file_copy_method_sql = self._build_file_copy_method_sql()
if file_copy_method_sql is not None:
await cur.execute(file_copy_method_sql)
await cur.execute(query)

@staticmethod
Expand Down
Loading
Loading