Search by

denetorus / galaxy-db-migration-postgres

Denetorus

PostgreSQL implementation for GalaxyDBMigration.

Package info

github.com/Denetorus/GalaxyDBMigrationPostgres

pkg:composer/denetorus/galaxy-db-migration-postgres

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-11-30 07:20 UTC

This package is auto-updated.

Last update: 2026-11-30 07:24:40 UTC


README

PostgreSQL/PDO adapter for GalaxyDBMigration, PHP >= 8.4 and ext-pdo_pgsql. MIT © 2026 Mylnikov Denis. Version 0.1.0 is available on Packagist. Русское руководство. Rationale/guarantees: ADR EN, ADR RU.

Preview the SQL before running a migration

Suppose you want to create a records table. In a project with the package installed, save 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 the code as plan.php and run php plan.php. This step requires no PostgreSQL connection.

<?php

use Galaxy\DBMigrationPostgres\GMigratorPostgres;

require __DIR__ . '/vendor/autoload.php';

$target = file_get_contents(__DIR__ . '/schema.json');
foreach (GMigratorPostgres::buildSchemaDiffSql(null, $target) as $statement) {
    echo $statement, ';', PHP_EOL;
}

You will see a CREATE TABLE statement for public.records. To preview adding a column to an existing table, save the original description as previous.json, add a new column to schema.json and pass the contents of previous.json in place of null. The plan will show ALTER TABLE … ADD COLUMN.

What to do next

  • Try applying a migration from scratch. Run the standalone example on a fresh test database using the instructions below. It creates a demo table and a journal entry. Running the same queue again skips the applied file.
  • Bring an existing database under management. Read the relevant tables with readDatabaseSchema(['records']) and compare the output with the expected structure. Register the checked JSON using registerDatabaseSchema($json, hash('sha256', $json)). The migrator stores it as the starting schema for later changes.
  • Prepare the next change. Edit the target JSON, review buildNextMigrationPlan(), save a file with createMigration() and apply the queue with executeMigrations() after checking it on a test database.

Install independently

Install version 0.1.0 with Composer: composer require denetorus/galaxy-db-migration-postgres:0.1.0. The adapter requires GalaxyDBMigration (denetorus/galaxy-db-migration:^0.1.0). The release manifest has no version, path repository or test dependency override.

To test a local checkout, create a separate Composer project from the package directory:

php tests/create-consumer.php /absolute/new-pg-consumer /absolute/GalaxyDBMigrationPostgres /absolute/GalaxyDBMigration
cd /absolute/new-pg-consumer
composer install --no-dev --no-scripts --no-plugins
composer dump-autoload --optimize --strict-psr --no-scripts --no-plugins
composer check-platform-reqs

Only the external fixture assigns local version 0.1.0 and mirror repositories. This is not a Packagist test. Omit the final common-path argument to require common from Packagist: CI does exactly that, so its first run requires an actually published common^0.1.0. Do not bypass that release dependency in the workflow.

Example 1: SQL planning without connecting

From the adapter directory:

php examples/plan.php /absolute/new-pg-consumer/vendor/autoload.php

This complete executable example embeds demo_records(id integer PRIMARY KEY) and calls GMigratorPostgres::buildSchemaDiffSql(null,$schemaJson). It prints CREATE TABLE SQL, does not create PDO, read application configuration or contact any server. For explicit operations:

$plan = GMigratorPostgres::buildMigrationPlan($baseJson, $targetJson, $operationsJson);

The plan includes base/target SHA256, normalized operations, SQL, data-validation/copy/backfill steps, destructive operations and a confirmation hash when required. Review the complete plan. Supply its exact confirmation to createMigration for destructive steps; changed inputs/order/SQL invalidate confirmation. SQL is quoted/typed structured output, not an arbitrary SQL import facility.

Example 2: execute only on an explicitly provisioned empty test database

Prepare a NEW, disposable database named galaxy_migration_acceptance_ on 127.0.0.1. Provide GALAXY_ACCEPTANCE_DSN in the exact form pgsql:host=127.0.0.1;port=5432;dbname=galaxy_migration_acceptance_, and GALAXY_ACCEPTANCE_USER/GALAXY_ACCEPTANCE_PASSWORD through the process environment. Never put real credentials in command arguments, migrations, examples or reports. The fixture role/database must be isolated from applications.

php examples/execute.php /absolute/new-pg-consumer/vendor/autoload.php

The complete example rejects any other database name before connecting, verifies current_database and empty public/galaxy_migration relations, writes its own random temporary queue, preflights and executes one initial schema file. It creates only demo_records plus its migration metadata. Synthetic database/files are retained for inspection; it does not create/drop databases or use a history application. Do not run it against an application database. Run it on a separate fresh database from acceptance tests.

Using the adapter in your own host

