diff --git a/go.mod b/go.mod index 23e5512..20c392a 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/gertd/go-pluralize v0.2.1 github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 - github.com/togo-framework/create-togo-app v0.2.2 + github.com/togo-framework/create-togo-app v0.2.3 golang.org/x/term v0.44.0 gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index 98c4e75..257114a 100644 --- a/go.sum +++ b/go.sum @@ -8,8 +8,8 @@ github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/togo-framework/create-togo-app v0.2.2 h1:f7hA+/guPqjJKtfSfYbF++gbVqPXZrvQIPhGA+wo6YM= -github.com/togo-framework/create-togo-app v0.2.2/go.mod h1:/5nUN9ZyR7df9pSS2pVQDyQcBkzRIbPlsYbJsiH6bI8= +github.com/togo-framework/create-togo-app v0.2.3 h1:ynnGsBcGcR1wnDFLP6xU+vK6vDbTxeft0wXHcvO2D7Y= +github.com/togo-framework/create-togo-app v0.2.3/go.mod h1:/5nUN9ZyR7df9pSS2pVQDyQcBkzRIbPlsYbJsiH6bI8= golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= diff --git a/internal/generator/dialect.go b/internal/generator/dialect.go index e339971..09651a4 100644 --- a/internal/generator/dialect.go +++ b/internal/generator/dialect.go @@ -1,6 +1,9 @@ package generator import ( + "os" + "path/filepath" + "regexp" "strings" "github.com/togo-framework/cli/internal/config" @@ -66,3 +69,58 @@ func MySQLType(f config.Field) string { return "text" } } + +// AtlasSchemaFile declares the Atlas schema every table.hcl fragment belongs to. +const AtlasSchemaFile = "db/atlas/schema/schema.hcl" + +var atlasSchemaRe = regexp.MustCompile(`(?m)^\s*schema\s+"([^"]+)"`) + +// AtlasSchema is the schema table.hcl fragments reference. Atlas needs the HCL +// schema to be the one the URL connects to: "public" on Postgres, "main" on +// SQLite and the database name on MySQL. The project's schema.hcl is the source +// of truth, so a renamed schema there carries over to new tables; without one, +// it falls back to the dialect's default (the app directory name for MySQL, +// which `togo new` uses as the database name). +func AtlasSchema(root, dialect string) string { + if root != "" { + if b, err := os.ReadFile(filepath.Join(root, AtlasSchemaFile)); err == nil { + if m := atlasSchemaRe.FindSubmatch(b); m != nil { + return string(m[1]) + } + } + } + return DefaultAtlasSchema(root, dialect) +} + +// DefaultAtlasSchema is the schema Atlas connects to for a fresh project. +func DefaultAtlasSchema(root, dialect string) string { + switch dialect { + case DialectPostgres: + return "public" + case DialectMySQL: + if abs, err := filepath.Abs(root); err == nil && root != "" { + return filepath.Base(abs) + } + return "app" + default: + return "main" + } +} + +// AtlasColumnType renders a field's column type as an Atlas HCL expression for +// the dialect. Bare tokens are used where Atlas has one; parameterised types +// (char(36), decimal(20,6), datetime(6)) go through sql("…"). +func AtlasColumnType(dialect string, f config.Field) string { + switch dialect { + case DialectPostgres: + return atlasType(f.PG) + case DialectMySQL: + t := MySQLType(f) + if strings.Contains(t, "(") { + return `sql("` + t + `")` + } + return t + default: + return SQLiteType(f) + } +} diff --git a/internal/generator/dialect_test.go b/internal/generator/dialect_test.go index 06f6854..0ca2395 100644 --- a/internal/generator/dialect_test.go +++ b/internal/generator/dialect_test.go @@ -46,19 +46,22 @@ func goldenResources(t *testing.T) []config.Resource { } } -// TestSchemaAndQueriesGolden pins the DDL and sqlc queries that make:resource -// writes for each database driver. Regenerate with: go test ./internal/generator -run Golden -update +// TestSchemaAndQueriesGolden pins the DDL, sqlc queries and Atlas HCL that +// make:resource writes for each database driver. Regenerate with: go test ./internal/generator -run Golden -update func TestSchemaAndQueriesGolden(t *testing.T) { for _, driver := range []string{"sqlite", "pgx", "mysql"} { dialect := SQLDialect(driver) for _, r := range goldenResources(t) { - for _, op := range ModelPlan("example.com/app", driver, r, &config.Manifest{}) { - var kind string + ops := append(ModelPlan("example.com/app", driver, r, &config.Manifest{}), SinglePlan("make:migration", "example.com/app", driver, r)...) + for _, op := range ops { + var name string switch op.Template { case "resource/schema.sql.tmpl": - kind = "schema" + name = "schema.sql" case "resource/queries.sql.tmpl": - kind = "queries" + name = "queries.sql" + case "resource/table.hcl.tmpl": + name = "table.hcl" default: continue } @@ -66,7 +69,8 @@ func TestSchemaAndQueriesGolden(t *testing.T) { if err != nil { t.Fatalf("%s %s: %v", dialect, op.Template, err) } - golden := filepath.Join("testdata", "golden", dialect, Snake(r.Name)+"."+kind+".sql") + got = bytes.ReplaceAll(got, []byte("\r"), nil) // CRLF checkouts of the stubs + golden := filepath.Join("testdata", "golden", dialect, Snake(r.Name)+"."+name) if *update { if err := os.MkdirAll(filepath.Dir(golden), 0o755); err != nil { t.Fatal(err) @@ -103,3 +107,48 @@ func TestPostgresSchemaHasNoSQLiteSyntax(t *testing.T) { } } } + +// Atlas only applies an HCL schema named like the one the URL connects to, so +// table.hcl must not hard-code Postgres' "public" for the other drivers. +func TestAtlasTableHasNoPostgresSyntax(t *testing.T) { + for _, dialect := range []string{DialectSQLite, DialectMySQL} { + for _, r := range goldenResources(t) { + out, err := render("", FileOp{Template: "resource/table.hcl.tmpl", Data: ResourceData{Dialect: dialect, Resource: r}}) + if err != nil { + t.Fatal(err) + } + for _, bad := range []string{"schema.public", "= uuid", "timestamptz", "jsonb", "gen_random_uuid", "now()"} { + if bytes.Contains(out, []byte(bad)) { + t.Errorf("%s table.hcl for %s contains %q:\n%s", dialect, r.Name, bad, out) + } + } + } + } +} + +func TestAtlasSchema(t *testing.T) { + root := filepath.Join(t.TempDir(), "shop") + for dialect, want := range map[string]string{DialectPostgres: "public", DialectSQLite: "main", DialectMySQL: "shop"} { + if got := AtlasSchema(root, dialect); got != want { + t.Errorf("AtlasSchema(no schema.hcl, %s) = %q, want %q", dialect, got, want) + } + } + // The project's schema.hcl wins, so a renamed schema carries over to new tables. + file := filepath.Join(root, AtlasSchemaFile) + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(file, []byte("# the app database\nschema \"shop_prod\" {\n}\n"), 0o644); err != nil { + t.Fatal(err) + } + if got := AtlasSchema(root, DialectMySQL); got != "shop_prod" { + t.Errorf("AtlasSchema(schema.hcl) = %q, want shop_prod", got) + } + out, err := render(root, FileOp{Template: "resource/table.hcl.tmpl", Data: ResourceData{Dialect: DialectMySQL, Resource: config.Resource{Name: "Post", Table: "posts"}}}) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(out, []byte("schema = schema.shop_prod")) { + t.Errorf("table.hcl does not reference the project's schema:\n%s", out) + } +} diff --git a/internal/generator/funcs.go b/internal/generator/funcs.go index aed7504..a70e961 100644 --- a/internal/generator/funcs.go +++ b/internal/generator/funcs.go @@ -27,6 +27,7 @@ func FuncMap() template.FuncMap { "inc": func(i int) int { return i + 1 }, "add": func(a, b int) int { return a + b }, "atlasType": atlasType, + "atlasCol": AtlasColumnType, "tsType": tsType, "sample": SampleValue, "sqliteType": SQLiteType, diff --git a/internal/generator/plan.go b/internal/generator/plan.go index 2101c35..9f06085 100644 --- a/internal/generator/plan.go +++ b/internal/generator/plan.go @@ -121,8 +121,13 @@ func render(root string, op FileOp) ([]byte, error) { if err != nil { return nil, err } + data := op.Data + if d, ok := data.(ResourceData); ok && d.AtlasSchema == "" { + d.AtlasSchema = AtlasSchema(root, d.Dialect) + data = d + } var buf bytes.Buffer - if err := tmpl.Execute(&buf, op.Data); err != nil { + if err := tmpl.Execute(&buf, data); err != nil { return nil, err } out := buf.Bytes() diff --git a/internal/generator/plans.go b/internal/generator/plans.go index 46dad7a..d01d077 100644 --- a/internal/generator/plans.go +++ b/internal/generator/plans.go @@ -10,6 +10,9 @@ type ResourceData struct { Dialect string // SQL dialect of the project's database: sqlite | postgres | mysql Resource config.Resource NeedsTime bool + // AtlasSchema is the Atlas schema the table.hcl fragment belongs to. Filled at + // render time from the project's db/atlas/schema/schema.hcl (see AtlasSchema). + AtlasSchema string } // RegistryData is the view model for regenerated aggregate registries. @@ -65,8 +68,11 @@ var singleTargets = map[string]string{ "make:e2e": "resource/e2e.spec.ts.tmpl", } -// extraTargets are generated only on demand (make:test, make:e2e). +// extraTargets are generated only on demand (make:test, make:e2e, make:migration). +// make:migration writes the Atlas HCL for the project's driver; `togo migrate` +// itself applies internal/db/schema/*.sql and doesn't need it. var extraTargets = []target{ + {"resource/table.hcl.tmpl", func(s, p string) string { return "db/atlas/schema/" + s + ".hcl" }, CreateOnly}, {"resource/feature_test.go.tmpl", func(s, p string) string { return "internal/rest/" + s + "_feature_test.go" }, CreateOnly}, {"resource/e2e.spec.ts.tmpl", func(s, p string) string { return "web/e2e/" + s + ".spec.ts" }, CreateOnly}, } diff --git a/internal/generator/rest_body_test.go b/internal/generator/rest_body_test.go new file mode 100644 index 0000000..644e93e --- /dev/null +++ b/internal/generator/rest_body_test.go @@ -0,0 +1,66 @@ +package generator + +import ( + "regexp" + "strings" + "testing" + + "github.com/togo-framework/cli/internal/config" +) + +// REST bodies follow the GraphQL input rules: required means "key present" +// (Huma's default for a non-pointer field, so 0/false/"" are accepted) and a +// nullable field may be omitted. validate:"required" rejected zero values. +func TestRestHandlerBodyTags(t *testing.T) { + fields, err := ParseFields([]string{"name:string", "views:int", "active:bool", "score:float?", "owner_id:uuid?"}) + if err != nil { + t.Fatal(err) + } + r := config.Resource{Name: "Gadget", Table: "gadgets", Fields: fields} + out, err := render("", FileOp{Path: "internal/rest/gadget_handler.go", Template: "resource/rest_handler.go.tmpl", Data: ResourceData{Module: "example.com/app", Resource: r}}) + if err != nil { + t.Fatal(err) + } + src := string(out) + if strings.Contains(src, `validate:"required"`) { + t.Errorf(`handler still uses validate:"required", which rejects 0/false:%s`, src) + } + for _, f := range []string{`Name\s+string`, `Views\s+int64`, `Active\s+bool`} { + re := regexp.MustCompile(f + `\s+` + "`json:\"[a-z_]+\"`") + if n := len(re.FindAllString(src, -1)); n != 2 { // create + update bodies + t.Errorf("want %q as a required (key present) body field twice, found %d", f, n) + } + } + for _, f := range []string{`Score\s+\*float64`, `OwnerID\s+\*string`} { + re := regexp.MustCompile(f + `\s+` + "`json:\"[a-z_]+\" required:\"false\"`") + if n := len(re.FindAllString(src, -1)); n != 2 { + t.Errorf("want nullable %q to be optional in both bodies, found %d", f, n) + } + } + for _, want := range []string{ + "errors.Is(err, orm.ErrInvalidInput)", + `huma.Error422UnprocessableEntity("invalid field value", err)`, + `huma.Error404NotFound("gadget not found")`, + } { + if !strings.Contains(src, want) { + t.Errorf("handler is missing %q", want) + } + } +} + +// An id the database can't parse is "no row" in GraphQL too, and a bad body +// value is a BAD_USER_INPUT error rather than an internal one. +func TestResolverMapsInvalidInput(t *testing.T) { + r := config.Resource{Name: "Gadget", Table: "gadgets"} + out, err := render("", FileOp{Path: "internal/graph/resolvers/gadget.resolver.go", Template: "resource/resolver.go.tmpl", Data: ResourceData{Module: "example.com/app", Resource: r}}) + if err != nil { + t.Fatal(err) + } + src := string(out) + if strings.Count(src, "errors.Is(err, orm.ErrInvalidInput)") != 3 { + t.Errorf("want query, create and delete to handle orm.ErrInvalidInput:\n%s", src) + } + if !strings.Contains(src, `"BAD_USER_INPUT"`) { + t.Error("create should report a bad value as BAD_USER_INPUT") + } +} diff --git a/internal/generator/testdata/golden/mysql/gadget.table.hcl b/internal/generator/testdata/golden/mysql/gadget.table.hcl new file mode 100644 index 0000000..f877dd2 --- /dev/null +++ b/internal/generator/testdata/golden/mysql/gadget.table.hcl @@ -0,0 +1,67 @@ +# Code generated by togo. Atlas schema fragment (MySQL) — safe to edit. +table "gadgets" { + schema = schema.app + column "id" { + null = false + type = sql("char(36)") + default = sql("(uuid())") + } + column "name" { + null = false + type = text + } + column "bio" { + null = true + type = text + } + column "views" { + null = false + type = bigint + } + column "stock" { + null = true + type = int + } + column "active" { + null = false + type = boolean + } + column "score" { + null = true + type = double + } + column "price" { + null = false + type = sql("decimal(20,6)") + } + column "owner_id" { + null = true + type = sql("char(36)") + } + column "published_at" { + null = true + type = sql("datetime(6)") + } + column "birthday" { + null = false + type = date + } + column "meta" { + null = true + type = json + } + column "created_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + } + column "updated_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + on_update = sql("CURRENT_TIMESTAMP(6)") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/mysql/post.table.hcl b/internal/generator/testdata/golden/mysql/post.table.hcl new file mode 100644 index 0000000..fe2992b --- /dev/null +++ b/internal/generator/testdata/golden/mysql/post.table.hcl @@ -0,0 +1,31 @@ +# Code generated by togo. Atlas schema fragment (MySQL) — safe to edit. +table "posts" { + schema = schema.app + column "id" { + null = false + type = sql("char(36)") + default = sql("(uuid())") + } + column "title" { + null = false + type = text + } + column "body" { + null = false + type = text + } + column "created_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + } + column "updated_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + on_update = sql("CURRENT_TIMESTAMP(6)") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/mysql/tag.table.hcl b/internal/generator/testdata/golden/mysql/tag.table.hcl new file mode 100644 index 0000000..82e20e4 --- /dev/null +++ b/internal/generator/testdata/golden/mysql/tag.table.hcl @@ -0,0 +1,23 @@ +# Code generated by togo. Atlas schema fragment (MySQL) — safe to edit. +table "tags" { + schema = schema.app + column "id" { + null = false + type = sql("char(36)") + default = sql("(uuid())") + } + column "created_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + } + column "updated_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + on_update = sql("CURRENT_TIMESTAMP(6)") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/postgres/gadget.table.hcl b/internal/generator/testdata/golden/postgres/gadget.table.hcl new file mode 100644 index 0000000..8258597 --- /dev/null +++ b/internal/generator/testdata/golden/postgres/gadget.table.hcl @@ -0,0 +1,63 @@ +# Code generated by togo. Atlas schema fragment (PostgreSQL) — safe to edit. +table "gadgets" { + schema = schema.public + column "id" { + type = uuid + default = sql("gen_random_uuid()") + } + column "name" { + null = false + type = text + } + column "bio" { + null = true + type = text + } + column "views" { + null = false + type = bigint + } + column "stock" { + null = true + type = integer + } + column "active" { + null = false + type = boolean + } + column "score" { + null = true + type = sql("double precision") + } + column "price" { + null = false + type = numeric + } + column "owner_id" { + null = true + type = uuid + } + column "published_at" { + null = true + type = timestamptz + } + column "birthday" { + null = false + type = date + } + column "meta" { + null = true + type = jsonb + } + column "created_at" { + type = timestamptz + default = sql("now()") + } + column "updated_at" { + type = timestamptz + default = sql("now()") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/postgres/post.table.hcl b/internal/generator/testdata/golden/postgres/post.table.hcl new file mode 100644 index 0000000..c67db97 --- /dev/null +++ b/internal/generator/testdata/golden/postgres/post.table.hcl @@ -0,0 +1,27 @@ +# Code generated by togo. Atlas schema fragment (PostgreSQL) — safe to edit. +table "posts" { + schema = schema.public + column "id" { + type = uuid + default = sql("gen_random_uuid()") + } + column "title" { + null = false + type = text + } + column "body" { + null = false + type = text + } + column "created_at" { + type = timestamptz + default = sql("now()") + } + column "updated_at" { + type = timestamptz + default = sql("now()") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/postgres/tag.table.hcl b/internal/generator/testdata/golden/postgres/tag.table.hcl new file mode 100644 index 0000000..5cc30fe --- /dev/null +++ b/internal/generator/testdata/golden/postgres/tag.table.hcl @@ -0,0 +1,19 @@ +# Code generated by togo. Atlas schema fragment (PostgreSQL) — safe to edit. +table "tags" { + schema = schema.public + column "id" { + type = uuid + default = sql("gen_random_uuid()") + } + column "created_at" { + type = timestamptz + default = sql("now()") + } + column "updated_at" { + type = timestamptz + default = sql("now()") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/sqlite/gadget.table.hcl b/internal/generator/testdata/golden/sqlite/gadget.table.hcl new file mode 100644 index 0000000..1b7377c --- /dev/null +++ b/internal/generator/testdata/golden/sqlite/gadget.table.hcl @@ -0,0 +1,66 @@ +# Code generated by togo. Atlas schema fragment (SQLite) — safe to edit. +table "gadgets" { + schema = schema.main + column "id" { + null = true + type = text + default = sql("lower(hex(randomblob(16)))") + } + column "name" { + null = false + type = text + } + column "bio" { + null = true + type = text + } + column "views" { + null = false + type = integer + } + column "stock" { + null = true + type = integer + } + column "active" { + null = false + type = boolean + } + column "score" { + null = true + type = real + } + column "price" { + null = false + type = text + } + column "owner_id" { + null = true + type = text + } + column "published_at" { + null = true + type = datetime + } + column "birthday" { + null = false + type = datetime + } + column "meta" { + null = true + type = text + } + column "created_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + column "updated_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/sqlite/post.table.hcl b/internal/generator/testdata/golden/sqlite/post.table.hcl new file mode 100644 index 0000000..243c423 --- /dev/null +++ b/internal/generator/testdata/golden/sqlite/post.table.hcl @@ -0,0 +1,30 @@ +# Code generated by togo. Atlas schema fragment (SQLite) — safe to edit. +table "posts" { + schema = schema.main + column "id" { + null = true + type = text + default = sql("lower(hex(randomblob(16)))") + } + column "title" { + null = false + type = text + } + column "body" { + null = false + type = text + } + column "created_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + column "updated_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/generator/testdata/golden/sqlite/tag.table.hcl b/internal/generator/testdata/golden/sqlite/tag.table.hcl new file mode 100644 index 0000000..161f72b --- /dev/null +++ b/internal/generator/testdata/golden/sqlite/tag.table.hcl @@ -0,0 +1,22 @@ +# Code generated by togo. Atlas schema fragment (SQLite) — safe to edit. +table "tags" { + schema = schema.main + column "id" { + null = true + type = text + default = sql("lower(hex(randomblob(16)))") + } + column "created_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + column "updated_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + primary_key { + columns = [column.id] + } +} diff --git a/internal/templates/files/resource/resolver.go.tmpl b/internal/templates/files/resource/resolver.go.tmpl index b7f39fc..628cc9b 100644 --- a/internal/templates/files/resource/resolver.go.tmpl +++ b/internal/templates/files/resource/resolver.go.tmpl @@ -3,14 +3,23 @@ package resolvers import ( "context" + "errors" + + "github.com/togo-framework/orm" + "github.com/vektah/gqlparser/v2/gqlerror" db "{{.Module}}/internal/db/gen" graphgen "{{.Module}}/internal/graph/gen" "{{.Module}}/internal/models" ) +// An id the database can't parse (orm.ErrInvalidInput) matches no row: null. func (r *queryResolver) {{.Resource.Name}}(ctx context.Context, id string) (*db.{{.Resource.Name}}, error) { - return models.{{plural .Resource.Name}}(r.App).Find(ctx, id) + row, err := models.{{plural .Resource.Name}}(r.App).Find(ctx, id) + if errors.Is(err, orm.ErrInvalidInput) { + return nil, nil + } + return row, err } func (r *queryResolver) {{plural .Resource.Name}}(ctx context.Context) ([]*db.{{.Resource.Name}}, error) { @@ -31,6 +40,12 @@ func (r *mutationResolver) Create{{.Resource.Name}}(ctx context.Context, input g "{{.Name}}": input.{{pascal .Name}}, {{- end}} }) + if errors.Is(err, orm.ErrInvalidInput) { + return nil, &gqlerror.Error{ + Message: "invalid field value: " + err.Error(), + Extensions: map[string]any{"code": "BAD_USER_INPUT"}, + } + } if err != nil { return nil, err } @@ -39,7 +54,11 @@ func (r *mutationResolver) Create{{.Resource.Name}}(ctx context.Context, input g } func (r *mutationResolver) Delete{{.Resource.Name}}(ctx context.Context, id string) (bool, error) { - if err := models.{{plural .Resource.Name}}(r.App).Where("id", "=", id).Delete(ctx); err != nil { + err := models.{{plural .Resource.Name}}(r.App).Where("id", "=", id).Delete(ctx) + if errors.Is(err, orm.ErrInvalidInput) { + return false, nil // no row has that id + } + if err != nil { return false, err } r.App.Emit(ctx, "{{snake .Resource.Name}}.deleted", id) diff --git a/internal/templates/files/resource/rest_handler.go.tmpl b/internal/templates/files/resource/rest_handler.go.tmpl index 0702863..1980ef1 100644 --- a/internal/templates/files/resource/rest_handler.go.tmpl +++ b/internal/templates/files/resource/rest_handler.go.tmpl @@ -3,12 +3,14 @@ package rest import ( "context" + "errors" "net/http" {{- if .NeedsTime}} "time" {{- end}} "github.com/danielgtaylor/huma/v2" + "github.com/togo-framework/orm" "github.com/togo-framework/validation" "{{.Module}}/internal/app" @@ -19,6 +21,11 @@ import ( // Register{{.Resource.Name}}Routes mounts CRUD endpoints for {{.Resource.Table}}. // Queries use the driver-agnostic ORM; responses go through resources.Transform{{.Resource.Name}}; // create/delete broadcast events ("{{snake .Resource.Name}}.created"/".deleted"). +// +// Bodies follow the GraphQL input rules: a non-null field's key must be present +// (0, false and "" are valid values); a nullable field may be omitted or null. +// An id or value the database can't parse (orm.ErrInvalidInput, e.g. a malformed +// uuid on Postgres) is a 404 for path ids and a 422 for body values. func Register{{.Resource.Name}}Routes(api huma.API, a *app.App) { huma.Register(api, huma.Operation{ OperationID: "list-{{kebab (plural .Resource.Name)}}", Method: http.MethodGet, Path: "/api/{{.Resource.Table}}", @@ -47,7 +54,7 @@ func Register{{.Resource.Name}}Routes(api huma.API, a *app.App) { Body resources.{{.Resource.Name}}Response }, error) { row, err := models.{{plural .Resource.Name}}(a).Find(ctx, in.ID) - if err != nil { + if err != nil && !errors.Is(err, orm.ErrInvalidInput) { return nil, huma.Error500InternalServerError("get failed", err) } if row == nil { @@ -64,7 +71,7 @@ func Register{{.Resource.Name}}Routes(api huma.API, a *app.App) { }, func(ctx context.Context, in *struct { Body struct { {{- range .Resource.Fields}} - {{pascal .Name}} {{if .Null}}*{{end}}{{.Go}} `json:"{{.Name}}"{{if not .Null}} validate:"required"{{end}}` + {{pascal .Name}} {{if .Null}}*{{end}}{{.Go}} `json:"{{.Name}}"{{if .Null}} required:"false"{{end}}` {{- end}} } }) (*struct { @@ -79,6 +86,9 @@ func Register{{.Resource.Name}}Routes(api huma.API, a *app.App) { "{{.Name}}": in.Body.{{pascal .Name}}, {{- end}} }) + if errors.Is(err, orm.ErrInvalidInput) { + return nil, huma.Error422UnprocessableEntity("invalid field value", err) + } if err != nil { return nil, huma.Error500InternalServerError("create failed", err) } @@ -95,17 +105,28 @@ func Register{{.Resource.Name}}Routes(api huma.API, a *app.App) { ID string `path:"id"` Body struct { {{- range .Resource.Fields}} - {{pascal .Name}} {{if .Null}}*{{end}}{{.Go}} `json:"{{.Name}}"` + {{pascal .Name}} {{if .Null}}*{{end}}{{.Go}} `json:"{{.Name}}"{{if .Null}} required:"false"{{end}}` {{- end}} } }) (*struct { Body resources.{{.Resource.Name}}Response }, error) { - if err := models.{{plural .Resource.Name}}(a).Where("id", "=", in.ID).Update(ctx, map[string]any{ + existing, err := models.{{plural .Resource.Name}}(a).Find(ctx, in.ID) + if err != nil && !errors.Is(err, orm.ErrInvalidInput) { + return nil, huma.Error500InternalServerError("update failed", err) + } + if existing == nil { + return nil, huma.Error404NotFound("{{lower .Resource.Name}} not found") + } + err = models.{{plural .Resource.Name}}(a).Where("id", "=", in.ID).Update(ctx, map[string]any{ {{- range .Resource.Fields}} "{{.Name}}": in.Body.{{pascal .Name}}, {{- end}} - }); err != nil { + }) + if errors.Is(err, orm.ErrInvalidInput) { + return nil, huma.Error422UnprocessableEntity("invalid field value", err) + } + if err != nil { return nil, huma.Error500InternalServerError("update failed", err) } row, err := models.{{plural .Resource.Name}}(a).Find(ctx, in.ID) @@ -124,7 +145,11 @@ func Register{{.Resource.Name}}Routes(api huma.API, a *app.App) { }, func(ctx context.Context, in *struct { ID string `path:"id"` }) (*struct{}, error) { - if err := models.{{plural .Resource.Name}}(a).Where("id", "=", in.ID).Delete(ctx); err != nil { + err := models.{{plural .Resource.Name}}(a).Where("id", "=", in.ID).Delete(ctx) + if errors.Is(err, orm.ErrInvalidInput) { + return nil, huma.Error404NotFound("{{lower .Resource.Name}} not found") + } + if err != nil { return nil, huma.Error500InternalServerError("delete failed", err) } a.Emit(ctx, "{{snake .Resource.Name}}.deleted", in.ID) diff --git a/internal/templates/files/resource/table.hcl.tmpl b/internal/templates/files/resource/table.hcl.tmpl index 2b4f60e..fbb9cdf 100644 --- a/internal/templates/files/resource/table.hcl.tmpl +++ b/internal/templates/files/resource/table.hcl.tmpl @@ -1,6 +1,37 @@ -# Code generated by togo. Atlas schema fragment — safe to edit. +{{- if eq .Dialect "mysql" -}} +# Code generated by togo. Atlas schema fragment (MySQL) — safe to edit. table "{{.Resource.Table}}" { - schema = schema.public + schema = schema.{{.AtlasSchema}} + column "id" { + null = false + type = sql("char(36)") + default = sql("(uuid())") + } +{{- range .Resource.Fields}} + column "{{.Name}}" { + null = {{.Null}} + type = {{atlasCol "mysql" .}} + } +{{- end}} + column "created_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + } + column "updated_at" { + null = false + type = sql("datetime(6)") + default = sql("CURRENT_TIMESTAMP(6)") + on_update = sql("CURRENT_TIMESTAMP(6)") + } + primary_key { + columns = [column.id] + } +} +{{- else if eq .Dialect "postgres" -}} +# Code generated by togo. Atlas schema fragment (PostgreSQL) — safe to edit. +table "{{.Resource.Table}}" { + schema = schema.{{.AtlasSchema}} column "id" { type = uuid default = sql("gen_random_uuid()") @@ -8,7 +39,7 @@ table "{{.Resource.Table}}" { {{- range .Resource.Fields}} column "{{.Name}}" { null = {{.Null}} - type = {{atlasType .PG}} + type = {{atlasCol "postgres" .}} } {{- end}} column "created_at" { @@ -23,3 +54,33 @@ table "{{.Resource.Table}}" { columns = [column.id] } } +{{- else -}} +# Code generated by togo. Atlas schema fragment (SQLite) — safe to edit. +table "{{.Resource.Table}}" { + schema = schema.{{.AtlasSchema}} + column "id" { + null = true + type = text + default = sql("lower(hex(randomblob(16)))") + } +{{- range .Resource.Fields}} + column "{{.Name}}" { + null = {{.Null}} + type = {{atlasCol "sqlite" .}} + } +{{- end}} + column "created_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + column "updated_at" { + null = false + type = datetime + default = sql("datetime('now')") + } + primary_key { + columns = [column.id] + } +} +{{- end}}