Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
58 changes: 58 additions & 0 deletions internal/generator/dialect.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package generator

import (
"os"
"path/filepath"
"regexp"
"strings"

"github.com/togo-framework/cli/internal/config"
Expand Down Expand Up @@ -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)
}
}
63 changes: 56 additions & 7 deletions internal/generator/dialect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,27 +46,31 @@ 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
}
got, err := render("", op)
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)
Expand Down Expand Up @@ -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)
}
}
1 change: 1 addition & 0 deletions internal/generator/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion internal/generator/plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
8 changes: 7 additions & 1 deletion internal/generator/plans.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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},
}
Expand Down
66 changes: 66 additions & 0 deletions internal/generator/rest_body_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
67 changes: 67 additions & 0 deletions internal/generator/testdata/golden/mysql/gadget.table.hcl
Original file line number Diff line number Diff line change
@@ -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]
}
}
31 changes: 31 additions & 0 deletions internal/generator/testdata/golden/mysql/post.table.hcl
Original file line number Diff line number Diff line change
@@ -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]
}
}
Loading
Loading