pgdesign v0.26.0 /internal/codegen
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

Go go
const SplitModeNone SplitMode = ""

SplitModeNone produces the default two-file output (schema_ddl.py + schema_executor.py).

#SplitModeFaceted

Go go
const SplitModeFaceted SplitMode = "faceted"

SplitModeFaceted splits output by concern (extensions, types, tables per source, post-tables).

#SplitModeSelfContained

Go go
const SplitModeSelfContained SplitMode = "self-contained"

SplitModeSelfContained splits output so each file is independently executable.

#LangGo

Go go
const LangGo     Lang = "go"

#LangTS

Go go
const LangTS     Lang = "ts"

#LangPython

Go go
const LangPython Lang = "python"

#LangJava

Go go
const LangJava   Lang = "java"

#LangKotlin

Go go
const LangKotlin Lang = "kotlin"

#LangZig

Go go
const LangZig    Lang = "zig"

#AllSplitModes

Go go
var AllSplitModes = []SplitMode{SplitModeFaceted, SplitModeSelfContained}

AllSplitModes lists the valid non-empty split modes.

#PolicyContext

Go go
type PolicyContext struct

PolicyContext holds the data needed to generate a validator for one policy.

#ConstantsLang

Go go
type ConstantsLang struct

ConstantsLang captures the formatting differences between target languages for the constants generator.

#PythonConstantsGenerator

Go go
type PythonConstantsGenerator struct{}

PythonConstantsGenerator generates Python constants for table and column names.

#ZigConstantsGenerator

Go go
type ZigConstantsGenerator struct{}

ZigConstantsGenerator generates Zig constants for table and column names.

#TSConstantsGenerator

Go go
type TSConstantsGenerator struct{}

TSConstantsGenerator generates TypeScript constants for table and column names.

#JavaConstantsGenerator

Go go
type JavaConstantsGenerator struct{}

JavaConstantsGenerator generates Java constants for table and column names.

#KotlinConstantsGenerator

Go go
type KotlinConstantsGenerator struct{}

KotlinConstantsGenerator generates Kotlin constants for table and column names.

#GoConstantsGenerator

Go go
type GoConstantsGenerator struct{}

GoConstantsGenerator generates Go constants for table and column names.

#ConstraintSet

Go go
type ConstraintSet struct

ConstraintSet holds extracted constraint information for a single table.

#EnumField

Go go
type EnumField struct

EnumField pairs a column name with its valid enum values.

#CheckExpr

Go go
type CheckExpr struct

CheckExpr pairs a column name with its CHECK expression.

#EnumsGenerator

Go go
type EnumsGenerator struct

EnumsGenerator 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

Go go
type GoConstraintsGenerator struct{}

GoConstraintsGenerator generates Go validation functions for table constraints.

#ValidationError

Go go
type ValidationError struct

ValidationError describes a single constraint violation.

#GoGormGenerator

Go go
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

Go go
type GoTypesGenerator struct{}

GoTypesGenerator generates Go struct types corresponding to database tables.

#GoValidatorGenerator

Go go
type GoValidatorGenerator struct{}

GoValidatorGenerator generates Go validator functions for RLS policies.

#PolicyResult

Go go
type PolicyResult struct

PolicyResult holds the result of a policy pre-check.

#JavaConstraintsGenerator

Go go
type JavaConstraintsGenerator struct{}

JavaConstraintsGenerator generates Java validation methods for table constraints.

#JavaJPAGenerator

Go go
type JavaJPAGenerator struct{}

JavaJPAGenerator generates JPA entity classes corresponding to database tables, including @ManyToOne and @OneToMany relationship annotations derived from foreign key metadata.

#JavaTypesGenerator

Go go
type JavaTypesGenerator struct{}

JavaTypesGenerator generates Java record types corresponding to database tables.

#JavaValidatorGenerator

Go go
type JavaValidatorGenerator struct{}

JavaValidatorGenerator generates Java validator functions for RLS policies.

