Search by

small / swoole-entity-manager-migration

small

Generate Small Swoole Entity Manager database layers from ORM entities and live schema drift

Package info

git.small-project.dev/lib/small-swoole-entity-manager-migration

pkg:composer/small/swoole-entity-manager-migration

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

0.3.0 2026-11-24 09:00 UTC

README

Generate database layers compatible with small/swoole-entity-manager-core and small/swoole-entity-manager-bundle.

Capabilities

  • Discover Composer PSR-4 PHP classes through small/class-manipulator.
  • Match #[OrmEntity] classes with #[Entity] and #[Connection] on their ORM managers.
  • Inspect #[Field], #[PrimaryKey], nullable property types, and the ValidateNumberCharsBetween / ValidateNumberCharsLessThan Small Forms rules.
  • Introspect MySQL/MariaDB metadata and PostgreSQL system catalogs without mutating the database.
  • Generate CREATE TABLE, nullable ADD COLUMN, CREATE INDEX / CREATE UNIQUE INDEX, and ADD CONSTRAINT FOREIGN KEY statements in dependency-safe order.
  • Warn about nullability/type mismatches, unexpected tables/columns, conflicting constraints, and changes requiring data migration.
  • Recognize prefix indexes in MySQL and partial/expression indexes in PostgreSQL without mistaking them for complete indexes.

Command

Install in a Symfony application with the Small ORM bundle and run the Composer binary:

composer require small/swoole-entity-manager-migration
DB_PASSWORD=secret vendor/bin/swoole-entity-manager-migration swoole:entity-manager:layers:create \
    --project=. \
    --dsn='mysql:host=127.0.0.1;dbname=app' \
    --user=app \
    --connection=default \
    --dialect=mysql \
    --output=database/layers \
    --dry-run

Remove --dry-run to produce database/layers/<UTC-timestamp>_schema/config.yaml and scripts/001_schema.php (default) or scripts/001_schema.sql with --format=sql. Configure the layer directory as a selector in small_swoole_entity_manager.database_layers and execute the standard swoole:entity-manager:layers:execute command. No migration is executed automatically by the generator.

For PostgreSQL, choose --dialect=postgres and a pgsql: DSN. For multiple connections, run once per connection with its own layer selector/directory.

Return code 0: no blocking drift; 1: input or execution error; 2: manual-review warnings. A warning does not suppress safe operations. When warnings exist, review the generated migration before running it. The generator does not automatically drop or rename tables/columns, remove or replace indexes/foreign keys, modify existing column types, or perform backfills. New foreign keys on populated tables and unique indexes require an explicit data review before executing the generated layer.

Explicit index and foreign-key attributes

Use the migration package attributes on an ORM entity, without changing the ORM runtime:

use Small\SwooleEntityManagerMigration\Attribute\Index;
use Small\SwooleEntityManagerMigration\Attribute\ForeignKey;

#[Index(columns: ['ownerId', 'slug'], name: 'idx_product_owner_slug')]
#[Index(columns: ['slug'], unique: true, name: 'uniq_product_slug')]
#[ForeignKey(
    columns: ['ownerId'],
    referencedManager: UserManager::class,
    referencedColumns: ['id'],
    name: 'fk_product_owner',
    onDelete: 'CASCADE',
    onUpdate: 'RESTRICT',
)]
#[OrmEntity]
class Product extends AbstractEntity
{
    // #[Field] properties and optional #[ToOne] mappings ...
}

Column lists use entity property names, automatically translated to SQL dbFieldName where needed. #[Index] is repeatable and supports compound/unique indexes. An owning #[ToOne(Manager::class, ['localId' => 'id'])] automatically provides a foreign key and a supporting index; #[ToMany] does not produce a second foreign key. An explicit #[ForeignKey] can override a matching #[ToOne] reference (for CASCADE, SET NULL, or custom naming), or declare a relation without a navigation property. Cross-connection references are rejected. The referenced columns must be a primary or unique key.

Foreign keys are added after all tables and indexes so circular references and composite targets can be generated. ON DELETE / ON UPDATE accept RESTRICT, NO ACTION, CASCADE and SET NULL. SET DEFAULT definitions are detected but require manual migration review because default values are not yet modeled. Neither explicit index nor FK mapping alters Small ORM's normal persistence behavior.

For existing tables, SQL to add a unique index or a foreign key is generated alongside a review warning; inspect duplicates/orphaned rows before executing. A differing existing index/foreign key is never dropped or replaced automatically. PostgreSQL partial/expression indexes and MySQL prefix indexes are recognized as non-equivalent to a regular full-column index. MariaDB 11.4 / PostgreSQL 16 are included in the integration tests.

