Search by

debuss-a / piccolo-database

debuss-a

Database access through stored procedures only for Piccolo: a class per procedure, typed for the IDE and PHPStan, run by a connection made for long-running PHP workers.

Package info

github.com/debuss/piccolo-database

pkg:composer/debuss-a/piccolo-database

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.0 2026-11-27 22:38 UTC

This package is auto-updated.

Last update: 2026-11-27 23:05:17 UTC


README

Database access through stored procedures only for the Piccolo framework, on top of debuss-a/stored-procedures (MySQL, PostgreSQL, SQL Server).

Made for the teams whose database user is only granted EXECUTE on procedures validated by the DBAs: there is no way to run a SQL query. Each procedure is a PHP class, whose constructor is the signature of the procedure, so that the IDE and PHPStan know its parameters and the type of its rows, and its values are validated before the call.

composer require debuss-a/piccolo-database
// config/container.php
$builder->addProvider(new Piccolo\Database\ServiceProvider\DatabaseServiceProvider());

A class per procedure

namespace Infrastructure\Country\Procedure;

use Piccolo\Database\Attribute\{Param, StoredProcedure};
use Piccolo\Database\Query;

/** @implements Query<CountryRow> */
#[StoredProcedure('sp_fetch_country_by_iso', timeout: 5)]
final readonly class FetchCountryByIso implements Query
{
    public function __construct(
        #[Param('p_iso')] public string $iso,
    ) {
        if (!preg_match('/^[A-Z]{2}$/', $iso)) {
            throw new InvalidArgumentException('An ISO code has two capital letters');
        }
    }

    public function rowClass(): string
    {
        return CountryRow::class;
    }
}
  • #[StoredProcedure(name, timeout)] names the procedure (or the PostgreSQL function). The timeout, in seconds, replaces the one of the connection (SQL Server and PostgreSQL).
  • The parameters of the procedure are the promoted parameters of the constructor, in their order. Their name is the name of the property with the prefix DB_PARAMETER_PREFIX (p_ gives p_iso for $iso), their type is inferred from the value, and their mode is IN. #[Param(name, type, mode, size)] gives another name, a type (e.g. DbType::DATE) or the INOUT mode.
  • The constructor validates the values: an invalid value fails with a clear message, before the call.
  • The class implements:
    • Query<TRow>, for the procedures returning rows, mapped to the row class (rowClass()) by the Hydrator of debuss-a/stored-procedures: the columns fill the constructor parameters of the same name, ignoring case and underscores (#[Column] gives another one);
    • ScalarQuery, for a single value (the first column of the first row);
    • Command, for the procedures changing data: their result gives the affected rows and the OUT and INOUT values.

The OUT parameters have no value to give: they are declared on the class, and come after the parameters of the constructor.

use Piccolo\Database\Attribute\{Output, Param, StoredProcedure};
use Piccolo\Database\Command;
use StoredProcedures\{DbType, ParameterMode};

#[StoredProcedure('sp_insert_country')]
#[Output('p_id', DbType::INTEGER)]
final readonly class InsertCountry implements Command
{
    public function __construct(
        #[Param('p_iso')] public string $iso,
        #[Param('p_name')] public string $name,
        #[Param('p_label', mode: ParameterMode::INOUT, size: 100)] public string $label = '',
    ) {}
}

Warning

With MySQL and SQL Server, the parameters are given by position: keep the order of the constructor (then of the OUT parameters) the one of the procedure, or set DB_MATCH_PARAMETERS_BY_NAME=true to match them by name. PostgreSQL always matches them by name.

A class not declared correctly (no #[StoredProcedure], a parameter not promoted, an OUT parameter in the constructor, two parameters with the same name) fails on its first call with an InvalidDefinitionException naming it.

Calling the procedures

ProcedureRunnerInterface is injected in the repositories of the Infrastructure, which implement the interfaces of the Domain and turn the rows into objects of the Domain:

final readonly class CountryRepository implements CountryRepositoryInterface
{
    public function __construct(
        private ProcedureRunnerInterface $procedures
    ) {}

    public function findByIso(string $iso): ?Country
    {
        return $this->procedures->singleOrNull(new FetchCountryByIso($iso))?->toCountry();
    }

    public function add(Country $country): int
    {
        return $this->procedures->execute(new InsertCountry($country->iso, $country->name))->getOutputValue('p_id');
    }
}
Method Gives
all(Query) list<TRow>
first(Query) / firstOrNull(Query) the first row, a NoResultsException or null when there is none
single(Query) / singleOrNull(Query) the only row, a NoResultsException or null when there is none; a MultipleResultsException when there are several
resultSet(Query) the whole ResultSet<TRow>, e.g. for several row sets (rowSet(1, OrderRow::class))
scalar(ScalarQuery) the first column of the first row, or null
execute(Command) the ResultSet: getAffectedRows(), getOutputValue('p_id')
transaction(Closure) runs the calls of the callback in a transaction: committed when it returns, rolled back when it throws

The failed calls throw the exceptions of debuss-a/stored-procedures: ProcedureErrorException for an error raised by the procedure, ConnectionLostException, TimeoutException, ...

The row classes belong to the Infrastructure, next to the procedures: their #[Column] attributes are a detail of the database, which the Domain must not know.

Configuration

Variable
DB_DSN The PDO data source: pgsql:host=db;dbname=app, mysql:host=db;dbname=app;charset=utf8mb4, sqlsrv:Server=db;Database=app
DB_USER, DB_PASSWORD A user only granted EXECUTE on the procedures
DB_TIMEOUT The maximum duration of a call in seconds (SQL Server and PostgreSQL), none by default
DB_MATCH_PARAMETERS_BY_NAME true to match the parameters by name with MySQL and SQL Server (one metadata query per procedure)
DB_PARAMETER_PREFIX The prefix of the names inferred from the properties, e.g. p_, none by default
DB_PING_AFTER The seconds without call after which the connection is checked before the next one, 60 by default, 0 never

SqlConnection is a transient service, created by the managed connection when needed: register it again in config/container.php for other PDO options, or inflect it to add interceptors (metrics, tracing):

$builder->inflect(SqlConnection::class, static fn (SqlConnection $connection) => $connection->addInterceptor(
    static function (Invocation $invocation, Closure $proceed): mixed { /* ... */ return $proceed(); }
));

bin/console container:check resolves every service, so it opens a connection with SqlConnection: where the database is not reachable (e.g. in the CI), leave it out with bin/console container:check -x 'StoredProcedures\SqlConnection'.

Worker mode

The ManagedConnection is a singleton, made for the FrankenPHP workers as for the classic PHP requests:

  • it connects on the first call only: a request not using the database does not connect to it;
  • a lost connection (server restarted, idle timeout, failover) is replaced on the next call;
  • after DB_PING_AFTER seconds without call, the next call checks the connection first (SELECT 1, allowed to a user only granted EXECUTE) and reconnects instead of failing;
  • during a transaction, the connection is never checked nor replaced: a call on a lost connection fails, rather than going on outside the transaction;
  • after each request of a worker, a transaction left open is rolled back and logged as an error, so that it does not reach the next request.

Testing the repositories

FakeProcedureRunner replaces the runner in the tests, without database:

use Piccolo\Database\Testing\FakeProcedureRunner;

$procedures = new FakeProcedureRunner()
    ->willReturnRows(FetchCountryByIso::class, fn (FetchCountryByIso $query) => [new CountryRow(1, $query->iso, 'France')])
    ->willReturnScalar(CountCountries::class, 42)
    ->willReturnResult(InsertCountry::class, outputs: ['p_id' => 42], affectedRows: 1)
    ->willThrow(DeleteCountry::class, new ProcedureErrorException('The country has cities', 'sp_delete_country', '45000'));

$repository = new CountryRepository($procedures);
// ...
$procedures->assertCalled(InsertCountry::class, fn (InsertCountry $command) => $command->iso === 'FI');
$procedures->assertNotCalled(DeleteCountry::class);

It reads the definitions as the runner does (a class not declared correctly fails in the tests too), and fails a call without result given with the name of the class and of its procedure.

Tests

composer test     # Pest
composer analyse  # PHPStan, level max

The integration tests call real procedures of PostgreSQL when PICCOLO_DATABASE_TEST_DSN is set (see tests/Integration/PostgreSqlTest.php), as in the CI.

License

MIT