Object Relational Mapping in Go with SQLC

Oct 01, 22

Install Go

Installing SQLC

First create a project directy and cd into it.

mkdir orm-tut && cd $_

Initalize a Go module:

go mod init orm-tut.dev/app

Initial Project Setup

Create a sqlc.yaml file:

version: "2"
sql:
  - engine: "postgresql"
    queries: "query.sql"
    schema: "schema.sql"
    gen:
      go:
        package: "orm-tut"
        out: "orm-tut"

Create a schema.sql file:

CREATE TABLE trades (
  id      BIGSERIAL PRIMARY KEY,
  name    text      NOT NULL,
  ticker  text
);

Create a query.sql file:

-- name: GetTrade :one
SELECT * FROM trades
WHERE id = $1 LIMIT 1;

-- name: ListTrades :many
SELECT * FROM trades
ORDER BY name;

-- name: CreateTrade :one
INSERT INTO trades (
  name, ticker
) VALUES (
  $1, $2
)
RETURNING *;

-- name: DeleteTrade :exec
DELETE FROM trades
WHERE id = $1;

-- name: UpdateTrade :exec
UPDATE trades
  set name = $2,
  ticker = $3
WHERE id = $1;