Schema inference limits

Small Forms rules are primarily input-validation rules. Only explicit upper-length constraints are used as optional SQL VARCHAR limits; rules like ValidateRequired, ValidateUnique, or conditional validators are not treated as database constraints. SQL nullability comes from the PHP property type. #[PrimaryKey] defines primary key status. SQL type mapping is intentionally conservative; verify UUID, numeric precision, JSON and database-specific schema behavior before execution.

Class discovery does not modify source code. Application classes are autoloaded to resolve inherited properties, attributes, and named arguments, so only use trusted application code. The target application must have its own vendor/autoload.php installed.

Fixtures par environnement

Deux nouvelles commandes permettent d'exporter les données des tables SQL par environnement et de les restaurer de manière contrôlée :

DB_PASSWORD=secret vendor/bin/swoole-entity-manager-migration \
    swoole:entity-manager:fixtures:dump \
    --environment=dev --name=baseline \
    --dsn='mysql:host=localhost;dbname=app' --user=app \
    --table=users --table=roles

DB_PASSWORD=secret vendor/bin/swoole-entity-manager-migration \
    swoole:entity-manager:fixtures:load \
    --environment=dev --source=fixtures/dev/baseline \
    --dsn='mysql:host=localhost;dbname=app' --user=app --apply

Le chargement sans --apply est une validation en lecture seule. Les fichiers sont stockés par défaut dans fixtures/<environnement>/<snapshot>/, protégé par un .gitignore généré automatiquement, avec empreinte SHA-256 et encodage des champs binaires. Les dumps ne sont pas anonymisés : ne pas les commiter ou diffuser sans inspection. Dump de production sur autorisation explicite seulement ; chargement vers la production interdit.

Consultez la documentation complète des fixtures pour les options, la sécurité et les limites.

Portable PHP layer generation

The migration generator can also emit a PHP-based layer:

vendor/bin/swoole-entity-manager-migration swoole:entity-manager:layers:create \
  --project=. \
  --dsn='pgsql:host=localhost;dbname=app' \
  --user=app \
  --connection=default \
  --dialect=postgres \
  --output=database/layers

This creates scripts/001_schema.php instead of 001_schema.sql. The PHP file returns an ordered list of portable Small ORM schema operations. Tables, columns, supported indexes, and foreign keys are emitted using Table, AlterTable and ColumnType. Unsupported SQL types or vendor-specific features remain RawSql statements scoped to the source dialect, not silently translated.

The default is --format=php. Use --format=sql explicitly to generate legacy SQL scripts. PHP schema operations are provided by this migration package under Small\\SwooleEntityManagerMigration\\Layers\\Schema. The existing Symfony command swoole:entity-manager:layers:execute from small/swoole-entity-manager-bundle delegates execution to this package. The Core API remains available during the compatibility transition. Review generated migrations before execution, especially when existing data must satisfy new unique or foreign-key constraints.

Layer runtime and compatibility

Database layer discovery, dependencies, execution ordering, portable PHP schema operations and SQL migration history are provided by this package in Small\\SwooleEntityManagerMigration\\Layers. The Symfony bundle's existing command and database_layers configuration remain unchanged when using the compatible bundle release. The pre-migration Core layer API is retained as a temporary compatibility path for applications that have not upgraded.

MySQL/MariaDB and PostgreSQL use a migration-owned PDO adapter for the existing _small_swoole_entity_manager_layers history table. The adapter does not use the ORM's Swoole connection pool and executes each SQL statement independently. SQL migration files can contain multiple statements, quoted semicolons, comments and PostgreSQL dollar-quoted procedural bodies. The DELIMITER directive used by the MySQL CLI is not supported; prefer individual SQL/PHP operations. SwooleDB continues to use the legacy in-memory adapter during the transition.

A PHP layer script returns a list of schema operations:

<?php
use Small\\SwooleEntityManagerMigration\\Layers\\Schema\\{Table, AlterTable, ColumnType, RawSql};

return [
    (new Table('accounts'))->addColumn('id', ColumnType::uuid)->addPrimaryKey('id'),
    (new AlterTable('accounts'))->addColumn('name', ColumnType::string, length: 120),
    new RawSql('UPDATE accounts SET name = \'Anonymous\' WHERE name IS NULL'),
];

Only execute trusted PHP migrations. MySQL DDL is not generally transactional; schema changes and the history record are not an atomic unit. Back up data before applying migrations, keep migration scripts idempotent where possible, and resolve partially applied layers manually. Both MySQL/MariaDB and PostgreSQL are tested against real databases.