Skip to content

Instantly share code, notes, and snippets.

@Fykec
Last active June 14, 2017 03:39
Show Gist options
  • Save Fykec/8c09a63371b49f702dde09db020bf725 to your computer and use it in GitHub Desktop.
Save Fykec/8c09a63371b49f702dde09db020bf725 to your computer and use it in GitHub Desktop.
Sqlite3 Migration Script
#!/usr/bin/env bash
## 数据库路径名
db_file="demo.db"
## 当前最新版本
cur_version=1
# 检查 sqlite3 命令行 工具是否已经安装
if ! [ -x "$(command -v sqlite3)" ]; then
echo 'Error: sqlite3 is not installed.' >&2
exit 1
fi
# 第一步检查数据库文件是否存在
## 不存在的情况
if ! test -e $db_file; then
### 检查 v[n].sql 是否存在,存在则直接创建新数据库,直接退出
if test -e "v"$cur_version".sql"; then
echo "int db with version "$cur_version
touch $db_file
sqlite3 $db_file < "v"$cur_version".sql"
exit 0;
fi
### 不存在v[n].sql, 就创建v1版本的数据库,然后升级
echo "int db with version 1"
touch $db_file
sqlite3 $db_file < "v1.sql"
fi
old_version=$(sqlite3 $db_file "pragma user_version;")
## 数据库已经最新不需要升级
if test $old_version = $cur_version; then
echo "db already at version "$cur_version
exit 0;
fi
## 数据库版本竟然比脚本里的大,出异常了,直接退出
if [ $old_version -gt $cur_version ]; then
echo "db version bigger than "$cur_version" why the version is "$old_version" ?"
exit -1;
fi
## 数据库升级,一个数据库版本m到n升级的过程就是,运行 v[m]tov[m+1].sql, v[m+1]tov[m+2].sql, 直到 v[n-1]tov[n].sql
from_version=$((old_version))
while [ $from_version -lt $cur_version ]
do
to_version=$(( from_version+1 ))
echo "update from version "$from_version" to "$to_version
sqlite3 $db_file < "v"$from_version"tov"$to_version".sql"
from_version=$to_version
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment