Files

140 lines
2.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 数据库迁移示例
这个目录包含了数据库迁移的示例SQL文件。
## 文件说明
```
examples/migrations/
├── migrations/ # 迁移文件目录
│ ├── 20240101000001_create_users_table.sql # 迁移SQL
│ └── 20240101000001_create_users_table.down.sql # 回滚SQL
└── README.md # 本文件
```
## 快速开始
### 在你的项目中使用
#### 1. 创建迁移工具
在项目根目录创建 `migrate.go`
```go
package main
import (
"log"
"os"
"git.toowon.com/jimmy/go-common/migration"
)
func main() {
command := "up"
if len(os.Args) > 1 {
command = os.Args[1]
}
err := migration.RunMigrationsFromConfigWithCommand("config.json", "migrations", command)
if err != nil {
log.Fatal(err)
}
}
```
#### 2. 创建迁移文件
```bash
# 创建目录
mkdir -p migrations
# 创建迁移文件(使用时间戳作为版本号)
vim migrations/20240101000001_create_users.sql
```
#### 3. 编写SQL
```sql
-- migrations/20240101000001_create_users.sql
CREATE TABLE users (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);
```
#### 4. 执行迁移
```bash
# 执行迁移
go run migrate.go up
# 查看状态
go run migrate.go status
# 回滚
go run migrate.go down
```
### 更简单:在应用启动时自动执行
在你的 `main.go` 中:
```go
import "git.toowon.com/jimmy/go-common/migration"
func main() {
// 一行代码,启动时自动迁移
migration.RunMigrationsFromConfig("config.json", "migrations")
// 继续启动应用
startServer()
}
```
## 配置方式
### 方式1配置文件
`config.json`:
```json
{
"database": {
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "password",
"database": "mydb"
}
}
```
### 方式2使用配置文件推荐
```bash
# 使用默认配置文件 config.json
go run migrate.go up
# 或指定配置文件路径
go run migrate.go up -config /path/to/config.json
```
**Docker 中**
```yaml
# docker-compose.yml
services:
app:
volumes:
# 挂载配置文件
- ./config.json:/app/config.json:ro
command: sh -c "go run migrate.go up && ./app"
```
**注意**:配置文件中的数据库主机应使用服务名(`db`),不是 `localhost`
## 更多信息
- [数据库迁移完整指南](../../MIGRATION.md) ⭐
- [详细功能文档](../../docs/migration.md)