Nim đã có 1 post thiết kế sường cho 1 project golang!
Giờ chúng ta là rõ việc làm sao để golang tương tác được với Database và ở đây là postgres
Chúng ta tiếp tục mục repository của bài viết sau:
1) Install and practise the migration DB with Golang
Chúng ta sẽ sử dụng sql-migrate để thực hiện tạo table hoặc insert data vào database.
Và chúng ta sử dụng package sau:
https://github.com/rubenv/sql-migrate
1.1) Install
chạy command sau:
```bash
go get -v github.com/rubenv/sql-migrate/...
```
Test lại bằng command help nếu như dưới anh là ngonsql-migrate --help

1.2) design sql file
Bạn tạo 1 thư mục migration và tạo 1 file sql như hình bên dưới

1.3) declare db config and pratice
Các cú pháp tạo table khá quen thuộc hi.
Cần chú ý 2 chỗ:-- +migrate Up
: là các Câu lệnh tạo bảng hay insert data-- +migrate Down
: Chúng ta anh để câu lệnh drop table
Tạo file config dbconfig.yml
development:
dialect: postgres
datasource: host=localhost port=5432 user=guru password=123456 dbname=timewise sslmode=disable
dir: migrations
table: migrations
production:
dialect: postgres
datasource: host=localhost port=5432 user=guru password=123456 dbname=timewise sslmode=disable
dir: migrations
table: migrations
Giải thích nhanh:
+ development: cái này để phân định config này thuộc môi trường nào, tý sẽ thấy phần command line
+ dialect: postgres : sử dụng database j?
+ datasource: host=localhost port=5432 user=guru password=123456 dbname=timewise sslmode=disable
-> đường dẫn khai báo kết nối đến database
+ dir: migrations: thự mục chứa các files .sql
+ table: migrations: nó tạo table tên là migrations trong database và ghi lại history migration.

Giờ thực hiện gõ comand tạo tablesql-migrate up -config="dbconfig.yml" -env="development"


Muốn xoá table thì cũng dễ gõ:sql-migrate down -config="dbconfig.yml" -env="development"
Ở trong thư mục migration bạn có thể tạo nhiều files sql
– 1_init.sql
– 2_wow.sql
các file sẽ được run từ 1 đến 2 -> n

2) Repository to manage the DB with Golang

Bạn sẽ tham khảo giúp mình bài load config file trong golang đã nhé!
2.1) db/db.go
Chúng ta sử dụng các thư viện sau:
https://github.com/jmoiron/sqlx
trong thư mục db mình tạo file

2.2) repository/voucher_repo.go
Các bạn làm theo như ảnh:

Đâu tiên là thành phần interface:
Nó sẽ chưa các method để tương tác với các table trong database.
2.3) model/hunter.go
Model thì chưa fields đại diện cho các table mà chúng ta đang làm việc
hunter model.Hunter là ntn?

Khi chúng ta sự dụng mode này cho repository(database) thì cần chú ý

2.4)repository/repo_impl/voucher_repo_impl.go
Lúc đó thì repository_implement nhận biết tag_db “hunter_id” lấy giá trị từ value: HunterId và đưa nó đúng vào column hunter_id trong DB
repo_implement nó sẽ implement cái interface repository và nó chưa các code làm việc trực tiếp mới database.
Ở đây mình viết tạm 1 file implement đơn giản:

3) Config handler
Handler sẽ gọi sang repository

4) Config main.go
Giờ thực kiên tạo kết nối với DB ngay ở file main.
