# Database connections

## Connection lifetime and configuration

`Mini\Core\Database::getConnection()` creates one non-persistent default PDO
connection per HTTP request or CLI invocation. Every model constructed without
an explicit connection reuses that PDO. Initialization uses `DB_TYPE`,
`DB_HOST`, `DB_NAME`, `DB_CHARSET`, `DB_USER` and `DB_PASS` from the existing
environment configuration. The fetch mode remains `FETCH_OBJ`, the error mode
remains `ERRMODE_WARNING`, and MySQL/MariaDB `lc_time_names` is set to `pl_PL`
once. A connection is cached only after successful initialization.

An explicitly injected PDO remains independent and never replaces the default.
Related models in enrollment, cancellation and notification operations receive
their parent's PDO so these operations also work with an injected connection.
The migration runner and database backup retain their independent connections.

The default PDO remains available during shutdown callbacks. PHP releases the
non-persistent connection when the request/invocation ends; models must not
close it in destructors. There is no automatic reconnect, write retry, pool or
transaction spanning the entire request. A future long-running CLI daemon would
need an explicitly designed connection lifecycle; current scheduled tasks are
separate script invocations.

## Transactions and deferred work

Existing business operations retain their transaction boundaries. Nested work
uses the caller's PDO; it must not commit or roll back the caller's transaction.
Recurring and one-time enrollment create a unique savepoint when called inside
an existing transaction. A failed enrollment rolls back its own writes, while
an outer rollback also removes all successful membership/booking writes.
Every membership and booking save is checked before reporting success. The
base model also checks insert execution before reading `lastInsertId()`.
Acceptance of terms retains its existing position before booking begins.

Transaction call-site audit:

- Enrollment and event creation share occurrence, membership and booking PDOs.
  Enrollment is composable and uses savepoints. Event creation remains an
  administrative operation owning its transaction.
- Payment saves join existing transactions. Coupon claims, user identity saves,
  RollPoints operations and individual-lesson scheduling retain their existing
  savepoints and restoration of temporarily changed PDO error modes.
- Group/individual cancellation joins related order cancellation on the same
  PDO. Order cancellation respects the transaction owner; notification queue
  writes use that connection as well.
- Payment confirmation, manual settlements, refunds, vouchers, course days,
  dictionaries, images, settings and rate limiting start transactions from
  their existing standalone entry points. They are not converted into a
  request-wide transaction or automatically retried.
- Receipt processing and RollPoints settlement refuse to run while their PDO
  has an open transaction. Their shutdown queues retain the original PDO and
  deduplicate saved payments/documents. Rollback removes the durable records;
  unfinished/rolled-back sales must not reach the document provider.
- Receipt and registration named locks retain their existing `finally` release
  paths. No persistent connection is introduced that could carry this state
  into another request.

Connection failure retains the existing contract: HTTP 503, `Retry-After: 60`
and a generic Polish outage page, or CLI stderr and exit status 1. Normal HTTP
bootstrap loads database settings before rendering, establishing the shared
PDO before page output. A connection lost after successful initialization is
not silently replaced and its transaction is not replayed.

## Verification

Database-backed tests require a separate `codex_rollpoints_*` schema prepared
with `scripts/prepare-rollpoints-tests.php`; never run them against application
or hosting databases. Set `RP_TEST_DATABASE` when running them.

- `tests/database_connections_test.php`: object/server connection identity,
  independent injection, initialization, failed insert in warning mode,
  nested enrollment, mid-operation failure and outer rollback.
- `tests/database_connection_failure_test.php`: injected PDO with an unreachable
  default connector, real HTTP 503/Retry-After and CLI failure. Uses a local
  fixture server and no application credentials.
- `tests/shared_payment_shutdown_test.php`: actual process shutdown with shared
  PDO; committed payment processed once, rolled-back/unfinished payments skipped.
- `tests/public_database_load_test.php local GROUP_ID` runs the public rendering
  check from the local web container. Use `test-next GROUP_ID` for the remote
  test site; remote results deliberately omit local database connection counts.
- Existing group/course signup, gift voucher, individual rental, skate-cover,
  RollPoints payment, receipt, receipt administration, user identity history,
  promo code and payment isolation suites cover transaction-dependent workflows.
  Receipt suites use fake providers and check rollback and duplicate prevention.

For public rendering, check the homepage, `/kalendarz/`, a public group and
`/kalendarz/sezon/`. Use short runs at 1, 2 and 6 concurrent requests, recording
HTTP statuses and timings. Measure server connection creation/session counts
with an independent observer where available. Avoid sharing one client session
cookie between requests, which would serialize them through the session lock.

Local verification on 2026-10-09 returned 36 complete HTTP 200 pages, with 12
requests at each concurrency level. The server created exactly 12 connections
at every level; peak account connections including the observer were 2, 3 and
7. Mean response times were 32.3, 30.5 and 41.9 ms respectively. These are local
measurements, not OVH capacity or latency guarantees.

## Hosting capacity and deployment

No migration, file transfer or configuration change is required. Deploy to
`test-next` using the existing workflow, verify public rendering, then promote
that exact tested SHA using the production workflow. Code rollback uses the
existing deployment procedure; there is no schema/data rollback for this change.

The read-only CLI command below returns a connection ID, the effective account
limit and current connection counts without credentials or other query text:

```bash
php scripts/database-connections-status.php test-next.rollschool.pl
php scripts/database-connections-status.php rollschool.pl
```

Run each command in its owning checkout on OVH. `max_user_connections = 0`
means no configured account limit. Counts include the observer connection and
any other connections using that database account. If the account is shared by
test, production or other applications, their connections consume the same
budget. A snapshot is not a peak measurement. A hosting restriction on access
to `information_schema.PROCESSLIST` must be resolved with OVH, not by granting
the application unnecessary administrative privileges.

The deployment verification prints this read-only snapshot in its workflow log
on both environments. An unavailable capacity snapshot produces a warning;
the existing mandatory database connectivity/version checks still determine
whether deployment succeeds.

After deployment inspect access/error logs for HTTP 503, PDO 1203 (account
connection limit), and PDO 2002 (connection/address failures). Shared PDO removes
the multiplication by model count, but capacity still depends on concurrent PHP
requests and CLI jobs, including shutdown work. Additional address-allocation
errors observed in the SEO audit require separate hosting diagnostics if they
continue. See `docs/seo-audit-2026-10-09.md` for the historical evidence.
