definitionc

package module
v0.1.50 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 16 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

definitionc is the code generator of a webtyp module. You declare the module once, in definition.go; it writes the module's operations and one rule file for every business rule you declare. You write the rules, never the wiring.

1. Why This Exists

Without it, a module mounts its entities by hand in an ops.go:

// ops.go, written by hand: every entity and every rule is a line someone must remember.
func (m *Module) MountOperations(reg crud.Registry) {
	reg.AddStoredEntity(crud.StoredEntity{Model: &Patient{}, /* … */ Create: createPatient})
	// a new entity with actions added to the module but forgotten here is never offered
}

A forgotten entity is silent: the API simply does not have it. A rule that exists only in a comment is silent too.

With it, the declaration is the only list. The entity says which actions it allows and which of them have a business rule. The generator mounts every allowed action, and for each business rule it creates a skeleton file that does not compile until someone writes the rule. The compiler is the reminder.

2. Step-by-Step Guide

Step 1 — declare each model with its actions and their rules. Allow is what the API offers; Rules says, for each allowed action, whether the entity has a business rule of its own (model.AddMyBusinessRule) or crud's checks are enough (model.HaveNoBusinessRule). An allowed action without a declared rule is an error.

var PatientModel = model.Definition{
	Name:  "patient",
	Allow: model.Create | model.Read | model.Update,
	Rules: model.Rules{Create: model.AddMyBusinessRule, Read: model.HaveNoBusinessRule, Update: model.AddMyBusinessRule},
	Fields: model.Fields{
		{Name: "id", Type: model.Text(), DB: &model.FieldDB{PK: true}},
		{Name: "name", Type: model.Text(), Item: model.ItemLabel},
	},
}

Step 2 — declare the module: its name and every entity it serves.

var Definition = model.ModuleDefinition{Name: "patient_directory", Entities: []model.Definition{PatientModel}}

Step 3 — write module.go, the hand-written part. The module type, and one store method per table entity:

package patientdirectory

import "webtyp.com/crud"

type Module struct{ store crud.Store }

func (m *Module) StorePatient() crud.Store { return m.store }

Step 4 — save definition.go (or run definitionc in the module). The generator writes definition_gen.go with ModelName(), Definition() and MountOperations(reg), and creates rule_patient_create.go with the rule skeleton.

Step 5 — complete the rule. The skeleton declares the outputs and leaves them unused, so the module reports declared and not used and missing return until you return an answer. The marker // COMPLETA TU REGLA DE NEGOCIO AQUÍ shows where to write it. Once the file exists, definitionc never overwrites it.

3. The Rule Signatures

Each rule is a method on the record (p or next); m is the module, so a rule reaches its dependencies through m. The signatures are fixed:

Action File Signature
create rule_patient_create.go func (p *Patient) Create(a crud.CurrentUser, tx crud.Tx, m *Module) (crud.RuleAnswer, error)
update rule_patient_update.go func (next *Patient) Update(a crud.CurrentUser, tx crud.Tx, old *Patient, fields []string, m *Module) (crud.RuleAnswer, error)
delete rule_patient_delete.go func (p *Patient) Delete(a crud.CurrentUser, tx crud.Tx, m *Module) (crud.RuleAnswer, error)
search (table, Rules.Read: AddMyBusinessRule) rule_patient_search.go func (p *Patient) Search(a crud.CurrentUser, filter *Patient, text string, m *Module) ([]storage.Condition, error)
read (model without a table, Rules.Read: AddMyBusinessRule) rule_health_read.go func (p *Health) Read(a crud.CurrentUser, filter *Health, args crud.ReadArgs, m *Module) (model.ModelSlice, error)
  • Search is called on a zero record ((&Patient{}).Search(…)): it uses no record data. filter carries only the fields the caller sent (the entity is its own filter), and text is "" when none was sent.
  • A table read declared model.HaveNoBusinessRule is crud's default read: id, search by the item label, page, cap and tenant.
  • A rule file for an action that is not declared model.AddMyBusinessRule is an error, so a deleted declaration cannot leave a rule behind silently.
  • A model with a Wire format may only be read, through its own rule (rule_<name>_read.go).
  • A read-only model declared in another package is listed with its package (Entities: []model.Definition{UserModel, me.MeModel}) and answered by a function, because Go allows no method on another package's type: func readMe(a crud.CurrentUser, filter *me.Me, args crud.ReadArgs, m *Module) (model.ModelSlice, error) in rule_me_read.go. Its type and codecs are generated in its own package. Only a read-only model (Allow: model.Read, no table) may live outside the module.
External Calls

When an entity declares ExternalCalls: []model.ExternalCallDefinition{...}:

  • definitionc generates one call type per declaration: type <Entity><Call> struct{} implementing crud.ExternalCall (ModelName() string). Rules return these in crud.ApplyAndPublish(calls...).
  • In definition_gen.go, it adds ExternalCalls: <Entity>Model.ExternalCalls and wires Calls: map[string]crud.ExternalCallFunc to delegate to <Entity>.<Call>(a, m, key).
  • It writes a call skeleton call_<entity>_<call>.go with signature: func (p *<Entity>) <Call>(a crud.CurrentUser, m *Module, key crud.IdempotencyKey) (crud.FieldsToSave, error) Like rule skeletons, the call skeleton does not compile until completed.

definitionc writes ModelName(), Definition() and MountOperations(reg) in definition_gen.go. It never writes Module, New or the Store<Entity>() methods: those are the module's own code.

4. Documentation Map

Run the tests with gotest in the module and in tests/.

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")

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
	Revision        bool // the integer column that counts the row's updates (model.FieldDB.Revision)
	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 ModuleEntity added in v0.1.50

type ModuleEntity struct {
	Name       string
	Qualifier  string
	ImportPath string
}

ModuleEntity is one element of Definition.Entities as written: PatientModel → {Name: "Patient"}; me.MeModel → {Name: "Me", Qualifier: "me", ImportPath: "webtyp.com/auth/me"}.

type ModuleInfo added in v0.1.40

type ModuleInfo struct {
	Name     string         // Definition.Name, e.g. "patient_directory"
	Package  string         // the Go package of definition.go
	Entities []ModuleEntity // each listed model, in the order written
}

ModuleInfo is `var Definition = model.ModuleDefinition{…}` as written in definition.go.

type ProbeRunner

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

type RulesInfo added in v0.1.40

type RulesInfo struct {
	Create, Read, Update, Delete uint8
}

RulesInfo is Definition.Rules as written in definition.go: for each action the value of model.RuleMode (0 = undeclared).

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
	ListsOnlyAfterSearch bool // model.Definition{ListsOnlyAfterSearch: true}: definitionc generates ListsOnlyAfterSearch()
	Allow                uint8
	Rules                RulesInfo // Definition.Rules as written
	MFA                  uint8     // Definition.MFA as written (a set of actions)
	ExternalCalls        []model.ExternalCallDefinition
	SourceFile           string
	// ImportPath and Qualifier are set only on a read-only entity a module lists from another package
	// (Entities: []model.Definition{me.MeModel}): its import path and the name definition.go calls it by ("me").
	ImportPath string
	Qualifier  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