On this page
Package codegen generates type-safe application-layer code from resolved pgdesign schemas across six target languages including Go, TypeScript, and Python.
#internal/codegen
#internal/codegen
Package codegen generates type-safe application-layer code from resolved pgdesign schemas across six target languages including Go, TypeScript, and Python.
It extracts RLS policies and produces language-specific validators that can pre-check policy conditions before hitting the database.
#SplitModeNone
const SplitModeNone SplitMode = ""SplitModeNone produces the default two-file output (schema_ddl.py + schema_executor.py).
#SplitModeFaceted
const SplitModeFaceted SplitMode = "faceted"SplitModeFaceted splits output by concern (extensions, types, tables per source, post-tables).
#SplitModeSelfContained
const SplitModeSelfContained SplitMode = "self-contained"SplitModeSelfContained splits output so each file is independently executable.
#LangGo
const LangGo Lang = "go"#LangTS
const LangTS Lang = "ts"#LangPython
const LangPython Lang = "python"#LangJava
const LangJava Lang = "java"#LangKotlin
const LangKotlin Lang = "kotlin"#LangZig
const LangZig Lang = "zig"#AllSplitModes
var AllSplitModes = []SplitMode{SplitModeFaceted, SplitModeSelfContained}AllSplitModes lists the valid non-empty split modes.
#PolicyContext
type PolicyContext structPolicyContext holds the data needed to generate a validator for one policy.
#ConstantsLang
type ConstantsLang structConstantsLang captures the formatting differences between target languages for the constants generator.
#PythonConstantsGenerator
type PythonConstantsGenerator struct{}PythonConstantsGenerator generates Python constants for table and column names.
#ZigConstantsGenerator
type ZigConstantsGenerator struct{}ZigConstantsGenerator generates Zig constants for table and column names.
#TSConstantsGenerator
type TSConstantsGenerator struct{}TSConstantsGenerator generates TypeScript constants for table and column names.
#JavaConstantsGenerator
type JavaConstantsGenerator struct{}JavaConstantsGenerator generates Java constants for table and column names.
#KotlinConstantsGenerator
type KotlinConstantsGenerator struct{}KotlinConstantsGenerator generates Kotlin constants for table and column names.
#GoConstantsGenerator
type GoConstantsGenerator struct{}GoConstantsGenerator generates Go constants for table and column names.
#ConstraintSet
type ConstraintSet structConstraintSet holds extracted constraint information for a single table.
#EnumField
type EnumField structEnumField pairs a column name with its valid enum values.
#CheckExpr
type CheckExpr structCheckExpr pairs a column name with its CHECK expression.
#EnumsGenerator
type EnumsGenerator structEnumsGenerator generates standalone enum definitions for all enums in a schema. Unlike the types generator which embeds enums alongside struct/class definitions, this produces a file containing only enum types.
#GoConstraintsGenerator
type GoConstraintsGenerator struct{}GoConstraintsGenerator generates Go validation functions for table constraints.
#ValidationError
type ValidationError structValidationError describes a single constraint violation.
#GoGormGenerator
type GoGormGenerator struct{}GoGormGenerator generates Go structs with GORM struct tags corresponding to database tables, including BelongsTo and HasMany relationship fields. The branded enum fields ride the same Scanner/Valuer as the types mode.
#GoTypesGenerator
type GoTypesGenerator struct{}GoTypesGenerator generates Go struct types corresponding to database tables.
#GoValidatorGenerator
type GoValidatorGenerator struct{}GoValidatorGenerator generates Go validator functions for RLS policies.
#PolicyResult
type PolicyResult structPolicyResult holds the result of a policy pre-check.
#JavaConstraintsGenerator
type JavaConstraintsGenerator struct{}JavaConstraintsGenerator generates Java validation methods for table constraints.
#JavaJPAGenerator
type JavaJPAGenerator struct{}JavaJPAGenerator generates JPA entity classes corresponding to database tables, including @ManyToOne and @OneToMany relationship annotations derived from foreign key metadata.
#JavaTypesGenerator
type JavaTypesGenerator struct{}JavaTypesGenerator generates Java record types corresponding to database tables.
#JavaValidatorGenerator
type JavaValidatorGenerator struct{}JavaValidatorGenerator generates Java validator functions for RLS policies.
#KotlinConstraintsGenerator
type KotlinConstraintsGenerator struct{}KotlinConstraintsGenerator generates Kotlin validation extension functions for table constraints. Types and constraints are emitted in the same file to avoid import issues.
#KotlinTypesGenerator
type KotlinTypesGenerator struct{}KotlinTypesGenerator generates Kotlin data classes corresponding to database tables.
#KotlinValidatorGenerator
type KotlinValidatorGenerator struct{}KotlinValidatorGenerator generates Kotlin validator functions for RLS policies.
#PythonGenerator
type PythonGenerator struct{}PythonGenerator generates Python async validator functions for RLS policies.
#PythonConstraintsGenerator
type PythonConstraintsGenerator struct{}PythonConstraintsGenerator generates Python validation functions for table constraints.
#SplitMode
type SplitMode stringSplitMode controls how PythonDDLGenerator distributes output across files.
#PythonDDLGenerator
type PythonDDLGenerator structPythonDDLGenerator generates a Python file containing DDL statements as DDLStmt namedtuples with 7 fields: sql, idempotent_sql, kind, name, table, phase, transactional. The output mirrors the exact section order of generateSQL in the generate package.
#PythonQueryLayerGenerator
type PythonQueryLayerGenerator structPythonQueryLayerGenerator generates Python protocol definitions and row dataclasses for a type-safe query layer. It produces multiple files: protocols.py contains context types, row dataclasses, and Reader/Writer/Backend protocols with methods derived from the schema's tables, FKs, uniques, and state machine transitions.
#PythonSQLAlchemyGenerator
type PythonSQLAlchemyGenerator struct{}PythonSQLAlchemyGenerator generates SQLAlchemy 2.0 declarative models corresponding to database tables, including mapped_column definitions and relationship fields derived from foreign key metadata.
#PythonTypesGenerator
type PythonTypesGenerator struct{}PythonTypesGenerator generates Python dataclass types corresponding to database tables.
#TSConstraintsGenerator
type TSConstraintsGenerator struct{}TSConstraintsGenerator generates TypeScript validation functions for table constraints.
#TSDrizzleGenerator
type TSDrizzleGenerator struct{}TSDrizzleGenerator generates Drizzle ORM schema TypeScript code corresponding to database tables, including column definitions, indexes, and relations.
#TSTypesGenerator
type TSTypesGenerator struct{}TSTypesGenerator generates TypeScript interface types corresponding to database tables.
#TSValidatorGenerator
type TSValidatorGenerator struct{}TSValidatorGenerator generates TypeScript validator functions for RLS policies.
#TypeResolver
type TypeResolver structTypeResolver resolves model columns to native type mappings based on TypeKind. It dispatches enum/state_machine columns to PascalCase type names, while scalar and builtin columns use the standard type lookup table.
#Lang
type Lang stringLang identifies a target language for code generation.
#TypeMapping
type TypeMapping structTypeMapping holds the native type name and optional import for a single PG-to-language mapping.
#ZigConstraintsGenerator
type ZigConstraintsGenerator struct{}ZigConstraintsGenerator generates Zig validation functions for table constraints.
#ZigTypesGenerator
type ZigTypesGenerator struct{}ZigTypesGenerator generates Zig struct types corresponding to database tables.
#ZigValidatorGenerator
type ZigValidatorGenerator struct{}ZigValidatorGenerator generates Zig validator functions for RLS policies.
#ExtractPolicies
func ExtractPolicies(schema *model.Schema) []PolicyContextExtractPolicies collects all policies from a schema into PolicyContexts.
#FilterGeneratable
func FilterGeneratable(policies []PolicyContext) ([]PolicyContext, []diagnostic.Diagnostic)FilterGeneratable returns policies that have an ErrorCode and whose expression parses into an AST matching at least one supported codegen pattern:
1. Exists-lookup: an ExistsExpr node (privacy check pattern) 2. Ownership: a BinaryOp{Op: "="} where one side (unwrapping Cast) is a FuncCall named "current_setting"
Policies that lack an ErrorCode are silently skipped. Policies whose expression cannot be parsed produce a C002 diagnostic, and those that do not match any pattern produce a C001 diagnostic; both are excluded from the result.
#ExtractConstraints
func ExtractConstraints(table model.Table, schema model.Schema) ConstraintSetExtractConstraints collects constraint metadata from a table for code generation. It identifies NOT NULL columns (excluding PK, identity, and generated columns), enum-typed columns, single-column CHECK constraints, and JSON schema annotations.
#GenerateEnums
func GenerateEnums(enums []model.Enum, lang Lang) stringGenerateEnums generates enum definitions for all enums in the given slice, separated by blank lines. Returns empty string if enums is empty.
#GenerateTransitionMaps
func GenerateTransitionMaps(smts []model.SMTransitionMap, lang Lang) stringGenerateTransitionMaps generates transition map declarations for all state machine types in the schema, formatted for the given language.
#GenerateConstantsTransitionMaps
func GenerateConstantsTransitionMaps(smts []model.SMTransitionMap, lang ConstantsLang) stringGenerateConstantsTransitionMaps generates transition map declarations using string constants (not type-safe enum references) for the constants output mode.
#NewTypeResolver
func NewTypeResolver(lang Lang) *TypeResolverNewTypeResolver creates a TypeResolver for the given target language.
#EnumTypeName
func EnumTypeName(name string) stringEnumTypeName converts a PG enum/state_machine type name to a PascalCase identifier suitable for use as a type name in generated code.
#LookupType
func LookupType(pgType string, lang Lang) TypeMappingLookupType returns the native type mapping for a PG type in the given language. Falls back to a string-like type if the PG type is unrecognized.
#LookupMoneyType
func LookupMoneyType(lang Lang) stringLookupMoneyType returns the native type for the "money" semantic type.
#ApplyNullable
func ApplyNullable(baseType string, lang Lang) stringApplyNullable wraps a base type with the language's nullable pattern.
Java is a no-op: Java's nullable handling requires boxing primitives to wrapper types (int -> Integer), which is context-dependent. Callers should use toJavaWrapper from java_types.go instead.
#ApplyArray
func ApplyArray(baseType string, lang Lang) stringApplyArray wraps a base type with the language's array/list pattern.
For Java, the caller must separately add a "java.util.List" import.
#likePattern.IsCaseInsensitive
func (p *likePattern) IsCaseInsensitive() boolIsCaseInsensitive returns true if the LIKE operator is case-insensitive (ILIKE or NOT ILIKE).
#likePattern.IsNegated
func (p *likePattern) IsNegated() boolIsNegated returns true if the LIKE operator is negated (NOT LIKE or NOT ILIKE).
#PythonConstantsGenerator.Generate
func (g *PythonConstantsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Python file with table name and column name constants for every table in the schema.
#ZigConstantsGenerator.Generate
func (g *ZigConstantsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Zig file with table name and column name constants for every table in the schema.
#TSConstantsGenerator.Generate
func (g *TSConstantsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a TypeScript file with table name and column name constants for every table in the schema.
#JavaConstantsGenerator.Generate
func (g *JavaConstantsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Java file with table name and column name constants for every table in the schema.
#KotlinConstantsGenerator.Generate
func (g *KotlinConstantsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Kotlin file with table name and column name constants for every table in the schema.
#GoConstantsGenerator.Generate
func (g *GoConstantsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Go file with table name and column name constants for every table in the schema.
#ConstraintSet.HasConstraints
func (cs ConstraintSet) HasConstraints() boolHasConstraints reports whether any constraints were extracted.
#ConstraintSet.SortedEnumFields
func (cs ConstraintSet) SortedEnumFields() []EnumFieldSortedEnumFields returns the enum-typed columns ordered by column name. Generators must iterate this instead of ranging EnumFields directly so that output is deterministic (Go map iteration order is randomized).
#ConstraintSet.SortedCheckExprs
func (cs ConstraintSet) SortedCheckExprs() []CheckExprSortedCheckExprs returns the single-column CHECK expressions ordered by column name. Generators must iterate this instead of ranging CheckExprs directly so that output is deterministic.
#EnumsGenerator.Generate
func (g *EnumsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a source file with enum definitions for all enums in the schema.
#GoConstraintsGenerator.Generate
func (g *GoConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Go file with Validate
#ValidationError.Error
func (e ValidationError) Error() stringError implements the error interface.
#GoGormGenerator.Generate
func (g *GoGormGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Go source file with one GORM-tagged struct per table in the schema, plus relationship fields derived from foreign key metadata.
#GoTypesGenerator.Generate
func (g *GoTypesGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Go source file with one struct per table in the schema. Each struct has exported fields matching the table's columns, with db struct tags for the original column names.
#GoValidatorGenerator.Generate
func (g *GoValidatorGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Go file with validator functions for all eligible policies in the schema.
#JavaConstraintsGenerator.Generate
func (g *JavaConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Java file with validate
#JavaConstraintsGenerator.GenerateFiles
func (g *JavaConstraintsGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)GenerateFiles implements MultiFileGenerator, emitting ValidationError.java and Constraints.java as separate single-public-type compilation units. When the schema has no extractable constraints, a single Constraints.java carrying the "no constraints" note is emitted so the stamp/orphan contracts still hold.
#JavaJPAGenerator.Generate
func (g *JavaJPAGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a single Java source file with one @Entity class per table. This combined form has multiple public classes and is not legal Java for multi-table schemas; GenerateFiles is the compilable, one-class-per-file form.
#JavaJPAGenerator.GenerateFiles
func (g *JavaJPAGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)GenerateFiles implements MultiFileGenerator, emitting one
#JavaTypesGenerator.Generate
func (g *JavaTypesGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Java source file with one record per table in the schema.
#JavaTypesGenerator.GenerateFiles
func (g *JavaTypesGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)GenerateFiles implements MultiFileGenerator, emitting one file per public Java type: one
#JavaValidatorGenerator.Generate
func (g *JavaValidatorGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Java file with validator functions for all eligible policies in the schema.
#KotlinConstraintsGenerator.Generate
func (g *KotlinConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Kotlin file with
#KotlinTypesGenerator.Generate
func (g *KotlinTypesGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Kotlin source file with one data class per table in the schema.
#KotlinValidatorGenerator.Generate
func (g *KotlinValidatorGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Kotlin file with validator functions for all eligible policies in the schema.
#PythonGenerator.Generate
func (g *PythonGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Python file with async validator functions for all eligible policies in the schema.
#PythonConstraintsGenerator.Generate
func (g *PythonConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Python file with validate_
#PythonDDLGenerator.Generate
func (g *PythonDDLGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Python file with all DDL statements as data tuples. This is the single-file Generator interface method.
#PythonDDLGenerator.GenerateFiles
func (g *PythonDDLGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)GenerateFiles implements MultiFileGenerator, producing two files: schema_ddl.py (tuples) and schema_executor.py (section executor). When SplitMode is set, produces split output instead.
#PythonQueryLayerGenerator.Generate
func (g *PythonQueryLayerGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate satisfies the Generator interface. For single-file output it concatenates all generated files separated by headers.
#PythonQueryLayerGenerator.GenerateFiles
func (g *PythonQueryLayerGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)GenerateFiles satisfies the MultiFileGenerator interface. It returns a map of relative file paths to their contents.
#PythonSQLAlchemyGenerator.Generate
func (g *PythonSQLAlchemyGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Python source file with SQLAlchemy 2.0 declarative models: one class per table with mapped_column definitions and relationship fields for single-column foreign keys.
#PythonTypesGenerator.Generate
func (g *PythonTypesGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Python source file with one dataclass per table in the schema.
#TSConstraintsGenerator.Generate
func (g *TSConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a TypeScript file with validate
#TSDrizzleGenerator.Generate
func (g *TSDrizzleGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a TypeScript source file with Drizzle ORM table definitions, index declarations, and relation blocks for all tables in the schema.
#TSTypesGenerator.Generate
func (g *TSTypesGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a TypeScript source file with one interface per table in the schema.
#TSValidatorGenerator.Generate
func (g *TSValidatorGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a TypeScript file with validator functions for all eligible policies in the schema.
#TypeResolver.Resolve
func (r *TypeResolver) Resolve(col model.Column) TypeMappingResolve returns the native type mapping for a column based on its TypeKind.
Dispatch logic: - "enum", "state_machine": PascalCase type name (Zig uses []const u8) - "scalar" with DomainName: domain-backed column, use underlying PG base type - "scalar" without DomainName, "": builtin type, use standard lookup - money semantic type: integer cents type
#ZigConstraintsGenerator.Generate
func (g *ZigConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Zig file with validate_
#ZigTypesGenerator.Generate
func (g *ZigTypesGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Zig source file with one struct per table in the schema.
#ZigValidatorGenerator.Generate
func (g *ZigValidatorGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)Generate produces a Zig file with validator functions for all eligible policies in the schema.