Database
PAM HTTP keeps its kernel independent of any database. When your application needs one, the optional Arcano
integration (pushinbr/arcano) gives you a data mapper ORM that is safe in a persistent worker: every request
Fiber gets its own connections and identity map, and request cleanup rolls back unfinished transactions and
releases the connections.
Arcano is derived from Cycle ORM. It supports attribute entities, relations, an identity map, generated migrations, and SQLite, MySQL, PostgreSQL and SQL Server.
Installation
Section titled “Installation”pam composer require pushinbr/arcanoConfiguration
Section titled “Configuration”DatabaseConfig::fromEnvironment() reads the usual variables:
| Variable | Default | Notes |
|---|---|---|
DB_CONNECTION |
pgsql |
pgsql, mysql, sqlite or sqlsrv. |
DB_HOST |
127.0.0.1 |
|
DB_PORT |
Driver default | |
DB_DATABASE |
pam (:memory: for SQLite) |
For SQLite, the database file path. |
DB_USERNAME, DB_PASSWORD |
pam, empty |
|
DB_SSLMODE, DB_SOCKET, DB_TRUST_SERVER_CERTIFICATE |
unset | Optional driver settings. |
Register the provider with a schema compiler that scans your entity directory:
use Pam\Api\Database\ArcanoSchemaCompiler;use Pam\Api\Database\ArcanoServiceProvider;use Pam\Api\Database\DatabaseConfig;
$app->provider(new ArcanoServiceProvider( DatabaseConfig::fromEnvironment(), new ArcanoSchemaCompiler( __DIR__ . '/src/Models', __DIR__ . '/var/cache/arcano-schema.php', refresh: getenv('PAM_ENV') !== 'production', ), migrations: __DIR__ . '/database/migrations',));The compiler caches the schema in a PHP file. With refresh: true it rebuilds the cache when an entity file
changes; in production pass refresh: false and build the cache during deployment. You can also pass a compiled
schema array or an Arcano\ORM\Schema instead of the compiler.
The provider registers ArcanoManager (also bound as TransactionManager), QueryMonitor,
ArcanoMigrationManager when a migrations directory is given, and the ArcanoLifecycleMiddleware that releases
each request’s connections.
For a hand-written configuration, build DatabaseConfig directly:
new DatabaseConfig('default', [ 'default' => ['driver' => 'sqlite', 'database' => __DIR__ . '/storage/database.sqlite', 'prefix' => ''],]);Defining Entities
Section titled “Defining Entities”Entities are plain classes with attributes:
namespace App\Models;
use App\Domain\Products\ProductStatus;use Arcano\Annotated\Annotation\Column;use Arcano\Annotated\Annotation\Entity;
#[Entity(role: 'product', table: 'products')]class Product{ #[Column(type: 'primary')] public ?int $id = null;
#[Column(type: 'datetime', name: 'created_at')] public \DateTimeImmutable $createdAt;
public function __construct( #[Column(type: 'string')] public string $name, #[Column(type: 'integer', name: 'price_in_cents')] public int $priceInCents, #[Column(type: 'tinyInteger', default: 1, typecast: ProductStatus::class)] public ProductStatus $status = ProductStatus::Active, ) { $this->createdAt = new \DateTimeImmutable(); }}Relations use the attributes in Arcano\Annotated\Annotation\Relation, for example
#[HasMany(target: Post::class, collection: 'array')].
Working With Entities
Section titled “Working With Entities”Resolve ArcanoManager from the container, typically in a repository:
use App\Models\Product;use Pam\Api\Database\ArcanoManager;
final readonly class ArcanoProductRepository implements ProductRepository{ public function __construct(private ArcanoManager $arcano) {}
public function all(): array { return $this->arcano->select(Product::class)->orderBy('id')->fetchAll(); }
public function find(int $id): ?Product { return $this->arcano->select(Product::class)->wherePK($id)->fetchOne(); }
public function save(Product $product): void { $this->arcano->entityManager()->persist($product)->run(); }}ArcanoManager exposes select(), repository(), entityManager(), orm(), database() for raw queries on a
named connection, and transaction().
Transactions
Section titled “Transactions”$order = $arcano->transaction(function () use ($arcano, $cart): Order { $order = Order::fromCart($cart); $arcano->entityManager()->persist($order)->run();
return $order;});To wrap a whole route, use TransactionalMiddleware. Unfinished
transactions are rolled back when the request ends.
Migrations
Section titled “Migrations”ArcanoMigrationManager generates migrations from the difference between your entities and the database, runs
them and rolls them back. Each migration runs in its own transaction and is recorded in the migrations table.
$migrations = $app->container()->get(ArcanoMigrationManager::class);
$migrations->generate(); // write files for changed entities; returns their paths$migrations->migrate(); // run pending migrations; returns their names$migrations->rollback(1); // revert the last migration$migrations->status(); // name, created_at and executed_at of every migrationGeneration requires every existing migration to have run. Generated files can be edited, and you can write
migrations by hand with the Arcano\Migrations\Migration table API.
Tenant-Owned Entities
Section titled “Tenant-Owned Entities”Protect a role once during boot. Selects are then limited to the current tenant, new entities get its key, an
entity cannot move to another tenant, and both fail closed when the request has no TenantContext:
$app->container()->get(ArcanoManager::class)->protectTenant(Order::class, column: 'tenant_id');Resolve the tenant with ResolveTenantMiddleware.
Health Checks
Section titled “Health Checks”DatabaseHealthCheck runs SELECT 1 and reports latency, or the failure class without credentials:
use Pam\Api\Database\DatabaseHealthCheck;use Pam\Api\Health\HealthRegistry;
$health = (new HealthRegistry()) ->add('database', new DatabaseHealthCheck($app->container()->get(ArcanoManager::class)));See Health checks.
Query Budgets
Section titled “Query Budgets”QueryBudgetMiddleware turns N+1 detection into an executable contract. It counts the queries of the request,
their accumulated time and repeated SQL patterns:
use Pam\Api\Database\QueryBudget;use Pam\Api\Database\QueryMonitor;use Pam\Api\Middleware\QueryBudgetMiddleware;
$app->middleware(new QueryBudgetMiddleware( monitor: $app->container()->get(QueryMonitor::class), budget: new QueryBudget( maximumQueries: 30, maximumElapsedMilliseconds: 100, maximumDuplicateQueries: 3, ), failOnViolation: true,));The defaults are 100 queries, 500 ms and 10 duplicates. With failOnViolation: true, a request over budget throws
QueryBudgetExceededException, whose report lists the count, elapsed time, duplicates and violations
(QueryBudgetViolation::QueryCount = 1, ElapsedTime = 2, DuplicateQuery = 3). Budgets are Fiber-local. Enable
failure in development and tests; in production, keep it off or apply it only to performance-sensitive routes.