跳到主要内容

Fiber 使用 sqlboiler

Github StackBlitz

🎯 Fiber + Sqlboiler 示例

👀 使用方法

1. 运行 Postgres

$ docker compose build
$ docker compose up

2. 等待 1-2 分钟

[+] Running 2/0
✔ Network sqlboiler_default Created 0.0s
✔ Container postgres Created 0.0s
Attaching to postgres
postgres |
postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres |
postgres | 2023-09-22 01:09:46.453 UTC [1] LOG: starting PostgreSQL 16.0 (Debian 16.0-1.pgdg120+1) on aarch64-unknown-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
postgres | 2023-09-22 01:09:46.453 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres | 2023-09-22 01:09:46.453 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres | 2023-09-22 01:09:46.454 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres | 2023-09-22 01:09:46.461 UTC [30] LOG: database system was shut down at 2023-09-22 01:09:44 UTC
postgres | 2023-09-22 01:09:46.468 UTC [1] LOG: database system is ready to accept connections

3. 你需要迁移数据库。

🎯 这是一个“数据库优先”的 ORM,而不是“代码优先”(如 gorm/gorp)。这意味着你必须首先创建数据库 schema。
🎯 我使用了 golang-migrate 来进行迁移。
1. 创建迁移文件
$ migrate create -ext sql -dir ./migrations -seq create_initial_table
sqlboiler/migrations/000001_create_initial_table.up.sql
sqlboiler/migrations/000001_create_initial_table.up.sql
2. 迁移
$ migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up
2023/09/22 20:00:00 Start buffering 1/u create_initial_table
2023/09/22 20:00:00 Read and execute 1/u create_initial_table
2023/09/22 20:00:00 Finished 1/u create_initial_table (read 24.693541ms, ran 68.30925ms)
2023/09/22 20:00:00 Finished after 100.661625ms
2023/09/22 20:00:00 Closing source and database
3. 回滚迁移
$ migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down
2023/09/22 20:00:00 Are you sure you want to apply all down migrations? [y/N]
y
2023/09/22 20:00:00 Applying all down migrations
2023/09/22 20:00:00 Start buffering 1/d create_initial_table
2023/09/22 20:00:00 Read and execute 1/d create_initial_table
2023/09/22 20:00:00 Finished 1/d create_initial_table (read 39.681125ms, ran 66.220125ms)
2023/09/22 20:00:00 Finished after 1.83152475s

4. 使用 sqlboiler

1. 安装
# Go 1.16 and above:
$ go install github.com/volatiletech/sqlboiler/v4@latest
$ go install github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-psql@latest
2. 创建配置文件
🎯 配置文件应命名为 sqlboiler.toml
示例
output   = "models"
wipe = true
no-tests = true
add-enum-types = true

[psql]
dbname = "fiber_demo"
host = "localhost"
port = 5432
user = "user"
pass = "password"
schema = "schema"
blacklist = ["migrations", "other"]
3. 创建模型
🎯 创建指向要生成模型的数据库的配置文件后,我们可以调用 sqlboiler 命令行工具。
$ sqlboiler psql
models/
├── author.go
├── boil_queries.go
├── boil_table_names.go
├── boil_types.go
├── boil_view_names.go
├── post.go
├── schema_migrations.go