$migrator = new GMigratorPostgres(
    connection: $pdo,
    migrationsDirectory: $queueDirectory,
    targetSchemaFile: $targetJsonFile,
    baseSchemaFile: null,
);
$status = $migrator->getMigrationQueueStatus();
$plan = $migrator->buildNextMigrationPlan();
// Review/back up/quiesce the application before the separate write step.
$results = $migrator->executeMigrations();

The caller supplies/owns PDO. The adapter requires driver pgsql and sets ERRMODE_EXCEPTION; it neither owns PDO disposal nor supports being called inside an existing transaction. It uses transaction-local search_path and standard_conforming_strings. Use a dedicated migration connection/role, not the application's low-privilege role.

Public API:

  • readStoredSchema():?array — version/config/sha256, checksum checked;
  • readDatabaseSchema(?array $scope=null):string — physical JSON export in a read-only transaction;
  • registerDatabaseSchema(config,expectedHash):bool — verify existing physical schema and register only if absent;
  • getMigrationQueueStatus():array — read-only preflight, applied/pending files;
  • buildNextMigrationPlan(?string $operations=null):array and createMigration(slug,operations?,confirmation?):string;
  • generatePhpSchema():string — returns PHP source for schema metadata;
  • executeMigrations():array — only public queue-execution entry point; static planning methods above perform no I/O.

Safety, transactions and scope

Back up first and quiesce ALL application access. The complete queue is structurally/journal/physical-schema checked before its first write; invalid later-file metadata blocks earlier writes. Data-dependent failures are checked inside EACH file's transaction, not a transaction for the whole queue. Earlier committed files remain applied when a later file fails. Replay skips already journaled identical files.

Each file uses a transaction, advisory transaction lock, lock_timeout of 5 seconds and relation locks (including ACCESS EXCLUSIVE for relevant checks). DDL, backfills/copies, final physical-schema verification, snapshot and journal entry commit together. Failed checks roll the file back. Read-only status does not reserve a future write; execution rechecks against the bytes read for that execution. No online-migration/concurrency, cross-database, backup, crash recovery or whole-queue rollback guarantee is made.

Managed scope is public tables from the recorded/current target plus pending target names; unrelated relations are ignored unless they occupy those names. Unscoped readDatabaseSchema exports ALL public relations and can reject unsupported types/features; pass an explicit scope for managed export. Only the documented general types, ordinary tables/indexes/PK/UNIQUE/FK/CHECK subset are supported, not arbitrary PostgreSQL objects. Use RESTRICT, never automatic CASCADE. Shrinking strings, NOT NULL, conversions and checks perform data validation; PK composition cannot change, supported integer widening/column rename can preserve keys. For copy-then-drop, verifyColumnCopy must follow the last write to the pair. Unsupported physical features fail instead of silently being rewritten. See the common guide for the full JSON grammar and explicit operation fields.

Queue files use UTC YYYYMMDDTHHMMSSZ_slug.json and raw-byte SHA256. Keep EVERY applied file, protect it against edits/removal and untrusted writes; whitespace changes invalidate journal identity. The schema snapshot stores raw JSON (including templates); comparisons expand/normalize it. galaxy_migration.schema_state holds one current snapshot, galaxy_migration.migrations journals applied files. Existing galaxy_migration.versions is read only as a fallback snapshot when schema_state is absent; rows are not deleted or appended. This retained data-reading rule is NOT compatibility for former classes/methods. No public API aliases are supplied.

The role needs CONNECT and ownership/ALTER rights on managed tables, appropriate SELECT/UPDATE/DDL/index/sequence rights, plus CREATE on the database for galaxy_migration and relevant rights on public. Metadata schema access is revoked from PUBLIC; protect migration metadata from application writes. Restricted/read-only roles must fail rather than partially apply. Review grants in your deployment; tests do not prove a universal role matrix.

Development checks

From the adapter directory, with an independent installed consumer:

php tests/planning.php /absolute/new-pg-consumer/vendor/autoload.php
php tests/acceptance.php /absolute/new-pg-consumer/vendor/autoload.php
php tests/lint.php

Planning uses no database. Acceptance enforces the dedicated localhost name/empty-database guards before writing, then tests rollback/journal/drift/replay/constraints/copies/destructive confirmations/metadata access. Credentials are environment-only. It retains its synthetic files/database, never touches a real history database. Installed mode verifies class provenance and does not register source-path overrides. Without an argument, tests use this checkout's normal vendor/autoload.php (after Composer install), never sibling source mappings.

CI is Ubuntu PHP 8.4 with PostgreSQL 15/19 fresh service databases, contents:read, pinned actions and no publishing. Compatibility was verified with PostgreSQL 10.20, 10.23 and one release from each major version from 11 through 19. Each server passed all 33 acceptance checks. For new deployments, choose a version still maintained by the PostgreSQL project. GitHub Actions verified the release on PostgreSQL 15 and 19.