Install
https://gobuffalo.io/documentation/database/soda/
Tạo database
- Cách 1: Sử dụng file
database.yml
:Sau khi tạo file database.yml, ta chạy lệnh1
2
3
4
5
6
7development:
dialect: postgres
database: myapp_development
user: postgres
password: postgres
host: 127.0.0.1
pool: 5soda create -a
để tạo database. - Cách 2: Sử dụng cli để tạo trực tiếp:
soda create -e test
Database Migrations
Tạo một thư mục migrations để quản lý các file .fizz
và .sql
1 | ├───cmd |
Gobuffalo có sử dụng một gói quản lý fizz để dễ dàng hơn trong việc viết các câu lệnh tạo bảng,… Tuy nhiên ta cũng có thể sử dụng sql migration.
Fizz migration
Tạo một migrations:
1 | soda generate fizz -p ./db/migrations name_of_migration |
Ví dụ:
1 | soda generate fizz -p ./db/migrations create_users_table |
Hai file 20230717051256_create_users_table.down.fizz
, 20230717051256_create_users_table.up.fizz
được tạo ra.
1 | $ soda g migration --help |
Sql migration
1 | soda generate sql name_of_migration |
1 | $ soda g sql --help |
Viết một fizz file
Ví dụ ta tạo một bảng users
:
- .up.fizz file:
1
2
3
4
5
6
7
8
9create_table("users") {
t.Column("id", "integer", {primary: true})
t.Column("first_name", "string", {"size": 255})
t.Column("last_name", "string", {"size": 255})
t.Column("user_active", "integer", {"default": 0})
t.Column("email", "string", {})
t.Column("password", "string", {"size": 60})
t.Column("deleted_at", "timestamp", {"null": true})
} - .down.fizz file:
1
drop_table("users")
Sau khi set xong, ta chạy lệnh soda migrate up
hoặc soda migrate
để tạo table. Sau khi chạy thành công ta có thể thấy cấu hình được dump ra từ sql file.
1 | │ database.yml |