數據庫遷移?

遷移是一種有條理、有組織的方式更改數據庫的便捷方式。你可以手動編輯SQL的片段,然后你要負責告訴其他開發人員他們也需要去運行這段SQL。你還必須跟蹤下次部署時需要對生產機器運行哪些更改。

數據庫表**遷移**會跟蹤已經運行的遷移,因此您只需更新應用程序文件并調用$migration->current()以確定應運行哪些遷移。當前版本位于**application/Config/Migrations.php**中。

  • 遷移文件名
  • 創建遷移
  • 使用$currentVersion
    • 數據庫組
    • 命名空間
    • 用法示例
  • 命令行工具
  • 遷移參數
  • 類參考

遷移文件名?

每個遷移都按數字順序向前或向后運行,具體取決于所采用的方法。有兩種編號樣式可供選擇:

  • 順序:每個遷移按順序編號,從001開始。每個數字必須是三位數,并且序列中不得有任何間隙。(這是CodeIgniter 3.0之前的編號方案。)
  • 時間戳:使用創建遷移時的時間戳對每個遷移進行編號,格式為**YYYYMMDDHHIES**格式(例如**20121031100537**)。這有助于防止在團隊環境中工作時出現編號沖突,并且是CodeIgniter 3.0及更高版本中的首選方案。

可以使用*application/Config/Migrations.php*文件中的$type設置選擇所需的樣式。默認設置為時間戳。

無論您選擇使用哪種編號樣式,請在遷移文件前加上遷移編號,后跟下劃線和遷移的描述性名稱。例如:

  • 001_add_blog.php(順序編號)
  • 20121031100537_add_blog.php(時間戳編號)

創建遷移?

這將是新博客站點的首次遷移。所有遷移都在 application/Database/Migrations/ 目錄中,并命名,如 20121031100537_Add_blog.php。

<?php namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddBlog extends Migration
{

        public function up()
        {
                $this->forge->addField([
                        'blog_id'          => [
                                'type'           => 'INT',
                                'constraint'     => 5,
                                'unsigned'       => true,
                                'auto_increment' => true,
                        ],
                        'blog_title'       => [
                                'type'           => 'VARCHAR',
                                'constraint'     => '100',
                        ],
                        'blog_description' => [
                                'type'           => 'TEXT',
                                'null'           => true,
                        ],
                ]);
                $this->forge->addKey('blog_id', true);
                $this->forge->createTable('blog');
        }

        public function down()
        {
                $this->forge->dropTable('blog');
        }
}

然后在 application/Config/Migrations.php 中設置 $currentVersion = 20121031100537;。

數據庫連接和數據庫Forge類都可以通過 $this->db和$this->forge分別使用。

或者,你可以使用命令行調用來生成框架遷移文件。請參閱下面的更多細節。

使用$currentVersion?

$currentVersion設置允許你標記應用程序命名空間應設置的位置。這對于在生產環境中使用尤其有用。在你的應用程序中,你始終可以將遷移更新到當前版本,而不是最新版本,以確保生產和登臺服務器正在運行正確的架構。在開發服務器上,你可以為尚未準備好生產的代碼添加其他遷移。通過使用該latest()方法,你可以確保你的開發機器始終運行前沿架構。

數據庫組?

只能針對單個數據庫組運行遷移。如果 在application/Config/Database.php 中定義了多個組 ,則它將針對該$defaultGroup同一配置文件中指定的組運行。有時你可能需要為不同的數據庫組使用不同的模式。也許你有一個用于所有常規站點信息的數據庫,而另一個數據庫用于關鍵任務數據。通過$DBGroup在遷移上設置屬性,可以確保僅針對正確的組運行遷移。此名稱必須與數據庫組的名稱完全匹配:

class Migration_Add_blog extends \CodeIgniter\Database\Migration
{
  protected $DBGroup = 'alternate_db_group';

  public function up() { . . . }

  public function down() { . . . }
}

命名空間?

遷移庫可以自動掃描你在 application/Config/Autoload.php 中定義的所有名稱空間 及其$psr4屬性以匹配目錄名稱。它將包括它在Database/Migrations中找到的所有遷移。

每個命名空間都有自己的版本序列,這將幫助您升級和降級每個模塊(命名空間),而不會影響其他命名空間。

例如,假設我們在Autoload配置文件中定義了以下命名空間:

$psr4 = [
        'App'       => APPPATH,
        'MyCompany' => ROOTPATH.'MyCompany'
];

這將查找位于**APPPATH/Database/Migrations**和**ROOTPATH/Database/Migrations**的任何遷移。這使得在可重用的模塊化代碼套件中包含遷移變得簡單。

用法示例?

在此示例中,一些簡單的代碼放在 application/Controllers/Migrate.php 中以更新架構:

<?php

class Migrate extends \CodeIgniter\Controller
{

