Skip to content

Commit 7c2d827

Browse files
committed
Add opt-in database creation strategies (refs dbfixtures#1260)
1 parent 2be4dcd commit 7c2d827

13 files changed

Lines changed: 343 additions & 2 deletions

File tree

‎README.rst‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,49 @@ For async tests against an external server, create a client fixture with
272272
273273
By default, it connects to ``127.0.0.1:5432``.
274274

275+
Choosing how test databases are cloned
276+
--------------------------------------
277+
278+
Use ``create_strategy`` on ``postgresql_proc`` or ``postgresql_noproc`` to choose
279+
how synchronous and asynchronous client fixtures clone the session's template
280+
database for each test. The setting only affects client database creation;
281+
initial and layered template databases keep PostgreSQL's default behavior.
282+
283+
.. code-block:: python
284+
285+
postgresql_my_proc = factories.postgresql_proc(create_strategy="clone")
286+
postgresql_my = factories.postgresql("postgresql_my_proc")
287+
288+
.. code-block:: sh
289+
290+
pytest --postgresql-create-strategy=clone
291+
292+
.. code-block:: ini
293+
294+
[pytest]
295+
postgresql_create_strategy = clone
296+
297+
The available values are:
298+
299+
* Unset (the default): no ``STRATEGY`` clause or session setting is sent, leaving
300+
the choice to PostgreSQL.
301+
* ``wal_log``: ``CREATE DATABASE ... STRATEGY WAL_LOG``.
302+
* ``file_copy``: ``SET file_copy_method = copy``, followed by
303+
``CREATE DATABASE ... STRATEGY FILE_COPY`` on the same connection.
304+
* ``clone``: ``SET file_copy_method = clone``, followed by
305+
``CREATE DATABASE ... STRATEGY FILE_COPY`` on the same connection.
306+
307+
The session setting applies immediately before database creation and does not
308+
require a server restart. Explicit strategies require PostgreSQL support:
309+
``WAL_LOG`` requires PostgreSQL 15 or newer, while ``file_copy`` and ``clone``
310+
require a server providing ``file_copy_method``. PostgreSQL reports unsupported
311+
settings or strategies directly.
312+
313+
``clone`` also requires filesystem reflink support for the PostgreSQL data
314+
directory. A filesystem or Docker storage driver without reflinks can reject
315+
cloning; tmpfs does not provide reflinks. Benchmark on your actual storage before
316+
choosing a strategy, since ``FILE_COPY`` also incurs checkpoint costs.
317+
275318
Using a maintenance database other than ``postgres``
276319
----------------------------------------------------
277320

@@ -416,6 +459,12 @@ You can define settings via fixture factory arguments, command line options, or
416459
- --postgresql-load-autocommit
417460
- postgresql_load_autocommit
418461
- False
462+
* - Test database cloning strategy
463+
- create_strategy
464+
- create_strategy
465+
- --postgresql-create-strategy
466+
- postgresql_create_strategy
467+
- PostgreSQL's default
419468
* - PostgreSQL connection options
420469
- options
421470
- options

‎newsfragments/1260.feature.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Add ``create_strategy`` to the process and noproc factories, with matching CLI
2+
and ini options, to select PostgreSQL's default, ``wal_log``, ``file_copy``, or
3+
reflink-based ``clone`` when client fixtures copy the template database.

‎pytest_postgresql/config.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@
77
import pytest
88
from _pytest._py.path import LocalPath
99

10+
CREATE_STRATEGIES = ("wal_log", "file_copy", "clone")
11+
12+
13+
def validate_create_strategy(create_strategy: str | None) -> str | None:
14+
"""Validate the optional database cloning strategy."""
15+
if create_strategy is not None and create_strategy not in CREATE_STRATEGIES:
16+
raise ValueError(
17+
f"Invalid PostgreSQL create_strategy {create_strategy!r}; "
18+
f"expected one of {', '.join(CREATE_STRATEGIES)} or None"
19+
)
20+
return create_strategy
21+
1022

1123
@dataclass(frozen=True)
1224
class PostgreSQLConfig:
@@ -26,6 +38,7 @@ class PostgreSQLConfig:
2638
load: list[Path | str]
2739
load_autocommit: bool
2840
postgres_options: str
41+
create_strategy: str | None
2942
drop_test_database: bool
3043

3144

@@ -37,6 +50,10 @@ def get_postgresql_option(option: str) -> Any:
3750
return request.config.getoption(name) or request.config.getini(name)
3851

3952
load_paths: list[Path | str] = detect_paths(get_postgresql_option("load"))
53+
try:
54+
create_strategy = validate_create_strategy(get_postgresql_option("create_strategy"))
55+
except ValueError as exc:
56+
raise pytest.UsageError(str(exc)) from exc
4057

4158
cfg = PostgreSQLConfig(
4259
exec=get_postgresql_option("exec"),
@@ -54,6 +71,7 @@ def get_postgresql_option(option: str) -> Any:
5471
load=load_paths,
5572
load_autocommit=bool(get_postgresql_option("load_autocommit")),
5673
postgres_options=get_postgresql_option("postgres_options"),
74+
create_strategy=create_strategy,
5775
drop_test_database=request.config.getoption("postgresql_drop_test_database"),
5876
)
5977
return cfg

‎pytest_postgresql/executors/noop.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ def __init__(
4040
dbname: str,
4141
password: str | None = None,
4242
maintenance_dbname: str = "postgres",
43+
create_strategy: str | None = None,
4344
):
4445
"""Initialize nooperator executor mock.
4546
@@ -52,6 +53,7 @@ def __init__(
5253
:param maintenance_dbname: database to connect to for server-level work,
5354
i.e. reading the server version. Defaults to ``postgres``. Point it at
5455
a database the user can reach when ``postgres`` is unavailable.
56+
:param create_strategy: strategy used by client fixtures to clone databases
5557
"""
5658
self.host = host
5759
self.port = int(port)
@@ -60,6 +62,7 @@ def __init__(
6062
self.password = password
6163
self.dbname = dbname
6264
self.maintenance_dbname = maintenance_dbname
65+
self.create_strategy = create_strategy
6366
self._version: Any = None
6467

6568
@property

‎pytest_postgresql/executors/proc.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ def __init__(
107107
password: str | None = None,
108108
options: str = "",
109109
postgres_options: str = "",
110+
create_strategy: str | None = None,
110111
):
111112
"""Initialize PostgreSQLExecutor executor.
112113
@@ -127,6 +128,7 @@ def __init__(
127128
:param dbname: database name (might not yet exist)
128129
:param options:
129130
:param postgres_options: extra arguments to `postgres start`
131+
:param create_strategy: strategy used by client fixtures to clone databases
130132
"""
131133
self._directory_initialised = False
132134
self.executable = executable
@@ -139,6 +141,7 @@ def __init__(
139141
self.logfile = logfile
140142
self.startparams = startparams
141143
self.postgres_options = postgres_options
144+
self.create_strategy = create_strategy
142145
if platform.system() == "Windows":
143146
command = self.WINDOWS_PROC_START_COMMAND.format(
144147
executable=self.executable,

‎pytest_postgresql/factories/client.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]:
9494
maintenance_dbname=proc_fixture.maintenance_dbname,
9595
password=pg_password,
9696
isolation_level=isolation_level,
97+
create_strategy=proc_fixture.create_strategy,
9798
)
9899
if config.drop_test_database:
99100
janitor.drop()
@@ -159,6 +160,7 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera
159160
maintenance_dbname=proc_fixture.maintenance_dbname,
160161
password=pg_password,
161162
isolation_level=isolation_level,
163+
create_strategy=proc_fixture.create_strategy,
162164
)
163165
if config.drop_test_database:
164166
await janitor.drop()

‎pytest_postgresql/factories/noprocess.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
import pytest
2525

26-
from pytest_postgresql.config import get_config
26+
from pytest_postgresql.config import get_config, validate_create_strategy
2727
from pytest_postgresql.executors import NoopExecutor
2828
from pytest_postgresql.janitor import DatabaseJanitor
2929

@@ -48,6 +48,7 @@ def postgresql_noproc(
4848
load: list[Callable | str | Path] | None = None,
4949
load_autocommit: bool | None = None,
5050
depends_on: str | None = None,
51+
create_strategy: str | None = None,
5152
) -> Callable[[pytest.FixtureRequest], Iterator[NoopExecutor]]:
5253
"""Postgresql noprocess factory.
5354
@@ -67,8 +68,11 @@ def postgresql_noproc(
6768
Required for statements that cannot run inside a transaction block,
6869
e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
6970
:param depends_on: Optional name of the fixture to depend on.
71+
:param create_strategy: strategy used by client fixtures to clone the template:
72+
``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
7073
:returns: function which makes a postgresql process
7174
"""
75+
validate_create_strategy(create_strategy)
7276

7377
@pytest.fixture(scope="session")
7478
def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopExecutor]:
@@ -120,6 +124,7 @@ def postgresql_noproc_fixture(request: pytest.FixtureRequest) -> Iterator[NoopEx
120124
dbname=noop_exec_dbname,
121125
options=pg_options,
122126
maintenance_dbname=pg_maintenance_dbname,
127+
create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
123128
)
124129
janitor = DatabaseJanitor(
125130
user=noop_exec.user,

‎pytest_postgresql/factories/process.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
import pytest
3030
from port_for import PortForException, get_port
3131

32-
from pytest_postgresql.config import PostgreSQLConfig, get_config
32+
from pytest_postgresql.config import PostgreSQLConfig, get_config, validate_create_strategy
3333
from pytest_postgresql.executors import PostgreSQLExecutor
3434
from pytest_postgresql.factories._pg import _pg_exe
3535
from pytest_postgresql.janitor import DatabaseJanitor
@@ -80,6 +80,7 @@ def postgresql_proc(
8080
postgres_options: str | None = None,
8181
load: list[Callable | str | Path] | None = None,
8282
load_autocommit: bool | None = None,
83+
create_strategy: str | None = None,
8384
) -> Callable[[pytest.FixtureRequest, pytest.TempPathFactory], Iterator[PostgreSQLExecutor]]:
8485
"""Postgresql process factory.
8586
@@ -103,8 +104,11 @@ def postgresql_proc(
103104
:param load_autocommit: run the SQL loader connection with autocommit on.
104105
Required for statements that cannot run inside a transaction block,
105106
e.g. ``CREATE DATABASE`` in a loaded ``.sql`` file.
107+
:param create_strategy: strategy used by client fixtures to clone the template:
108+
``wal_log``, ``file_copy``, or ``clone``. Defaults to configuration.
106109
:returns: function which makes a postgresql process
107110
"""
111+
validate_create_strategy(create_strategy)
108112

109113
@pytest.fixture(scope="session")
110114
def postgresql_proc_fixture(
@@ -201,6 +205,7 @@ def _cleanup_executor_resources() -> None:
201205
logfile=str(logfile_path.resolve()),
202206
startparams=startparams or config.startparams,
203207
postgres_options=postgres_options or config.postgres_options,
208+
create_strategy=create_strategy if create_strategy is not None else config.create_strategy,
204209
)
205210
postgresql_executor.start()
206211
postgresql_executor.wait_for_postgres()

‎pytest_postgresql/janitor.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from packaging.version import Version, parse
1515
from psycopg import AsyncCursor, Connection, Cursor
1616

17+
from pytest_postgresql.config import validate_create_strategy
1718
from pytest_postgresql.loader import build_loader, sql_async
1819
from pytest_postgresql.retry import retry, retry_async
1920

@@ -36,6 +37,7 @@ class BaseDatabaseJanitor:
3637
isolation_level: "psycopg.IsolationLevel | None"
3738
autocommit: bool
3839
version: Version | None
40+
create_strategy: str | None
3941

4042
def __init__(
4143
self,
@@ -52,6 +54,7 @@ def __init__(
5254
isolation_level: "psycopg.IsolationLevel | None" = None,
5355
autocommit: bool = False,
5456
connection_timeout: int = 60,
57+
create_strategy: str | None = None,
5558
) -> None:
5659
"""Initialize janitor.
5760
@@ -75,6 +78,9 @@ def __init__(
7578
affects the loader connection, not the janitor's admin cursor.
7679
:param connection_timeout: how long to retry connection before
7780
raising a TimeoutError
81+
:param create_strategy: strategy for cloning a test database from its
82+
template: ``wal_log``, ``file_copy``, or ``clone``. None leaves the
83+
choice to PostgreSQL. Does not affect template creation.
7884
"""
7985
self.user = user
8086
self.password = password
@@ -87,6 +93,7 @@ def __init__(
8793
self._connection_timeout = connection_timeout
8894
self.isolation_level = isolation_level
8995
self.autocommit = autocommit
96+
self.create_strategy = validate_create_strategy(create_strategy)
9097
if version is not None:
9198
warnings.warn(
9299
"version argument is deprecated and will be removed in a future release",
@@ -109,8 +116,20 @@ def _build_create_database_sql(self) -> sql.Composed:
109116
query = query + sql.SQL(" TEMPLATE {}").format(sql.Identifier(self.template_dbname))
110117
if self.is_template():
111118
query = query + sql.SQL(" IS_TEMPLATE = true")
119+
elif self.template_dbname and self.create_strategy is not None:
120+
strategy = "WAL_LOG" if self.create_strategy == "wal_log" else "FILE_COPY"
121+
query = query + sql.SQL(" STRATEGY {}").format(sql.SQL(strategy))
112122
return query
113123

124+
def _build_file_copy_method_sql(self) -> sql.SQL | None:
125+
"""Build a session setting for the explicit file-copy methods."""
126+
if self.template_dbname and not self.is_template():
127+
if self.create_strategy == "file_copy":
128+
return sql.SQL("SET file_copy_method = copy")
129+
if self.create_strategy == "clone":
130+
return sql.SQL("SET file_copy_method = clone")
131+
return None
132+
114133

115134
class DatabaseJanitor(BaseDatabaseJanitor):
116135
"""Manage database state for specific tasks."""
@@ -123,6 +142,9 @@ def init(self) -> None:
123142
# Otherwise, Creating database from template will fail
124143
self._terminate_connection(cur, self.template_dbname)
125144
query = self._build_create_database_sql()
145+
file_copy_method_sql = self._build_file_copy_method_sql()
146+
if file_copy_method_sql is not None:
147+
cur.execute(file_copy_method_sql)
126148
cur.execute(query)
127149

128150
@staticmethod
@@ -231,6 +253,9 @@ async def init(self) -> None:
231253
# Otherwise, Creating database from template will fail
232254
await self._terminate_connection(cur, self.template_dbname)
233255
query = self._build_create_database_sql()
256+
file_copy_method_sql = self._build_file_copy_method_sql()
257+
if file_copy_method_sql is not None:
258+
await cur.execute(file_copy_method_sql)
234259
await cur.execute(query)
235260

236261
@staticmethod

‎pytest_postgresql/plugin.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
from pytest_postgresql import factories
3232
from pytest_postgresql._asyncio_compat import supports_loop_factories
33+
from pytest_postgresql.config import CREATE_STRATEGIES
3334

3435
try:
3536
import pytest_asyncio
@@ -50,6 +51,7 @@
5051
_help_maintenance_dbname = "Database used to create/drop test databases and read server version. Noproc fixture only"
5152
_help_load = "Dotted-style or entrypoint-style path to callable or path to SQL File"
5253
_help_postgres_options = "Postgres executable extra parameters. Passed via the -o option to pg_ctl"
54+
_help_create_strategy = "Database cloning strategy: wal_log, file_copy, or clone (default: PostgreSQL's default)"
5355
_help_drop_test_database = (
5456
"Drop test database in noproc and client fixture, for the cases, "
5557
"when database was not cleared due to errors in previous test runs. "
@@ -176,6 +178,7 @@ def pytest_addoption(parser: Parser) -> None:
176178

177179
parser.addini(name="postgresql_load", type="pathlist", help=_help_load)
178180
parser.addini(name="postgresql_postgres_options", help=_help_postgres_options, default="")
181+
parser.addini(name="postgresql_create_strategy", help=_help_create_strategy, default=None)
179182
parser.addini(name="postgresql_load_autocommit", type="bool", default=False, help=_help_load_autocommit)
180183

181184
parser.addoption(
@@ -239,6 +242,14 @@ def pytest_addoption(parser: Parser) -> None:
239242
help=_help_postgres_options,
240243
)
241244

245+
parser.addoption(
246+
"--postgresql-create-strategy",
247+
action="store",
248+
choices=CREATE_STRATEGIES,
249+
dest="postgresql_create_strategy",
250+
help=_help_create_strategy,
251+
)
252+
242253
parser.addoption(
243254
"--postgresql-drop-test-database",
244255
action="store_true",

0 commit comments

Comments
 (0)