### Example Usage of DatabaseMigrationRepository Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Demonstrates how to instantiate and use the DatabaseMigrationRepository to manage database migrations, including ensuring the table, getting applied migrations, and marking them as applied or rolled back. ```php use AsceticSoft\RowcastSchema\Migration\DatabaseMigrationRepository; $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'password'); $repo = new DatabaseMigrationRepository($pdo, '_rowcast_migrations'); $repo->ensureTable(); // Get applied migrations $applied = $repo->getApplied(); echo "Applied: " . implode(', ', $applied) . "\n"; // Record a new migration $repo->markApplied('20240525_143000'); // Rollback $repo->markRolledBack('20240525_143000'); ``` -------------------------------- ### Complete Migration Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/schema-builder.md This example demonstrates creating two tables, 'users' and 'posts', with various column types and constraints, including primary keys, foreign keys, enums, and indexes. ```php createTable('users', function ($table) { $table->column('id', 'integer') ->primaryKey() ->autoIncrement(); $table->column('email', 'string') ->length(255) ->unique(); $table->column('name', 'string') ->length(100); $table->column('status', 'enum') ->values(['active', 'inactive', 'banned']) ->default('active'); $table->column('created_at', 'datetime') ->default('CURRENT_TIMESTAMP'); $table->index('idx_status', ['status']); }); $schema->createTable('posts', function ($table) { $table->column('id', 'bigint') ->primaryKey() ->autoIncrement(); $table->column('user_id', 'integer'); $table->column('title', 'string')->length(255); $table->column('content', 'text'); $table->column('published_at', 'datetime')->nullable(); $table->foreignKey( 'fk_posts_user', ['user_id'], 'users', ['id'], ReferentialAction::Cascade, ); }); } public function down(SchemaBuilder $schema): void { $schema->dropTable('posts'); $schema->dropTable('users'); } } ``` -------------------------------- ### Install and Run Tests Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Commands to install dependencies and run the test suite using PHPUnit. Also includes the command for static analysis with PHPStan. ```bash composer install vendor/bin/phpunit ``` ```bash vendor/bin/phpstan analyse ``` -------------------------------- ### Install symfony/yaml Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/parser.md Install the symfony/yaml component to enable YAML schema parsing. ```bash composer require symfony/yaml ``` -------------------------------- ### PHP Schema File Format Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/parser.md Example structure for a schema definition in a PHP file. ```php [ 'users' => [ 'columns' => [ 'id' => ['type' => 'integer', 'primaryKey' => true, 'autoIncrement' => true], 'email' => ['type' => 'string', 'length' => 255], ], 'indexes' => [ 'idx_email' => ['columns' => ['email'], 'unique' => true], ], ], ], ]; ``` -------------------------------- ### Migrate Command: Example Output Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Displays the output after successfully applying pending migrations, including a summary of applied migrations and total time. ```text migrate ——————— Applied migrations: • Migration_20240525_130000 (5.2ms) • Migration_20240525_140000 (12.1ms) • Migration_20240525_143000 (2.8ms) Summary: 3 migrations applied (20.1ms total) Schema is up to date. ``` -------------------------------- ### Database Connection Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Configure the PDO connection details. Supports MySQL/MariaDB, PostgreSQL, and SQLite. ```php 'connection' => [ 'dsn' => 'mysql:host=db.example.com;dbname=myapp', 'username' => 'db_user', 'password' => 'secure_password', ], ``` -------------------------------- ### Migrations Directory Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Define the directory where migration files are stored. The directory will be created if it does not exist. ```php 'migrations' => __DIR__ . '/database/migrations', ``` -------------------------------- ### Basic PHP Configuration (MySQL) Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Example of a basic configuration file for MySQL, specifying connection details, schema path, and migrations path. ```php [ 'dsn' => 'mysql:host=localhost;dbname=myapp', 'username' => 'app_user', 'password' => 'password123', ], 'schema' => __DIR__ . '/schema.php', 'migrations' => __DIR__ . '/migrations', ]; ``` -------------------------------- ### Diff Command: Example Output Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Shows the typical output when the `diff` command detects schema changes and generates a migration file. ```text diff —————————————— Detected 3 operations: • CreateTable: users • AddColumn: users.email • AddIndex: users.idx_email Summary: 1 table created, 1 column added, 1 index added Migration generated: Migration_20240525_143000 /app/migrations/Migration_20240525_143000.php ``` -------------------------------- ### CreateTable Operation Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/differ.md Example of creating a CreateTable operation. The reverse() method returns a DropTable operation for the same table. ```php use AsceticSoft\RowcastSchema\Diff\Operation\CreateTable; use AsceticSoft\RowcastSchema\Schema\Table; use AsceticSoft\RowcastSchema\Schema\Column; use AsceticSoft\RowcastSchema\Schema\ColumnType; $operation = new CreateTable(new Table( name: 'users', columns: [ 'id' => new Column(name: 'id', type: ColumnType::Integer, primaryKey: true), ], )); $reverse = $operation->reverse(); // DropTable ``` -------------------------------- ### Complete Schema Example with ForeignKey Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/attributes.md A comprehensive example showcasing the usage of the ForeignKey attribute within a full table schema definition, including other attributes like Table, Index, and Column. ```php create(__DIR__ . '/schema.php'); $desiredSchema = $parser->parse(__DIR__ . '/schema.php'); // Step 2: Read current database state $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'password'); $introspectorFactory = new IntrospectorFactory(); $introspector = $introspectorFactory->create($pdo); $currentSchema = $introspector->introspect($pdo); // Step 3: Compute differences $differ = new SchemaDiffer(); $operations = $differ->diff($currentSchema, $desiredSchema); echo "Found " . count($operations) . " schema changes:\n"; foreach ($operations as $op) { $className = (new ReflectionClass($op))->getShortName(); echo "- $className\n"; } // Step 4: Generate migration if (count($operations) > 0) { $generator = new MigrationGenerator(); $filePath = $generator->generate($operations, __DIR__ . '/migrations'); echo "\nGenerated migration: $filePath\n"; } else { echo "\nSchema is already up to date.\n"; } ``` -------------------------------- ### DropTable Operation Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/differ.md Example of creating a DropTable operation. The reverse() method returns null as it's irreversible without the original table definition. ```php use AsceticSoft\RowcastSchema\Diff\Operation\DropTable; $operation = new DropTable('legacy_table'); $reverse = $operation->reverse(); // null ``` -------------------------------- ### Install Rowcast Schema Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Install the Rowcast Schema package using Composer. For optional YAML schema support, also install symfony/yaml. ```bash composer require ascetic-soft/rowcast-schema ``` ```bash composer require symfony/yaml ``` -------------------------------- ### PHP Configuration with Attributes (PostgreSQL) Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Example of a PHP configuration file for PostgreSQL, including connection details, schema path, migrations path, and migration table name. ```php [ 'dsn' => 'pgsql:host=db.internal.local;dbname=myapp;port=5432', 'username' => 'postgres', 'password' => 'secure_pass', ], 'schema' => __DIR__ . '/src/Entity', 'migrations' => __DIR__ . '/db/migrations', 'migration_table' => 'schema_versions', ]; ``` -------------------------------- ### Complete SQL Generation Workflow Example Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/platform.md Demonstrates the end-to-end process of generating SQL for database schema migrations. It involves parsing the desired schema, introspecting the current database state, calculating differences, and generating platform-specific SQL statements. ```php use AsceticSoft\RowcastSchema\Parser\SchemaParserFactory; use AsceticSoft\RowcastSchema\Introspector\IntrospectorFactory; use AsceticSoft\RowcastSchema\Diff\SchemaDiffer; use AsceticSoft\RowcastSchema\Platform\PlatformFactory; // Setup $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'password'); // Parse and introspect $parserFactory = new SchemaParserFactory(); $desiredSchema = $parserFactory->create('schema.php')->parse('schema.php'); $introspectorFactory = new IntrospectorFactory(); $currentSchema = $introspectorFactory->create($pdo)->introspect($pdo); // Compute differences $differ = new SchemaDiffer(); $operations = $differ->diff($currentSchema, $desiredSchema); // Generate SQL $platformFactory = new PlatformFactory(); $platform = $platformFactory->createForPdo($pdo); echo "Generated SQL:\n"; foreach ($operations as $operation) { $sqlStatements = $platform->toSql($operation); foreach ($sqlStatements as $sql) { echo $sql . ";\n"; } } // Check if DDL transactions are supported if ($platform->supportsDdlTransactions()) { echo "\nDDL transactions are supported\n"; } else { echo "\nDDL transactions are NOT supported\n"; } ``` -------------------------------- ### ReferentialAction Usage Examples Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/types.md Demonstrates how to use the ReferentialAction enum to define foreign key constraints. Includes examples of using enum cases and raw strings with static helper methods. ```php use AsceticSoft\RowcastSchema\Schema\ReferentialAction; // Using enum case $action = ReferentialAction::Cascade; $sql = ReferentialAction::toSql($action); // 'CASCADE' // Using string $sql = ReferentialAction::toSql('cascade'); // 'CASCADE' // Try to resolve from user input $action = ReferentialAction::tryFromString('CASCADE'); if ($action instanceof ReferentialAction) { // Known action } else { // Custom string action } ``` -------------------------------- ### Schema Path Examples Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Specify the path to schema definitions. Supports PHP arrays, YAML files, or directories with PHP attributes. ```php 'schema' => __DIR__ . '/database/schema.php', ``` ```php 'schema' => __DIR__ . '/config/schema.yaml', ``` ```php 'schema' => __DIR__ . '/src/Entity', ``` -------------------------------- ### Create Introspector using Factory Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/introspector.md Demonstrates how to create a database introspector using the IntrospectorFactory. This is the recommended way to get an introspector instance, as it automatically detects the correct driver. ```php use AsceticSoft\RowcastSchema\Introspector\IntrospectorFactory; $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'password'); $factory = new IntrospectorFactory(); $introspector = $factory->create($pdo); // Returns: MysqlIntrospector // Read current database schema $schema = $introspector->introspect($pdo); foreach ($schema->tables as $table) { echo $table->name . "\n"; } ``` -------------------------------- ### Column Attribute Example Usage Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/attributes.md Demonstrates various configurations of the Column attribute for different property types and constraints. ```php use AsceticSoft\RowcastSchema\Attribute\Column; use AsceticSoft\RowcastSchema\Schema\ColumnType; class User { #[Column(primaryKey: true, autoIncrement: true)] public int $id; #[Column(length: 255)] public string $email; #[Column(type: ColumnType::Text)] public string $bio; #[Column(nullable: true)] public ?string $phoneNumber; #[Column(default: false)] public bool $isActive; #[Column(precision: 10, scale: 2)] public float $balance; #[Column(nullable: true, databaseType: 'vector(1536)')] public ?string $embedding; } ``` -------------------------------- ### SQLite Platform SQL Generation Examples Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/platform.md Illustrates how the SQLite platform generates SQL. Simple operations produce direct SQL, while complex alterations like ALTER TABLE are handled via a table rebuild process using SqliteTableRebuilder. ```php use AsceticSoft\RowcastSchema\Platform\SqlitePlatform; $platform = new SqlitePlatform(); // Simple operations generate direct SQL // CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL) // Complex operations like ALTER are not generated directly // Instead, the MigrationRunner uses SqliteTableRebuilder ``` -------------------------------- ### Environment-Based MySQL Configuration Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Load database credentials from a .env file or environment variables for a MySQL connection. Includes example ignore rules for tables. ```php [ 'dsn' => "mysql:host=$dbHost;dbname=$dbName", 'username' => $dbUser, 'password' => $dbPass, ], 'schema' => $cwd . '/database/schema.yaml', 'migrations' => $cwd . '/database/migrations', 'ignore_tables' => [ '/^tmp_/', static fn (string $table): bool => str_starts_with($table, '_'), ], ]; }; ``` -------------------------------- ### Composite ForeignKey Usage Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/attributes.md Example demonstrating a composite foreign key constraint involving multiple columns on both the referencing and referenced tables. ```php #[Table] #[ForeignKey( name: 'fk_items_product', columns: ['product_id', 'warehouse_id'], referenceTable: 'products', referenceColumns: ['id', 'warehouse_id'], )] class Inventory { #[Column] public int $product_id; #[Column] public int $warehouse_id; } ``` -------------------------------- ### Table Attribute Usage Examples Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/attributes.md Demonstrates how to use the Table attribute to define table names, including inferred names, custom names, and specifying engine and charset. ```php use AsceticSoft\RowcastSchema\Attribute\Table; // Inferred table name: users (from class name) #[Table] class User { // properties } // Custom table name #[Table('client_accounts')] class User { // properties } // With engine and charset #[Table( name: 'products', engine: 'InnoDB', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci', )] class Product { // properties } ``` -------------------------------- ### Migration Table Name Examples Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Set the name for the database table that tracks applied migrations. This table is automatically created and excluded from schema diffs. ```php 'migration_table' => '_rowcast_migrations', ``` ```php 'migration_table' => 'schema_versions', ``` -------------------------------- ### Create Platform Instance and Generate SQL Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/platform.md Demonstrates how to create a platform instance for a PDO connection and then use it to generate SQL statements from a CreateTable operation. Ensure necessary classes are imported. ```php use AsceticSoft\RowcastSchema\Platform\PlatformFactory; $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'password'); $factory = new PlatformFactory(); $platform = $factory->createForPdo($pdo); // Returns: MysqlPlatform // Generate SQL from an operation use AsceticSoft\RowcastSchema\Diff\Operation\CreateTable; use AsceticSoft\RowcastSchema\Schema\Table; use AsceticSoft\RowcastSchema\Schema\Column; use AsceticSoft\RowcastSchema\Schema\ColumnType; $operation = new CreateTable(new Table( name: 'users', columns: [ 'id' => new Column(name: 'id', type: ColumnType::Integer, primaryKey: true), ], )); $sqlStatements = $platform->toSql($operation); foreach ($sqlStatements as $sql) { echo $sql . "\n"; } ``` -------------------------------- ### Global Options: Config and No-ANSI Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Demonstrates the two supported formats for specifying the configuration file path and disabling colored output. ```bash vendor/bin/rowcast-schema --config=path/to/config.php diff ``` ```bash vendor/bin/rowcast-schema --config path/to/config.php diff ``` -------------------------------- ### Get Schema Operations Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/schema-builder.md Retrieves the list of all operations that have been defined using the schema builder. Useful for inspection or debugging. ```php $schema = new SchemaBuilder(); $schema->createTable('users', fn ($t) => $t->column('id', 'integer')->primaryKey()); $schema->addColumn('users', new Column(name: 'name', type: ColumnType::String)); $ops = $schema->getOperations(); // $ops contains 2 operations: CreateTable and AddColumn ``` -------------------------------- ### Parse YAML Schema Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/parser.md Use YamlSchemaParser to parse a schema definition from a YAML file. Ensure the symfony/yaml component is installed. ```php use AsceticSoft\RowcastSchema\Parser\YamlSchemaParser; $parser = new YamlSchemaParser(); $schema = $parser->parse(__DIR__ . '/database/schema.yaml'); // Use schema var_dump($schema->tables); ``` -------------------------------- ### Configure Database Connection Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/README.md Set up the database connection and schema/migration paths by creating a `rowcast-schema.php` configuration file. This file specifies DSN, username, password, and directory locations. ```php [ 'dsn' => 'mysql:host=localhost;dbname=app', 'username' => 'root', 'password' => 'secret', ], 'schema' => __DIR__ . '/schema.php', 'migrations' => __DIR__ . '/migrations', ]; ``` -------------------------------- ### RowcastSchema CLI Workflow Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/README.md Demonstrates the command-line workflow for using RowcastSchema to diff schemas, generate migrations, and apply them to the database. ```bash vendor/bin/rowcast-schema diff --dry-run # Preview vendor/bin/rowcast-schema diff # Generate migration vendor/bin/rowcast-schema migrate # Apply ``` -------------------------------- ### Write Manual Migrations Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/README.md Create manual migration files by extending `AbstractMigration` and using the `SchemaBuilder` to define schema changes. This allows for complex or custom migration logic. ```php createTable('users', function ($table) { $table->column('id', 'integer')->primaryKey()->autoIncrement(); $table->column('email', 'string')->length(255); }); } } ``` -------------------------------- ### Load Configuration from File Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Load configuration settings from a PHP file into a Config object. Handles schema path, migrations path, and database connection. ```php use AsceticSoft\RowcastSchema\Cli\Config; $config = Config::fromFile(__DIR__ . '/rowcast-schema.php'); // Use configuration echo "Schema path: " . $config->schemaPath . "\n"; echo "Migrations path: " . $config->migrationsPath . "\n"; // Get database connection $pdo = $config->pdo; ``` -------------------------------- ### ForeignKey Usage on Class Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/attributes.md Example of applying the ForeignKey attribute to a class to define a foreign key constraint, typically for multiple or complex foreign keys. ```php use AsceticSoft\RowcastSchema\Attribute\ForeignKey; use AsceticSoft\RowcastSchema\Attribute\Table; use AsceticSoft\RowcastSchema\Schema\ReferentialAction; #[Table] #[ForeignKey( name: 'fk_posts_user', columns: ['user_id'], referenceTable: 'users', referenceColumns: ['id'], onDelete: ReferentialAction::Cascade, )] class Post { #[Column] public int $user_id; } ``` -------------------------------- ### Run Migrations with MigrationRunner Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Initialize and use MigrationRunner to apply pending migrations. Provide the path to migration files and an optional callback for version-specific actions. ```php use AsceticSoft\RowcastSchema\Migration\MigrationRunner; use AsceticSoft\RowcastSchema\Introspector\IntrospectorFactory; use AsceticSoft\RowcastSchema\Platform\PlatformFactory; use AsceticSoft\RowcastSchema\Migration\DatabaseMigrationRepository; use AsceticSoft\RowcastSchema\Migration\MigrationLoader; $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'password'); $runner = new MigrationRunner( pdo: $pdo, loader: new MigrationLoader(), repository: new DatabaseMigrationRepository($pdo, '_rowcast_migrations'), platform: PlatformFactory::create($pdo), ); $count = $runner->migrate( migrationsPath: __DIR__ . '/migrations', onVersion: function (string $version) { echo "Applied: $version\n"; }, ); echo "Migrated $count files\n"; ``` -------------------------------- ### DatabaseMigrationRepository getApplied() Method Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Retrieves a sorted list of all migration versions that have been applied to the database. ```php public function getApplied(): array ``` -------------------------------- ### PostgreSQL Column Alteration Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/platform.md Example of altering a column type in PostgreSQL. This snippet demonstrates the specific syntax for changing a column's data type. ```php use AsceticSoft\RowcastSchema\Platform\PostgresPlatform; $platform = new PostgresPlatform(); // Column alteration uses ALTER COLUMN TYPE $sql = [ 'ALTER TABLE users ALTER COLUMN email TYPE VARCHAR(320)', ]; // Full table creation with proper PostgreSQL syntax // CREATE TABLE users ( // id BIGSERIAL PRIMARY KEY, // email VARCHAR(255) NOT NULL, // created_at TIMESTAMP NOT NULL // ) ``` -------------------------------- ### Make Command: Generate Empty Migration Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Creates a new, empty migration file with placeholder `up()` and `down()` methods. Useful for manual migration creation. ```bash vendor/bin/rowcast-schema make ``` ```bash vendor/bin/rowcast-schema --config=db/schema.php make ``` -------------------------------- ### Custom Database Types Schema Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Example of defining a schema with custom database types like 'vector(1536)' for pgvector and 'citext' for case-insensitive text. ```php [ 'embeddings' => [ 'columns' => [ 'id' => ['type' => 'bigint', 'primaryKey' => true, 'autoIncrement' => true], 'gigachat_vector' => ['type' => 'vector(1536)', 'nullable' => true], 'title_ci' => ['type' => 'citext'], ], ], ], ]; ``` -------------------------------- ### Manual Migration: Apply and Rollback Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Applies a manually created migration and demonstrates how to rollback if necessary. This sequence is used when adjustments are needed after an initial migration. ```bash vendor/bin/rowcast-schema migrate vendor/bin/rowcast-schema rollback ``` -------------------------------- ### ForeignKey Usage on Property Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/attributes.md Example of applying the ForeignKey attribute directly to a property for a single-column foreign key. The 'columns' parameter can be omitted, defaulting to the property's column name. ```php #[Table] class OrderItem { #[Column] #[ForeignKey( name: 'fk_order_id', referenceTable: 'orders', referenceColumns: ['id'], onDelete: ReferentialAction::Cascade, )] public int $order_id; } ``` -------------------------------- ### Register Custom Platforms with PlatformFactory Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/platform.md Shows how to register custom platform implementations with the PlatformFactory using a registry array. This allows the factory to create instances of your custom platforms. ```php use AsceticSoft\RowcastSchema\Platform\PlatformFactory; use MyApp\CustomPlatform; $registry = [ 'custom' => fn () => new CustomPlatform(), ]; $factory = new PlatformFactory(registry: $registry); ``` -------------------------------- ### Specify Custom Configuration File Path Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Use the --config option with the CLI to point to a custom configuration file. This is useful when your configuration is not in the default location. ```bash vendor/bin/rowcast-schema --config=path/to/custom-config.php diff vendor/bin/rowcast-schema --config path/to/custom-config.php migrate ``` -------------------------------- ### make Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Generates an empty, timestamped migration file with `up()` and `down()` methods. This command is used when you need to manually write migration logic. ```APIDOC ## make ### Description Generates an empty migration file with a timestamp. This is useful for manually writing migration logic in the `up()` and `down()` methods. ### Method `make` ### Behavior Creates a new timestamped migration file with empty `up()` and `down()` methods. ### Generated File Example ```php new Table( name: 'users', columns: [ 'id' => new Column( name: 'id', type: ColumnType::Integer, primaryKey: true, autoIncrement: true, ), ], ), ]); // Check and retrieve tables if ($schema->hasTable('users')) { $usersTable = $schema->getTable('users'); // $usersTable is a Table object } $nonexistent = $schema->getTable('posts'); // null ``` -------------------------------- ### Use Custom Configuration File Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Specify a custom configuration file path using the --config CLI option when running Rowcast Schema commands. ```bash vendor/bin/rowcast-schema --config=database/rowcast-schema.php diff ``` -------------------------------- ### Generate Migrations using CLI Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/README.md Use the Rowcast Schema CLI to preview schema changes, generate migration files, or create empty migration files for manual editing. ```bash # Preview changes vendor/bin/rowcast-schema diff --dry-run # Generate migration file vendor/bin/rowcast-schema diff # Create empty migration for manual editing vendor/bin/rowcast-schema make ``` -------------------------------- ### DatabaseMigrationRepository markApplied() Method Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Records a specific migration version as having been successfully applied. ```php public function markApplied(string $version): void ``` -------------------------------- ### Make Command: Generated File Structure Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md The structure of an empty migration file generated by the `make` command, including necessary imports and abstract class. ```php sql("UPDATE users SET status = 'active' WHERE status IS NULL"); $schema->sql("INSERT INTO roles (name) VALUES ('admin'), ('user')"); ``` ``` -------------------------------- ### Load Migration Files Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Scans a specified directory for migration files and returns a mapping of migration versions to their file paths. The results are sorted by version. ```php /** * @return array */ public function load(string $migrationsPath): array ``` ```php use AsceticSoft\RowcastSchema\Migration\MigrationLoader; $loader = new MigrationLoader(); $migrations = $loader->load(__DIR__ . '/migrations'); foreach ($migrations as $version => $filePath) { echo "$version => $filePath\n"; // Output: // 20240525_143000 => /app/migrations/Migration_20240525_143000.php // 20240526_100000 => /app/migrations/Migration_20240526_100000.php } ``` -------------------------------- ### Check Status with Custom Configuration Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Checks the migration status using a custom configuration file. Provide the path to your configuration file with the `--config` option. ```bash vendor/bin/rowcast-schema --config=db/prod.php status ``` -------------------------------- ### Migration Builder API - Execute SQL Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Shows how to execute arbitrary SQL statements within a migration's 'up' method using the SchemaBuilder. ```php public function up(SchemaBuilder $schema): void { $schema->sql("UPDATE users SET status = 'active' WHERE status IS NULL"); } ``` -------------------------------- ### RowcastSchema Architecture Overview Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md This diagram outlines the core components and their relationships within the RowcastSchema library, illustrating the flow from parsing and introspection to diffing, platform-specific SQL generation, and migration execution. ```text AsceticSoft\RowcastSchema\ ├── Attribute\ │ ├── Table, Column # Entity/table and property/column metadata │ └── Index, ForeignKey # Index and FK metadata ├── Schema\ │ ├── Schema # Root schema model │ ├── Table, Column, Index, ForeignKey # Schema components │ └── ColumnType # Abstract type enum ├── Parser\ │ ├── SchemaParserInterface # Parser contract │ ├── PhpSchemaParser # PHP array parser (default) │ ├── YamlSchemaParser # YAML parser (optional) │ ├── AttributeSchemaParser # Attribute directory parser │ ├── ArraySchemaBuilder # Shared array → Schema builder │ ├── AttributeSchemaBuilder # Reflection attributes → Schema builder │ ├── ClassScanner # Directory PHP class scanner │ └── NamingStrategy # class/property -> table/column naming ├── Introspector\ │ ├── IntrospectorInterface # Introspector contract │ ├── IntrospectorFactory # PDO driver → introspector │ ├── MysqlIntrospector # MySQL introspection │ ├── PostgresIntrospector # PostgreSQL introspection │ └── SqliteIntrospector # SQLite introspection ├── Diff\ │ ├── SchemaDiffer # Schema comparison engine │ └── Operation\ │ ├── OperationInterface # Operation contract │ ├── CreateTable, DropTable # Table-level operations │ ├── AddColumn, AlterColumn, DropColumn │ ├── AddIndex, DropIndex │ └── AddForeignKey, DropForeignKey ├── Platform\ │ ├── PlatformInterface # SQL generation contract │ ├── PlatformFactory # PDO driver → platform │ ├── AbstractPlatform # Shared SQL logic │ ├── MysqlPlatform # MySQL DDL │ ├── PostgresPlatform # PostgreSQL DDL │ └── SqlitePlatform # SQLite DDL (with rebuild) ├── Migration │ ├── MigrationInterface # Migration contract │ ├── AbstractMigration # Base migration class │ ├── MigrationGenerator # PHP migration file generator │ ├── MigrationLoader # Loads migration files from disk │ ├── MigrationRunner # Applies/rollbacks migrations │ ├── MigrationRepositoryInterface # Repository contract │ ├── DatabaseMigrationRepository # Tracks applied migrations in DB │ └── SqliteTableRebuilder # SQLite rebuild pipeline ├── SchemaBuilder\ │ ├── SchemaBuilder # Fluent API for migration operations │ ├── TableBuilder # Fluent table/column definition │ └── ColumnBuilder # Fluent column properties ├── TypeMapper\ │ ├── TypeMapperInterface # Type mapper contract │ ├── MysqlTypeMapper # MySQL type mapping │ ├── PostgresTypeMapper # PostgreSQL type mapping │ └── SqliteTypeMapper # SQLite type mapping ├── Pdo\ │ └── PdoDriverResolver # Centralized PDO driver detection └── Cli\ ├── Application # CLI entry point ├── Config # Configuration loader └── Command\ ├── CommandInterface # Command contract ├── DiffCommand # diff command ├── MakeCommand # make command ├── MigrateCommand # migrate command ├── RollbackCommand # rollback command └── StatusCommand # status command ``` -------------------------------- ### Load Configuration File Manually Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Manually load a configuration file using ConfigFileLoader. Supports array-based or closure-based configurations. ```php use AsceticSoft\RowcastSchema\Cli\ConfigFileLoader; $loader = new ConfigFileLoader(); $config = $loader->load(__DIR__ . '/rowcast-schema.php', getcwd()); if (is_callable($config)) { // Closure-based config $config = $config(getcwd()); } ``` -------------------------------- ### Apply Migrations using CLI Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/README.md Manage database migrations using the Rowcast Schema CLI. Apply pending migrations, check the migration status, or rollback recent migrations. ```bash # Apply all pending migrations vendor/bin/rowcast-schema migrate # Check status vendor/bin/rowcast-schema status # Rollback recent migrations vendor/bin/rowcast-schema rollback --step=2 ``` -------------------------------- ### Creating a Simple ForeignKey Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/schema.md Instantiates a ForeignKey object for a basic foreign key constraint. Ensure the name, columns, reference table, and reference columns are correctly provided. ```php use AsceticSoft\RowcastSchema\Schema\ForeignKey; use AsceticSoft\RowcastSchema\Schema\ReferentialAction; // Simple foreign key $userFk = new ForeignKey( name: 'fk_posts_user', columns: ['user_id'], referenceTable: 'users', referenceColumns: ['id'], ); ``` -------------------------------- ### Rollback with Custom Configuration Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Performs a rollback operation using a custom configuration file. Specify the path to your configuration file using the `--config` option. ```bash vendor/bin/rowcast-schema --config=db.php rollback --step=2 ``` -------------------------------- ### Implement Migration Interface Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Define a new migration by implementing the MigrationInterface. This requires defining both `up()` to apply changes and `down()` to revert them. ```php use AsceticSoft\RowcastSchema\Migration\MigrationInterface; use AsceticSoft\RowcastSchema\SchemaBuilder\SchemaBuilder; final class Migration_20240525_143000 implements MigrationInterface { public function up(SchemaBuilder $schema): void { $schema->createTable('users', function ($table) { $table->column('id', 'integer')->primaryKey()->autoIncrement(); $table->column('email', 'string')->length(255); }); } public function down(SchemaBuilder $schema): void { $schema->dropTable('users'); } } ``` -------------------------------- ### DatabaseMigrationRepository::getApplied Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Retrieves a sorted list of all migration versions that have been successfully applied to the database. ```APIDOC ## DatabaseMigrationRepository::getApplied ### Description Returns a list of applied migration versions, sorted. ### Method `public function getApplied(): array` ### Parameters None ### Response #### Success Response - **applied_migrations** (array) - List of version strings (e.g., ['20240525_143000', '20240526_100000']) ### Example ```php $applied = $repo->getApplied(); ``` ``` -------------------------------- ### Production MySQL Configuration with Ignore Rules Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Production-ready MySQL configuration using environment variables for credentials and extensive ignore rules for various table types. ```php [ 'dsn' => 'mysql:host=db.prod.internal;dbname=app_prod', 'username' => getenv('DB_USER'), 'password' => getenv('DB_PASSWORD'), ], 'schema' => __DIR__ . '/config/schema.php', 'migrations' => __DIR__ . '/database/migrations', 'migration_table' => 'migrations_applied', 'ignore_tables' => [ // Ignore temporary and system tables '/^tmp_/', '/^_temp/', '/^backup_/', // Ignore audit/log tables '/^audit_/', '/^log_/', '/^event_log/', // Ignore sync/external data '/^sync_/', '/^external_/', // Ignore test/development tables static fn (string $table): bool => str_contains($table, 'staging'), static fn (string $table): bool => str_contains($table, 'dev_'), ], ]; ``` -------------------------------- ### Verify Migration Syntax Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md Checks the PHP syntax of migration files. This is a crucial step to ensure that migration files are valid before attempting to apply them. ```bash php -l migrations/Migration_*.php ``` -------------------------------- ### Create Schema Parser Instance Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/parser.md Use SchemaParserFactory to create an instance of the appropriate schema parser based on the provided schema path. ```php use AsceticSoft\RowcastSchema\Parser\SchemaParserFactory; $factory = new SchemaParserFactory(); // PHP file $parser = $factory->create(__DIR__ . '/schema.php'); // Returns: PhpSchemaParser // YAML file $parser = $factory->create(__DIR__ . '/schema.yaml'); // Returns: YamlSchemaParser // Directory with attributes $parser = $factory->create(__DIR__ . '/src/Entity'); // Returns: AttributeSchemaParser ``` -------------------------------- ### MigrationLoader::load() Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Scans a specified directory for migration files and returns a mapping of migration versions to their full file paths. The results are sorted by version. ```APIDOC ## MigrationLoader::load() ### Description Scans a directory and returns migration version → file path mapping. ### Method `public function load(string $migrationsPath): array` ### Parameters #### Path Parameters - `migrationsPath` (string) - Required - Directory containing migration files ### Returns `array` - Map of version string (e.g., '20240525_143000') to full file path, sorted by version ### Version Format: Migrations must be named `Migration_YYYYMMDD_HHMMSS.php` where the timestamp is the version. ### Example ```php use AsceticSoft\RowcastSchema\Migration\MigrationLoader; $loader = new MigrationLoader(); $migrations = $loader->load(__DIR__ . '/migrations'); foreach ($migrations as $version => $filePath) { echo "$version => $filePath\n"; // Output: // 20240525_143000 => /app/migrations/Migration_20240525_143000.php // 20240526_100000 => /app/migrations/Migration_20240526_100000.php } ``` ``` -------------------------------- ### Closure Format Configuration Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/configuration.md Return a closure that dynamically generates the configuration array. This allows for environment-specific settings and dynamic path resolution. ```php [ 'dsn' => $_ENV['DATABASE_URL'] ?? 'mysql:host=localhost;dbname=app', 'username' => $_ENV['DATABASE_USER'] ?? 'root', 'password' => $_ENV['DATABASE_PASSWORD'] ?? '', ], 'schema' => $projectDir . '/src/Entity', 'migrations' => $projectDir . '/migrations', 'migration_table' => '_rowcast_migrations', 'ignore_tables' => [ '/^_/', ], ]; }; ``` -------------------------------- ### DatabaseMigrationRepository Full Signature Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/api-reference/migration.md Defines the structure and methods of the DatabaseMigrationRepository class. ```php final readonly class DatabaseMigrationRepository implements MigrationRepositoryInterface { public function __construct( private \PDO $pdo, private string $tableName = '_rowcast_migrations', ) public function ensureTable(): void public function getApplied(): array public function markApplied(string $version): void public function markRolledBack(string $version): void } ``` -------------------------------- ### Rowcast Schema CLI Commands Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Common Rowcast Schema commands for managing database migrations: diff, make, migrate, and status. Supports a global --config option. ```bash # Generate a migration from schema diff vendor/bin/rowcast-schema diff # Generate an empty migration file vendor/bin/rowcast-schema make # Apply pending migrations vendor/bin/rowcast-schema migrate # Check sync status vendor/bin/rowcast-schema status ``` -------------------------------- ### Basic Invocation Source: https://github.com/ascetic-soft/rowcastschema/blob/master/_autodocs/cli.md The basic structure for invoking the Rowcast Schema CLI with global options and a command. ```bash vendor/bin/rowcast-schema [global-options] [command-options] ``` -------------------------------- ### RowcastSchema CLI Commands Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md List of available CLI commands for RowcastSchema, including diff, make, migrate, rollback, and status. ```bash vendor/bin/rowcast-schema [options] ``` -------------------------------- ### Rowcast Schema Global CLI Option Source: https://github.com/ascetic-soft/rowcastschema/blob/master/README.md Use a custom configuration file path for all Rowcast Schema CLI commands with the --config option. ```bash - --config=path (or --config path) — use a custom configuration file path. ```