Skip to Content
fusion-orm
API Reference

Schema & naming symbols

The metadata layer plugins and advanced users touch — Table, Field, Relation, namers, appenders, scanners, and serializers from package schema.

Package schema provides cached reflection metadata for models: tables, fields, relations and precompiled per-field closures. It depends on neither the session layer nor the query engine. Plugins and advanced users reach it through db.Parse / Tables.

Parse entry points

Tables and NewTables

func NewTables(namer Namer, strict bool, warn func(string)) *Tables

Creates a per-naming-strategy parse cache. strict rejects unknown tag keys; warn (when non-nil) receives each leniently ignored key. Each session's Config owns one Tables; parsing is deduplicated across concurrent callers and supports recursive models via two-phase init.

Parse and Get

func (ts *Tables) Parse(model any) (*Table, error)

func (ts *Tables) Get(typ reflect.Type) (*Table, error)

Parses a struct (or pointer to struct) and returns its cached Table. Repeated parses return the identical pointer. On a *DB:

func (db *DB) Parse(model any) (*schema.Table, error)

Table

type Table struct {
	Type      reflect.Type
	Name      string       // table name
	ModelName string       // snake_case model name
	Fields    []*Field     // declaration order
	PKs       []*Field     // primary-key fields
	FieldMap  map[string]*Field // by Go name
	DBNames   map[string]*Field // by column name
	Relations map[string]*Relation
	Hooks     Hooks        // detected hook methods
	InsertColumns []string // columns written by a plain INSERT
	SoftDeleteField *Field // nil when the model has none
	Strict    bool
}

Lookup helpers:

func (t *Table) Field(name string) *Field  // by Go name
func (t *Table) Column(name string) *Field // by column name

Hooks records which model hook methods are present, detected at parse time (BeforeCreate, AfterCreate, BeforeUpdate, AfterUpdate, BeforeDelete, AfterDelete, BeforeFind, AfterFind — each a bool).

Field

Key fields of the parsed metadata:

type Field struct {
	Table        *Table
	StructField  reflect.StructField
	Index        []int        // path to the field in the struct
	Name         string       // Go name
	DBName       string       // column name
	IndirectType reflect.Type // pointer-elem'd type
	IsPtr        bool
	DataType     DataType
	SQLType      string       // explicit `type:` tag, e.g. "TIMESTAMP" for soft-delete fields
	DefaultValue string
	Serializer   Serializer
	Tag          Tag

	PrimaryKey     bool
	AutoIncrement  bool
	NotNull        bool
	NullZero       bool // write NULL instead of the zero value
	AutoCreateTime bool // named CreatedAt
	AutoUpdateTime bool // named UpdatedAt
	SoftDelete     bool // named DeletedAt or tagged softdelete
	SoftDeleteZero string  // `zerovalue:` — live-row value
	SoftDeleteValue string // `deletevalue:` — deleted marker
	Creatable      bool // not `->`
	Updatable      bool // not `->` and not `<-`
	Readable       bool // not `<-`
	IndexName  string // name generated/tagged for the index
	UniqueName string
	IndexSQLName  string // name issued in CREATE INDEX
	UniqueSQLName string
	OnUpdate  string
	OnDelete  string

	Appender    AppenderFunc // compiled once at table init
	Scanner     ScannerFunc
	IsZero      IsZeroFunc
	PKGenerator func(reflect.Value) error // uuid.UUID PKs without autoincrement
}

PKGenerator is resolved only for uuid.UUID (or *uuid.UUID, whose pointer is allocated and set) primary keys without autoincrement; it fills a zero primary-key value at create time with uuid.NewV7().

Relations

type RelationKind string

