调整工具类的方法,优化方法调用及增加迁移工具及其用法

This commit is contained in:
2025-12-04 22:30:48 +08:00
parent de8fc13f18
commit 0650feb0d2
28 changed files with 3753 additions and 162 deletions

View File

@@ -0,0 +1,134 @@
# 数据库迁移示例
这个目录包含了数据库迁移的示例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环境变量Docker友好
```bash
DATABASE_URL="mysql://root:password@localhost:3306/mydb" go run migrate.go up
```
**Docker 中**
```yaml
# docker-compose.yml
services:
app:
environment:
DATABASE_URL: mysql://root:password@db:3306/mydb
command: sh -c "go run migrate.go up && ./app"
```
**注意**Docker 中使用服务名(`db`),不是 `localhost`
## 更多信息
- [数据库迁移完整指南](../../MIGRATION.md) ⭐
- [详细功能文档](../../docs/migration.md)