Gobuffalo Soda-cli


Install

https://gobuffalo.io/documentation/database/soda/

Tạo database

  • Cách 1: Sử dụng file database.yml:
    1
    2
    3
    4
    5
    6
    7
    development:
    dialect: postgres
    database: myapp_development
    user: postgres
    password: postgres
    host: 127.0.0.1
    pool: 5
    Sau khi tạo file database.yml, ta chạy lệnh soda 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.sql

1
2
3
4
├───cmd
│ └───web
└───db
└───migrations

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ soda g migration --help
Generates Up/Down migrations for your database using fizz.

Usage:
soda generate fizz [name] [flags]

Aliases:
fizz, migration

Flags:
-h, --help help for fizz

Global Flags:
-c, --config string The configuration file you would like to use.
-d, --debug Use debug/verbose mode
-e, --env string The environment you want to run migrations against. Will use $GO_ENV if set. (default "development")
-p, --path string Path to the migrations folder (default "./migrations")

Sql migration

1
soda generate sql name_of_migration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ soda g sql --help
Generates Up/Down migrations for your database using SQL.

Usage:
soda generate sql [name] [flags]

Flags:
-h, --help help for sql

Global Flags:
-c, --config string The configuration file you would like to use.
-d, --debug Use debug/verbose mode
-e, --env string The environment you want to run migrations against. Will use $GO_ENV if set. (default "development")
-p, --path string Path to the migrations folder (default "./migrations")

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
    9
    create_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
2
3
4
5
6
7
│   database.yml
│ db.go

└───migrations
20230717051256_create_users_table.down.fizz
20230717051256_create_users_table.up.fizz
schema.sql