const (
	HasOne     RelationKind = "has-one"
	HasMany    RelationKind = "has-many"
	BelongsTo  RelationKind = "belongs-to"
	ManyToMany RelationKind = "many2many"
)
type Relation struct {
	Name             string
	Kind             RelationKind
	Field            *Field
	Table            *Table  // declaring table
	JoinTable        *Table  // target table
	M2MName          string  // junction table name
	M2MForeignKey    string  // junction column for this side
	M2MReferences    string  // junction column for the other side
	ForeignKey       *Field  // FK column on the owning side
	Reference        *Field  // referenced (usually PK) column
	Polymorphic      bool
	PolymorphicValue string  // e.g. "user" for polymorphic_type
	PolymorphicField *Field
	OnUpdate         string
	OnDelete         string
}

References() reports whether the declaring table owns the foreign-key constraint (belongs-to and non-PK has-one relations). Default FK names follow field.Name + "ID" (belongs-to) and table name + "ID" (has-one/has-many); many2many junction columns are <model>_id on both sides, and the junction table defaults to the sorted pair joined by _.

Naming

Namer and Tabler

type Namer interface {
	TableName(string) string
	ColumnName(table, column string) string
	JoinTableName(string) string
	FKName(table, column string) string
	IndexName(table, column string) string
	UniqueName(table, column string) string
}

type Tabler interface {
	TableName() string
}

Tabler lets a model override its table name; the method wins over the Namer. Replacer rewrites model identifiers before naming (e.g. acronyms).

NamingStrategy

Derives pluralized snake_case database names, gorm-style:

type NamingStrategy struct {
	TablePrefix         string
	SingularTable       bool
	NameReplacer        Replacer
	NoLowerCase         bool
	IdentifierMaxLength int // 0 = 64
}

Generated index/constraint names follow idx_table_column, uni_table_column, and fk_table_column patterns; names exceeding the identifier max length are truncated with an 8-hex-char SHA-1 suffix. Explicit index tag values get the table appended when emitted in CREATE INDEX, because index names share one namespace per database.

Field closures

type AppenderFunc func(b []byte, v reflect.Value, d dialect.Dialector) []byte

type ScannerFunc func(dst reflect.Value, src any) error

type IsZeroFunc func(reflect.Value) bool

All three are resolved once at table-init time, so per-row work performs no reflection type dispatch:

  • Appender renders a field value as a SQL literal using the active dialect (driver.Valuer implementers go through their Value).
  • Scanner assigns a database value to a field (sql.Scanner implementers go through their Scan; times accept five layouts).
  • IsZero reports the zero value for the type; types implementing IsZero() bool are honored first.

Serializers

type Serializer interface {
	Serialize(reflect.Value) ([]byte, error)
	Deserialize([]byte, reflect.Value) error
}

type JSONSerializer struct{}

Serializer customizes how a field is stored as a JSON/SQL value. JSONSerializer marshals through encoding/json and is applied by the json tag or serializer:"json". A serialized field's DataType becomes json.

DataType constants

const (
	DataTypeBool      DataType = "bool"
	DataTypeInt       DataType = "int"
	DataTypeUint      DataType = "uint"
	DataTypeFloat     DataType = "float"
	DataTypeString    DataType = "string"
	DataTypeBytes     DataType = "bytes"
	DataTypeTime      DataType = "time"
	DataTypeJSON      DataType = "json"
	DataTypeInterface DataType = "interface"
)

The broad SQL family inferred from a Go field type: slices other than []byte, maps, and structs map to json; time.Time maps to time; types implementing sql.Scanner (directly or by pointer) map to string.

Schema errors

SentinelPackage/SourceTrigger
schema.ErrInvalidModelschema/table.go:12Non-struct (or nil) model passed to Parse/Get.
schema.ErrInvalidTagschema/tag.go:10Unknown or malformed fusion tag in strict mode.
schema.ErrAmbiguousFieldschema/table.go:14Two fields resolving to the same column, or duplicate Go field names.
schema.ErrInvalidRelationschema/relation.go:10Unknown rel kind, missing FK/references column, or a composite key where single-column is required.

All four are aliased by the root package — see Error sentinels.

Caches are session-owned

A Tables cache is bound to one Namer and one tag-strictness setting, created by Open. Do not share parsed *Table pointers across sessions with different naming strategies.

Next

On this page