Phinx 數(shù)據(jù)庫遷移工具的安裝和使用

簡介

Phinx 可以讓開發(fā)者簡潔的修改和維護數(shù)據(jù)庫。 它避免了人為的手寫 SQL 語句,它使用強大的 PHP API 去管理數(shù)據(jù)庫遷移。開發(fā)者可以使用版本控制管理他們的數(shù)據(jù)庫遷移。 Phinx 可以方便的進行不同數(shù)據(jù)庫之間數(shù)據(jù)遷移。還可以追蹤到哪些遷移腳本被執(zhí)行,開發(fā)者可以不再擔(dān)心數(shù)據(jù)庫的狀態(tài)從而更加關(guān)注如何編寫出更好的系統(tǒng)。

下載安裝

系統(tǒng)環(huán)境

Phinx 至少需要PHP 5.4 或更新的版本

  • 使用 Composer 進行安裝 Phinx:
$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar require robmorgan/phinx
$ php composer.phar install

此時會生成vendor 文件夾,說明安裝完成。

  • 在你項目目錄/data/www/test/中創(chuàng)建目錄 db/migrations ,并給予充足權(quán)限。這個目錄將是你遷移腳本放置的地方,并且應(yīng)該被設(shè)置為可寫權(quán)限。

  • 安裝后,Phinx 現(xiàn)在可以在你的項目中執(zhí)行初始化(注意
    :此時的vendor文件在目錄/data/www/test/下)
    init 命令用來Phinx初始化整個項目的時候使用。命令會生成一個phinx.yml 文件在項目根目錄

$ vendor/bin/phinx init

此時生成phinx.yml文件

$ vim phinx.yml
paths:
    migrations: 'test/db/migrations'
    seeds: 'test/db/seeds'

environments:
    default_migration_table: phinxlog
    default_database: development
    production:
        adapter: mysql
        host: localhost
        name: production_db
        user: root
        pass: ''
        port: 3306
        charset: utf8

    development:
        adapter: mysql
        host: localhost
        name: development_db
        user: root
        pass: ''
        port: 3306
        charset: utf8

    testing:
        adapter: mysql
        host: localhost
        name: testing_db
        user: root
        pass: ''
        port: 3306
        charset: utf8

version_order: creation

創(chuàng)建遷移腳本
create 命令用來創(chuàng)建遷移腳本文件。需要一個參數(shù):腳本名。遷移腳本命名應(yīng)該保持 駝峰命名法

$ vendor/bin/phinx create MyNewMigrate
Phinx by CakePHP - https://phinx.org. 0.10.5

using config file ./phinx.yml
using config parser yaml
using migration paths
 - /data/www/test/test/db/migrations
using seed paths
using migration base class Phinx\Migration\AbstractMigration
using default template
created test/db/migrations/20180808155721_my_new_migrate.php

編輯腳本

$ vim test/db/migrations/20180808155721_my_new_migrate.php
<?php


use Phinx\Migration\AbstractMigration;

class MyNewMigrate extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    addCustomColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Any other destructive changes will result in an error when trying to
     * rollback the migration.
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        // create the table
        $table = $this->table('user_logins');
        $table->addColumn('user_id', 'integer')
              ->addColumn('created', 'datetime')
              ->create();
    }
}

執(zhí)行腳本

$ vendor/bin/phinx migrate -e production
Phinx by CakePHP - https://phinx.org. 0.10.5

using config file ./phinx.yml
using config parser yaml
using migration paths
 - /data/www/test/test/db/migrations
using seed paths
using environment production
using adapter mysql
using database goods

 == 20180808155721 MyNewMigrate: migrating
 == 20180808155721 MyNewMigrate: migrated 0.0390s

All Done. Took 0.0468s

Migrate 命令默認運行執(zhí)行所有腳本,可選指定環(huán)境
$ phinx migrate -e development
可以使用 --target 或者 -t 來指定執(zhí)行某個遷移腳本
$ phinx migrate -e development -t 20180808155721

進入數(shù)據(jù)庫查看,已經(jīng)生成user_logins表,并且還生成phinxlog操作記錄表。

mysql> show tables;
+--------------------+
| Tables_in_goods    |
+--------------------+
| phinxlog           |
| user_logins        |
+--------------------+

執(zhí)行查詢

