1. Install
go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest
2. Create sqlc.yaml file
Example:
version: "2"
sql:
- schema: "db/schema/schema.sql"
queries: "db/queries"
engine: "postgresql"
gen:
go:
package: "sqlc"
out: "internal/infra/db/sqlc"
3. Edit query.sql to add all the queries you will use on the application
Example:
-- name: ListProducts :many
SELECT * FROM products;
-- name: GetProduct :one
SELECT * FROM products WHERE id = $1;
-- name: CreateProduct :one
INSERT INTO products (name, created_at, updated_at)
VALUES ($1, $2, $3)
RETURNING id, name, created_at, updated_at;
-- name: UpdateProduct :exec
UPDATE products
SET name = $1,
updated_at = $2
WHERE id = $3;
-- name: DeleteProduct :exec
DELETE FROM products WHERE id = $1;
4. Last step:
sqlc generate
And you’re ready to use the Go code created by SQLC!