#KotlinConstraintsGenerator

Go go
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

Go go
type KotlinTypesGenerator struct{}

KotlinTypesGenerator generates Kotlin data classes corresponding to database tables.

#KotlinValidatorGenerator

Go go
type KotlinValidatorGenerator struct{}

KotlinValidatorGenerator generates Kotlin validator functions for RLS policies.

#PythonGenerator

Go go
type PythonGenerator struct{}

PythonGenerator generates Python async validator functions for RLS policies.

#PythonConstraintsGenerator

Go go
type PythonConstraintsGenerator struct{}

PythonConstraintsGenerator generates Python validation functions for table constraints.

#SplitMode

Go go
type SplitMode string

SplitMode controls how PythonDDLGenerator distributes output across files.

#PythonDDLGenerator

Go go
type PythonDDLGenerator struct

PythonDDLGenerator 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

Go go
type PythonQueryLayerGenerator struct

PythonQueryLayerGenerator 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

Go go
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

Go go
type PythonTypesGenerator struct{}

PythonTypesGenerator generates Python dataclass types corresponding to database tables.

#TSConstraintsGenerator

Go go
type TSConstraintsGenerator struct{}

TSConstraintsGenerator generates TypeScript validation functions for table constraints.

#TSDrizzleGenerator

Go go
type TSDrizzleGenerator struct{}

TSDrizzleGenerator generates Drizzle ORM schema TypeScript code corresponding to database tables, including column definitions, indexes, and relations.

#TSTypesGenerator

Go go
type TSTypesGenerator struct{}

TSTypesGenerator generates TypeScript interface types corresponding to database tables.

#TSValidatorGenerator

Go go
type TSValidatorGenerator struct{}

TSValidatorGenerator generates TypeScript validator functions for RLS policies.

#TypeResolver

Go go
type TypeResolver struct

TypeResolver 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

Go go
type Lang string

Lang identifies a target language for code generation.

#TypeMapping

Go go
type TypeMapping struct

TypeMapping holds the native type name and optional import for a single PG-to-language mapping.

#ZigConstraintsGenerator

Go go
type ZigConstraintsGenerator struct{}

ZigConstraintsGenerator generates Zig validation functions for table constraints.

#ZigTypesGenerator

Go go
type ZigTypesGenerator struct{}

ZigTypesGenerator generates Zig struct types corresponding to database tables.

#ZigValidatorGenerator

Go go
type ZigValidatorGenerator struct{}

ZigValidatorGenerator generates Zig validator functions for RLS policies.

#ExtractPolicies

Go go
func ExtractPolicies(schema *model.Schema) []PolicyContext

ExtractPolicies collects all policies from a schema into PolicyContexts.

#FilterGeneratable

Go go
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

Go go
func ExtractConstraints(table model.Table, schema model.Schema) ConstraintSet

ExtractConstraints 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

Go go
func GenerateEnums(enums []model.Enum, lang Lang) string

GenerateEnums generates enum definitions for all enums in the given slice, separated by blank lines. Returns empty string if enums is empty.

#GenerateTransitionMaps

Go go
func GenerateTransitionMaps(smts []model.SMTransitionMap, lang Lang) string

GenerateTransitionMaps generates transition map declarations for all state machine types in the schema, formatted for the given language.

#GenerateConstantsTransitionMaps

Go go
func GenerateConstantsTransitionMaps(smts []model.SMTransitionMap, lang ConstantsLang) string

GenerateConstantsTransitionMaps generates transition map declarations using string constants (not type-safe enum references) for the constants output mode.

#NewTypeResolver

Go go
func NewTypeResolver(lang Lang) *TypeResolver

NewTypeResolver creates a TypeResolver for the given target language.

#EnumTypeName

Go go
func EnumTypeName(name string) string

EnumTypeName converts a PG enum/state_machine type name to a PascalCase identifier suitable for use as a type name in generated code.

#LookupType

Go go
func LookupType(pgType string, lang Lang) TypeMapping