可以使用 execute()query() 方法進行查詢。execute() 方法會返回查詢條數(shù),query() 方法會返回結(jié)果。

<?php

use Phinx\Migration\AbstractMigration;

class MyNewMigration extends AbstractMigration
{
    /**
     * Migrate Up.
     */
    public function up()
    {
        // execute()
        $count = $this->execute('DELETE FROM users'); // returns the number of affected rows

        // query()
        $rows = $this->query('SELECT * FROM users'); // returns the result as an array
    }

    /**
     * Migrate Down.
     */
    public function down()
    {

    }
}
  • Up 方法
    up方法會在Phinx執(zhí)行遷移命令時自動執(zhí)行,并且該腳本之前并沒有執(zhí)行過。你應(yīng)該將修改數(shù)據(jù)庫的方法寫在這個方法里。
  • Down 方法
    down方法會在Phinx執(zhí)行回滾命令時自動執(zhí)行,并且該腳本之前已經(jīng)執(zhí)行過遷移。你應(yīng)該將回滾代碼放在這個方法里。

字段操作

字段類型

biginteger
binary
boolean
date
datetime
decimal
float
integer
string
text
time
timestamp
uuid

另外,MySQL adapter 支持 enum 、set 、blob 和 json (json 需要 MySQL 5.7 或者更高)
Postgres adapter 支持 smallint 、json 、jsonb 和 uuid (需要 PostgresSQL 9.3 或者更高)

字段選項

  • 所有字段:
選項 描述
limit 為string設(shè)置最大長度
length limit 的別名
default 設(shè)置默認值
null 允許空
after 指定字段放置在哪個字段后面
comment 字段注釋
  • decimal 類型字段:
選項 描述
precision 和 scale 組合設(shè)置精度
scale和 precision 組合設(shè)置精度
signed 開啟或關(guān)閉 unsigned 選項(僅適用于 MySQL)
  • enum 和 set 類型字段:
選項 描述
values 用逗號分隔代表值

-integer 和 biginteger 類型字段:

選項 描述
identity 開啟或關(guān)閉自增長
signed 開啟或關(guān)閉 unsigned 選項(僅適用于 MySQL)
  • timestamp 類型字段:
選項 描述
default 設(shè)置默認值 (CURRENT_TIMESTAMP)
update 當(dāng)數(shù)據(jù)更新時的觸發(fā)動作 (CURRENT_TIMESTAMP)
timezone 開啟或關(guān)閉 with time zone 選項
  • boolean 類型字段:
選項 描述
signed 開啟或關(guān)閉 unsigned 選項(僅適用于 MySQL)
  • string 和text 類型字段:
選項 描述
collation 設(shè)置字段的 collation (僅適用于 MySQL)
encoding 設(shè)置字段的 encoding (僅適用于 MySQL)

索引操作

  • 使用 addIndex() 方法可以指定索引

Phinx 默認創(chuàng)建的是普通索引, 我們可以通過添加 unique 參數(shù)來指定唯一值。也可以使用 name 參數(shù)來制定索引名。

public function up()
    {
        $table = $this->table('users');
        $table->addColumn('email', 'string')
              ->addIndex(array('email'), array('unique' => true, 'name' => 'idx_users_email'))
              ->save();
    }
  • 調(diào)用 removeIndex() 方法可以刪除索引。必須一條條刪除
 public function up()
    {
        $table = $this->table('users');
        $table->removeIndex(array('email'));

        // alternatively, you can delete an index by its name, ie:
        $table->removeIndexByName('idx_users_email');
    }

數(shù)據(jù)庫 Seeding

Phinx 0.5.0 支持數(shù)據(jù)庫中使用seeding插入測試數(shù)據(jù)。Seed 類可以很方便的在數(shù)據(jù)庫創(chuàng)建以后填充數(shù)據(jù)。這些文件默認放置在 seeds 目錄(本文路徑:test/db/seeds),路徑可以在配置文件中修改

數(shù)據(jù)庫 seeding 是可選的,Phinx 并沒有默認創(chuàng)建 seeds 目錄,所以要提前創(chuàng)建seed目錄。

創(chuàng)建Seed類

Phinx 用下面命令創(chuàng)建一個新的 seed 類
$ php vendor/bin/phinx seed:create UserSeeder
如此會在目錄test/db/seeds下生成UserSeeder.php文件。
編輯UserSeeder.php文件,插入測試數(shù)據(jù)。

