definitionc

package module
v0.1.39 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

definitionc

Go code generator for webtyp/model definitions: reads hand-written model.Definition literals via AST and emits the concrete struct, schema, codec, validation, and typed query helpers the runtime consumes.

Quick-start

Install the CLI:

go install webtyp.com/definitionc/cmd/definitionc@latest

Author a definition.go (or definition.go) with one or more model.Definition literals. Each field declares its kind in the single Type: slot as a constructor expression — never a bare enum, never a struct tag:

package myapp

import (
	"webtyp.com/model"
	"webtyp.com/input"
)

var AddressModel = model.Definition{
	Name: "address",
	Fields: model.Fields{
		{Name: "street", Type: model.Text()},
		{Name: "city", Type: model.Text()},
	},
}

var UserModel = model.Definition{
	Name: "user",
	Fields: model.Fields{
		{Name: "id", Type: model.Int(), DB: &model.FieldDB{PK: true, AutoInc: true}},
		{Name: "email", Type: input.Email(), NotNull: true},   // form kind: validates + renders
		{Name: "status", Type: model.Text()},                   // base kind: validates only
		{Name: "address", Type: model.Struct(&AddressModel)},   // composition: ref IN the constructor
		{Name: "manager_id", Type: model.Int(), Ref: &UserModel}, // scalar FK: Ref's ONLY meaning
	},
}

Run the generator from the module root:

definitionc

It walks the module for definition.go/definition.go files and writes one <file>_gen.go per source file, containing the plain struct, the Fielder methods (Schema(), Pointers(), encode/decode), Validate(), typed query-field helpers (User_.Email), and SchemaExt() for any scalar FKs. model.* kinds resolve via a builtin table; every other kind (form kinds, project-custom kinds) resolves by executing its real Storage() through a cached, generation-time dependency probe — see docs/ARCHITECTURE.md for the resolution order and failure modes.

Inside webtyp/app's dev console, definitionc runs as a live TUI handler instead of the standalone CLI: New() returns a *Generator implementing the handler contract (Name(), SupportedExtensions(), NewFileEvent(...)), so the tool regenerates the affected _gen.go on every save and, once SetSyncer is called, syncs the DB schema. See docs/SYNC_DESIGN.md and docs/diagrams/DB_SYNC.md for the watcher/sync flow.

API

Models(root) ([]model.Model, error) — the database models of root in file order: foreign keys in SchemaExt(), a select's Options table, and an instant's kind (UnixTime, NanoTime), not just its storage; ErrNoModelsFound when none. Used by webtyp/erd.

List Items

definitionc generates a typed func (m *X) Item() model.Item for every model with at least one field marked Item: (model.ItemLabel, model.ItemDescription, model.ItemBadge). Multiple description fields are joined with model.JoinItem. A date field marked ItemBadge is rendered as seconds since 1970 (fmt.Convert(int64(m.At)/1000000000).String()).

Invalid item declarations are rejected at generation time via model.ValidateItem:

  • At most one ItemLabel and at most one ItemBadge.
  • Any ItemDescription or ItemBadge requires an ItemLabel.
  • Listed models require a primary key.
  • Only scalar fields can be shown in a list item.
  • Row: was replaced by Item:; legacy Row: marks are rejected.

Instants

model.UnixTime() and model.NanoTime() generate fields typed time.Unix and time.Nano (webtyp.com/time), imported automatically. They are stored as integers: Pointers() exposes them as (*int64)(&m.Field), and the codec converts explicitly (w.Int("x", int64(m.X)), m.X = time.Unix(v)), so storage backends and codecs need no change while the compiler rejects a nanosecond instant in a seconds field.

Generated CRUD mounts

When the nearest go.mod requires webtyp.com/crud, definitionc writes <source>_crud.go next to <source>_gen.go with one typed Mount<Entity> function:

Allow in the definition → Mount<E>(reg, store, <E>Rules{…}):

type PatientRules struct {
	Create    func(c crud.Caller, tx crud.Tx, p *Patient) error
	Update    func(c crud.Caller, tx crud.Tx, old, next *Patient, fields []string) error
	Delete    func(c crud.Caller, tx crud.Tx, p *Patient) error
	Search    func(c crud.Caller, text string) ([]storage.Condition, error)
	NewFilter func() model.Model
	Committed func(c crud.Caller, action model.Action, p *Patient, fields []string)
	MFA       model.Action
}

func MountPatient(reg crud.Registry, store crud.Store, rules PatientRules)

Only table entities that declare Allow (!info.NoDB && !info.Wire && info.Allow != 0) receive mounts; without Allow, nothing is generated. Packages without crud generate no CRUD file, and existing stale CRUD files are removed.

Documentation

Documentation

Index

Constants

View Source
const (
	DefinitionFile  = "definition.go"
	GeneratedSuffix = "_gen.go"
)

DefinitionFile is the one file name definitionc reads: every model.Definition of a package lives in it. GeneratedSuffix ends the file it writes next to it (definition.go → definition_gen.go).

View Source
const (
	GeneratedHeader = "// DO NOT EDIT. generated by webtyp.com/definitionc"
)

Variables

View Source
var ErrNoModelsFound = fmt.Err("no", "models", "found")

ErrNoModelsFound is returned by ExportSQL when the target directory has no definition.go files (or none define an exported, non-NoDB model). Signals "nothing to export" distinctly from a successful empty schema.

Functions

func FieldTypeToGoType

func FieldTypeToGoType(ft model.FieldType, ref string) string

func ToSnakeCase

func ToSnakeCase(s string) string

