init
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Phinx documentation build configuration file, created by
|
||||
# sphinx-quickstart on Thu Jun 14 17:39:42 2012.
|
||||
#
|
||||
|
||||
# Import the base theme configuration
|
||||
from cakephpsphinx.config.all import *
|
||||
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '0.16.x'
|
||||
|
||||
# The search index version.
|
||||
search_version = 'phinx-0'
|
||||
|
||||
# The marketing display name for the book.
|
||||
version_name = ''
|
||||
|
||||
# Project name shown in the black header bar
|
||||
project = 'Phinx'
|
||||
|
||||
# Other versions that display in the version picker menu.
|
||||
version_list = [
|
||||
{'name': '0.16', 'number': '/phinx/0', 'title': '0.16', 'current': True},
|
||||
]
|
||||
|
||||
# Languages available.
|
||||
languages = ['en']
|
||||
|
||||
# The GitHub branch name for this version of the docs
|
||||
# for edit links to point at.
|
||||
branch = '0.x'
|
||||
|
||||
# Current version being built
|
||||
version = '0.16'
|
||||
|
||||
show_root_link = True
|
||||
|
||||
repository = 'cakephp/phinx'
|
||||
|
||||
source_path = 'docs/'
|
||||
|
||||
hide_page_contents = ('search', '404', 'contents')
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
.. index::
|
||||
single: Commands
|
||||
|
||||
Commands
|
||||
========
|
||||
|
||||
Phinx is run using a number of commands.
|
||||
|
||||
The Breakpoint Command
|
||||
----------------------
|
||||
|
||||
The Breakpoint command is used to set breakpoints, allowing you to limit
|
||||
rollbacks. You can toggle the breakpoint of the most recent migration by
|
||||
not supplying any parameters.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development
|
||||
|
||||
To toggle a breakpoint on a specific version then use the ``--target``
|
||||
parameter or ``-t`` for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development -t 20120103083322
|
||||
|
||||
You can remove all the breakpoints by using the ``--remove-all`` parameter
|
||||
or ``-r`` for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development -r
|
||||
|
||||
You can set or unset (rather than just toggle) the breakpoint on the most
|
||||
recent migration (or on a specific migration when combined with the
|
||||
``--target`` or ``-t`` parameter) by using ``-set`` or ``--unset``.
|
||||
|
||||
Breakpoints are visible when you run the ``status`` command.
|
||||
|
||||
The Create Command
|
||||
------------------
|
||||
|
||||
The Create command is used to create a new migration file. It requires one
|
||||
argument: the name of the migration. The migration name should be specified in
|
||||
CamelCase format.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration
|
||||
|
||||
Open the new migration file in your text editor to add your database
|
||||
transformations. Phinx creates migration files using the path specified in your
|
||||
phinx configuration file. Please see the :doc:`Configuration <configuration>` chapter
|
||||
for more information.
|
||||
|
||||
You are able to override the template file used by Phinx by supplying an
|
||||
alternative template filename.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration --template="<file>"
|
||||
|
||||
You can also supply a template generating class. This class must implement the
|
||||
interface ``Phinx\Migration\CreationInterface``.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration --class="<class>"
|
||||
|
||||
In addition to providing the template for the migration, the class can also define
|
||||
a callback that will be called once the migration file has been generated from the
|
||||
template.
|
||||
|
||||
You cannot use ``--template`` and ``--class`` together.
|
||||
|
||||
The Init Command
|
||||
----------------
|
||||
|
||||
The Init command (short for initialize) is used to prepare your project for
|
||||
Phinx. This command generates the phinx configuration file in the root of your
|
||||
project directory. By default, this file will be named ``phinx.php``.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx init
|
||||
|
||||
Optionally you can specify a custom location for Phinx's config file:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx init ./custom/location/
|
||||
|
||||
You can also specify a custom file name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx init custom-config.yml
|
||||
|
||||
As well as a different format from php, yml, and json. For example, to create yml file:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx init --format yml
|
||||
|
||||
Open this file in your text editor to setup your project configuration. Please
|
||||
see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
The Migrate Command
|
||||
-------------------
|
||||
|
||||
The Migrate command runs all of the available migrations, optionally up to a
|
||||
specific version.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate -e development
|
||||
|
||||
To migrate to a specific version then use the ``--target`` parameter or ``-t``
|
||||
for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate -e development -t 20110103081132
|
||||
|
||||
Use ``--dry-run`` to print the queries to standard output without executing them
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate --dry-run
|
||||
|
||||
The Rollback Command
|
||||
--------------------
|
||||
|
||||
The Rollback command is used to undo previous migrations executed by Phinx. It
|
||||
is the opposite of the Migrate command.
|
||||
|
||||
You can rollback to the previous migration by using the ``rollback`` command
|
||||
with no arguments.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development
|
||||
|
||||
To rollback all migrations to a specific version then use the ``--target``
|
||||
parameter or ``-t`` for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 20120103083322
|
||||
|
||||
Specifying 0 as the target version will revert all migrations.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 0
|
||||
|
||||
To rollback all migrations to a specific date then use the ``--date``
|
||||
parameter or ``-d`` for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -d 2012
|
||||
$ phinx rollback -e development -d 201201
|
||||
$ phinx rollback -e development -d 20120103
|
||||
$ phinx rollback -e development -d 2012010312
|
||||
$ phinx rollback -e development -d 201201031205
|
||||
$ phinx rollback -e development -d 20120103120530
|
||||
|
||||
If a breakpoint is set, blocking further rollbacks, you can override the
|
||||
breakpoint using the ``--force`` parameter or ``-f`` for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 0 -f
|
||||
|
||||
Use ``--dry-run`` to print the queries to standard output without executing them
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback --dry-run
|
||||
|
||||
.. note::
|
||||
|
||||
When rolling back, Phinx orders the executed migrations using
|
||||
the order specified in the ``version_order`` option of your
|
||||
phinx configuration file.
|
||||
Please see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
The Status Command
|
||||
------------------
|
||||
|
||||
The Status command prints a list of all migrations, along with their current
|
||||
status. You can use this command to determine which migrations have been run.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx status -e development
|
||||
|
||||
This command exits with code 0 if the database is up-to-date (ie. all migrations are up) or one of the following codes otherwise:
|
||||
|
||||
* 2: There is at least one missing migration.
|
||||
* 3: There is at least one down migration.
|
||||
|
||||
An exit code of 1 means an application error has occurred.
|
||||
|
||||
The Seed Create Command
|
||||
-----------------------
|
||||
|
||||
The Seed Create command can be used to create new database seed classes. It
|
||||
requires one argument, the name of the class. The class name should be specified
|
||||
in CamelCase format.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:create MyNewSeeder
|
||||
|
||||
Open the new seed file in your text editor to add your database seed commands.
|
||||
Phinx creates seed files using the path specified in your configuration file.
|
||||
Please see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
You are able to override the template file used by Phinx by supplying an
|
||||
alternative template filename.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:create MyNewSeeder --template="<file>"
|
||||
|
||||
The Seed Run Command
|
||||
--------------------
|
||||
|
||||
The Seed Run command runs all of the available seed classes or optionally just
|
||||
one.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:run -e development
|
||||
|
||||
To run only one seed class use the ``--seed`` parameter or ``-s`` for short.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:run -e development -s MyNewSeeder
|
||||
|
||||
Configuration File Parameter
|
||||
----------------------------
|
||||
|
||||
When running Phinx from the command line, you may specify a configuration file
|
||||
using the ``--configuration`` or ``-c`` parameter. In addition to YAML, the
|
||||
configuration file may be the computed output of a PHP file as a PHP array:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
return [
|
||||
"paths" => [
|
||||
"migrations" => "application/migrations"
|
||||
],
|
||||
"environments" => [
|
||||
"default_migration_table" => "phinxlog",
|
||||
"default_environment" => "dev",
|
||||
"dev" => [
|
||||
"adapter" => "mysql",
|
||||
"host" => $_ENV['DB_HOST'],
|
||||
"name" => $_ENV['DB_NAME'],
|
||||
"user" => $_ENV['DB_USER'],
|
||||
"pass" => $_ENV['DB_PASS'],
|
||||
"port" => $_ENV['DB_PORT']
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
Phinx auto-detects which language parser to use for files with ``*.yaml``, ``*.yml``, ``*.json``, and ``*.php`` extensions.
|
||||
The appropriate parser may also be specified via the ``--parser`` and ``-p`` parameters. Anything other than ``"json"`` or
|
||||
``"php"`` is treated as YAML.
|
||||
|
||||
When using a PHP array, you can provide a ``connection`` key with an existing PDO instance. It is also important to pass
|
||||
the database name too, as Phinx requires this for certain methods such as ``hasTable()``:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
return [
|
||||
"paths" => [
|
||||
"migrations" => "application/migrations"
|
||||
),
|
||||
"environments" => [
|
||||
"default_migration_table" => "phinxlog",
|
||||
"default_environment" => "dev",
|
||||
"dev" => [
|
||||
"name" => "dev_db",
|
||||
"connection" => $pdo_instance
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
Running Phinx in a Web App
|
||||
--------------------------
|
||||
|
||||
Phinx can also be run inside of a web application by using the ``Phinx\Wrapper\TextWrapper``
|
||||
class. An example of this is provided in ``app/web.php``, which can be run as a
|
||||
standalone server:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php -S localhost:8000 vendor/robmorgan/phinx/app/web.php
|
||||
|
||||
This will create local web server at `<http://localhost:8000>`__ which will show current
|
||||
migration status by default. To run migrations up, use `<http://localhost:8000/migrate>`__
|
||||
and to rollback use `<http://localhost:8000/rollback>`__.
|
||||
|
||||
**The included web app is only an example and should not be used in production!**
|
||||
|
||||
.. note::
|
||||
|
||||
To modify configuration variables at runtime and override ``%%PHINX_DBNAME%%``
|
||||
or other another dynamic option, set ``$_SERVER['PHINX_DBNAME']`` before
|
||||
running commands. Available options are documented in the Configuration page.
|
||||
|
||||
Wrapping Phinx in another Symfony Console Application
|
||||
-----------------------------------------------------
|
||||
|
||||
Phinx can be wrapped and run as part of a separate Symfony console application. This
|
||||
may be desirable to present a unified interface to the user for all aspects of your
|
||||
application, or because you wish to run multiple Phinx commands. While you could
|
||||
run the commands through ``exec`` or use the above ``Phinx\Wrapper\TextWrapper``,
|
||||
though this makes it hard to deal with the return code and output in a similar fashion
|
||||
as your application.
|
||||
|
||||
Luckily, Symfony makes doing this sort of "meta" command straight-forward:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
use Symfony\Component\Console\Input\ArrayInput;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Phinx\Console\PhinxApplication;
|
||||
|
||||
// ...
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output)
|
||||
{
|
||||
|
||||
$phinx = new PhinxApplication();
|
||||
$command = $phinx->find('migrate');
|
||||
|
||||
$arguments = [
|
||||
'command' => 'migrate',
|
||||
'--environment' => 'production',
|
||||
'--configuration' => '/path/to/phinx/config/file'
|
||||
];
|
||||
|
||||
$input = new ArrayInput($arguments);
|
||||
$returnCode = $command->run(new ArrayInput($arguments), $output);
|
||||
// ...
|
||||
}
|
||||
|
||||
Here, you are instantianting the ``PhinxApplication``, telling it to find the ``migrate``
|
||||
command, defining the arguments to pass to it (which match the commandline arguments and flags),
|
||||
and then finally running the command, passing it the same ``OutputInterface`` that your
|
||||
application uses.
|
||||
|
||||
See this `Symfony page <https://symfony.com/doc/current/console/calling_commands.html>`_ for more information.
|
||||
|
||||
Using Phinx with PHPUnit
|
||||
--------------------------
|
||||
|
||||
Phinx can be used within your unit tests to prepare or seed the database. You can use it programatically :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
public function setUp ()
|
||||
{
|
||||
$app = new PhinxApplication();
|
||||
$app->setAutoExit(false);
|
||||
$app->run(new StringInput('migrate'), new NullOutput());
|
||||
}
|
||||
|
||||
If you use a memory database, you'll need to give Phinx a specific PDO instance. You can interact with Phinx directly
|
||||
using the Manager class :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
use PDO;
|
||||
use Phinx\Config\Config;
|
||||
use Phinx\Migration\Manager;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Console\Input\StringInput;
|
||||
use Symfony\Component\Console\Output\NullOutput;
|
||||
|
||||
class DatabaseTestCase extends TestCase {
|
||||
|
||||
public function setUp ()
|
||||
{
|
||||
$pdo = new PDO('sqlite::memory:', null, null, [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
|
||||
]);
|
||||
$configPath = __DIR__ . '/../phinx.php';
|
||||
$configArray = require $configPath;
|
||||
$configArray['environments']['test'] = [
|
||||
'adapter' => 'sqlite',
|
||||
'connection' => $pdo,
|
||||
'name' => ':memory:',
|
||||
];
|
||||
$config = new Config(
|
||||
$configArray,
|
||||
$configPath
|
||||
);
|
||||
$manager = new Manager($config, new StringInput(' '), new NullOutput());
|
||||
$manager->migrate('test');
|
||||
$manager->seed('test');
|
||||
$this->pdo = $pdo;
|
||||
// You can change default fetch mode after the seeding
|
||||
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import sys, os
|
||||
|
||||
# Append the top level directory of the docs, so we can import from the config dir.
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
# Pull in all the configuration options defined in the global config file..
|
||||
from config.all import *
|
||||
|
||||
language = 'en'
|
||||
@@ -0,0 +1,579 @@
|
||||
.. index::
|
||||
single: Configuration
|
||||
|
||||
Configuration
|
||||
=============
|
||||
|
||||
When you initialize your project using the :doc:`Init Command<commands>`, Phinx
|
||||
creates a default file in the root of your project directory. By default, this
|
||||
file uses the YAML data serialization format, but you can use the ``--format``
|
||||
command line option to specify either ``yaml``, ``yml``, ``json``, or ``php``.
|
||||
|
||||
If a ``--configuration`` command line option is given, Phinx will load the
|
||||
specified file. Otherwise, it will attempt to find ``phinx.php``, ``phinx.json``,
|
||||
``phinx.yml``, or ``phinx.yaml`` and load the first file found. See the
|
||||
:doc:`Commands <commands>` chapter for more information.
|
||||
|
||||
.. warning::
|
||||
|
||||
Remember to store the configuration file outside of a publicly accessible
|
||||
directory on your webserver. This file contains your database credentials
|
||||
and may be accidentally served as plain text.
|
||||
|
||||
Note that while JSON and YAML files are *parsed*, the PHP file is *included*.
|
||||
This means that:
|
||||
|
||||
* It must `return` an array of configuration items.
|
||||
* The variable scope is local, i.e. you would need to explicitly declare
|
||||
any global variables your initialization file reads or modifies.
|
||||
* Its standard output is suppressed.
|
||||
* Unlike with JSON and YAML, it is possible to omit environment connection details
|
||||
and instead specify ``connection`` which must contain an initialized PDO instance.
|
||||
This is useful when you want your migrations to interact with your application
|
||||
and/or share the same connection. However remember to also pass the database name
|
||||
as Phinx cannot infer this from the PDO connection.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$app = require 'app/phinx.php';
|
||||
$pdo = $app->getDatabase()->getPdo();
|
||||
|
||||
return [
|
||||
'environments' => [
|
||||
'default_environment' => 'development',
|
||||
'development' => [
|
||||
'name' => 'devdb',
|
||||
'connection' => $pdo
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
Migration Paths
|
||||
---------------
|
||||
|
||||
The first option specifies the path to your migration directory. Phinx uses
|
||||
``%%PHINX_CONFIG_DIR%%/db/migrations`` by default.
|
||||
|
||||
.. note::
|
||||
|
||||
``%%PHINX_CONFIG_DIR%%`` is a special token and is automatically replaced
|
||||
with the root directory where your phinx configuration file is stored.
|
||||
|
||||
In order to overwrite the default ``%%PHINX_CONFIG_DIR%%/db/migrations``, you
|
||||
need to add the following to the configuration.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: /your/full/path
|
||||
|
||||
You can also provide multiple migration paths by using an array in your configuration:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations:
|
||||
- application/module1/migrations
|
||||
- application/module2/migrations
|
||||
|
||||
Class namespaces may be specified by adding a key to each migration path:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations:
|
||||
App\Module1\Migrations: application/module1/migrations
|
||||
App\Module2\Migrations: application/module2/migrations
|
||||
|
||||
|
||||
|
||||
You can also use the ``%%PHINX_CONFIG_DIR%%`` token in your path.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: '%%PHINX_CONFIG_DIR%%/your/relative/path'
|
||||
|
||||
Migrations are captured with ``glob``, so you can define a pattern for multiple
|
||||
directories.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: '%%PHINX_CONFIG_DIR%%/module/*/{data,scripts}/migrations'
|
||||
|
||||
Custom Migration Base
|
||||
---------------------
|
||||
|
||||
By default all migrations will extend from Phinx's `AbstractMigration` class.
|
||||
This can be set to a custom class that extends from `AbstractMigration` by
|
||||
setting ``migration_base_class`` in your config:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
migration_base_class: MyMagicalMigration
|
||||
|
||||
Seed Paths
|
||||
----------
|
||||
|
||||
The second option specifies the path to your seed directory. Phinx uses
|
||||
``%%PHINX_CONFIG_DIR%%/db/seeds`` by default.
|
||||
|
||||
.. note::
|
||||
|
||||
``%%PHINX_CONFIG_DIR%%`` is a special token and is automatically replaced
|
||||
with the root directory where your configuration file is stored.
|
||||
|
||||
In order to overwrite the default ``%%PHINX_CONFIG_DIR%%/db/seeds``, you
|
||||
need to add the following to the yaml configuration.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds: /your/full/path
|
||||
|
||||
You can also provide multiple seed paths by using an array in your configuration:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds:
|
||||
- /your/full/path1
|
||||
- /your/full/path2
|
||||
|
||||
|
||||
You can also use the ``%%PHINX_CONFIG_DIR%%`` token in your path.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds: '%%PHINX_CONFIG_DIR%%/your/relative/path'
|
||||
|
||||
Class namespaces may be specified by adding a key to each seed path:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds:
|
||||
App\Module1\Seeds: application/module1/seeds
|
||||
App\Module2\Seeds: application/module2/seeds
|
||||
|
||||
|
||||
Custom Seeder Base
|
||||
---------------------
|
||||
|
||||
By default all seeders will extend from Phinx's `AbstractSeed` class.
|
||||
This can be set to a custom class that extends from `AbstractSeed` by
|
||||
setting ``seed_base_class`` in your config:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
seed_base_class: MyMagicalSeeder
|
||||
|
||||
Custom Migration Template
|
||||
-------------------------
|
||||
|
||||
Custom template for Migrations could be used either by defining template file path
|
||||
in configuration file:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
templates:
|
||||
file: src/templates/customMigrationTemplate.php
|
||||
|
||||
|
||||
Custom Seeder Template
|
||||
----------------------
|
||||
|
||||
Custom Seeder template could be used either by defining template file path
|
||||
in configuration file:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
templates:
|
||||
seedFile: src/templates/customSeederTemplate.php
|
||||
|
||||
|
||||
Environments
|
||||
------------
|
||||
|
||||
One of the key features of Phinx is support for multiple database environments.
|
||||
You can use Phinx to create migrations on your development environment, then
|
||||
run the same migrations on your production environment. Environments are
|
||||
specified under the ``environments`` nested collection. For example:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_environment: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: localhost
|
||||
name: production_db
|
||||
user: root
|
||||
pass: ''
|
||||
port: 3306
|
||||
charset: utf8mb4
|
||||
collation: utf8mb4_unicode_ci
|
||||
|
||||
would define a new environment called ``production``.
|
||||
|
||||
In a situation when multiple developers work on the same project and each has
|
||||
a different environment (e.g. a convention such as ``<environment
|
||||
type>-<developer name>-<machine name>``), or when you need to have separate
|
||||
environments for separate purposes (branches, testing, etc) use environment
|
||||
variable `PHINX_ENVIRONMENT` to override the default environment in the yaml
|
||||
file:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
export PHINX_ENVIRONMENT=dev-`whoami`-`hostname`
|
||||
|
||||
Migration Table
|
||||
---------------
|
||||
|
||||
To keep track of the migration statuses for an environment, phinx creates
|
||||
a table to store this information. You can customize where this table
|
||||
is created by configuring ``default_migration_table`` to be used as default
|
||||
for all environments:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environment:
|
||||
default_migration_table: phinxlog
|
||||
|
||||
If this field is omitted, then it will default to ``phinxlog``. For
|
||||
databases that support it, e.g. Postgres, the schema name can be prefixed
|
||||
with a period separator (``.``). For example, ``phinx.log`` will create
|
||||
the table ``log`` in the ``phinx`` schema instead of ``phinxlog`` in the
|
||||
``public`` (default) schema.
|
||||
|
||||
You may also specify the ``migration_table`` on a per environment basis.
|
||||
Any environment that does not have a ``migration_table`` specified will
|
||||
fallback to using the ``default_migration_table`` that is defined at the
|
||||
top level. An example of how you might use this is as follows:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environment:
|
||||
default_migration_table: phinxlog
|
||||
development:
|
||||
migration_table: phinxlog_dev
|
||||
# rest of the development settings
|
||||
production:
|
||||
# rest of the production settings
|
||||
|
||||
In the above example, ``development`` will look to the ``phinxlog_dev``
|
||||
table for migration statues while ``production`` will use ``phinxlog``.
|
||||
|
||||
Table Prefix and Suffix
|
||||
-----------------------
|
||||
|
||||
You can define a table prefix and table suffix:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
development:
|
||||
....
|
||||
table_prefix: dev_
|
||||
table_suffix: _v1
|
||||
testing:
|
||||
....
|
||||
table_prefix: test_
|
||||
table_suffix: _v2
|
||||
|
||||
|
||||
Socket Connections
|
||||
------------------
|
||||
|
||||
When using the MySQL adapter, it is also possible to use sockets instead of
|
||||
network connections. The socket path is configured with ``unix_socket``:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_environment: development
|
||||
production:
|
||||
adapter: mysql
|
||||
name: production_db
|
||||
user: root
|
||||
pass: ''
|
||||
unix_socket: /var/run/mysql/mysql.sock
|
||||
charset: utf8
|
||||
|
||||
External Variables
|
||||
------------------
|
||||
|
||||
Phinx will automatically grab any environment variable prefixed with ``PHINX_``
|
||||
and make it available as a token in the config file. The token will have
|
||||
exactly the same name as the variable but you must access it by wrapping two
|
||||
``%%`` symbols on either side. e.g: ``'%%PHINX_DBUSER%%'``. This is especially
|
||||
useful if you wish to store your secret database credentials directly on the
|
||||
server and not in a version control system. This feature can be easily
|
||||
demonstrated by the following example:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_environment: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: '%%PHINX_DBHOST%%'
|
||||
name: '%%PHINX_DBNAME%%'
|
||||
user: '%%PHINX_DBUSER%%'
|
||||
pass: '%%PHINX_DBPASS%%'
|
||||
port: 3306
|
||||
charset: utf8
|
||||
|
||||
Data Source Names
|
||||
-----------------
|
||||
|
||||
Phinx supports the use of data source names (DSN) to specify the connection
|
||||
options, which can be useful if you use a single environment variable to hold
|
||||
the database credentials. PDO has a different DSN formats depending on the
|
||||
underlying driver, so Phinx uses a database-agnostic DSN format used by other
|
||||
projects (Doctrine, Rails, AMQP, PaaS, etc).
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
<adapter>://[<user>[:<pass>]@]<host>[:<port>]/<name>[?<additionalOptions>]
|
||||
|
||||
* A DSN requires at least ``adapter``, ``host`` and ``name``.
|
||||
* You cannot specify a password without a username.
|
||||
* ``port`` must be a positive integer.
|
||||
* ``additionalOptions`` takes the form of a query string, and will be passed to
|
||||
the adapter in the options array.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_environment: development
|
||||
production:
|
||||
# Example data source name
|
||||
dsn: mysql://root@localhost:3306/mydb?charset=utf8
|
||||
|
||||
Once a DSN is parsed, it's values are merged with the already existing
|
||||
connection options. Values in specified in a DSN will never override any value
|
||||
specified directly as connection options.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_environment: development
|
||||
development:
|
||||
dsn: '%%DATABASE_URL%%'
|
||||
production:
|
||||
dsn: '%%DATABASE_URL%%'
|
||||
name: production_database
|
||||
|
||||
If the supplied DSN is invalid, then it is completely ignored.
|
||||
|
||||
Supported Adapters
|
||||
------------------
|
||||
|
||||
Phinx currently supports the following database adapters natively:
|
||||
|
||||
* `MySQL <https://www.mysql.com/>`_: specify the ``mysql`` adapter.
|
||||
* `PostgreSQL <https://www.postgresql.org/>`_: specify the ``pgsql`` adapter.
|
||||
* `SQLite <https://www.sqlite.org/>`_: specify the ``sqlite`` adapter.
|
||||
* `SQL Server <https://www.microsoft.com/sqlserver>`_: specify the ``sqlsrv`` adapter.
|
||||
|
||||
The following settings are available for the adapters:
|
||||
|
||||
adapter
|
||||
The name of the adapter to use, e.g. ``pgsql``.
|
||||
host
|
||||
The database server's hostname (or IP address).
|
||||
port
|
||||
The database server's TCP port number.
|
||||
user
|
||||
The username for the database.
|
||||
pass
|
||||
The password for the database.
|
||||
name
|
||||
The name of the database for this environment. For SQLite, it's recommended to use an absolute path,
|
||||
without the file extension.
|
||||
suffix
|
||||
The suffix to use for the SQLite database file. Defaults to ``.sqlite3``.
|
||||
schema
|
||||
For PostgreSQL, allows specifying the schema to use for the database. Defaults to ``public``.
|
||||
|
||||
For each adapter, you may configure the behavior of the underlying PDO object by setting in your
|
||||
config object the lowercase version of the constant name. This works for both PDO options
|
||||
(e.g. ``\PDO::ATTR_CASE`` would be ``attr_case``) and adapter specific options (e.g. for MySQL
|
||||
you may set ``\PDO::MYSQL_ATTR_IGNORE_SPACE`` as ``mysql_attr_ignore_space``). Please consult
|
||||
the `PDO documentation <https://www.php.net/manual/en/book.pdo.php>`_ for the allowed attributes
|
||||
and their values.
|
||||
|
||||
For example, to set the above example options:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$config = [
|
||||
"environments" => [
|
||||
"development" => [
|
||||
"adapter" => "mysql",
|
||||
# other adapter settings
|
||||
"attr_case" => \PDO::ATTR_CASE,
|
||||
"mysql_attr_ignore_space" => 1,
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
By default, the only attribute that Phinx sets is ``\PDO::ATTR_ERRMODE`` to ``PDO::ERRMODE_EXCEPTION``. It is
|
||||
not recommended to override this.
|
||||
|
||||
MySQL
|
||||
`````````````````
|
||||
|
||||
The MySQL adapter has an unfortunate limitation in that certain actions cause an
|
||||
`implicit commit <https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html>`_ regardless of transaction
|
||||
state. Notably this list includes ``CREATE TABLE``, ``ALTER TABLE``, and ``DROP TABLE``, which are the most
|
||||
common operations that Phinx will run. This means that unlike other adapters which will attempt to gracefully
|
||||
rollback a transaction on a failed migration, if a migration fails for MySQL, it may leave your DB in a partially
|
||||
migrated state.
|
||||
|
||||
SQLite
|
||||
`````````````````
|
||||
|
||||
Declaring an SQLite database uses a simplified structure:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
development:
|
||||
adapter: sqlite
|
||||
name: ./data/derby
|
||||
suffix: ".db" # Defaults to ".sqlite3"
|
||||
testing:
|
||||
adapter: sqlite
|
||||
memory: true # Setting memory to *any* value overrides name
|
||||
|
||||
Starting with PHP 8.1 the SQlite adapter supports ``cache`` and ``mode``
|
||||
query parameters by using the `URI scheme <https://www.sqlite.org/uri.html>`_ as long as ``open_basedir`` is unset.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
testing:
|
||||
adapter: sqlite
|
||||
name: my_app
|
||||
mode: memory # Determines if the new database is opened read-only, read-write, read-write and created if it does not exist, or that the database is a pure in-memory database that never interacts with disk, respectively.
|
||||
cache: shared # Determines if the new database is opened using shared cache mode or with a private cache.
|
||||
|
||||
SQL Server
|
||||
`````````````````
|
||||
|
||||
When using the ``sqlsrv`` adapter and connecting to a named instance you should
|
||||
omit the ``port`` setting as SQL Server will negotiate the port automatically.
|
||||
Additionally, omit the ``charset: utf8`` or change to ``charset: 65001`` which
|
||||
corresponds to UTF8 for SQL Server.
|
||||
|
||||
Custom Adapters
|
||||
`````````````````
|
||||
|
||||
You can provide a custom adapter by registering an implementation of the `Phinx\\Db\\Adapter\\AdapterInterface`
|
||||
with `AdapterFactory`:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$name = 'fizz';
|
||||
$class = 'Acme\Adapter\FizzAdapter';
|
||||
|
||||
AdapterFactory::instance()->registerAdapter($name, $class);
|
||||
|
||||
Adapters can be registered any time before `$app->run()` is called, which normally
|
||||
called by `bin/phinx`.
|
||||
|
||||
Templates
|
||||
---------
|
||||
|
||||
You may override how phinx generates the template used with in a handful of ways:
|
||||
|
||||
* file - path to an alternative file to use.
|
||||
* class - class to use for the template, must implement the ``Phinx\Migration\CreationInterface`` interface.
|
||||
* style - style to use for template, either ``change`` or ``up_down``, defaults to ``change`` if not set.
|
||||
|
||||
You should only use one of these options. These can be overridden by passing command line options to the
|
||||
:doc:`Create Command <commands`. Example usage within the config file is:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
templates:
|
||||
style: up_down
|
||||
|
||||
Aliases
|
||||
-------
|
||||
|
||||
Template creation class names can be aliased and used with the ``--class`` command line option for the :doc:`Create Command <commands>`.
|
||||
|
||||
The aliased classes will still be required to implement the ``Phinx\Migration\CreationInterface`` interface.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
aliases:
|
||||
permission: \Namespace\Migrations\PermissionMigrationTemplateGenerator
|
||||
view: \Namespace\Migrations\ViewMigrationTemplateGenerator
|
||||
|
||||
Version Order
|
||||
-------------
|
||||
|
||||
When rolling back or printing the status of migrations, Phinx orders the executed migrations according to the
|
||||
``version_order`` option, which can have the following values:
|
||||
|
||||
* ``creation`` (the default): migrations are ordered by their creation time, which is also part of their filename.
|
||||
* ``execution``: migrations are ordered by their execution time, also known as start time.
|
||||
|
||||
Bootstrap Path
|
||||
---------------
|
||||
|
||||
You can provide a path to a `bootstrap` php file that will be included before any phinx commands are run. Note that
|
||||
setting External Variables to modify the config will not work because the config has already been parsed by this point.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
bootstrap: 'phinx-bootstrap.php'
|
||||
|
||||
Within the bootstrap script, the following variables will be available:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
/**
|
||||
* @var string $filename The file name as provided by the configuration
|
||||
* @var string $filePath The absolute, real path to the file
|
||||
* @var \Symfony\Component\Console\Input\InputInterface $input The executing command's input object
|
||||
* @var \Symfony\Component\Console\Output\OutputInterface $output The executing command's output object
|
||||
* @var \Phinx\Console\Command\AbstractCommand $context the executing command object
|
||||
*/
|
||||
|
||||
Feature Flags
|
||||
-------------
|
||||
|
||||
For some breaking changes, Phinx offers a way to opt-out of new behavior. The following flags are available:
|
||||
|
||||
* ``unsigned_primary_keys``: Should Phinx create primary keys as unsigned integers? (default: ``true``)
|
||||
* ``column_null_default``: Should Phinx create columns as null by default? (default: ``true``)
|
||||
|
||||
Since MySQL ``TIMESTAMP`` fields do not support dates past 2038-01-19, you have the option to use ``DATETIME`` field
|
||||
types for fields created by the ``addTimestamps()`` function:
|
||||
|
||||
* ``add_timestamps_use_datetime``: Should Phinx create created_at and updated_at fields as datetime? (default: ``false``)
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
feature_flags:
|
||||
unsigned_primary_keys: false
|
||||
|
||||
These values can also be set by modifying class fields on the ```Phinx\Config\FeatureFlags``` class, converting
|
||||
the flag name to ``camelCase``, for example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
Phinx\Config\FeatureFlags::$unsignedPrimaryKeys = false;
|
||||
@@ -0,0 +1,14 @@
|
||||
Contents
|
||||
########
|
||||
|
||||
.. toctree::
|
||||
:caption: Phinx
|
||||
|
||||
intro
|
||||
goals
|
||||
install
|
||||
migrations
|
||||
seeding
|
||||
commands
|
||||
configuration
|
||||
copyright
|
||||
@@ -0,0 +1,29 @@
|
||||
.. index::
|
||||
single: Copyright
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
License
|
||||
|
||||
(The MIT license)
|
||||
|
||||
Copyright (c) 2012 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.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
.. index::
|
||||
single: Goals
|
||||
|
||||
Goals
|
||||
=====
|
||||
|
||||
Phinx was developed with the following goals in mind:
|
||||
|
||||
* Be portable amongst the most popular database vendors.
|
||||
* Be PHP framework independent.
|
||||
* Have a simple install process.
|
||||
* Have an easy to use command-line operation.
|
||||
* Integrate with various other PHP tools (Phing, PHPUnit) and web frameworks.
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
:orphan:
|
||||
|
||||
Phinx Documentation
|
||||
===================
|
||||
|
||||
Phinx makes it ridiculously easy to manage the database migrations for your PHP
|
||||
app. In less than 5 minutes, you can install Phinx using Composer and create
|
||||
your first database migration. Phinx is just about migrations without all the
|
||||
bloat of a database ORM system or application framework.
|
||||
|
||||
Phinx requires a 64-bit version of PHP to function.
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
intro
|
||||
goals
|
||||
install
|
||||
migrations
|
||||
seeding
|
||||
commands
|
||||
configuration
|
||||
copyright
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
@@ -0,0 +1,28 @@
|
||||
.. index::
|
||||
single: Installation
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
Phinx should be installed using Composer, which is a tool for dependency
|
||||
management in PHP. Please visit the `Composer <https://getcomposer.org/>`_
|
||||
website for more information.
|
||||
|
||||
.. note::
|
||||
|
||||
Phinx requires at least PHP 8.1 (or later).
|
||||
|
||||
To install Phinx, simply require it using Composer:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
php composer.phar require robmorgan/phinx
|
||||
|
||||
Create folders in your project following the structure ``db/migrations`` with adequate permissions.
|
||||
It is where your migration files will live and should be writable.
|
||||
|
||||
Phinx can now be executed from within your project:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
vendor/bin/phinx init
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
.. index::
|
||||
single: Introduction
|
||||
|
||||
Introduction
|
||||
============
|
||||
|
||||
Good developers always version their code using a SCM system, so why don't they
|
||||
do the same for their database schema?
|
||||
|
||||
Phinx allows developers to alter and manipulate databases in a clear and
|
||||
concise way. It avoids the use of writing SQL by hand and instead offers a
|
||||
powerful API for creating migrations using PHP code. Developers can then
|
||||
version these migrations using their preferred SCM system. This makes Phinx
|
||||
migrations portable between different database systems. Phinx keeps track of
|
||||
which migrations have been run, so you can worry less about the state of your
|
||||
database and instead focus on building better software.
|
||||
+1988
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
:orphan:
|
||||
|
||||
.. index::
|
||||
single: Supporting namespaces
|
||||
|
||||
PSR-4 compliance
|
||||
==================
|
||||
|
||||
Phinx allows the use of namespaces in Migrations and Seeders.
|
||||
Migrations require a timestamp in the filename, and therefore won't be fully PSR-4 compliant. Seeders do not need a timestamp and will be fully PSR-4 compliant.
|
||||
|
||||
Using namespaces
|
||||
------------------------
|
||||
1) locate your Phinx config file, the config file may be in one of following three formats: PHP, YAML or JSON.
|
||||
2) Locate the "paths" key inside the config file, it should look something like one of the below examples.
|
||||
- (NB. the "migrations" and "seeds" keys may be both an array or a string, so don't be alarmed if yours looks different)
|
||||
|
||||
PHP:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
'paths' => [
|
||||
'migrations' => 'database/migrations',
|
||||
'seeds' => 'database/seeds',
|
||||
],
|
||||
|
||||
|
||||
YAML:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: ./database/migrations
|
||||
seeds: ./database/seeds
|
||||
|
||||
JSON:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"paths": {
|
||||
"migrations": "database/migrations",
|
||||
"seeds": "database/seeds"
|
||||
}
|
||||
}
|
||||
|
||||
3) Enabling namespaces is a fairly simple task, we're going to turn the "migrations" and "seeds" keys into arrays.
|
||||
- Any value without a key is a global-non-namespaced path
|
||||
- Any keyed value will use the key as namespace
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
'paths' => [
|
||||
'migrations' => [
|
||||
'/path/to/migration/without/namespace', // Non-namespaced migrations
|
||||
'Foo' => '/path/to/migration/Foo', // Migrations in the Foo namespace
|
||||
],
|
||||
'seeds' => [
|
||||
'/path/to/seeds/without/namespace', // Non-namespaced seeders
|
||||
'Baz' => '/path/to/seeds/Baz', // Seeders in the Baz namespace
|
||||
]
|
||||
],
|
||||
|
||||
PHP is a bit special in this case, as it allows keyless and keyed values in the same array. To make this configuration work in YAML and JSON, we have to key the non-namespaced path with "0".
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"paths": {
|
||||
"migrations": {
|
||||
"0": "./db/migrations",
|
||||
"Foo\\Bar": "./src/FooBar/db/migrations"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations:
|
||||
0: ./db/migrations
|
||||
Foo\\Bar: ./src/FooBar/db/migrations
|
||||
|
||||
Path resolving
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
Let's take a closer look on how the paths are resolved, let's start with the non-namespaced path.
|
||||
|
||||
"./" refers to the project-root, therefore "./db/migrations" would resolve to <project-root>/db/migrations.
|
||||
This is the directory where Phinx will look for migrations when migrating.
|
||||
NB. these migrations must not have a namespace.
|
||||
|
||||
.. image:: https://i.imgur.com/l84308Q.jpg
|
||||
|
||||
This image shows the path for "./db/migrations" where "Phinx" is the project root.
|
||||
|
||||
And the namespaced path would be resolved as shown below.
|
||||
|
||||
"./src/FooBar/db/migrations" would resolve to <project-root>/src/FooBar/db/migrations, which is where Phinx will look for migrations in the Foo\\Bar namespace.
|
||||
|
||||
.. image:: https://i.imgur.com/2mg0V8V.jpg
|
||||
|
||||
The file path would look like this, if the project-root was "Phinx"
|
||||
|
||||
File examples
|
||||
^^^^^^^^^^^^^
|
||||
|
||||
The non-namespaced file in <project-root>/db/migrations may look like the following example.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
class CreateUserTable extends AbstractMigration
|
||||
{
|
||||
public function change()
|
||||
{
|
||||
$table = $this->table('users');
|
||||
$table->addColumn('name', 'string')->create();
|
||||
}
|
||||
}
|
||||
|
||||
Whereas the namespaced file will be found in <project-root>/src/FoorBar/db/migrations and can look like this:
|
||||
(Notice the namespace is the same as defined in the paths config).
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
namespace Foo\Bar;
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
class CreateUserTable extends AbstractMigration
|
||||
{
|
||||
public function change()
|
||||
{
|
||||
$table = $this->table('users');
|
||||
$table->addColumn('name', 'string')->create();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
4) That's it, you're ready to go, to create a migration simply run: *$ phinx create CreateUsersTable [--path ./src/FoorBar/db/migrations]*
|
||||
|
||||
- If multiple paths are configured, but none provided with the --path flag, you will be prompted for which path to use.
|
||||
|
||||
|
||||
Did you run into an issue?
|
||||
--------------------------
|
||||
|
||||
- Due to the way the migrations are created, it is impossible to generate a migration in the *global* namespace with a class-name that is the same as a migration in a user-defined namespace.
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
.. index::
|
||||
single: Database Seeding
|
||||
|
||||
Database Seeding
|
||||
================
|
||||
|
||||
In version 0.5.0 Phinx introduced support for seeding your database with test
|
||||
data. Seed classes are a great way to easily fill your database with data after
|
||||
it's created. By default they are stored in the `seeds` directory; however, this
|
||||
path can be changed in your configuration file.
|
||||
|
||||
.. note::
|
||||
|
||||
Database seeding is entirely optional, and Phinx does not create a `seeds`
|
||||
directory by default.
|
||||
|
||||
Creating a New Seed Class
|
||||
-------------------------
|
||||
|
||||
Phinx includes a command to easily generate a new seed class:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:create UserSeeder
|
||||
|
||||
If you have specified multiple seed paths, you will be asked to select which
|
||||
path to create the new seed class in.
|
||||
|
||||
It is based on a skeleton template:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class MyNewSeeder extends AbstractSeed
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run() : void
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
The AbstractSeed Class
|
||||
----------------------
|
||||
|
||||
All Phinx seeds extend from the ``AbstractSeed`` class. This class provides the
|
||||
necessary support to create your seed classes. Seed classes are primarily used
|
||||
to insert test data.
|
||||
|
||||
The Run Method
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
The run method is automatically invoked by Phinx when you execute the `seed:run`
|
||||
command. You should use this method to insert your test data.
|
||||
|
||||
.. note::
|
||||
|
||||
Unlike with migrations, Phinx does not keep track of which seed classes have
|
||||
been run. This means database seeders can be run repeatedly. Keep this in
|
||||
mind when developing them.
|
||||
|
||||
The Init Method
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The ``init()`` method is run by Phinx before the run method if it exists. This
|
||||
can be used to initialize properties of the Seed class before using run.
|
||||
|
||||
The Should Execute Method
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``shouldExecute()`` method is run by Phinx before executing the seed.
|
||||
This can be used to prevent the seed from being executed at this time. It always
|
||||
returns true by default. You can override it in your custom ``AbstractSeed``
|
||||
implementation.
|
||||
|
||||
Foreign Key Dependencies
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Often you'll find that seeders need to run in a particular order, so they don't
|
||||
violate foreign key constraints. To define this order, you can implement the
|
||||
``getDependencies()`` method that returns an array of seeders to run before the
|
||||
current seeder:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class ShoppingCartSeeder extends AbstractSeed
|
||||
{
|
||||
public function getDependencies()
|
||||
{
|
||||
return [
|
||||
'UserSeeder',
|
||||
'ShopItemSeeder'
|
||||
];
|
||||
}
|
||||
|
||||
public function run() : void
|
||||
{
|
||||
// Seed the shopping cart after the `UserSeeder` and
|
||||
// `ShopItemSeeder` have been run.
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
Dependencies are only considered when executing all seed classes (default behavior).
|
||||
They won't be considered when running specific seed classes.
|
||||
|
||||
Inserting Data
|
||||
--------------
|
||||
|
||||
Using The Table Object
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Seed classes can also use the familiar `Table` object to insert data. You can
|
||||
retrieve an instance of the Table object by calling the ``table()`` method from
|
||||
within your seed class and then use the `insert()` method to insert data:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class PostsSeeder extends AbstractSeed
|
||||
{
|
||||
public function run() : void
|
||||
{
|
||||
$data = [
|
||||
[
|
||||
'body' => 'foo',
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
],[
|
||||
'body' => 'bar',
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
]
|
||||
];
|
||||
|
||||
$posts = $this->table('posts');
|
||||
$posts->insert($data)
|
||||
->saveData();
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
You must call the `saveData()` method to commit your data to the table. Phinx
|
||||
will buffer data until you do so.
|
||||
|
||||
Truncating Tables
|
||||
-----------------
|
||||
|
||||
In addition to inserting data Phinx makes it trivial to empty your tables using the
|
||||
SQL `TRUNCATE` command:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class UserSeeder extends AbstractSeed
|
||||
{
|
||||
public function run() : void
|
||||
{
|
||||
$data = [
|
||||
[
|
||||
'body' => 'foo',
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
],
|
||||
[
|
||||
'body' => 'bar',
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
]
|
||||
];
|
||||
|
||||
$posts = $this->table('posts');
|
||||
$posts->insert($data)
|
||||
->saveData();
|
||||
|
||||
// empty the table
|
||||
$posts->truncate();
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
SQLite doesn't natively support the `TRUNCATE` command so behind the scenes
|
||||
`DELETE FROM` is used. It is recommended to call the `VACUUM` command
|
||||
after truncating a table. Phinx does not do this automatically.
|
||||
|
||||
Executing Seed Classes
|
||||
----------------------
|
||||
|
||||
This is the easy part. To seed your database, simply use the `seed:run` command:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run
|
||||
|
||||
By default, Phinx will execute all available seed classes. If you would like to
|
||||
run a specific class, simply pass in the name of it using the `-s` parameter:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run -s UserSeeder
|
||||
|
||||
You can also run multiple seeders:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run -s UserSeeder -s PermissionSeeder -s LogSeeder
|
||||
|
||||
You can also use the `-v` parameter for more output verbosity:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run -v
|
||||
|
||||
The Phinx seed functionality provides a simple mechanism to easily and repeatably
|
||||
insert test data into your database.
|
||||
Reference in New Issue
Block a user