<?php

use Phinx\Seed\AbstractSeed;

class UserSeeder 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()
    {
        $data = array(
            array(
                'name'    => 'foo',
                'created_at' => date('Y-m-d H:i:s'),
            ),
            array(
                'name'    => 'bar',
                'created_at' => date('Y-m-d H:i:s'),
            )
        );

        $posts = $this->table('test');
        $posts->insert($data)
              ->save();
    }
}

提交數(shù)據(jù)時必須調(diào)用 save() 方法。Phinx 將緩存數(shù)據(jù)直到你調(diào)用save
所有 Phinx Seed 都繼承 AbstractSeed類。這個類提供了 Seed 需要的基礎(chǔ)方法。Seed 類 大部分用來插入測試數(shù)據(jù)。

Run 方法將在 Phinx 執(zhí)行 seed:run 時被自動調(diào)用。你可以將測試數(shù)據(jù)的插入寫在里面。

不像數(shù)據(jù)庫遷移,Phinx 并不記錄 seed 是否執(zhí)行過。這意味著 seeders 可以被重復(fù)執(zhí)行。

當(dāng)然也可以在run方法中寫原生Sql,如:

<?php

use Phinx\Seed\AbstractSeed;

class UserSeeder 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()
    {
        $sql = " insert into `test` set `name`='zhangsan', `created_at`='2018-08-15 23:00:00' ";
        $this-> execute($sql);
    }
}

執(zhí)行 Seed

這很簡單,當(dāng)注入數(shù)據(jù)庫時,只需要運行 seed:run 命令
$ php vendor/bin/phinx seed:run
默認Phinx會執(zhí)行所有 seed。 如果你想要指定執(zhí)行一個,只要增加 -s 參數(shù)并接 seed 的名字
$ php vendor/bin/phinx seed:run -s UserSeeder
也可以一次性執(zhí)行多個 seed
$ php vendor/bin/phinx seed:run -s UserSeeder -s PermissionSeeder -s LogSeeder
可以使用 -v 參數(shù)獲取更多提示信息
$ php vendor/bin/phinx seed:run -v
Phinx seed 提供了一個很簡單的機制方便開發(fā)者可重復(fù)的插入測試數(shù)據(jù)

清空數(shù)據(jù)表

可以用truncate來清空數(shù)據(jù)表

<?php

use Phinx\Seed\AbstractSeed;

class UserSeeder 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()
    {
        $posts = $this->table('test');
        $posts->truncate();
    }
}

命令

  • Rollback
    Rollback 命令用來回滾之前的遷移腳本。與 Migrate 命令相反。
    你可以使用 rollback 命令回滾上一個遷移腳本。不帶任何參數(shù)
    $ phinx rollback -e development
    使用 --target 或者 -t 回滾指定版本遷移腳本
    $ phinx rollback -e development -t 20120103083322
    指定版本如果設(shè)置為0則回滾所有腳本
    $ phinx rollback -e development -t 0
    可以使用 --date 或者 -d 參數(shù)回滾指定日期的腳本
$ 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參數(shù)強制回滾
$ phinx rollback -e development -t 0 -f

  • Status 命令
    Status 命令可以打印所有遷移腳本和他們的狀態(tài)。你可以用這個命令來看哪些腳本被運行過了
    $ phinx status -e development
    當(dāng)所有腳本都已經(jīng)執(zhí)行(up)該命令將退出并返回 0
    1:至少有一個回滾過的腳本(down)
    2:至少有一個未執(zhí)行的腳本

具體還有更多phinx數(shù)據(jù)庫遷移操作可以參考官網(wǎng)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 關(guān)于Mongodb的全面總結(jié) MongoDB的內(nèi)部構(gòu)造《MongoDB The Definitive Guide》...
    中v中閱讀 32,316評論 2 89
  • Awesome PHP 一個PHP資源列表,內(nèi)容包括:庫、框架、模板、安全、代碼分析、日志、第三方庫、配置工具、W...
    guanguans閱讀 6,163評論 0 47
  • Composer Repositories Composer源 Firegento - Magento模塊Comp...
    零一間閱讀 4,021評論 1 66
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,228評論 3 119
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,844評論 6 427

友情鏈接更多精彩內(nèi)容