        public function index()
        {
                $migrate = \Config\Services::migrations();

                try
                {
                $migrate->current();
                }
                catch (\Exception $e)
                {
                  // Do something with the error here...
                }
        }

}

命令行工具?

CodeIgniter附帶了幾個:doc:commands </cli/cli_commands>,它們可以從命令行獲得,以幫助你處理遷移。這些工具不需要使用遷移,但可能會使那些希望使用它們的人更容易。這些工具主要提供對MigrationRunner類中可用的相同方法的訪問。

migrate

Migrates a database group with all available migrations:

> php spark migrate

You can use (migrate) with the following options:

  • -g - to chose database group, otherwise default database group will be used.
  • -n - to choose namespace, otherwise (App) namespace will be used.
  • -all - to migrate all namespaces to the latest migration

This example will migrate Blog namespace with any new migrations on the test database group:

> php spark migrate -g test -n Blog

When using the -all option, it will scan through all namespaces attempting to find any migrations that have not been run. These will all be collected and then sorted as a group by date created. This should help to minimize any potential conflicts between the main application and any modules.

rollback

回滾所有遷移,將所有數據庫組轉為空白平板,有效遷移0:

> php spark migrate:rollback

你可以使用(rollback)以下選項:

  • (-g)選擇數據庫組,否則將使用默認數據庫組。
  • (-n)選擇名稱空間,否則將使用(App)名稱空間。
  • (all)將所有名稱空間遷移到最新的遷移

refresh

首先回滾所有遷移,然后遷移到最新版本,刷新數據庫狀態:

> php spark migrate:refresh

你可以使用(refresh)以下選項:

  • (-g)選擇數據庫組,否則將使用默認數據庫組。
  • (-n)選擇名稱空間,否則將使用(App)名稱空間。
  • (all)將所有名稱空間遷移到最新的遷移

status

顯示所有遷移的列表及其運行的日期和時間,如果尚未運行,則顯示’–’:

> php spark migrate:status
Filename               Migrated On
First_migration.php    2016-04-25 04:44:22

你可以使用(status)以下選項:

  • (-g)選擇數據庫組,否則將使用默認數據庫組。

make:migration

Creates a skeleton migration file in app/Database/Migrations. It automatically prepends the current timestamp. The class name it creates is the Pascal case version of the filename.

> php spark make:migration <class> [options]

You can use (make:migration) with the following options:

  • -n - to choose namespace, otherwise the value of APP_NAMESPACE will be used.
  • -force - If a similarly named migration file is present in destination, this will be overwritten.

遷移參數?

以下是 app/Config/Migrations.php 中提供的所有遷移配置選項的表。

參數 默認值 可選項 描述
enabled true true / false 啟用或者禁用遷移
table migrations None 用于存儲當前版本的數據庫表名
timestampFormat Y-m-d-His_   The format to use for timestamps when creating a migration.

類參考?

class CodeIgniterDatabaseMigrationRunner?
current($group)?
參數:
  • $group (mixed) – database group name, if null (App) namespace will be used.
返回:

TRUE if no migrations are found, current version string on success, FALSE on failure

返回類型:

mixed

Migrates up to the current version (whatever is set for $currentVersion in application/Config/Migrations.php).

findMigrations()?
返回:An array of migration files
返回類型:array

An array of migration filenames are returned that are found in the path property.

latest($namespace, $group)?
參數:
  • $namespace (mixed) – application namespace, if null (App) namespace will be used.
  • $group (mixed) – database group name, if null default database group will be used.
返回:

Current version string on success, FALSE on failure

返回類型:

mixed

This works much the same way as current() but instead of looking for the $currentVersion the Migration class will use the very newest migration found in the filesystem.

latestAll($group)?
參數:
  • $group (mixed) – database group name, if null default database group will be used.
返回:

TRUE on success, FALSE on failure

返回類型:

mixed

This works much the same way as latest() but instead of looking for one namespace, the Migration class will use the very newest migration found for all namespaces.

version($target_version, $namespace, $group)?
參數:
  • $namespace (mixed) – application namespace, if null (App) namespace will be used.
  • $group (mixed) – database group name, if null default database group will be used.
  • $target_version (mixed) – Migration version to process
返回:

TRUE if no migrations are found, current version string on success, FALSE on failure

返回類型:

mixed

Version can be used to roll back changes or step forwards programmatically to specific versions. It works just like current() but ignores $currentVersion.

$migration->version(5);
setNamespace($namespace)?
參數:
  • $namespace (string) – application namespace.
返回:

The current MigrationRunner instance

返回類型:

CodeIgniterDatabaseMigrationRunner

Sets the path the library should look for migration files:

$migration->setNamespace($path)
          ->latest();
setGroup($group)?
參數:
  • $group (string) – database group name.
返回:

The current MigrationRunner instance

返回類型:

CodeIgniterDatabaseMigrationRunner

Sets the path the library should look for migration files:

$migration->setNamespace($path)
          ->latest();