ormc

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 14 Imported by: 0

README

ormc

Go code generator for tinywasm/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 github.com/tinywasm/ormc/cmd/ormc@latest

Author a model.go (or models.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 (
	"github.com/tinywasm/model"
	"github.com/tinywasm/form/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:

ormc

It walks the module for model.go/models.go files and writes one <file>_orm.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 tinywasm/app's dev console, ormc 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 _orm.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.

Documentation

Documentation

Index

Constants

View Source
const (
	GeneratedHeader = "// DO NOT EDIT. generated by github.com/tinywasm/ormc"
)

Variables

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

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

Functions

func FieldTypeToGoType added in v0.0.2

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

func ToSnakeCase added in v0.0.2

func ToSnakeCase(s string) string

Types

type Exporter added in v0.1.0

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 added in v0.0.2

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
	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 added in v0.0.2

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

Ormc is the code generator handler for the ormc tool.

func New

func New() *Generator

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

func (*Generator) ExportSQL added in v0.0.2

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 added in v0.0.2

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

GenerateForFile writes ORM implementations for all infos into one file.

func (*Generator) GenerateForStruct added in v0.0.2

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 added in v0.0.2

func (g *Generator) MainInputFileRelativePath() string

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

func (*Generator) Name added in v0.0.2

func (g *Generator) Name() string

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

func (*Generator) NewFileEvent added in v0.0.2

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

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

func (*Generator) Run added in v0.0.2

func (g *Generator) Run() error

Run is the entry point for the CLI tool.

func (*Generator) ScanModules added in v0.0.2

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>_orm.go from model.go, then sync each DB struct.
  • Read-only module (cache): parse the committed model_orm.go, then sync.

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

func (*Generator) SetFinder added in v0.0.2

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

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

func (*Generator) SetLog added in v0.0.2

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 added in v0.0.2

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 added in v0.0.2

func (g *Generator) SetSkipTidy(skip bool)

SetSkipTidy enables or disables the go mod tidy pass.

func (*Generator) SetSyncer added in v0.0.2

func (g *Generator) SetSyncer(s SchemaSyncer)

SetSyncer sets the schema syncer for the generator.

func (*Generator) SupportedExtensions added in v0.0.2

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

SupportedExtensions returns the list of file extensions this generator handles.

func (*Generator) UnobservedFiles added in v0.0.2

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

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

type ProbeRunner added in v0.0.2

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

type SchemaSyncer added in v0.0.2

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

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

type StructInfo added in v0.0.2

type StructInfo struct {
	Name              string
	ModelName         string
	PackageName       string
	Fields            []FieldInfo
	ModelNameDeclared bool
	IsForm            bool
	NoDB              bool
	SourceFile        string
}

Directories

Path Synopsis
cmd
ormc command

Jump to

Keyboard shortcuts

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