Example project for developing a banking api with golang, grpc and postgres
- Generate SQL CRUD with sqlc
make sqlc
- Generate DB mock with gomock:
make mock
- Create a new db migration
migrate create -ext sql -dir db/migration -seq <migration_name>
- Install
golang-migrate
cd db
make create-container
make createdb
make migrate-up
# Add TablePlus gpg key
wget -qO - https://deb.tableplus.com/apt.tableplus.com.gpg.key | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/tableplus-archive.gpg > /dev/null
# Add TablePlus repo
sudo add-apt-repository "deb [arch=amd64] https://deb.tableplus.com/debian/22 tableplus main"
# Install
sudo apt update
sudo apt install tableplus
curl -s https://packagecloud.io/install/repositories/golang-migrate/migrate/script.deb.sh | sudo bash
sudo apt udpate
sudo apt install migrate
mkdir -p db/migration
migrate create --ext sql --dir db/migration --seq init_schema
- This creates up an down migrations
- If we call
migrate up
it will upgrade the database to the last number of up migrations - If we call
migrate down
it will downgrade the database from the last to the first of down migrations
- Create migrations file with dbdiagram.io
- Copy the content to the
up
-migration - Add the reverting commands to the
down
-migration
DROP TABLE IF EXISTS entries CASCADE;
DROP TABLE IF EXISTS transfers CASCADE;
DROP TABLE IF EXISTS accounts CASCADE;
- Fully supports postgres
- Translates SQL to ideomatic golang std library for sql
sudo snap install sqlc
sqlc version
sqlc help
- Initialize sqlc --> Will create a
sqlc.yaml
in your project folder
sqlc init
- Add postgresql engine and the correct file paths for queries and schema
- Remove
cloud
anddatabase
for using sqlc without the cloud
version: "2"
sql:
- engine: "postgresql"
queries: "./db/query/"
schema: "./db/migration/"
gen:
go:
package: "db"
out: "./db/sqlc"
sql_package: "pgx/v5"
emit_json_tags: true
emit_prepared_queries: false
emit_interface: false
emit_exact_table_names: false
- Write your own queries in SQL and generate code from these queries using
sqlc generate
- Get the binary
go install github.com/golang/mock/mockgen@vX.X.X
- The binary will be installed to ~/go/bin
- Check if it is already available
which mockgen
- If not available, you have add the folder to PATH
# ~/.zshrc
# ...
export PATH="$PATH:$HOME/go/bin"
# ...
- Set sqlc option
emit_interface
to true ->make sqlc
mockgen -destination db/mock/store.go github.com/PfMartin/secure-bank/db/sqlc Store