Types

type Exporter

type Exporter interface {
	ExportDDL(models []model.Model) (string, error)
}

Exporter is implemented by SQL adapter compilers (sqlt, postgres) that can render a full schema export. Defined here — not imported from ddlc — per Go convention: the consumer of a single-method interface owns the interface, not the implementer.

type FieldInfo

type FieldInfo struct {
	Name            string
	ColumnName      string
	Type            model.FieldType
	KindConstructor string
	KindImportPath  string   // resolved import path of the constructor's package (empty for model.* builtins)
	KindImportAlias string   // alias/selector used in the scanned source (e.g. "input" in "input.Email()")
	KindArgIdents   []string // bare identifiers passed as direct arguments to the constructor call
	PK              bool
	Unique          bool
	NotNull         bool
	AutoInc         bool
	Ref             string
	RefColumn       string
	OnDelete        string
	Item            model.ItemSlot // list-item slot from Field.Item; ItemNone when absent
	Options         string         // Definition var name from Field.Options (e.g. "ZoneModel"); "" when absent
	IsPK            bool
	OldName         string
	GoType          string
	IsPointer       bool // true if the original field is *T (only meaningful for FieldStruct)
	OmitEmpty       bool
	Exclude         bool
	HasDB           bool
	// Permitted config — populated from validate:"..." tag
	Letters bool
	Tilde   bool
	Numbers bool
	Spaces  bool
	Extra   []rune
	Minimum int
	Maximum int
	Tags    []string // input modifiers e.g. "notilde", "min=2"
}

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator is the code generator handler for the definitionc tool.

func New

func New() *Generator

NewOrmc creates a new Definitionc handler with rootDir defaulting to ".".

func (*Generator) ExportSQL

func (g *Generator) ExportSQL(root string, exporter Exporter) (string, error)

ExportSQL scans the directory for models and returns the full DDL. Requires an injected Exporter (e.g. from sqlt or postgres).

func (*Generator) GenerateForFile

func (o *Generator) GenerateForFile(infos []StructInfo, sourceFile string) error

GenerateForFile writes ORM implementations for all infos into one file.

func (*Generator) GenerateForStruct

func (g *Generator) GenerateForStruct(structName string, goFile string) error

GenerateForStruct reads the Go File and generates the ORM implementations for a given struct name.

func (*Generator) MainInputFileRelativePath

func (g *Generator) MainInputFileRelativePath() string

MainInputFileRelativePath returns the relative path to the main input file, if any.

func (*Generator) Models

func (g *Generator) Models(root string) ([]model.Model, error)

Models scans root for definition.go and returns one model.Model per database struct (NoDB structs skipped), in the order the files and declarations were read — the same root always gives the same order. A model's foreign keys are in its SchemaExt(). It returns ErrNoModelsFound when there is none.

func (*Generator) Name

func (g *Generator) Name() string

Name returns the TUI handler label shown in the development console.

func (*Generator) NewFileEvent

func (g *Generator) NewFileEvent(fileName, extension, filePath, event string) error

NewFileEvent implements the file-event contract for watchers (e.g. webtyp/app's devwatch).

func (*Generator) Run

func (g *Generator) Run() error

Run is the entry point for the CLI tool.

func (*Generator) ScanModules

func (g *Generator) ScanModules(rootDir string) error

ScanModules syncs the DB schema of every discovered module to the injected SchemaSyncer. Called once at startup by the tool (app), after SetSyncer.

  • Writable module (main / replace): regenerate <file>_gen.go from definition.go, then sync each DB struct.
  • Read-only module (cache): parse the committed definition_gen.go, then sync.

No-op if no syncer is injected (CLI codegen-only path).

func (*Generator) SetFinder

func (g *Generator) SetFinder(f modfind.Discoverer)

SetFinder injects the shared modfind.Finder (one go list across ssr/image/definitionc).

func (*Generator) SetLog

func (g *Generator) SetLog(fn func(messages ...any))

SetLog sets the log function for warnings and informational messages. If not set, messages are silently discarded.

func (*Generator) SetRootDir

func (g *Generator) SetRootDir(dir string)

SetRootDir sets the root directory that Run() will scan. Defaults to ".". Useful in tests to point to a specific directory without needing os.Chdir.

func (*Generator) SetSkipTidy

func (g *Generator) SetSkipTidy(skip bool)

SetSkipTidy enables or disables the go mod tidy pass.

func (*Generator) SetSyncer

func (g *Generator) SetSyncer(s SchemaSyncer)

SetSyncer sets the schema syncer for the generator.

func (*Generator) SupportedExtensions

func (g *Generator) SupportedExtensions() []string

SupportedExtensions returns the list of file extensions this generator handles.

func (*Generator) UnobservedFiles

func (g *Generator) UnobservedFiles() []string

UnobservedFiles returns a list of files that should be ignored by the watcher.

type ProbeRunner

type ProbeRunner func(mainContent string, workDir string) (string, error)

type SchemaSyncer

type SchemaSyncer interface {
	SyncSchema(table string, fields []model.Field) error
}

SchemaSyncer applies a parsed table schema. Implemented by the consumer (webtyp/app) over *orm.DB; definitionc only ever sees this interface.

type StructInfo

type StructInfo struct {
	Name              string
	ModelName         string
	PackageName       string
	Fields            []FieldInfo
	ModelNameDeclared bool
	NoDB              bool
	Wire              bool // model.Definition{Wire: true}: a transport format, never a form
	Allow             uint8
	SourceFile        string
}

Directories

Path Synopsis
cmd
definitionc command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL