Last active
November 9, 2020 14:23
-
-
Save wastemobile/ef7bfff8e2a7fcb2ead0 to your computer and use it in GitHub Desktop.
使用Git與Git Hooks同步專案MySQL資料庫
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
使用 Git 與 Git Hooks 同步 MySQL 資料庫 | |
===================================== | |
參考來源: [Synchronizing a MySQL Database with Git and Git Hooks](http://ben.kulbertis.org/2011/10/synchronizing-a-mysql-database-with-git-and-git-hooks/) | |
目前採用的方法,也是利用 Git Hooks,基本有兩個: | |
1. push-db:將本地異動推到遠端前運行,讓本地資料庫 => 遠端資料庫(pre-push)。 | |
2. pull-db:將遠端異動拉回本地後運行,讓遠端資料庫 => 本地資料庫(post-update)。 | |
這樣的 Scripts 必須使用的是 ssh 連線,並且要將帳號密碼寫在程序檔中,有一點安全疑慮。 | |
另一種方法,則是在本地使用 mysqldump 儲存檔案、加入 Git、同步,再把 mysqldump 的資料匯入資料庫。 | |
使用 `pre-commit` 可以在提交前就立即備份資料庫(會不會太頻繁?)。使用 `post-merge` 則可以在拉回遠端、合併完成之後,使用備份資料檔更新資料庫。 | |
Git 預設提供的範例檔共有: | |
- applypatch-msg | |
- commit-msg | |
- prepare-commit-msg | |
- pre-applypatch | |
- pre-commit | |
- pre-push | |
- pre-rebase | |
- post-update | |
- update | |
[更多](http://githooks.com) | |
## 提交之前執行 [pre-commit](https://github.com/git/git/blob/master/templates/hooks--pre-commit.sample) | |
直接編輯 `/path/.git/hooks/pre-commit`,因為是在提交之前備份資料庫、添加到 Git 暫存區,因此會自動在此次提交中加入。為了讓程序能在所有環境中運行,`mysqldump` 與 `mysql` 都必須在系統上有正確對應(特別是使用 MAMP 時);也可以在自己的執行檔目錄下,建立執行檔的對應。 | |
``` | |
#!/bin/sh | |
mysqldump -u [mysql user] -p[mysql password] --skip-extended-insert [database] > /path/to/your/repo/[database].sql | |
cd /path/to/your/repo | |
git add [database].sql | |
``` | |
要特別注意: `-u` 與使用者名稱之間有空白,但 `-p` 與密碼之間「沒有」。而 `--skip-extended-insert` 是讓 mysqldump 產生的備份檔一行一筆資料(不壓縮在同一行),雖然可能檔案會大一些,但比較不會出問題。 | |
記得替檔案加上執行權限: | |
``` | |
chmod +x /path/to/your/repo/.git/hooks/pre-commit | |
``` | |
## 合併之後執行 [post-merge](https://github.com/git/git/blob/master/Documentation/githooks.txt#L167) | |
編輯 `/path/.git/hooks/post-merge`,把同步完的資料庫備份檔匯回資料庫。 | |
``` | |
#!/bin/sh | |
mysql -u [mysql user] -p[mysql password] [database] < /path/to/your/repo/[database].sql | |
``` | |
Done. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment