PHP Database Migrations for Everyone

Last update: Jun 24, 2022

Phinx: Simple PHP Database Migrations

Build Status Code Coverage Latest Stable Version Minimum PHP Version Total Downloads

Intro

Phinx makes it ridiculously easy to manage the database migrations for your PHP app. In less than 5 minutes, you can install Phinx and create your first database migration. Phinx is just about migrations without all the bloat of a database ORM system or framework.

Check out book.cakephp.org/phinx (EN, ZH) for the comprehensive documentation.

phinxterm

Features

  • Write database migrations using database agnostic PHP code.
  • Migrate up and down.
  • Migrate on deployment.
  • Seed data after database creation.
  • Get going in less than 5 minutes.
  • Stop worrying about the state of your database.
  • Take advantage of SCM features such as branching.
  • Integrate with any app.

Supported Adapters

Phinx natively supports the following database adapters:

  • MySQL
  • PostgreSQL
  • SQLite
  • Microsoft SQL Server

Install & Run

See version and branch overview for branch and PHP compatibility.

Composer

The fastest way to install Phinx is to add it to your project using Composer (https://getcomposer.org/).

  1. Install Composer:

    curl -sS https://getcomposer.org/installer | php
    
  2. Require Phinx as a dependency using Composer:

    php composer.phar require robmorgan/phinx
    
  3. Install Phinx:

    php composer.phar install
    
  4. Execute Phinx:

    php vendor/bin/phinx
    

As a Phar

You can also use the Box application to build Phinx as a Phar archive (https://box-project.github.io/box2/).

  1. Clone Phinx from GitHub

    git clone https://github.com/cakephp/phinx.git
    cd phinx
    
  2. Install Composer

    curl -s https://getcomposer.org/installer | php
    
  3. Install the Phinx dependencies

    php composer.phar install
    
  4. Install Box:

    curl -LSs https://box-project.github.io/box2/installer.php | php
    
  5. Create a Phar archive

    php box.phar build
    

Documentation

Check out https://book.cakephp.org/phinx for the comprehensive documentation.

Other translations include:

Contributing

Please read the CONTRIBUTING document.

News & Updates

Follow @CakePHP on Twitter to stay up to date.

Limitations

PostgreSQL

Misc

Version History

Please read the release notes.

License

(The MIT license)

Copyright (c) 2017 Rob Morgan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

GitHub

https://github.com/robmorgan/phinx
Comments
  • 1. Multiple Databases

    It would be cool if Phinx could handle migrations for different databases all from the same instance. In our company setup we have one application which uses n databases, with different migrations for each that need to be handled.

    What are you thoughts on handling multiple databases? I might fork and see if I can get it working but I want to know if you'd ever merge something like that?

    Reviewed by wpillar at 2014-02-02 16:08
  • 2. Create an Initial Migration from an Existing Database

    Is it possible for Phinx to create an initial migration from an existing database? My scenario is that I have an application with a database and it's tables already and I'd like to start using Phinx to handle my migrations (previously i was manually creating SQL scripts). I'd love if Phinx could inspect my database and create an initial migration file with the current table structures as a starting point.

    I hope that made sense.

    Reviewed by ylynfatt at 2013-07-11 20:23
  • 3. Suggestion to add a seed()

    A suggestion to add a seed() function that is defined inside any migration classes. If it exists, Phinx will run the seed() only after it runs up().

    I often need this to seed tables with initial data, which goes along with migration.

    Reviewed by CMCDragonkai at 2014-01-04 15:04
  • 4. Add update and updateData methods

    Added update and updateData methods. Also added a shortcut method for updating.

    @rquadling @robmorgan I'm sure there may be changes needed. Please let me know and I'll implement ASAP.

    Thanks for the opportunity to work with you.

    Fixes #862

    Reviewed by BallisticPain at 2016-06-23 19:37
  • 5. Rollbacks by start time

    A new Configuration option named version_order was added. Its possible values are:

    • creation-time (the default): causes the Rollback and Status commands to order the executed migrations by their creation times (aka Migration IDs or Names).
    • start-time: causes the Rollback and Status commands to order the executed migrations by their start times (aka Execution Times).

    This means that when invoking the Rollback command:

    • With a start-time version order, the last executed migration will be rollbacked.
    • With a start-time version order and a -d (date) option, the migration start times will be used to determine the target version to rollback to. In other words, all migrations which were executed after that date will be rollbacked.
    • With a start-time version order and a -t (target version) option, all migrations which were executed after the target version was executed will be rollbacked.

    In terms of testing:

    • The old testRollbacksByDate test was renamed to testRollbackToDateTime and turned into a unit test, ensuring the rollback method is called with the right target version. A new testRollback was added which ensures the correct output of the rollback operation (as was being done in the old testRollbacksByDate test).
    • More test cases were added.
    • General test improvements were done (like adding the expected arguments to the underlying Manager calls in RollbackTest and StatusTest.

    Other notes:

    • The old rollback and rollbackToDateTime methods were merged into a single rollback method that handles all cases and version orders.
    • This PR replaces https://github.com/robmorgan/phinx/pull/745.
    Reviewed by ghost at 2016-07-13 16:24
  • 6. Support for UPDATE & DELETE methods?

    Rob, have you given any thought to creating insert, update, and delete methods instead of having queries written inline?

    I don't know that they'd add any specific functionality, but something like the way Zend_Db (v1, not v2) does would be nice to have.

    Reviewed by gms8994 at 2013-06-05 14:15
  • 7. Implemented Dry Runs

    A new --dry-run option was added to the Migrate and Rollback commands, which causes the executed/rollbacked Migrations Code to be outputted instead of executed.

    Technically speaking, I implemented it in a way that the new option is passed from the Migrate and Rollback Commands to the Manager class, whose executeMigration method was updated to print a different text header for the migrations being executed/rollbacked when dry-running. The parameter is then passed on to the Environment class' executeMigration method which enables dry-running in the PDOAdapter. Finally, when a statement is executed via the PDOAdapter.execute method, if dry-running was enabled it simply prints the SQL code and returns, instead of actually executing it via the underlying database connection.

    For #567 and based on https://github.com/wheniwork/phinx/pull/1

    Reviewed by ghost at 2016-01-12 16:35
  • 8. Add debug option to show raw SQL

    Sometimes when trying to run migration and failing for weird database errors it's hard to debug the problem without knowing what exact SQL is being issued against the server. The --verbose option shows what Phinx is trying to do, but not exactly how.

    Maybe another option -vv or --debug could show the commands sent to the server?

    Reviewed by igorsantos07 at 2013-05-30 19:57
  • 9. Support pre and post migrations for zero-downtime deployments

    It is common to run migrations at deploy time, and those migrations are often split into pre- and post-deploy migrations. Pre-deploy migrations affect the current version of the app for a few moments before the new version is deployed. Post-deploy migrations are only applied after the new version has been deployed. This is to ensure no errors occur during a live, zero-downtime deployment.

    For example, new columns are usually added during pre-deploy, because if those columns are not present the moment the new version goes live, errors will occur because the app will try to access non-existent columns. Deleted columns should often be removed during post-deploy, because if they are removed whilst the current app version is running, errors will occur because the current version may still be trying to access them.

    To support these two types of migrations, there needs to be a mechanism to mark a given migration is either pre or post and the migration command must accept an option to toggle which migration subgroup is being targeted. This changes migration command behaviour from one-pass two two-pass style, where the command must be invoked twice - once for each migration subgroup - to perform the complete migration.

    Key discussion points

    1. Should we implement this feature?
    2. How should migrations be marked as pre and post?
    3. Should a new migration command be added or should the existing command be repurposed to support this behaviour with additional arguments or options?
    Reviewed by Bilge at 2020-06-25 00:30
  • 10. Error when trying to run init

    platform: windows8 trying to run: php vendor/bin/phinx init output result: SRC_DIR="pwd" cd "dirname "$0"" cd "../robmorgan/phinx/bin" BIN_TARGET="pwd/phinx" cd "$SRC_DIR" "$BIN_TARGET" "[email protected]"

    Reviewed by ahmarov at 2014-11-20 09:15
  • 11. Supporting namespaces in configuration, Migrations and Seeds.

    Please consider my pull request, in which I made some enhancement. The pull request fixes following issues:

    • #168 Move migrations under the Phinx\Migration namespace
    • #756 Namespace loading failed
    • #1054 BUG: The same migration name can be created in multiple directories. (if add namespace in configuration)

    I implemented an idea of @rquadling (view comment). So, support of namespaces looks like this: php like:

    return [
        'paths' => [
            'migrations' => [
                '/path/to/migration/without/namespace',
                'Foo' => '/path/to/migration/Foo',
            ],
            'seeds' => [
                '/path/to/seeds/without/namespace',
                'Baz' => '/path/to/seeds/Baz',
            ]
        ],
    ];
    

    yaml like:

    paths:
        migrations:
          0: ./db/migrations
          Foo\Bar: ./db/FooBar
        seeds:
          0: ./db/seeds
          Foo\Bar: ./db/seeds/Foo/Bar
    

    json like:

    {
        "paths": {
            "migrations": {
                "0": "./db/migrations",
                "Foo\\Bar": "./db/FooBar"
            }
        }
    }
    
    

    Migrations/Seeds contain namespace just at the beginning of the file.

    Migrations/Seeds files without namespace are still working for backward compatibility.

    For using namespaces in migrations/seeds make new folders and change configuration.

    The solution doesn't fully compatible with PSR-4 (there are versions in file names).

    I tryed to covered the code with the unit's tests as full as possible.

    Reviewed by andrey-mokhov at 2017-04-03 12:20
  • 12. Add public getDsn method to adapters for unit testing constructed DSN strings

    For each adapter, there's a handful of ways to customize the DSN string we generate that is passed to PDO. However, there's not currently a good way we have to test that said behavior is correct / good and so we have some nonsensical tests like:

    https://github.com/cakephp/phinx/blob/48d8e1f686852882a319e6deff1ae6748d04ab5c/tests/Phinx/Db/Adapter/SqlServerAdapterTest.php#L62-L68

    Was unsetting the port meaningful? Who knows!

    While we could maybe get what we want out of some level of reflection / mocking around the protected createPdoConnection method, that should be avoided if possible.

    Instead, having a getDsn method that returns a string instead would more easily solve the problem, and allow for best practices around unit testing these things, and ensure behavior is good and correct. It's possible that said method could also be useful to someone downstream, but I'm not overly concerned at the moment with that.

    Reviewed by MasterOdin at 2022-05-21 23:25
  • 13. Add TrustServerCertificate to SqlServerAdapter

    Fixes #2093

    This PR adds TrustServerCertificate=true to the connection string. This is needed for sqlserver 2017 and 2019. Tested that phinx works with sqlsrv 2019 after this fix.

    @markstory

    Reviewed by ingLomeland at 2022-05-19 20:07
  • 14. How to use sqlsrv 2019?

    Hi,

    using docker with mssql image mcr.microsoft.com/mssql/server:2019-latest

    how to set up phinx with TrustServerCertificate=true ?

    Getting this error when trying to migrate PDOException: SQLSTATE[08001]: [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed:self signed certificate] in /var/www/api/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php:84

    Reviewed by ingLomeland at 2022-05-15 09:42
  • 15. support PDO persistent connection

    This fixes the ability to use persistent connections by PDO. One can set generic PDO attributes (#1904) but the attribute - \PDO::ATTR_PERSISTENT - is useless while setting it by setAttribute after PDO object instantiation:

    Note: If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections. https://www.php.net/manual/en/pdo.connections.php

    From the point of view of usage, nothing changes: like other PDO arguments we specify attr_persistent => true config option. Before the PDO instatiation this attribute (if specified) is passed to driver options instead of setting in setAttribute after it.

    It's done in Mysql, Postgres and SQLite adapters. SQL Server PDO driver does not support this specific attribute.

    Reviewed by paulermo at 2022-05-10 22:05
  • 16. SqlServerAdapter::parseDefault

    The SqlServerAdapter::parseDefault($default) function returns "" if $default is null Because of the returned empty string, the column can not be changed to have an empty string as default value (no differnce detected)

    Example for an existing column which has no effect:

    $this->table('tableName')->changeColumn('columnName', 'string', ['default' => '', 'null' => false])
    
    Reviewed by reeperbahnause at 2022-04-25 18:45
Extract SQL statements from migrations

This is my package MigrationToSql To install: composer require bcleverly/migrationtosql --dev This repo is here to help you extract the SQL queries fr

Apr 15, 2022
Migrations for MongoDB based on PHPMongo ODM

PHPMongo Migrator Migrations for MongoDB based on PHPMongo ODM Schema not required in MongoDb, so we dont need to create databases, collections or alt

Jan 31, 2022
Pure PHP NoSQL database with no dependency. Flat file, JSON based document database.
Pure PHP NoSQL database with no dependency. Flat file, JSON based document database.

Please give it a Star if you like the project ?? ❤️ SleekDB - A NoSQL Database made using PHP Full documentation: https://sleekdb.github.io/ SleekDB i

Jul 3, 2022
SleekwareDB is a NoSQL database storage service. A database storage service that can be used for various platforms and is easy to integrate.
SleekwareDB is a NoSQL database storage service. A database storage service that can be used for various platforms and is easy to integrate.

SleekwareDB is a NoSQL database storage service. A database storage service that can be used for various platforms and is easy to integrate. NoSQL API

Jun 25, 2022
The lightweight PHP database framework to accelerate development
The lightweight PHP database framework to accelerate development

The lightweight PHP database framework to accelerate development Features Lightweight - Less than 100 KB, portable with only one file Easy - Extremely

Jun 24, 2022
Database management in a single PHP file

Adminer - Database management in a single PHP file Adminer Editor - Data manipulation for end-users https://www.adminer.org/ Supports: MySQL, MariaDB

Jul 2, 2022
A php class for managing and connecting to a database

Query builder class php This class is responsible for creating and executing sql commands and helps you to execute as easily as possible and safely. I

May 11, 2022
Database lookup tool in php, skidlookup has not been claimed so if u want to use this src all right's go to u, idea came from fedsearch
Database lookup tool in php, skidlookup has not been claimed so if u want to use this src all right's go to u, idea came from fedsearch

skidlookup Database lookup tool in php, skidlookup has not been claimed so if u want to use this src, all right's go to u, idea came from fedsearch in

Dec 1, 2021
A complete, simple and powerful database framework written in PHP

BaseSQL BaseSQL is a complete database framework written in PHP. It was built to accelerate projects development by handle database connections and qu

Sep 21, 2021
Connect and work with MySQL/MariaDB database through MySQLi in PHP. This is an introductory project, If you need a simple and straightforward example that takes you straight to the point, you can check out these examples.
Connect and work with MySQL/MariaDB database through MySQLi in PHP. This is an introductory project, If you need a simple and straightforward example that takes you straight to the point, you can check out these examples.

First MySQLi PHP Connect and work with MySQL/MariaDB database through MySQLi in PHP. The above exercises are designed for students. This is an introdu

Feb 22, 2022
Database lookup tool in php, skidlookup has not been claimed so if u want to use this src all right's go to u, idea came from fedsearch
Database lookup tool in php, skidlookup has not been claimed so if u want to use this src all right's go to u, idea came from fedsearch

skidlookup Database lookup tool in php, skidlookup has not been claimed so if u want to use this src, all right's go to u, idea came from fedsearch in

Dec 1, 2021
The fastest pure PHP database framework with a powerful static code generator, supports horizontal scale up, designed for PHP7
The fastest pure PHP database framework with a powerful static code generator, supports horizontal scale up, designed for PHP7

Maghead 4.0.x IS CURRENTLY UNDER HEAVY DEVELOPMENT, API IS NOT STABLE Maghead is an open-source Object-Relational Mapping (ORM) designed for PHP7. Mag

Jun 21, 2022
phpSleekDBAdmin - a web-based SleekDB database admin tool written in PHP
phpSleekDBAdmin - a web-based SleekDB database admin tool written in PHP

phpSleekDBAdmin is a web-based SleekDB database admin tool written in PHP. Following in the spirit of the flat-file system used by SleekDB, phpSleekDBAdmin consists of a single source file, phpsleekdbadmin.php. The interface and user experience is comparable to that of phpLiteAdmin and phpMyAdmin.

Feb 18, 2022
PHP Reader for the MaxMind DB Database Format

This is the PHP API for reading MaxMind DB files. MaxMind DB is a binary file format that stores data indexed by IP address subnets (IPv4 or IPv6).

Jun 28, 2022
PHP application-level database locking mechanisms to implement concurrency control patterns.
PHP application-level database locking mechanisms to implement concurrency control patterns.

PHP DB Locker Introduction PHP application-level database locking mechanisms to implement concurrency control patterns. Supported drivers: Postgres In

May 11, 2022
[READ ONLY] Subtree split of the Illuminate Database component (see laravel/framework)

Illuminate Database The Illuminate Database component is a full database toolkit for PHP, providing an expressive query builder, ActiveRecord style OR

Jun 30, 2022
ORM layer that creates models, config and database on the fly

RedBeanPHP 5 RedBeanPHP is an easy to use ORM tool for PHP. Automatically creates tables and columns as you go No configuration, just fire and forget

Jun 21, 2022
Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer

Spot DataMapper ORM v2.0 Spot v2.x is built on the Doctrine DBAL, and targets PHP 5.4+. The aim of Spot is to be a lightweight DataMapper alternative

May 26, 2022
SQL database access through PDO.

Aura.Sql Provides an extension to the native PDO along with a profiler and connection locator. Because ExtendedPdo is an extension of the native PDO,

May 23, 2022