mirror of
https://github.com/therootcompany/golib.git
synced 2026-11-04 06:55:00 +00:00
feat(sql-migrate/examples): add pg-todos embedded migration runner
This commit is contained in:
parent
2256b12223
commit
e210295dda
8
cmd/sql-migrate/examples/pg-todos/.gitignore
vendored
Normal file
8
cmd/sql-migrate/examples/pg-todos/.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
.env
|
||||||
|
LOCAL.md
|
||||||
|
pg-todos
|
||||||
|
internal/tododb/
|
||||||
|
agents/tmp/
|
||||||
|
TASKS.md
|
||||||
|
REVIEW.md
|
||||||
|
HANDOFF.md
|
||||||
345
cmd/sql-migrate/examples/pg-todos/demo.go
Normal file
345
cmd/sql-migrate/examples/pg-todos/demo.go
Normal file
@ -0,0 +1,345 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"github.com/therootcompany/golib/cmd/sql-migrate/examples/pg-todos/internal/tododb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func runAdd(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("add requires a title")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := tododb.New(pool)
|
||||||
|
|
||||||
|
// check if the last arg is a folder name
|
||||||
|
var folderID string
|
||||||
|
if len(args) >= 2 {
|
||||||
|
candidate := strings.TrimSuffix(args[len(args)-1], "/")
|
||||||
|
folder, err := q.FolderGetByName(ctx, candidate)
|
||||||
|
if err == nil {
|
||||||
|
folderID = folder.ID
|
||||||
|
args = args[:len(args)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("add requires a title")
|
||||||
|
}
|
||||||
|
title := strings.Join(args, " ")
|
||||||
|
id := mustRandomHex(4)
|
||||||
|
|
||||||
|
todo, err := q.TodoCreate(ctx, tododb.TodoCreateParams{
|
||||||
|
ID: id,
|
||||||
|
Title: title,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("creating todo: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if folderID != "" {
|
||||||
|
err = q.FolderAddTodo(ctx, tododb.FolderAddTodoParams{
|
||||||
|
FolderID: folderID,
|
||||||
|
TodoID: todo.ID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("adding to folder: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Created: %s %s\n", todo.ID, todo.Title)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runList(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||||
|
q := tododb.New(pool)
|
||||||
|
|
||||||
|
if len(args) > 0 {
|
||||||
|
name := strings.TrimSuffix(strings.Join(args, " "), "/")
|
||||||
|
folder, err := q.FolderGetByName(ctx, name)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("folder %q: %w", name, err)
|
||||||
|
}
|
||||||
|
todos, err := q.FolderTodos(ctx, folder.ID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listing folder todos: %w", err)
|
||||||
|
}
|
||||||
|
if len(todos) == 0 {
|
||||||
|
fmt.Printf("No todos in %s/\n", folder.Name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, t := range todos {
|
||||||
|
printTodo(t.ID, t.Title, t.Status, t.CompletedAt, t.Priority)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
todos, err := q.TodoListUnfoldered(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listing todos: %w", err)
|
||||||
|
}
|
||||||
|
for _, t := range todos {
|
||||||
|
printTodo(t.ID, t.Title, t.Status, t.CompletedAt, t.Priority)
|
||||||
|
}
|
||||||
|
|
||||||
|
folders, err := q.FolderList(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listing folders: %w", err)
|
||||||
|
}
|
||||||
|
for _, f := range folders {
|
||||||
|
fmt.Printf(" %s %s/\n", f.ID, f.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(todos) == 0 && len(folders) == 0 {
|
||||||
|
fmt.Println("No todos.")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printTodo(id, title, status string, completedAt pgtype.Timestamp, priority int32) {
|
||||||
|
if completedAt.Valid {
|
||||||
|
status = fmt.Sprintf("done %s", completedAt.Time.Format("2006-01-02"))
|
||||||
|
}
|
||||||
|
pri := ""
|
||||||
|
if priority > 0 {
|
||||||
|
pri = fmt.Sprintf(" [p%d]", priority)
|
||||||
|
}
|
||||||
|
fmt.Printf(" %s %-10s %s%s\n", id, status, title, pri)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDone(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("done requires a todo ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := tododb.New(pool)
|
||||||
|
todo, err := q.TodoMarkDone(ctx, args[0])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("marking done: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Done: %s %s\n", todo.ID, todo.Title)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runRm(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("rm requires a todo ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := tododb.New(pool)
|
||||||
|
if err := q.TodoDelete(ctx, args[0]); err != nil {
|
||||||
|
return fmt.Errorf("deleting todo: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Deleted: %s\n", args[0])
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runFolder(ctx context.Context, pool *pgxpool.Pool, args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("folder requires a subcommand: create, list, add, rm, todos, delete")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := tododb.New(pool)
|
||||||
|
|
||||||
|
switch args[0] {
|
||||||
|
case "create":
|
||||||
|
if len(args) < 2 {
|
||||||
|
return fmt.Errorf("folder create requires a name")
|
||||||
|
}
|
||||||
|
name := strings.Join(args[1:], " ")
|
||||||
|
id := mustRandomHex(4)
|
||||||
|
folder, err := q.FolderCreate(ctx, tododb.FolderCreateParams{
|
||||||
|
ID: id,
|
||||||
|
Name: name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("creating folder: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Created folder: %s %s\n", folder.ID, folder.Name)
|
||||||
|
|
||||||
|
case "list":
|
||||||
|
folders, err := q.FolderList(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listing folders: %w", err)
|
||||||
|
}
|
||||||
|
if len(folders) == 0 {
|
||||||
|
fmt.Println("No folders.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, f := range folders {
|
||||||
|
fmt.Printf(" %s %s\n", f.ID, f.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "add":
|
||||||
|
if len(args) < 3 {
|
||||||
|
return fmt.Errorf("folder add requires <folder-id> <todo-id>")
|
||||||
|
}
|
||||||
|
err := q.FolderAddTodo(ctx, tododb.FolderAddTodoParams{
|
||||||
|
FolderID: args[1],
|
||||||
|
TodoID: args[2],
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("adding todo to folder: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Added todo %s to folder %s\n", args[2], args[1])
|
||||||
|
|
||||||
|
case "rm":
|
||||||
|
if len(args) < 3 {
|
||||||
|
return fmt.Errorf("folder rm requires <folder-id> <todo-id>")
|
||||||
|
}
|
||||||
|
err := q.FolderRemoveTodo(ctx, tododb.FolderRemoveTodoParams{
|
||||||
|
FolderID: args[1],
|
||||||
|
TodoID: args[2],
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("removing todo from folder: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Removed todo %s from folder %s\n", args[2], args[1])
|
||||||
|
|
||||||
|
case "todos":
|
||||||
|
if len(args) < 2 {
|
||||||
|
return fmt.Errorf("folder todos requires a folder ID")
|
||||||
|
}
|
||||||
|
todos, err := q.FolderTodos(ctx, args[1])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listing folder todos: %w", err)
|
||||||
|
}
|
||||||
|
if len(todos) == 0 {
|
||||||
|
fmt.Println("No todos in this folder.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, t := range todos {
|
||||||
|
printTodo(t.ID, t.Title, t.Status, t.CompletedAt, t.Priority)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "delete":
|
||||||
|
if len(args) < 2 {
|
||||||
|
return fmt.Errorf("folder delete requires a folder ID")
|
||||||
|
}
|
||||||
|
if err := q.FolderDelete(ctx, args[1]); err != nil {
|
||||||
|
return fmt.Errorf("deleting folder: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Deleted folder: %s\n", args[1])
|
||||||
|
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown folder subcommand: %s", args[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runSeed(ctx context.Context, pool *pgxpool.Pool) error {
|
||||||
|
// Use raw SQL with ON CONFLICT DO NOTHING for idempotent seed data.
|
||||||
|
// This is seed data — it doesn't need to go through sqlc.
|
||||||
|
|
||||||
|
type seedFolder struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
type seedTodo struct {
|
||||||
|
ID string
|
||||||
|
Title string
|
||||||
|
}
|
||||||
|
|
||||||
|
folders := []seedFolder{
|
||||||
|
{ID: "seed0001", Name: "Work"},
|
||||||
|
{ID: "seed0002", Name: "Personal"},
|
||||||
|
}
|
||||||
|
|
||||||
|
unfolderedTodos := []seedTodo{
|
||||||
|
{ID: "seed0010", Title: "Review Q2 financial reports"},
|
||||||
|
{ID: "seed0011", Title: "Update SSL certificates"},
|
||||||
|
}
|
||||||
|
|
||||||
|
workTodos := []seedTodo{
|
||||||
|
{ID: "seed0020", Title: "Deploy v2.3.1 to staging"},
|
||||||
|
{ID: "seed0021", Title: "Rotate API keys"},
|
||||||
|
{ID: "seed0022", Title: "Audit access logs"},
|
||||||
|
}
|
||||||
|
|
||||||
|
personalTodos := []seedTodo{
|
||||||
|
{ID: "seed0030", Title: "Buy groceries"},
|
||||||
|
{ID: "seed0031", Title: "Schedule dentist appointment"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert folders
|
||||||
|
for _, f := range folders {
|
||||||
|
_, err := pool.Exec(ctx,
|
||||||
|
`INSERT INTO folders (id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||||
|
f.ID, f.Name,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("seeding folder %q: %w", f.Name, err)
|
||||||
|
}
|
||||||
|
fmt.Printf(" Folder: %s %s\n", f.ID, f.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert all todos
|
||||||
|
allTodos := make([]seedTodo, 0, len(unfolderedTodos)+len(workTodos)+len(personalTodos))
|
||||||
|
allTodos = append(allTodos, unfolderedTodos...)
|
||||||
|
allTodos = append(allTodos, workTodos...)
|
||||||
|
allTodos = append(allTodos, personalTodos...)
|
||||||
|
for _, t := range allTodos {
|
||||||
|
_, err := pool.Exec(ctx,
|
||||||
|
`INSERT INTO todos (id, title) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||||
|
t.ID, t.Title,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("seeding todo %q: %w", t.Title, err)
|
||||||
|
}
|
||||||
|
fmt.Printf(" Todo: %s %s\n", t.ID, t.Title)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assign todos to folders
|
||||||
|
for _, t := range workTodos {
|
||||||
|
_, err := pool.Exec(ctx,
|
||||||
|
`INSERT INTO folders_todos (folder_id, todo_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||||
|
"seed0001", t.ID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("seeding folder assignment: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, t := range personalTodos {
|
||||||
|
_, err := pool.Exec(ctx,
|
||||||
|
`INSERT INTO folders_todos (folder_id, todo_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||||
|
"seed0002", t.ID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("seeding folder assignment: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark two as done
|
||||||
|
for _, id := range []string{"seed0010", "seed0011"} {
|
||||||
|
_, err := pool.Exec(ctx,
|
||||||
|
`UPDATE todos SET status = 'done', completed_at = CURRENT_TIMESTAMP WHERE id = $1 AND status != 'done'`,
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("seeding mark done %s: %w", id, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Seed complete.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustRandomHex(n int) string {
|
||||||
|
b := make([]byte, n)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(b)
|
||||||
|
}
|
||||||
18
cmd/sql-migrate/examples/pg-todos/go.mod
Normal file
18
cmd/sql-migrate/examples/pg-todos/go.mod
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
module github.com/therootcompany/golib/cmd/sql-migrate/examples/pg-todos
|
||||||
|
|
||||||
|
go 1.26.1
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgx/v5 v5.9.1
|
||||||
|
github.com/joho/godotenv v1.5.1
|
||||||
|
github.com/therootcompany/golib/database/sqlmigrate v1.0.2
|
||||||
|
github.com/therootcompany/golib/database/sqlmigrate/pgmigrate v1.0.2
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
golang.org/x/sync v0.17.0 // indirect
|
||||||
|
golang.org/x/text v0.29.0 // indirect
|
||||||
|
)
|
||||||
32
cmd/sql-migrate/examples/pg-todos/go.sum
Normal file
32
cmd/sql-migrate/examples/pg-todos/go.sum
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc=
|
||||||
|
github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/therootcompany/golib/database/sqlmigrate v1.0.2 h1:hcmhYyUFVj/GqyChP+0Ry2WZCHnoruFMbsy+2KVzsfA=
|
||||||
|
github.com/therootcompany/golib/database/sqlmigrate v1.0.2/go.mod h1:7PQUjwT78Hx+SftcIKI2PH4zSFlrSO0V9h618PJqC38=
|
||||||
|
github.com/therootcompany/golib/database/sqlmigrate/pgmigrate v1.0.2 h1:0lVmat6XYiK0VYg757LRP/KZ9gu04Y3C5ag9gkNFCxc=
|
||||||
|
github.com/therootcompany/golib/database/sqlmigrate/pgmigrate v1.0.2/go.mod h1:WkiJyF90Lldxw2cqZkddyhzlX/XzJ2hwtVDk8Mryolc=
|
||||||
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||||
|
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
237
cmd/sql-migrate/examples/pg-todos/main.go
Normal file
237
cmd/sql-migrate/examples/pg-todos/main.go
Normal file
@ -0,0 +1,237 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"embed"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
|
"github.com/therootcompany/golib/database/sqlmigrate"
|
||||||
|
"github.com/therootcompany/golib/database/sqlmigrate/pgmigrate"
|
||||||
|
)
|
||||||
|
|
||||||
|
const version = "0.1.0"
|
||||||
|
|
||||||
|
//go:generate sqlc generate
|
||||||
|
|
||||||
|
//go:embed sql/migrations/*.sql
|
||||||
|
var migrationsFS embed.FS
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
_ = godotenv.Load()
|
||||||
|
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "-V", "-version", "--version", "version":
|
||||||
|
printVersion(os.Stdout)
|
||||||
|
os.Exit(0)
|
||||||
|
case "help", "-help", "--help":
|
||||||
|
printVersion(os.Stdout)
|
||||||
|
fmt.Fprintln(os.Stdout, "")
|
||||||
|
printUsage(os.Stdout)
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs := flag.NewFlagSet("pg-todos", flag.ContinueOnError)
|
||||||
|
fs.Usage = func() { printUsage(os.Stderr) }
|
||||||
|
if err := fs.Parse(os.Args[1:]); err != nil {
|
||||||
|
if errors.Is(err, flag.ErrHelp) {
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
args := fs.Args()
|
||||||
|
if len(args) == 0 {
|
||||||
|
printVersion(os.Stdout)
|
||||||
|
fmt.Fprintln(os.Stdout, "")
|
||||||
|
printUsage(os.Stdout)
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
pgURL := os.Getenv("PG_URL")
|
||||||
|
if pgURL == "" {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: PG_URL environment variable is required\n")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
pool, err := pgxpool.New(ctx, pgURL)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: connecting to database: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
migrations := mustCollectMigrations()
|
||||||
|
runner := pgmigrate.New(pool)
|
||||||
|
|
||||||
|
subcmd := args[0]
|
||||||
|
subArgs := args[1:]
|
||||||
|
|
||||||
|
switch subcmd {
|
||||||
|
case "migrate":
|
||||||
|
err = runMigrate(ctx, runner, migrations, subArgs)
|
||||||
|
case "add":
|
||||||
|
autoMigrate(ctx, runner, migrations)
|
||||||
|
err = runAdd(ctx, pool, subArgs)
|
||||||
|
case "list":
|
||||||
|
autoMigrate(ctx, runner, migrations)
|
||||||
|
err = runList(ctx, pool, subArgs)
|
||||||
|
case "done":
|
||||||
|
autoMigrate(ctx, runner, migrations)
|
||||||
|
err = runDone(ctx, pool, subArgs)
|
||||||
|
case "rm":
|
||||||
|
autoMigrate(ctx, runner, migrations)
|
||||||
|
err = runRm(ctx, pool, subArgs)
|
||||||
|
case "seed":
|
||||||
|
autoMigrate(ctx, runner, migrations)
|
||||||
|
err = runSeed(ctx, pool)
|
||||||
|
case "folder":
|
||||||
|
autoMigrate(ctx, runner, migrations)
|
||||||
|
err = runFolder(ctx, pool, subArgs)
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "Unknown command: %s\n\n", subcmd)
|
||||||
|
printUsage(os.Stderr)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustCollectMigrations() []sqlmigrate.Script {
|
||||||
|
migrations, err := sqlmigrate.Collect(migrationsFS, "sql/migrations")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: collecting migrations: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
return migrations
|
||||||
|
}
|
||||||
|
|
||||||
|
func autoMigrate(ctx context.Context, runner sqlmigrate.Migrator, migrations []sqlmigrate.Script) {
|
||||||
|
if _, err := sqlmigrate.Latest(ctx, runner, migrations); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: auto-migrate: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printVersion(w *os.File) {
|
||||||
|
fmt.Fprintf(w, "pg-todos v%s\n", version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printUsage(w *os.File) {
|
||||||
|
fmt.Fprintln(w, `USAGE
|
||||||
|
pg-todos <command> [args]
|
||||||
|
|
||||||
|
COMMANDS
|
||||||
|
migrate up [n] apply pending migrations (all by default)
|
||||||
|
migrate down [n] roll back migrations (1 by default)
|
||||||
|
migrate status show applied and pending migrations
|
||||||
|
migrate reset drop all tables (rollback all migrations)
|
||||||
|
|
||||||
|
seed insert deterministic test data (idempotent)
|
||||||
|
|
||||||
|
add <title> [folder] create a new todo (optionally in a folder)
|
||||||
|
list [folder-name] list todos (in a folder, or root + folders)
|
||||||
|
done <id> mark a todo as done
|
||||||
|
rm <id> delete a todo
|
||||||
|
|
||||||
|
folder create <name> create a folder
|
||||||
|
folder list list all folders
|
||||||
|
folder add <folder-id> <todo-id> assign a todo to a folder
|
||||||
|
folder rm <folder-id> <todo-id> remove a todo from a folder
|
||||||
|
folder todos <folder-id> list todos in a folder
|
||||||
|
folder delete <folder-id> delete a folder
|
||||||
|
|
||||||
|
ENVIRONMENT
|
||||||
|
PG_URL PostgreSQL connection string (loaded from .env)`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMigrate(ctx context.Context, runner sqlmigrate.Migrator, migrations []sqlmigrate.Script, args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Errorf("migrate requires a subcommand: up, down, status, or reset")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch args[0] {
|
||||||
|
case "up":
|
||||||
|
n := -1
|
||||||
|
if len(args) > 1 {
|
||||||
|
var err error
|
||||||
|
n, err = strconv.Atoi(args[1])
|
||||||
|
if err != nil || n < 0 {
|
||||||
|
return fmt.Errorf("%q is not a valid count", args[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
applied, err := sqlmigrate.Up(ctx, runner, migrations, n)
|
||||||
|
if len(applied) == 0 && err == nil {
|
||||||
|
fmt.Println("Already up-to-date.")
|
||||||
|
} else if err == nil {
|
||||||
|
fmt.Printf("Applied %d migration(s).\n", len(applied))
|
||||||
|
for _, m := range applied {
|
||||||
|
fmt.Printf(" %s\n", m.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
|
||||||
|
case "down":
|
||||||
|
n := 1
|
||||||
|
if len(args) > 1 {
|
||||||
|
var err error
|
||||||
|
n, err = strconv.Atoi(args[1])
|
||||||
|
if err != nil || n < 0 {
|
||||||
|
return fmt.Errorf("%q is not a valid count", args[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rolled, err := sqlmigrate.Down(ctx, runner, migrations, n)
|
||||||
|
if len(rolled) == 0 && err == nil {
|
||||||
|
fmt.Println("No migrations to roll back.")
|
||||||
|
} else if err == nil {
|
||||||
|
fmt.Printf("Rolled back %d migration(s).\n", len(rolled))
|
||||||
|
for _, m := range rolled {
|
||||||
|
fmt.Printf(" %s\n", m.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
|
||||||
|
case "status":
|
||||||
|
status, err := sqlmigrate.GetStatus(ctx, runner, migrations)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("Applied: %d\n", len(status.Applied))
|
||||||
|
for _, m := range status.Applied {
|
||||||
|
fmt.Printf(" %s\n", m.Name)
|
||||||
|
}
|
||||||
|
fmt.Printf("\nPending: %d\n", len(status.Pending))
|
||||||
|
for _, m := range status.Pending {
|
||||||
|
fmt.Printf(" %s\n", m.Name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
|
||||||
|
case "reset":
|
||||||
|
rolled, err := sqlmigrate.Drop(ctx, runner, migrations)
|
||||||
|
if len(rolled) == 0 && err == nil {
|
||||||
|
fmt.Println("Nothing to reset.")
|
||||||
|
} else if err == nil {
|
||||||
|
fmt.Printf("Reset: rolled back %d migration(s).\n", len(rolled))
|
||||||
|
for _, m := range rolled {
|
||||||
|
fmt.Printf(" %s\n", m.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown migrate subcommand: %s (use up, down, status, or reset)", args[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
-- init-migrations (down)
|
||||||
|
|
||||||
|
DELETE FROM _migrations WHERE id = '00000001';
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS _migrations;
|
||||||
@ -0,0 +1,10 @@
|
|||||||
|
-- init-migrations (up)
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS _migrations (
|
||||||
|
id CHAR(8) PRIMARY KEY,
|
||||||
|
name VARCHAR(80) NULL UNIQUE,
|
||||||
|
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
INSERT INTO _migrations (name, id) VALUES ('0001-01-01-001000_init-migrations', '00000001');
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
-- create-todos (down)
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS todos;
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
DELETE FROM _migrations WHERE id = 'a1b2c3d4';
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
-- create-todos (up)
|
||||||
|
|
||||||
|
CREATE TABLE todos (
|
||||||
|
id CHAR(8) PRIMARY KEY,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
INSERT INTO _migrations (name, id) VALUES ('2026-04-05-001000_create-todos', 'a1b2c3d4');
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
-- create-users-and-todos-users (down)
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS todos_users;
|
||||||
|
DROP TABLE IF EXISTS users;
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
DELETE FROM _migrations WHERE id = 'b2c3d4e5';
|
||||||
@ -0,0 +1,17 @@
|
|||||||
|
-- create-users-and-todos-users (up)
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id CHAR(8) PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
email VARCHAR(254) NOT NULL UNIQUE,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE todos_users (
|
||||||
|
todo_id CHAR(8) NOT NULL REFERENCES todos(id) ON DELETE CASCADE,
|
||||||
|
user_id CHAR(8) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (todo_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
INSERT INTO _migrations (name, id) VALUES ('2026-04-05-002000_create-users-and-todos-users', 'b2c3d4e5');
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
-- create-folders-and-folders-todos (down)
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS folders_todos;
|
||||||
|
DROP TABLE IF EXISTS folders;
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
DELETE FROM _migrations WHERE id = 'c3d4e5f6';
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
-- create-folders-and-folders-todos (up)
|
||||||
|
|
||||||
|
CREATE TABLE folders (
|
||||||
|
id CHAR(8) PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE folders_todos (
|
||||||
|
folder_id CHAR(8) NOT NULL REFERENCES folders(id) ON DELETE CASCADE,
|
||||||
|
todo_id CHAR(8) NOT NULL REFERENCES todos(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (folder_id, todo_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
INSERT INTO _migrations (name, id) VALUES ('2026-04-05-003000_create-folders-and-folders-todos', 'c3d4e5f6');
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
-- add-todo-fields (down)
|
||||||
|
|
||||||
|
ALTER TABLE todos DROP COLUMN IF EXISTS priority;
|
||||||
|
ALTER TABLE todos DROP COLUMN IF EXISTS completed_at;
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
DELETE FROM _migrations WHERE id = 'd4e5f6a7';
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
-- add-todo-fields (up)
|
||||||
|
|
||||||
|
ALTER TABLE todos ADD COLUMN completed_at TIMESTAMP;
|
||||||
|
ALTER TABLE todos ADD COLUMN priority INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
INSERT INTO _migrations (name, id) VALUES ('2026-04-05-004000_add-todo-fields', 'd4e5f6a7');
|
||||||
@ -0,0 +1,9 @@
|
|||||||
|
-- add-indexes-and-constraints (down)
|
||||||
|
|
||||||
|
ALTER TABLE todos DROP CONSTRAINT IF EXISTS chk_todo_status;
|
||||||
|
DROP INDEX IF EXISTS idx_todos_completed_at;
|
||||||
|
DROP INDEX IF EXISTS idx_folders_todos_todo_id;
|
||||||
|
DROP INDEX IF EXISTS idx_todos_users_user_id;
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
DELETE FROM _migrations WHERE id = 'e5f6a7b8';
|
||||||
@ -0,0 +1,10 @@
|
|||||||
|
-- add-indexes-and-constraints (up)
|
||||||
|
|
||||||
|
CREATE INDEX idx_todos_users_user_id ON todos_users(user_id);
|
||||||
|
CREATE INDEX idx_folders_todos_todo_id ON folders_todos(todo_id);
|
||||||
|
CREATE INDEX idx_todos_completed_at ON todos(completed_at) WHERE completed_at IS NULL;
|
||||||
|
ALTER TABLE todos ADD CONSTRAINT chk_todo_status
|
||||||
|
CHECK (status IN ('pending', 'in_progress', 'done'));
|
||||||
|
|
||||||
|
-- leave this as the last line
|
||||||
|
INSERT INTO _migrations (name, id) VALUES ('2026-04-05-005000_add-indexes-and-constraints', 'e5f6a7b8');
|
||||||
33
cmd/sql-migrate/examples/pg-todos/sql/queries/folders.sql
Normal file
33
cmd/sql-migrate/examples/pg-todos/sql/queries/folders.sql
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
-- name: FolderCreate :one
|
||||||
|
INSERT INTO folders (id, name)
|
||||||
|
VALUES (sqlc.arg('id'), sqlc.arg('name'))
|
||||||
|
RETURNING id, name, created_at;
|
||||||
|
|
||||||
|
-- name: FolderList :many
|
||||||
|
SELECT id, name, created_at
|
||||||
|
FROM folders
|
||||||
|
ORDER BY name ASC;
|
||||||
|
|
||||||
|
-- name: FolderDelete :exec
|
||||||
|
DELETE FROM folders WHERE id = sqlc.arg('id');
|
||||||
|
|
||||||
|
-- name: FolderAddTodo :exec
|
||||||
|
INSERT INTO folders_todos (folder_id, todo_id)
|
||||||
|
VALUES (sqlc.arg('folder_id'), sqlc.arg('todo_id'));
|
||||||
|
|
||||||
|
-- name: FolderRemoveTodo :exec
|
||||||
|
DELETE FROM folders_todos
|
||||||
|
WHERE folder_id = sqlc.arg('folder_id')
|
||||||
|
AND todo_id = sqlc.arg('todo_id');
|
||||||
|
|
||||||
|
-- name: FolderGetByName :one
|
||||||
|
SELECT id, name, created_at
|
||||||
|
FROM folders
|
||||||
|
WHERE name = sqlc.arg('name');
|
||||||
|
|
||||||
|
-- name: FolderTodos :many
|
||||||
|
SELECT t.id, t.title, t.status, t.completed_at, t.priority, t.created_at, t.updated_at
|
||||||
|
FROM todos t
|
||||||
|
JOIN folders_todos ft ON ft.todo_id = t.id
|
||||||
|
WHERE ft.folder_id = sqlc.arg('folder_id')
|
||||||
|
ORDER BY t.priority DESC, t.created_at ASC;
|
||||||
26
cmd/sql-migrate/examples/pg-todos/sql/queries/todos.sql
Normal file
26
cmd/sql-migrate/examples/pg-todos/sql/queries/todos.sql
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
-- name: TodoCreate :one
|
||||||
|
INSERT INTO todos (id, title, status)
|
||||||
|
VALUES (sqlc.arg('id'), sqlc.arg('title'), 'pending')
|
||||||
|
RETURNING id, title, status, completed_at, priority, created_at, updated_at;
|
||||||
|
|
||||||
|
-- name: TodoList :many
|
||||||
|
SELECT id, title, status, completed_at, priority, created_at, updated_at
|
||||||
|
FROM todos
|
||||||
|
ORDER BY priority DESC, created_at ASC;
|
||||||
|
|
||||||
|
-- name: TodoListUnfoldered :many
|
||||||
|
SELECT id, title, status, completed_at, priority, created_at, updated_at
|
||||||
|
FROM todos
|
||||||
|
WHERE id NOT IN (SELECT todo_id FROM folders_todos)
|
||||||
|
ORDER BY priority DESC, created_at ASC;
|
||||||
|
|
||||||
|
-- name: TodoMarkDone :one
|
||||||
|
UPDATE todos
|
||||||
|
SET status = 'done',
|
||||||
|
completed_at = CURRENT_TIMESTAMP,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = sqlc.arg('id')
|
||||||
|
RETURNING id, title, status, completed_at, priority, created_at, updated_at;
|
||||||
|
|
||||||
|
-- name: TodoDelete :exec
|
||||||
|
DELETE FROM todos WHERE id = sqlc.arg('id');
|
||||||
14
cmd/sql-migrate/examples/pg-todos/sqlc.yaml
Normal file
14
cmd/sql-migrate/examples/pg-todos/sqlc.yaml
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
version: "2"
|
||||||
|
sql:
|
||||||
|
- engine: postgresql
|
||||||
|
schema: sql/migrations/
|
||||||
|
queries: sql/queries/
|
||||||
|
gen:
|
||||||
|
go:
|
||||||
|
package: tododb
|
||||||
|
out: internal/tododb
|
||||||
|
sql_package: pgx/v5
|
||||||
|
emit_json_tags: true
|
||||||
|
initialisms:
|
||||||
|
- "id"
|
||||||
|
- "url"
|
||||||
Loading…
x
Reference in New Issue
Block a user