denetorus / galaxy-db-migration
Database schema validation and structured migration planning.
Requires
- php: >=8.4
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-30 06:54:47 UTC
README
PHP >= 8.4 database-independent schema validation, structured migration planning, file queues and PHP metadata generation. Schema validation and planning run without a database connection. MIT © 2026 Mylnikov Denis. Version 0.1.0 is available on Packagist. Русское руководство. Design rationale: ADR EN, ADR RU.
Build your first plan without a database
Suppose you want a records table with an ID and an optional name. In a project with the package installed, save this description as schema.json next to vendor/. See the installation instructions below.
{
"tables": {
"records": {
"columns": {
"id": {"type": "integer", "bits": 32},
"name": {"type": "string", "length": 80, "nullable": true}
},
"primaryKey": ["id"]
}
}
}
Save this code as plan.php and run php plan.php.
<?php use Galaxy\DBMigration\SchemaPlanner; require __DIR__ . '/vendor/autoload.php'; $target = file_get_contents(__DIR__ . '/schema.json'); $operations = SchemaPlanner::buildSchemaDiffOperations(null, $target); foreach ($operations as $operation) { echo $operation['kind'], ' ', $operation['table'], PHP_EOL; }
The output is createTable records, an operation in the plan. Passing null means the starting schema is empty. To plan a second change, save the first schema as previous.json, add an email column to schema.json and pass the contents of previous.json in place of null. The output is now addColumn records.
Use a table template for shared fields. For example, move id and the primary key into templates.baseRecord, set "template": "baseRecord" in records and leave only its own name column in the table. The plan from an empty schema still creates a table with both columns.
Install and verify independently
Install version 0.1.0 with Composer: composer require denetorus/galaxy-db-migration:0.1.0.
To test a local checkout, use a separate Composer project:
php tests/create-consumer.php /absolute/new-common-consumer /absolute/GalaxyDBMigration
cd /absolute/new-common-consumer
composer install --no-dev --no-scripts --no-plugins
composer dump-autoload --optimize --strict-psr --no-scripts --no-plugins
composer check-platform-reqs
The external fixture alone declares a path repository, symlink=false and version 0.1.0. This verifies local files, not Packagist or a published tag. The release manifest has no version, repositories or fixture dependencies; its version comes from the release tag.
Example 1: a structured plan, no SQL or database
From the package directory:
php examples/plan.php /absolute/new-common-consumer/vendor/autoload.php
The complete executable example contains its own records schema (a 64-bit integer id and a nullable name string of length 80), loads only the independent consumer and prints a createTable operation with columns/primary key. It reads no application configuration and makes no database connection. Its main call is:
$operations = SchemaPlanner::buildSchemaDiffOperations(null, $schemaJson);
Pass the previous JSON instead of null for later transitions. Automatic diffs add tables, columns, indexes and constraints; changes/removals of existing definitions require an explicit plan. Tables are planned before foreign keys.
Example 2: generate PHP metadata
php examples/generate.php /absolute/new-common-consumer/vendor/autoload.php
The executable example embeds a schema and prints syntax-checked PHP. PhpSchemaGenerator::generate($json)
returns PHP source for column, primary-key and unique-key metadata. Executing the generated file
requires compatible Galaxy\DB\TableSchema, Galaxy\DB\ColumnSchema, Galaxy\DB\DataType and
Galaxy\DB\UniqueKey classes in the consumer’s environment. Generation itself runs independently.
Schema format
Root tables map plus optional templates map. Tables have columns and optional primaryKey list, indexes map<name,list>, uniqueKeys, foreignKeys and checks. Identifiers are validated; arbitrary SQL is not accepted. Types: integer (bits 16/32/64, optional generated:sequence), string(optional positive length), binary,json,boolean,localDateTime,instant. nullable defaults to false. Defaults are typed integer/string/boolean literals or {"expression":"now"} for instant. A null default is not a distinct SQL DEFAULT NULL declaration. Existing serial/text/varchar50/bytea/timestamp/timestamptz normalization remains part of the JSON data grammar, not compatibility aliases for former public APIs.
Templates/table definitions may name one parent template. Inheritance adds definitions; overrides, cycles and unknown parents are rejected. {table} expands in index/constraint names before collision validation. Foreign keys specify columns/references.table/references.columns; types/order must match a primary/unique target. onDelete supports restrict or setNull (nullable local columns required). Checks compare one column with a typed literal using =/!=/</<=/>/>=, or isNull/isNotNull without a value.
Explicit operations
SchemaPlanner::buildMigrationOperations($base,$target,$operationsJson) accepts {"operations":[...]}.
It simulates the full resulting schema and rejects a mismatch. Operations: renameTable,renameColumn,
addColumn,dropColumn,dropTable,createIndex/dropIndex/renameIndex,addUniqueKey/dropUniqueKey,
addForeignKey/dropForeignKey,addCheck/dropCheck/renameConstraint,setDefault/dropDefault,
setNotNull/dropNotNull,alterColumnLength,alterColumnType,backfillColumn,copyColumn,verifyColumnCopy.
These are structured steps, not an SQL executor.
Explicit addColumn requires nullable/no default. backfillColumn uses a typed literal and where:isNull. copyColumn converts string→integer with conversion:decimalStringToInteger and where:targetIsNull. Dropping the source requires a matching verifyColumnCopy after the last write involving the pair. alterColumnType supports decimalStringToInteger or widenInteger. PK composition changes and string→integer PK conversion are forbidden. Remove dependent objects before removing columns/keys. No arbitrary USING SQL, CASCADE, rename guessing or automatic workaround for unsupported changes is provided.
Files and adapters
MigrationFiles::list(directory), ::parseTimestamp(filename), ::create(directory,slug,string|Closure). Names use unique YYYYMMDDTHHMMSSZ_slug.json UTC timestamps; slugs are lowercase a-z0-9_. Invalid/duplicate dates and symlink/nonregular files are rejected. Creation uses a directory lock, temporary file and rename without overwriting an existing migration. Protect the trusted local queue against foreign writes and back it up; this is not a sandbox for arbitrary paths.
Files contain base(previous raw JSON SHA256 or null), schema(target JSON string or null for data-only), and optional operations/confirmation. Hashes cover EXACT bytes, not semantic JSON. Retain every applied file unchanged, including whitespace, together with the queue.
GDBMigratorInterface/abstract GMigrator expose readStoredSchema,readDatabaseSchema,registerDatabaseSchema, getMigrationQueueStatus,buildNextMigrationPlan,createMigration,generatePhpSchema,executeMigrations. The abstract class delegates database validation/execution; it does not supply transactions/privileges. Constructor options: migrationsDirectory,targetSchemaFile,baseSchemaFile. Pending files project the base for the next file. Invalid formats/operations throw InvalidArgumentException/JsonException; I/O failures throw RuntimeException.
Development checks
php tests/standalone.php needs no dependencies; php -n tests/standalone.php runs without PDO.
php tests/standalone.php CONSUMER/vendor/autoload.php verifies installed classes without source overrides.
Run php tests/lint.php and composer validate --strict. Tests retain their own random temporary fixtures.
CI verifies the standalone planner and an independent consumer on Ubuntu with PHP 8.4.
GalaxyDBMigrationPostgres is an example of a database-specific implementation.