LookupType 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

Go go
func LookupMoneyType(lang Lang) string

LookupMoneyType returns the native type for the "money" semantic type.

#ApplyNullable

Go go
func ApplyNullable(baseType string, lang Lang) string

ApplyNullable 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

Go go
func ApplyArray(baseType string, lang Lang) string

ApplyArray 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

Go go
func (p *likePattern) IsCaseInsensitive() bool

IsCaseInsensitive returns true if the LIKE operator is case-insensitive (ILIKE or NOT ILIKE).

#likePattern.IsNegated

Go go
func (p *likePattern) IsNegated() bool

IsNegated returns true if the LIKE operator is negated (NOT LIKE or NOT ILIKE).

#PythonConstantsGenerator.Generate

Go go
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

Go go
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

Go go
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

Go go
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

Go go
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

Go go
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

Go go
func (cs ConstraintSet) HasConstraints() bool

HasConstraints reports whether any constraints were extracted.

#ConstraintSet.SortedEnumFields

Go go
func (cs ConstraintSet) SortedEnumFields() []EnumField

SortedEnumFields 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

Go go
func (cs ConstraintSet) SortedCheckExprs() []CheckExpr

SortedCheckExprs 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

Go go
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

Go go
func (g *GoConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)

Generate produces a Go file with Validate functions for each table that has extractable constraints (NOT NULL, enum, CHECK, JSON schema).

#ValidationError.Error

Go go
func (e ValidationError) Error() string

Error implements the error interface.

#GoGormGenerator.Generate

Go go
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

Go go
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

Go go
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

Go go
func (g *JavaConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)

Generate produces a Java file with validate static methods for each table that has extractable constraints (NOT NULL, enum, CHECK, JSON schema). The combined form declares two public types (ValidationError and Constraints); GenerateFiles is the compilable one-public-type-per-file form.

#JavaConstraintsGenerator.GenerateFiles

Go go
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

Go go
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

Go go
func (g *JavaJPAGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)

GenerateFiles implements MultiFileGenerator, emitting one .java per table. Each file carries only the imports its own fields require (plus the shared javax.persistence.*), so every file is a legal single-public-class compilation unit.

#JavaTypesGenerator.Generate

Go go
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

Go go
func (g *JavaTypesGenerator) GenerateFiles(schema *model.Schema) (map[string][]byte, []diagnostic.Diagnostic)

GenerateFiles implements MultiFileGenerator, emitting one file per public Java type: one .java per enum, one .java per table, and a Transitions.java holder class for state-machine transition maps. Java allows only one public top-level type per file (with a matching filename), so the single-file Generate output above is not legal Java for multi-type schemas; this split is the compilable form.

#JavaValidatorGenerator.Generate

Go go
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

Go go
func (g *KotlinConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)

Generate produces a Kotlin file with .validate() extension functions for each table that has extractable constraints (NOT NULL, enum, CHECK, JSON schema).

#KotlinTypesGenerator.Generate

Go go
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

Go go
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

Go go
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

Go go
func (g *PythonConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)

Generate produces a Python file with validate_ functions for each table that has extractable constraints (NOT NULL, enum, CHECK, JSON schema).

#PythonDDLGenerator.Generate

Go go
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

Go go
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

Go go
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

Go go
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

Go go
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

Go go
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

Go go
func (g *TSConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)

Generate produces a TypeScript file with validate functions for each table that has extractable constraints.

#TSDrizzleGenerator.Generate

Go go
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

Go go
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

Go go
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

Go go
func (r *TypeResolver) Resolve(col model.Column) TypeMapping

Resolve 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

Go go
func (g *ZigConstraintsGenerator) Generate(schema *model.Schema) ([]byte, []diagnostic.Diagnostic)

Generate produces a Zig file with validate_ functions for each table that has extractable constraints (NOT NULL, enum, CHECK, JSON schema).

#ZigTypesGenerator.Generate

Go go
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

Go go
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.

Search