在 CI 測試環境中使用 SQLite

Why SQLite?In Memory 模式

SQLite 可開啟 In Memory 模式在記憶體中操作資料庫,程式關閉後,記憶體內的 SQLite 資料庫也會清空,相當適合測試環境使用(無副作用)。

建置步驟:

  • 產生假資料,先匯出 MySQL 備份檔
  • 將 MySQL 的備份檔轉換成 SQLite 格式的備份檔。
  • 最後再將 SQLite 備份檔配置到 CodeIgniter 的 database.php 設定檔中。
config/database.php
if (ENVIRONMENT == "testing") {
    $db['main'] = [
        'dsn'          => ':memory:',                             // 啟動 In Memory 模式
        'hostname'     => '',                                     // 不需填寫 
        'username'     => '',                                     // 不需填寫
        'password'     => '',                                     // 不需填寫
        'database'     => APPPATH . 'database/sqlite/sqlite.db',  // SQLite 備份檔案,絕對路徑。
        'dbdriver'     => 'sqlite3',                              // 使用 SQLite
        'dbprefix'     => '',
        'pconnect'     => false,
        'db_debug'     => (ENVIRONMENT !== 'production'),
        'cache_on'     => false,
        'cachedir'     => '',
        'char_set'     => 'utf8',
        'dbcollat'     => 'utf8_general_ci',
        'swap_pre'     => '',
        'autoinit'     => true,
        'encrypt'      => false,
        'compress'     => false,
        'stricton'     => false,
        'failover'     => [],
        'save_queries' => true,
    ];
}
建置完成 SQLite 後,即每次開啟 In Memory 模式時,都是以這份 SQLite 備份檔案為假資料操作資料庫。
以下提供轉換 Mysql To SQLite 備份檔案之工具「mysql2sqlite.sh」。

mysql2sqlite.sh

Converts MySQL dump to SQLite3 compatible dump

範例

  1. 匯出 MySQL DB
#mysqldump --skip-extended-insert --compact -u root -p DB_name > mysql\_dump.sql
or
#mysqldump --no-data -u root -p DB\_name > mysql\_dump.sql
  1. 使用 mysql2sqlite.sh 轉換 MySQL to SQLite3 DB
./mysql2sqlite mysql\_dump.sql | sqlite3 sqlite.db

留言

這個網誌中的熱門文章

Git Commit Message 這樣寫會更好,替專案引入規範與範例

Gitlab 合併請求 Merge Request 是什麼?

PHP OO 物件導向基礎教學