Initial commit: apps.prometeysev.ru
This commit is contained in:
commit
96ccabcd8b
6561 files changed
+1270349
No files matched your search
Whitespace-only changes.
+43
@@ -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.11.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.11', 'number': '/phinx/11', 'title': '0.11', 'current': True},
|
||||
]
|
||||
|
||||
# Languages available.
|
||||
languages = ['en', 'es', 'fr', 'ja']
|
||||
|
||||
# The GitHub branch name for this version of the docs
|
||||
# for edit links to point at.
|
||||
branch = 'master'
|
||||
|
||||
# Current version being built
|
||||
version = '0.11'
|
||||
|
||||
show_root_link = True
|
||||
|
||||
repository = 'cakephp/phinx'
|
||||
|
||||
source_path = 'docs/'
|
||||
|
||||
hide_page_contents = ('search', '404', 'contents')
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
.. 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.yml`` 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.yml`` file in the root of your
|
||||
project directory.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd yourapp
|
||||
$ phinx init
|
||||
|
||||
Optionally you can specify a custom location for Phinx's config file:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd yourapp
|
||||
$ phinx init ./custom/location/
|
||||
|
||||
You can also specify a custom file name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd yourapp
|
||||
$ phinx init custom-config.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.yml`` 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 ``phinx.yml`` file.
|
||||
Please see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
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_database" => "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 ``*.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_database" => "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/config/phinx.yml'
|
||||
];
|
||||
|
||||
$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
|
||||
]);
|
||||
$configArray = require('phinx.php');
|
||||
$configArray['environments']['test'] = [
|
||||
'adapter' => 'sqlite',
|
||||
'connection' => $pdo
|
||||
];
|
||||
$config = new Config($configArray);
|
||||
$manager = new Manager($config, new StringInput(' '), new NullOutput());
|
||||
$manager->migrate('test');
|
||||
$manager->seed('test');
|
||||
// You can change default fetch mode after the seeding
|
||||
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
|
||||
$this->pdo = $pdo;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -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'
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
.. 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 ``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`` or
|
||||
``phinx.yml`` 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_database' => '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.yml`` file is stored.
|
||||
|
||||
In order to overwrite the default ``%%PHINX_CONFIG_DIR%%/db/migrations``, you
|
||||
need to add the following to the yaml 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
|
||||
|
||||
|
||||
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 ``phinx.yml`` 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'
|
||||
|
||||
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_database: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: localhost
|
||||
name: production_db
|
||||
user: root
|
||||
pass: ''
|
||||
port: 3306
|
||||
charset: utf8
|
||||
collation: utf8_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`
|
||||
|
||||
|
||||
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_database: 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_database: 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_database: 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_database: 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 <http://www.mysql.com/>`_: specify the ``mysql`` adapter.
|
||||
* `PostgreSQL <http://www.postgresql.org/>`_: specify the ``pgsql`` adapter.
|
||||
* `SQLite <http://www.sqlite.org/>`_: specify the ``sqlite`` adapter.
|
||||
* `SQL Server <http://www.microsoft.com/sqlserver>`_: specify the ``sqlsrv`` adapter.
|
||||
|
||||
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
|
||||
|
||||
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`.
|
||||
|
||||
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 included before any commands 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'
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
Contents
|
||||
########
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: Phinx
|
||||
|
||||
intro
|
||||
goals
|
||||
install
|
||||
migrations
|
||||
seeding
|
||||
commands
|
||||
configuration
|
||||
copyright
|
||||
+29
@@ -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.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
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.
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
intro
|
||||
goals
|
||||
install
|
||||
migrations
|
||||
seeding
|
||||
commands
|
||||
configuration
|
||||
copyright
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
+28
@@ -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 5.6 (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.
|
||||
+1802
File diff suppressed because it is too large.
Load diff
+152
@@ -0,0 +1,152 @@
|
||||
.. 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:: http://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:: http://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.
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
.. 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:
|
||||
* http://docs.phinx.org/en/latest/seeding.html
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
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()
|
||||
{
|
||||
// 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()
|
||||
{
|
||||
$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.
|
||||
|
||||
Integrating with the Faker library
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
It's trivial to use the awesome
|
||||
`Faker library <https://github.com/fzaninotto/Faker>`_ in your seed classes.
|
||||
Simply install it using Composer:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ composer require fzaninotto/faker
|
||||
|
||||
Then use it in your seed classes:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class UserSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$faker = Faker\Factory::create();
|
||||
$data = [];
|
||||
for ($i = 0; $i < 100; $i++) {
|
||||
$data[] = [
|
||||
'username' => $faker->userName,
|
||||
'password' => sha1($faker->password),
|
||||
'password_salt' => sha1('foo'),
|
||||
'email' => $faker->email,
|
||||
'first_name' => $faker->firstName,
|
||||
'last_name' => $faker->lastName,
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
|
||||
$this->table('users')->insert($data)->saveData();
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
$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.
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
. index::
|
||||
single: Commands
|
||||
|
||||
Comandos
|
||||
########
|
||||
|
||||
Phinx se corre usando un numero de comandos.
|
||||
|
||||
Migracion de Comandos
|
||||
=====================
|
||||
|
||||
Comando de Inicio
|
||||
|
||||
El comanado de inicio (manera corta de inicialización) se usa para preparar el proyecto Phinix. Este comando genera el archivo phinx.yml en el directorio raiz del proyecto:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd yourapp
|
||||
$ phinx init .
|
||||
|
||||
Abre este archivo en tu editor de texto para configurar tu projecto. Por favot mira el :doc:`Configuration <configuration>` para mas información.
|
||||
|
||||
Comando de creación.
|
||||
--------------------
|
||||
|
||||
El comando de creación se usa para crear un nuevo archivo de migración. Requiere un argumento: el nombre de la migración. El nombre de la migracion debera especificarse en el formato CamelCase:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration
|
||||
|
||||
Abre el nuevo archivo de migración en tu editor de texto para agregar las transformaciones de tu base de datos. Phinx crea archivos de migracion usando direcciones especificas en tu archivo phinx.yml . Por favor mire :doc:`Configuration <configuration>` para mas información.
|
||||
|
||||
Usted puede sobreescribir el archivo modelo usado por Phinx suministrando una alternativa del modelo de archivo:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration --template="<file>"
|
||||
|
||||
Tambien puedes suministrar un modelo de clase general. Esta clase deberá implementar la interfaz ``Phinx\Migration\CreationInterface``.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration --class="<class>"
|
||||
|
||||
Además de proveer el modelo para la migracion, la clase tambien puede definir una "callback" que sera llamada una vez que el archivo de migración haya sido generado por el modelo.
|
||||
|
||||
No puede usar ``--template`` y ``--class`` juntos.
|
||||
|
||||
El comando de migración
|
||||
-----------------------
|
||||
|
||||
El comando de migración corre todas las migraciones que se encuentren disponibles, opcionalmente hasta una version especificada.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate -e development
|
||||
|
||||
Para migrar a una version especifica se utiliza el parametro ``--targe`` o ``-t`` resumido.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate -e development -t 20110103081132
|
||||
|
||||
Use ``--dry-run`` para imprimir las consultas a la salida sin ejecutarlas
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate --dry-run
|
||||
|
||||
|
||||
El comando para revertir
|
||||
------------------------
|
||||
|
||||
El comando para revertir se utiliza para deshacer las migraciones anteriores ejecutadas por Phinx. Es lo opuesto al comando Migrar.
|
||||
|
||||
Puede revertir a la migración anterior usando el comando rollback sin argumentos.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development
|
||||
|
||||
Para revertir todas las migraciones a una versión específica, use el parámetro ``--target`` o ``-t`` para abreviar
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 20120103083322
|
||||
|
||||
Especificar 0 como la versión de destino revertirá todas las migraciones.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 0
|
||||
|
||||
Para revertir todas las migraciones a una fecha específica, use el parámetro ``--date`` o -d para abreviar.
|
||||
|
||||
.. 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
|
||||
|
||||
Si se establece un punto de interrupción, bloqueando más reversiones, puede anular el punto de interrupción utilizando el parámetro ``--force`` o ``-f`` para abreviar
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 0 -f
|
||||
|
||||
Utilice ``--dry-run`` para imprimir las consultas a la salida estándar sin ejecutarlas
|
||||
|
||||
.. 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.yml file. Please see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
El comando de estado
|
||||
--------------------
|
||||
|
||||
El comando Estado imprime una lista de todas las migraciones, junto con su estado actual. Puede usar este comando para determinar qué migraciones se han ejecutado.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx status -e development
|
||||
|
||||
La salida de este comando es 0 si la base de datos está actualizada (es decir, todas las migraciones están activas) o uno de los siguientes códigos de lo contrario:
|
||||
|
||||
#. Queda por lo menos una migración por ejecutar.
|
||||
#: se ejecutó una migración y se registró en la base de datos, pero ahora falta
|
||||
el archivo de migración
|
||||
|
||||
El comando de interrupción
|
||||
---------------------------
|
||||
|
||||
El comando Punto de interrupción se usa para establecer puntos de interrupción, lo que le permite limitar los retrotracción. Puede alternar el punto de interrupción de la migración más reciente al no proporcionar ningún parámetro
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development
|
||||
|
||||
Para alternar un punto de interrupción en una versión específica, use el parámetro ``--target`` o ``-t`` para abreviar
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development -t 20120103083322
|
||||
|
||||
Puede eliminar todos los puntos de interrupción utilizando el parámetro ``--remove-all`` o ``-r`` para abreviar.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development -r
|
||||
|
||||
Los puntos de interrupción son visibles cuando ejecuta el comando de estado.
|
||||
|
||||
"Database Seeding"
|
||||
------------------
|
||||
|
||||
El comando Crear semilla se puede usar para crear nuevas clases de base de datos. Requiere un argumento, el nombre de la clase. El nombre de la clase debe especificarse en formato CamelCase.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:create MyNewSeeder
|
||||
|
||||
Abra el nuevo archivo semilla en su editor de texto para agregar los comandos semilla de su base de datos. Phinx crea archivos semilla utilizando la ruta especificada en su archivo phinx.yml. Consulte el capítulo: doc: `Configuration <configuración>` para obtener más información.
|
||||
|
||||
El comando de ejecución de semillas
|
||||
-----------------------------------
|
||||
|
||||
El comando Seed Run ejecuta todas las clases semilla disponibles u opcionalmente solo una.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:run -e development
|
||||
|
||||
Para ejecutar solo una clase semilla, use el parámetro ``--seed`` o ``-s`` para abreviar.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:run -e development -s MyNewSeeder
|
||||
|
||||
|
||||
Parámetro del archivo de configuración
|
||||
--------------------------------------
|
||||
|
||||
Al ejecutar Phinx desde la línea de comandos, puede especificar un archivo de configuración usando el parámetro ``--configuration`` o ``-c``. Además de YAML, el archivo de configuración puede ser la salida calculada de un archivo PHP como una matriz de PHP::
|
||||
|
||||
<?php
|
||||
return [
|
||||
"paths" => [
|
||||
"migrations" => "application/migrations"
|
||||
],
|
||||
"environments" => [
|
||||
"default_migration_table" => "phinxlog",
|
||||
"default_database" => "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 detecta automáticamente qué analizador de idioma usar para los archivos con las extensiones ``.yml`` y ``.php``. El analizador apropiado también se puede especificar a través de los parámetros ``--parser`` y ``-p``. Cualquier otra cosa que no sea "php" se trata como YAML.
|
||||
|
||||
Al usar una matriz de PHP, puede proporcionar una clave de conexión con una instancia de PDO existente. También es importante pasar el nombre de la base de datos, ya que Phinx lo requiere para ciertos métodos como ``hasTable()``::
|
||||
|
||||
<?php
|
||||
return [
|
||||
"paths" => [
|
||||
"migrations" => "application/migrations"
|
||||
],
|
||||
"environments" => [
|
||||
"default_migration_table" => "phinxlog",
|
||||
"default_database" => "dev",
|
||||
"dev" => [
|
||||
"name" => "dev_db",
|
||||
"connection" => $pdo_instance
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
Ejecutando Phinx en una aplicación web
|
||||
--------------------------------------
|
||||
|
||||
Phinx también se puede ejecutar dentro de una aplicación web utilizando la clase ``Phinx\Wrapper\TextWrapper``. Un ejemplo de esto se proporciona en **app/web.php**, que se puede ejecutar como un servidor independiente:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php -S localhost:8000 vendor/robmorgan/phinx/app/web.php
|
||||
|
||||
Esto creará un servidor web local en http://localhost:8000 que mostrará el estado actual de la migración de forma predeterminada. Para ejecutar las migraciones, use http://localhost:8000/migrate y para revertir use http: // localhost: 8000 / rollback.
|
||||
|
||||
La aplicación web incluida es solo un ejemplo y no debe utilizarse en producción
|
||||
|
||||
|
||||
.. note::
|
||||
Para modificar las variables de configuración en tiempo de ejecución
|
||||
e invalidar ``%%PHINX_DBNAME%%`` u otra opción dinámica, establezca ``$
|
||||
_SERVER['PHINX_DBNAME']`` antes de ejecutar los comandos. Las opciones
|
||||
disponibles están documentadas en la página de Configuración.
|
||||
|
||||
Usando Phinx con PHPUnit
|
||||
------------------------
|
||||
|
||||
Phinx puede usarse dentro de las pruebas de su unidad para preparar o sembrar la base de datos. Puedes usarlo programáticamente::
|
||||
|
||||
public function setUp ()
|
||||
{
|
||||
$app = new PhinxApplication();
|
||||
$app->setAutoExit(false);
|
||||
$app->run(new StringInput('migrate'), new NullOutput());
|
||||
}
|
||||
|
||||
Si usa una base de datos de memoria, deberá darle a Phinx una instancia de PDO específica. Puedes interactuar con Phinx directamente usando la clase Manager::
|
||||
|
||||
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
|
||||
]);
|
||||
$configArray = require('phinx.php');
|
||||
$configArray['environments']['test'] = [
|
||||
'adapter' => 'sqlite',
|
||||
'connection' => $pdo
|
||||
];
|
||||
$config = new Config($configArray);
|
||||
$manager = new Manager($config, new StringInput(' '), new NullOutput());
|
||||
$manager->migrate('test');
|
||||
$manager->seed('test');
|
||||
// You can change default fetch mode after the seeding
|
||||
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
|
||||
$this->pdo = $pdo;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -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 = 'es'
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
Contents
|
||||
########
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: Phinx
|
||||
|
||||
commands
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
.. index::
|
||||
single: Commands
|
||||
|
||||
Commands
|
||||
########
|
||||
|
||||
Phinx is run using a number of commands.
|
||||
|
||||
Migration Commands
|
||||
==================
|
||||
|
||||
The Init Command
|
||||
|
||||
The Init command (short for initialize) is used to prepare your project for
|
||||
Phinx. This command generates the ``phinx.yml`` file in the root of your
|
||||
project directory.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd yourapp
|
||||
$ phinx init .
|
||||
|
||||
Open this file in your text editor to setup your project configuration. Please
|
||||
see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
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.yml`` 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 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.yml`` 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:
|
||||
|
||||
* 1: There is at least one migration left to be executed.
|
||||
* 2: There was a migration run and recorded in the database, but the migration file is now missing.
|
||||
|
||||
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
|
||||
|
||||
Breakpoints are visible when you run the ``status`` command.
|
||||
|
||||
Database Seeding
|
||||
================
|
||||
|
||||
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 ``phinx.yml`` file.
|
||||
Please see the :doc:`Configuration <configuration>` chapter for more information.
|
||||
|
||||
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_database" => "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 ``*.yml`` and ``*.php`` extensions. The appropriate
|
||||
parser may also be specified via the ``--parser`` and ``-p`` parameters. Anything other than ``"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_database" => "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.
|
||||
|
||||
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
|
||||
]);
|
||||
$configArray = require('phinx.php');
|
||||
$configArray['environments']['test'] = [
|
||||
'adapter' => 'sqlite',
|
||||
'connection' => $pdo
|
||||
];
|
||||
$config = new Config($configArray);
|
||||
$manager = new Manager($config, new StringInput(' '), new NullOutput());
|
||||
$manager->migrate('test');
|
||||
$manager->seed('test');
|
||||
// You can change default fetch mode after the seeding
|
||||
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
|
||||
$this->pdo = $pdo;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -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 = 'fr'
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
.. index::
|
||||
single: Configuration
|
||||
|
||||
Configuration
|
||||
=============
|
||||
|
||||
When you initialize your project using the :doc:`Init Command<commands>`, Phinx
|
||||
creates a default file called ``phinx.yml`` in the root of your project directory.
|
||||
This file uses the YAML data serialization format.
|
||||
|
||||
If a ``--configuration`` command line option is given, Phinx will load the
|
||||
specified file. Otherwise, it will attempt to find ``phinx.php``, ``phinx.json`` or
|
||||
``phinx.yml`` 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.
|
||||
|
||||
::
|
||||
|
||||
<?php
|
||||
require 'app/init.php';
|
||||
|
||||
global $app;
|
||||
$pdo = $app->getDatabase()->getPdo();
|
||||
|
||||
return ['environments' =>
|
||||
[
|
||||
'default_database' => '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.yml`` file is stored.
|
||||
|
||||
In order to overwrite the default ``%%PHINX_CONFIG_DIR%%/db/migrations``, you
|
||||
need to add the following to the yaml 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
|
||||
|
||||
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 ``phinx.yml`` 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'
|
||||
|
||||
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_database: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: localhost
|
||||
name: production_db
|
||||
user: root
|
||||
pass: ''
|
||||
port: 3306
|
||||
charset: utf8
|
||||
collation: utf8_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`
|
||||
|
||||
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_database: 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_database: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: '%%PHINX_DBHOST%%'
|
||||
name: '%%PHINX_DBNAME%%'
|
||||
user: '%%PHINX_DBUSER%%'
|
||||
pass: '%%PHINX_DBPASS%%'
|
||||
port: 3306
|
||||
charset: utf8
|
||||
|
||||
Supported Adapters
|
||||
------------------
|
||||
|
||||
Phinx currently supports the following database adapters natively:
|
||||
|
||||
* `MySQL <http://www.mysql.com/>`_: specify the ``mysql`` adapter.
|
||||
* `PostgreSQL <http://www.postgresql.org/>`_: specify the ``pgsql`` adapter.
|
||||
* `SQLite <http://www.sqlite.org/>`_: specify the ``sqlite`` adapter.
|
||||
* `SQL Server <http://www.microsoft.com/sqlserver>`_: specify the ``sqlsrv`` adapter.
|
||||
|
||||
SQLite
|
||||
~~~~~~
|
||||
|
||||
Declaring an SQLite database uses a simplified structure:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
development:
|
||||
adapter: sqlite
|
||||
name: ./data/derby
|
||||
testing:
|
||||
adapter: sqlite
|
||||
memory: true # Setting memory to *any* value overrides name
|
||||
|
||||
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`.
|
||||
|
||||
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.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Contenus
|
||||
========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
index
|
||||
migrations
|
||||
seeding
|
||||
commands
|
||||
configuration
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
Phinx Migrations
|
||||
################
|
||||
|
||||
Phinx est un utilitaire autonome en ligne de commande pour gérer les Migrations de bases de données. Le plugin officiel de Migrations de CakePHP est basé sur cet outil.
|
||||
|
||||
Phinx rend ridiculement simple la gestion des migrations de bases de données pour vos applications PHP. En moins de 5 minutes,
|
||||
vous pouvez installer Composer et créer votre première migration de base de données. Phinx ne s'occupe que de la migration des
|
||||
bases de données, il laisse de côté les aspects ORM de la base de données et le cadre applicatif.
|
||||
|
||||
Introduction
|
||||
============
|
||||
|
||||
Les bons développeurs gèrent toujours leurs codes sources avec un outil de gestion de versions,
|
||||
alors pourquoi ne feraient-ils pas la même chose avec leurs schémas de bases de données.
|
||||
|
||||
Phinx permet aux développeurs de modifier et de manipuler leurs bases de données d'une façon claire et concise. Il évite
|
||||
d'avoir à écrire du SQL à la main et offre à la place une API puissante pour écrire des scripts de migration en utilisant PHP.
|
||||
Les développeurs peuvent alors versionner ces fichiers de migration en utilisant leur outil de versionnement préféré. Cela rend
|
||||
les migrations Phinx indépendantes des moteurs de base de données. Phinx conserve la trace des migrations précédentes, cela
|
||||
permet de se concentrer un peu plus sur l'amélioration de votre application et un peu moins sur l'état de votre base de
|
||||
données.
|
||||
|
||||
Objectifs
|
||||
=========
|
||||
|
||||
Phinx a été développé avec les objectifs suivants en tête :
|
||||
|
||||
* Être portable entre les principaux moteurs de base de données.
|
||||
* Être indépendant de tout framework PHP.
|
||||
* Être aisement installable.
|
||||
* Être utilisable facilement en ligne de commande.
|
||||
* Être intégrable avec d'autres outils PHP (Phing, PHPUnit) et des frameworks web.
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
Phinx devrait être installé en utilisant Composer, qui est un outil pour la gestion des dépendances en PHP. Visiter le site
|
||||
internet de `Composer <https://getcomposer.org/>`_ pour avoir plus d’informations.
|
||||
|
||||
.. note::
|
||||
|
||||
Phinx a besoin au minimum de PHP 5.4 (ou supérieur)
|
||||
|
||||
Pour installer Phinx, il suffit simplement de l'appeler via Composer
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
php composer.phar require robmorgan/phinx
|
||||
|
||||
Créez les dossiers ``db/migrations`` dans votre projet en vous assurant que les droits sont bien configurés.
|
||||
C’est à cet endroit que vos fichiers de migrations devraient être créés et laissés.
|
||||
|
||||
Phinx peut maintenant être exécuté depuis la racine de votre projet.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
vendor/bin/phinx init
|
||||
+1305
File diff suppressed because it is too large.
Load diff
+217
@@ -0,0 +1,217 @@
|
||||
.. 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::
|
||||
|
||||
<?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:
|
||||
* http://docs.phinx.org/en/latest/seeding.html
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
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::
|
||||
|
||||
<?php
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class PostsSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$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)
|
||||
->save();
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
You must call the ``save()`` method to commit your data to the table. Phinx
|
||||
will buffer data until you do so.
|
||||
|
||||
Integrating with the Faker library
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
It's trivial to use the awesome
|
||||
`Faker library <https://github.com/fzaninotto/Faker>`_ in your seed classes.
|
||||
Simply install it using Composer:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ composer require fzaninotto/faker
|
||||
|
||||
Then use it in your seed classes::
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class UserSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$faker = Faker\Factory::create();
|
||||
$data = [];
|
||||
for ($i = 0; $i < 100; $i++) {
|
||||
$data[] = [
|
||||
'username' => $faker->userName,
|
||||
'password' => sha1($faker->password),
|
||||
'password_salt' => sha1('foo'),
|
||||
'email' => $faker->email,
|
||||
'first_name' => $faker->firstName,
|
||||
'last_name' => $faker->lastName,
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
|
||||
$this->insert('users', $data);
|
||||
}
|
||||
}
|
||||
|
||||
Truncating Tables
|
||||
-----------------
|
||||
|
||||
In addition to inserting data Phinx makes it trivial to empty your tables using
|
||||
the SQL ``TRUNCATE`` command::
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class UserSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$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)
|
||||
->save();
|
||||
|
||||
// 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.
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
.. index::
|
||||
single: Commands
|
||||
|
||||
コマンド
|
||||
########
|
||||
|
||||
Phinx は多くのコマンドを使用して実行されます。
|
||||
|
||||
マイグレーションコマンド
|
||||
========================
|
||||
|
||||
init コマンド
|
||||
----------------
|
||||
|
||||
init コマンド (initialize の略) は、Phinx のプロジェクトを準備するために使用されます。
|
||||
このコマンドはプロジェクトディレクトリーのルートに ``phinx.yml`` ファイルを生成します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd yourapp
|
||||
$ phinx init .
|
||||
|
||||
このファイルをテキストエディターで開き、プロジェクトの設定を行います。
|
||||
詳しくは :doc:`設定 <configuration>` の章をご覧下さい。
|
||||
|
||||
create コマンド
|
||||
---------------
|
||||
|
||||
create コマンドは、新しいマイグレーションファイルを作成するために使用されます。
|
||||
1つの引数、つまりマイグレーション名が必要です。
|
||||
マイグレーション名は、キャメルケース形式で指定する必要があります。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration
|
||||
|
||||
新しいマイグレーションファイルをテキストエディターで開き、データベースの変更を追加します。
|
||||
Phinx は ``phinx.yml`` ファイルで指定されたパスを使ってマイグレーションファイルを作成します。
|
||||
詳しくは :doc:`設定 <configuration>` の章をご覧下さい。
|
||||
|
||||
代替のテンプレートファイル名を指定することで、
|
||||
Phinx が使用するテンプレートファイルを上書きすることができます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration --template="<file>"
|
||||
|
||||
テンプレート生成クラスを提供することもできます。このクラスはインタフェース
|
||||
``Phinx\Migration\CreationInterface`` を実装しなければなりません。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx create MyNewMigration --class="<class>"
|
||||
|
||||
マイグレーションのテンプレートを提供するだけでなく、クラスはマイグレーションファイルが
|
||||
テンプレートから生成されると呼び出されるコールバックを定義することもできます。
|
||||
|
||||
``--template`` と ``--class`` の両方を使用することはできません。
|
||||
|
||||
migrate コマンド
|
||||
----------------
|
||||
|
||||
migrate コマンドは、すべての使用可能なマイグレーションを実行します。
|
||||
オプションで特定のバージョンまで実行できます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate -e development
|
||||
|
||||
特定のバージョンにマイグレーションするには、 ``--target`` パラメーターまたは省略して
|
||||
``-t`` を使用します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate -e development -t 20110103081132
|
||||
|
||||
``--dry-run`` を使って、クエリーを実行せずに標準出力に出力します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx migrate --dry-run
|
||||
|
||||
rollback コマンド
|
||||
-----------------
|
||||
|
||||
rollback コマンドは、Phinx によって実行された以前のマイグレーションを取り消すために使用されます。
|
||||
これは、migrate コマンドの反対です。
|
||||
|
||||
引数を指定せずに ``rollback`` コマンドを使用すると、以前の移行にロールバックすることができます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development
|
||||
|
||||
すべてのマイグレーションを特定のバージョンにロールバックするには、 ``--target`` パラメーターまたは
|
||||
省略して ``-t`` を使用します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 20120103083322
|
||||
|
||||
ターゲットバージョンとして 0 を指定すると、すべてのマイグレーションが元に戻ります。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 0
|
||||
|
||||
すべてのマイグレーションを特定の日付にロールバックするには、 ``--date`` パラメーターまたは省略して
|
||||
``-d`` を省略して使用します。
|
||||
|
||||
.. 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
|
||||
|
||||
ブレークポイントが設定され、さらにロールバックをブロックしている場合は、 ``--force`` パラメーターまたは
|
||||
``-f`` を使ってブレークポイントをオーバーライドすることができます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback -e development -t 0 -f
|
||||
|
||||
``--dry-run`` を使って、クエリーを実行せずに標準出力に出力します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx rollback --dry-run
|
||||
|
||||
.. note::
|
||||
|
||||
ロールバックすると、Phinx は ``phinx.yml`` ファイルの ``version_order`` オプションで
|
||||
指定された順序で実行されたマイグレーションを処理します。
|
||||
詳しくは :doc:`設定 <configuration>` の章をご覧下さい。
|
||||
|
||||
status コマンド
|
||||
---------------
|
||||
|
||||
status コマンドは、すべてのマイグレーションのリストを現在のステータスとともに表示します。
|
||||
このコマンドを使用して、実行されたマイグレーションを確認できます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx status -e development
|
||||
|
||||
このコマンドは、データベースが最新の場合(つまり、すべてのマイグレーションが稼働している場合)
|
||||
コード0で終了します。またはそれ以外の場合は、次のコードのいずれかで終了します。
|
||||
|
||||
* 1: 実行されるマイグレーションが少なくとも1つ残っています。
|
||||
* 2: マイグレーションが実行され、データベースに記録されましたが、マイグレーションファイルが有りません。
|
||||
|
||||
breakpoint コマンド
|
||||
-------------------
|
||||
|
||||
breakpoint コマンドは、ブレークポイントを設定するために使用され、ロールバックを制限することができます。
|
||||
最新のマイグレーションのブレークポイントは、パラメーターを指定しないで切り替えることができます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development
|
||||
|
||||
特定のバージョンでブレークポイントを切り替えるには、 ``--target`` パラメーターまたは省略して
|
||||
``-t`` を使用します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development -t 20120103083322
|
||||
|
||||
全てのブレークポイントを削除するには、 ``--remove-all`` パラメーターまたは省略して
|
||||
``-r`` を使用します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx breakpoint -e development -r
|
||||
|
||||
ブレークポイントは、 ``status`` コマンドを実行すると表示されます。
|
||||
|
||||
データベースの初期データ投入
|
||||
============================
|
||||
|
||||
seed:create コマンド
|
||||
--------------------
|
||||
|
||||
seed:create コマンドを使用して、新しいデータベースシードクラスを作成できます。
|
||||
1つの引数、クラスの名前が必要です。クラス名はキャメルケース形式で指定する必要があります。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:create MyNewSeeder
|
||||
|
||||
テキストエディターで新しいシードファイルを開き、データベースシードコマンドを追加します。
|
||||
Phinx は ``phinx.yml`` ファイルで指定されたパスを使ってシードファイルを作成します。
|
||||
詳しくは :doc:`設定 <configuration>` の章をご覧下さい。
|
||||
|
||||
seed:run コマンド
|
||||
-----------------
|
||||
|
||||
seed:run コマンドは、使用可能なすべてのシードクラスを実行するか、オプションで1つだけを実行します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:run -e development
|
||||
|
||||
シードクラスを1つだけ実行するには、 ``--seed`` パラメーターまたは省略して ``-s`` を使用します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ phinx seed:run -e development -s MyNewSeeder
|
||||
|
||||
設定ファイルパラメーター
|
||||
------------------------
|
||||
|
||||
コマンドラインから Phinx を実行するときは、 ``--configuration`` または
|
||||
``-c`` パラメーターを使って設定ファイルを指定することができます。
|
||||
YAML に加えて、設定ファイルは PHP 配列として PHP ファイルの計算された出力でもよいです。
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
return [
|
||||
"paths" => [
|
||||
"migrations" => "application/migrations"
|
||||
],
|
||||
"environments" => [
|
||||
"default_migration_table" => "phinxlog",
|
||||
"default_database" => "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 は ``*.yml`` と ``*.php`` 拡張子を持つファイルにどの言語パーサーを使うかを自動的に検出します。
|
||||
適切なパーサーは、 ``--parser`` と ``-p`` パラメーターで指定することもできます。
|
||||
``"php"`` 以外は YAML として扱われます。
|
||||
|
||||
PHP 配列を使用する場合、既存の PDO インスタンスに ``connection`` キーを提供することができます。
|
||||
Phinx は ``hasTable()`` のような特定のメソッドに対してデータベース名を必要とするため、
|
||||
データベース名も渡すことも重要です。
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
return [
|
||||
"paths" => [
|
||||
"migrations" => "application/migrations"
|
||||
],
|
||||
"environments" => [
|
||||
"default_migration_table" => "phinxlog",
|
||||
"default_database" => "dev",
|
||||
"dev" => [
|
||||
"name" => "dev_db",
|
||||
"connection" => $pdo_instance
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
ウェブアプリ内で Phinx を実行
|
||||
-----------------------------
|
||||
|
||||
Phinx は ``Phinx\Wrapper\TextWrapper`` クラスを使ってウェブアプリケーションの内部で
|
||||
実行することもできます。この例は ``app/web.php`` で提供されています。
|
||||
これはスタンドアロンサーバーとして実行できます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php -S localhost:8000 vendor/robmorgan/phinx/app/web.php
|
||||
|
||||
これはデフォルトで現在のマイグレーションの状態を表示する `<http://localhost:8000>`__
|
||||
にローカルウェブサーバーを作成します。マイグレーションを実行するには、
|
||||
`<http://localhost:8000/migrate>`__ を使用し、ロールバックには
|
||||
`<http://localhost:8000/rollback>`__ を使用します。
|
||||
|
||||
**付属のウェブアプリは一例に過ぎません、本番環境では使用しないでください!**
|
||||
|
||||
.. note::
|
||||
|
||||
実行時に設定変数を変更し、 ``%%PHINX_DBNAME%%`` やその他の動的オプションを変更するには、
|
||||
コマンドを実行する前に ``$_SERVER['PHINX_DBNAME']`` を設定します。
|
||||
使用可能なオプションは、設定ページに記載されています。
|
||||
|
||||
PHPUnit で Phinx を使用
|
||||
-----------------------
|
||||
|
||||
Phinx は、ユニットテスト内でデータベースを準備またはシードするために使用できます。
|
||||
プログラムによって使用することができます。
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
public function setUp ()
|
||||
{
|
||||
$app = new PhinxApplication();
|
||||
$app->setAutoExit(false);
|
||||
$app->run(new StringInput('migrate'), new NullOutput());
|
||||
}
|
||||
|
||||
メモリーデータベースを使用する場合は、Phinx に特定の PDO インスタンスを提供する必要があります。
|
||||
Manager クラスを使用して Phinx と直接対話することができます。
|
||||
|
||||
.. 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
|
||||
]);
|
||||
$configArray = require('phinx.php');
|
||||
$configArray['environments']['test'] = [
|
||||
'adapter' => 'sqlite',
|
||||
'connection' => $pdo
|
||||
];
|
||||
$config = new Config($configArray);
|
||||
$manager = new Manager($config, new StringInput(' '), new NullOutput());
|
||||
$manager->migrate('test');
|
||||
$manager->seed('test');
|
||||
// シード後にデフォルトのフェッチモードを変更することができます
|
||||
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
|
||||
$this->pdo = $pdo;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -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 = 'ja'
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
.. index::
|
||||
single: Configuration
|
||||
|
||||
構成設定
|
||||
=============
|
||||
|
||||
:doc:`init コマンド <commands>` を使ってプロジェクトを初期化すると、
|
||||
Phinx はプロジェクトディレクトリーのルートに ``phinx.yml`` というデフォルトファイルを作成します。
|
||||
このファイルは、YAML データのシリアル化形式を使用します。
|
||||
|
||||
``--configuration`` コマンドラインオプションが与えられた場合、Phinx は指定されたファイルを
|
||||
ロードします。それ以外の場合は、 ``phinx.php`` 、 ``phinx.json`` または ``phinx.yml``
|
||||
を見つけて、最初に見つかったファイルを読み込みます。詳しくは、 :doc:`コマンド <commands>`
|
||||
の章をご覧下さい。
|
||||
|
||||
.. warning::
|
||||
|
||||
設定ファイルは、ウェブサーバー上の一般公開されているディレクトリーの外に保存してください。
|
||||
このファイルにはデータベースの信用情報が含まれており、
|
||||
誤ってプレーンテキストとして提供される可能性があります。
|
||||
|
||||
JSON ファイルと YAML ファイルは *パース* されますが、PHP ファイルは *インクルード* されています。
|
||||
つまり、こういうことです。
|
||||
|
||||
* 設定項目の配列を `return` する必要があります。
|
||||
* 変数スコープはローカルです。つまり、初期化ファイルが読み取ったり変更したりするグローバル変数を
|
||||
明示的に宣言する必要があります。
|
||||
* その標準出力は抑制されます。
|
||||
* JSON や YAML とは異なり、環境接続の詳細を省略し、代わりに初期化された PDO インスタンスを含む
|
||||
``connection`` を指定することができます。
|
||||
これは、マイグレーションがアプリケーションとやり取りしたり、同じ接続を共有したりする場合に便利です。
|
||||
ただし、Phinx は PDO 接続からデータベース名を推測できないため、データベース名を渡すことを
|
||||
忘れないでください。
|
||||
|
||||
::
|
||||
|
||||
<?php
|
||||
require 'app/init.php';
|
||||
|
||||
global $app;
|
||||
$pdo = $app->getDatabase()->getPdo();
|
||||
|
||||
return ['environments' =>
|
||||
[
|
||||
'default_database' => 'development',
|
||||
'development' => [
|
||||
'name' => 'devdb',
|
||||
'connection' => $pdo,
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
マイグレーションのパス
|
||||
----------------------
|
||||
|
||||
最初のオプションは、マイグレーションのディレクトリーへのパスを指定します。
|
||||
デフォルトでは Phinx は ``%%PHINX_CONFIG_DIR%%/db/migrations`` を使用します。
|
||||
|
||||
.. note::
|
||||
|
||||
``%%PHINX_CONFIG_DIR%%`` は特別なトークンで、
|
||||
``phinx.yml`` ファイルが保存されているルートディレクトリーに自動的に置き換えられます。
|
||||
|
||||
デフォルトの ``%%PHINX_CONFIG_DIR%%/db/migrations`` を上書きするには、
|
||||
yaml 設定に次の行を追加する必要があります。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: /your/full/path
|
||||
|
||||
また、設定内の配列を使用して複数のマイグレーションパスを提供することもできます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations:
|
||||
- application/module1/migrations
|
||||
- application/module2/migrations
|
||||
|
||||
パスに ``%%PHINX_CONFIG_DIR%%`` トークンを使うこともできます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: '%%PHINX_CONFIG_DIR%%/your/relative/path'
|
||||
|
||||
マイグレーションは ``glob`` で取り込まれるので、複数のディレクトリーのパターンを定義することができます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
migrations: '%%PHINX_CONFIG_DIR%%/module/*/{data,scripts}/migrations'
|
||||
|
||||
カスタムベースクラス
|
||||
---------------------
|
||||
|
||||
デフォルトでは、すべてのマイグレーションは Phinx の ``AbstractMigration`` クラスを継承します。
|
||||
これは、設定の中で ``migration_base_class`` を設定することによって、 ``AbstractMigration``
|
||||
を継承したカスタムクラスに設定することができます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
migration_base_class: MyMagicalMigration
|
||||
|
||||
シードのパス
|
||||
------------
|
||||
|
||||
2番目のオプションは、シードディレクトリーへのパスを指定します。
|
||||
デフォルトでは Phinx は ``%%PHINX_CONFIG_DIR%%/db/seeds`` を使用します。
|
||||
|
||||
.. note::
|
||||
|
||||
``%%PHINX_CONFIG_DIR%%`` は特別なトークンで、
|
||||
``phinx.yml`` ファイルが保存されているルートディレクトリーに自動的に置き換えられます。
|
||||
|
||||
デフォルトの ``%%PHINX_CONFIG_DIR%%/db/seeds`` を上書きするには、
|
||||
yaml 設定に以下を追加する必要があります。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds: /your/full/path
|
||||
|
||||
また、設定内で配列を使用して複数のシードパスを指定することもできます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds:
|
||||
- /your/full/path1
|
||||
- /your/full/path2
|
||||
|
||||
パスに ``%%PHINX_CONFIG_DIR%%`` トークンを使うこともできます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
paths:
|
||||
seeds: '%%PHINX_CONFIG_DIR%%/your/relative/path'
|
||||
|
||||
環境
|
||||
----
|
||||
|
||||
Phinx の主な機能の1つは、複数のデータベース環境をサポートすることです。Phinx を使用して、
|
||||
開発環境でマイグレーションを作成した後、本番環境で同じマイグレーションを実行することができます。
|
||||
環境は ``environments`` 以下にネストされたコレクションで指定されます。例:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_database: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: localhost
|
||||
name: production_db
|
||||
user: root
|
||||
pass: ''
|
||||
port: 3306
|
||||
charset: utf8
|
||||
collation: utf8_unicode_ci
|
||||
|
||||
上記は ``production`` と呼ばれる新しい環境を定義します。
|
||||
|
||||
複数の開発者が同じプロジェクトで作業し、それぞれが異なる環境を持つ状況
|
||||
(例えば、 ``<environment type>-<developer name>-<machine name>`` のような規約)、
|
||||
または、別々の目的(ブランチ、テストなど)のために別々の環境を持つ必要がある場合には、
|
||||
環境変数 `PHINX_ENVIRONMENT` を使用して yaml ファイルのデフォルト環境を上書きします。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
export PHINX_ENVIRONMENT=dev-`whoami`-`hostname`
|
||||
|
||||
テーブルのプレフィクスとサフィックス
|
||||
------------------------------------
|
||||
|
||||
テーブルのプレフィックスとサフィックスを定義することができます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
development:
|
||||
....
|
||||
table_prefix: dev_
|
||||
table_suffix: _v1
|
||||
testing:
|
||||
....
|
||||
table_prefix: test_
|
||||
table_suffix: _v2
|
||||
|
||||
ソケット接続
|
||||
------------
|
||||
|
||||
MySQL アダプターを使用する場合、ネットワーク接続の代わりにソケットを使用することもできます。
|
||||
ソケットのパスは ``unix_socket`` で設定されます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_database: development
|
||||
production:
|
||||
adapter: mysql
|
||||
name: production_db
|
||||
user: root
|
||||
pass: ''
|
||||
unix_socket: /var/run/mysql/mysql.sock
|
||||
charset: utf8
|
||||
|
||||
外部変数
|
||||
--------
|
||||
|
||||
Phinx は ``PHINX_`` というプレフィックスが付いた環境変数を自動的に取得し、
|
||||
設定ファイルのトークンとして利用できるようにします。
|
||||
トークンは変数とまったく同じ名前になりますが、どちらの側にも2つの
|
||||
``%%`` のシンボルをラップすることによってアクセスする必要があります。
|
||||
例: ``%%PHINX_DBUSER%%`` 。これは、秘密のデータベース資格情報をバージョン管理システムではなく
|
||||
サーバーに直接格納する場合に特に便利です。この機能は、次の例で簡単に実証できます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
default_migration_table: phinxlog
|
||||
default_database: development
|
||||
production:
|
||||
adapter: mysql
|
||||
host: '%%PHINX_DBHOST%%'
|
||||
name: '%%PHINX_DBNAME%%'
|
||||
user: '%%PHINX_DBUSER%%'
|
||||
pass: '%%PHINX_DBPASS%%'
|
||||
port: 3306
|
||||
charset: utf8
|
||||
|
||||
サポートするアダプター
|
||||
----------------------
|
||||
|
||||
Phinx は現在、次のデータベースアダプターをネイティブにサポートしています。
|
||||
|
||||
* `MySQL <http://www.mysql.com/>`_: ``mysql`` アダプターを指定。
|
||||
* `PostgreSQL <http://www.postgresql.org/>`_: ``pgsql`` アダプターを指定。
|
||||
* `SQLite <http://www.sqlite.org/>`_: ``sqlite`` アダプターを指定。
|
||||
* `SQL Server <http://www.microsoft.com/sqlserver>`_: ``sqlsrv`` アダプターを指定。
|
||||
|
||||
SQLite
|
||||
~~~~~~
|
||||
|
||||
SQLite データベースを宣言すると、単純化された構造が使用されます。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
environments:
|
||||
development:
|
||||
adapter: sqlite
|
||||
name: ./data/derby
|
||||
testing:
|
||||
adapter: sqlite
|
||||
memory: true # *任意* の値で memory を設定すると、 name が上書きされます
|
||||
|
||||
SQL Server
|
||||
~~~~~~~~~~
|
||||
|
||||
``sqlsrv`` アダプターを使用して名前付きインスタンスに接続するときは、
|
||||
SQL Server が自動的にポートをネゴシエートするので、 ``port`` 設定を省略してください。
|
||||
さらに、 ``charset: utf8`` を省略するか、SQL Server の UTF8 に対応する
|
||||
``charset: 65001`` に変更してください。
|
||||
|
||||
カスタムアダプター
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
``Phinx\\Db\\Adapter\\AdapterInterface`` の実装を ``AdapterFactory`` で登録することで
|
||||
カスタムアダプターを提供できます。
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$name = 'fizz';
|
||||
$class = 'Acme\Adapter\FizzAdapter';
|
||||
|
||||
AdapterFactory::instance()->registerAdapter($name, $class);
|
||||
|
||||
アダプターは `$app->run()` が呼び出される前にいつでも登録することができます。
|
||||
通常は `bin/phinx` によって呼び出されます。
|
||||
|
||||
エイリアス
|
||||
----------
|
||||
|
||||
テンプレート作成クラス名は、別名をつけて :doc:`create コマンド<commands>` の
|
||||
``--class`` コマンドラインオプションで使うことができます。
|
||||
|
||||
エイリアス化されたクラスは ``Phinx\Migration\CreationInterface`` インタフェースを実装する
|
||||
必要があります。
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
aliases:
|
||||
permission: \Namespace\Migrations\PermissionMigrationTemplateGenerator
|
||||
view: \Namespace\Migrations\ViewMigrationTemplateGenerator
|
||||
|
||||
バージョンの順序
|
||||
----------------
|
||||
|
||||
マイグレーションの状態をロールバックまたは表示するとき、Phinx は ``version_order``
|
||||
オプションに従って実行されたマイグレーションを処理します。これは次の値をとります。
|
||||
|
||||
* ``creation`` (デフォルト): マイグレーションはファイル名の一部でもある作成時間順に並べ替えられます。
|
||||
* ``execution``: マイグレーションは実行時間(開始時間とも呼ばれます)によって順序付けられます。
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
コンテンツ
|
||||
===========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: Phinx
|
||||
|
||||
index
|
||||
migrations
|
||||
seeding
|
||||
commands
|
||||
configuration
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
Phinx マイグレーション
|
||||
######################
|
||||
|
||||
Phinx は、データベースのマイグレーションを管理するためのスタンドアロンのコマンドラインツールです。
|
||||
CakePHP の公式 Migrations プラグインはこのツールに基づいています。
|
||||
|
||||
Phinx は、あなたの PHP アプリケーションのデータベースマイグレーションを超簡単に管理できます。
|
||||
5分以内に、Composer を使用して Phinx をインストールし、最初のデータベースマイグレーションを作成できます。
|
||||
Phinx は、データベース ORM システムやアプリケーションフレームワークを使わずに、マイグレーションします。
|
||||
|
||||
はじめに
|
||||
============
|
||||
|
||||
良い開発者は常に SCM システムを使ってコードをバージョン管理します。それでは、なぜ、
|
||||
データベーススキーマについても同じことをしないのでしょうか?
|
||||
|
||||
Phinx は、開発者がデータベースを明確かつ簡潔な方法で変更および操作できるようにします。
|
||||
これは手作業で SQL を書くことを避け、代わりに PHP コードを使用してマイグレーションを作成するための
|
||||
強力な API を提供します。開発者は、好みの SCM システムを使用して、これらのマイグレーションを
|
||||
バージョン管理することができます。これにより、異なるデータベースシステム間で Phinx のマイグレーションを
|
||||
移植可能にします。Phinx はどのマイグレーションが実行されたかを把握しているので、
|
||||
データベースの状態については心配する必要はなく、より良いソフトウェアを構築することに
|
||||
集中することができます。
|
||||
|
||||
ゴール
|
||||
=======
|
||||
|
||||
Phinx は以下の目標を念頭に置いて開発されました。
|
||||
|
||||
* 最も普及しているデータベースベンダー間の可搬性。
|
||||
* PHP フレームワークに依存しない。
|
||||
* シンプルなインストール手順。
|
||||
* 使いやすいコマンドライン操作。
|
||||
* 他のさまざまな PHP ツール(Phing、PHPUnit)やウェブフレームワークとの統合。
|
||||
|
||||
インストール
|
||||
=============
|
||||
|
||||
Phinx は、PHP の依存関係管理のためのツールである Composer を使用してインストールする必要があります。
|
||||
詳しくは `Composer <https://getcomposer.org/>`_ のウェブサイトを見てください。
|
||||
|
||||
.. note::
|
||||
|
||||
Phinx には少なくともPHP 5.4(またはそれ以降)が必要です。
|
||||
|
||||
Phinx をインストールするには、Composer を使用する必要があります。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
php composer.phar require robmorgan/phinx
|
||||
|
||||
適切なパーミッションを持つ ``db/migrations`` 構造に従って、プロジェクト内にフォルダーを作成します。
|
||||
これは、マイグレーションファイルが存在し、書き込み可能である場所です。
|
||||
|
||||
今、プロジェクト内から Phinx を実行できるようになりました。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
vendor/bin/phinx init
|
||||
|
||||
+1293
File diff suppressed because it is too large.
Load diff
+214
@@ -0,0 +1,214 @@
|
||||
.. index::
|
||||
single: Database Seeding
|
||||
|
||||
データベースの初期データ投入
|
||||
============================
|
||||
|
||||
バージョン0.5.0 では、Phinx はデータベースにテストデータをシードするためのサポートを導入しました。
|
||||
シードクラスは、作成済みのデータをデータベースに簡単に投入するための優れた方法です。
|
||||
デフォルトでは ``seeds`` ディレクトリーに保存されます。 ただし、このパスは設定ファイルで変更できます。
|
||||
|
||||
.. note::
|
||||
|
||||
データベースのシードは完全にオプションで、
|
||||
Phinx はデフォルトで ``seeds`` ディレクトリーを作成しません。
|
||||
|
||||
シードクラスの新規作成
|
||||
----------------------
|
||||
|
||||
Phinx には、新しいシードクラスを簡単に生成するコマンドが含まれています。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:create UserSeeder
|
||||
|
||||
複数のシードのパスを指定した場合は、新しいシードクラスを作成するパスを選択するように求められます。
|
||||
|
||||
以下は、スケルトンテンプレートを元にしています。 ::
|
||||
|
||||
<?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:
|
||||
* http://docs.phinx.org/en/latest/seeding.html
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
AbstractSeed クラス
|
||||
-------------------
|
||||
|
||||
すべての Phinx のシードは ``AbstractSeed`` クラスを継承します。
|
||||
このクラスは、シードクラスを作成するために必要なサポートを提供します。
|
||||
シードクラスは主にテストデータの挿入に使用されます。
|
||||
|
||||
run メソッド
|
||||
~~~~~~~~~~~~
|
||||
|
||||
run メソッドは、 `seed:run` コマンドを実行すると、Phinx によって自動的に呼び出されます。
|
||||
このメソッドを使用してテストデータを挿入してください。
|
||||
|
||||
.. note::
|
||||
|
||||
マイグレーションとは異なり、Phinx はどのシードクラスが実行されたかを把握していません。
|
||||
これは、データベースシーダーを繰り返し実行できることを意味します。
|
||||
開発時にはこのことに留意してください。
|
||||
|
||||
データの挿入
|
||||
------------
|
||||
|
||||
Table オブジェクトの使用
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
シードクラスは、使い慣れた ``Table`` オブジェクトを使ってデータを挿入することもできます。
|
||||
シードクラス内から ``table()`` メソッドを呼び出し、 ``insert()`` メソッドを使用して
|
||||
データを挿入することで、Table オブジェクトのインスタンスを取得できます。 ::
|
||||
|
||||
<?php
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class PostsSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$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)
|
||||
->save();
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
``save()`` メソッドを呼び出して、データをテーブルにコミットする必要があります。
|
||||
Phinx はデータをバッファリングします。
|
||||
|
||||
Faker ライブラリーとの統合
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
シードクラスですばらしい `Faker ライブラリー <https://github.com/fzaninotto/Faker>`_
|
||||
を使うのは簡単です。Composer を使用してインストールするだけです。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ composer require fzaninotto/faker
|
||||
|
||||
そして、シードクラスの中で、それを使用してください。 ::
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class UserSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$faker = Faker\Factory::create();
|
||||
$data = [];
|
||||
for ($i = 0; $i < 100; $i++) {
|
||||
$data[] = [
|
||||
'username' => $faker->userName,
|
||||
'password' => sha1($faker->password),
|
||||
'password_salt' => sha1('foo'),
|
||||
'email' => $faker->email,
|
||||
'first_name' => $faker->firstName,
|
||||
'last_name' => $faker->lastName,
|
||||
'created' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
|
||||
$this->insert('users', $data);
|
||||
}
|
||||
}
|
||||
|
||||
テーブルのデータ消去
|
||||
--------------------
|
||||
|
||||
データを挿入することに加えて、Phinx は SQL の ``TRUNCATE`` コマンドを使って
|
||||
テーブルを空にすることを容易にします。 ::
|
||||
|
||||
<?php
|
||||
|
||||
use Phinx\Seed\AbstractSeed;
|
||||
|
||||
class UserSeeder extends AbstractSeed
|
||||
{
|
||||
public function run()
|
||||
{
|
||||
$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)
|
||||
->save();
|
||||
|
||||
// テーブルを空にします
|
||||
$posts->truncate();
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
SQLite は ``TRUNCATE`` コマンドをネイティブにサポートしていないので、 ``DELETE FROM``
|
||||
が使用されています。テーブルのデータ消去後、 ``VACUUM`` コマンドを呼び出すことをお勧めします。
|
||||
Phinx はこれを自動的には行いません。
|
||||
|
||||
シードクラスの実行
|
||||
------------------
|
||||
|
||||
これは簡単な部分です。データベースをシードするには、 ``seed:run`` コマンドを使います。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run
|
||||
|
||||
デフォルトでは、Phinx は利用可能なすべてのシードクラスを実行します。
|
||||
特定のクラスを実行したい場合は、 ``-s`` パラメーターを使ってそのクラスの名前を渡します。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run -s UserSeeder
|
||||
|
||||
複数のシーダーを実行することもできます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run -s UserSeeder -s PermissionSeeder -s LogSeeder
|
||||
|
||||
``-v`` パラメーターを使用して、より詳細な出力を表示することもできます。
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php vendor/bin/phinx seed:run -v
|
||||
|
||||
Phinx のシード機能は、テストデータをデータベースに簡単かつ繰り返し挿入するための
|
||||
簡単なメカニズムを提供します。
|
||||
Reference in new issue
Block a user