generator

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ColumnConstraints

func ColumnConstraints(col *schema.Column) string

ColumnConstraints extracts validation constraints from column definitions to generate validate tags for input structs when no request struct exists.

func DocsJSON

func DocsJSON() string

DocsJSON returns the raw JSON string of embedded documentation.

func EnumFieldMap

func EnumFieldMap(requests []RequestDef) map[string]string

EnumFieldMap maps input field keys ("CreatePostInput.Status") to enum type names ("PostStatus").

func FormatDocsMarkdown

func FormatDocsMarkdown(typeName string) (string, error)

FormatDocsMarkdown formats docs as readable markdown, optionally filtering by type name.

func Generate

func Generate(project *Project, picklePkgDir string) error

Generate runs all generators for a project and writes output.

Layout (Laravel-style):

  • {root}/app/http/pickle_gen.go — HTTP types (Context, Response, Router, etc.)
  • {root}/app/http/requests/bindings_gen.go — Request deserialization + validation
  • {root}/app/models/pickle_gen.go — QueryBuilder[T]
  • {root}/app/models/*.go — Model structs and query scopes
  • {root}/database/migrations/types_gen.go — Schema DSL types (Migration, Table, etc.)
  • {root}/config/pickle_gen.go — Config glue

func GenerateActionWiring

func GenerateActionWiring(set *ActionSet, packageName, actionImportPath string) ([]byte, error)

GenerateActionWiring produces a Go source file with gated action methods on the model struct.

func GenerateAuthRegistry

func GenerateAuthRegistry(drivers []AuthDriverInfo, modulePath, httpImport string) ([]byte, error)

GenerateAuthRegistry produces auth/pickle_gen.go with the AuthDriver interface, driver registry, and default middleware.

func GenerateBindings

func GenerateBindings(requests []RequestDef, packageName string) ([]byte, error)

GenerateBindings produces a Go source file with Bind functions for each request struct.

func GenerateBuiltinDriver

func GenerateBuiltinDriver(driver AuthDriverInfo, httpImport string) ([]byte, error)

GenerateBuiltinDriver writes driver_gen.go for a built-in auth driver. Replaces __PACKAGE__ and __HTTP_IMPORT__ placeholders.

func GenerateColumnAnnotations

func GenerateColumnAnnotations(packageName string, roles []RoleAnnotation) ([]byte, error)

GenerateColumnAnnotations produces Go source with XxxSees() methods on Column for each non-manages role. The methods call RoleSees(slug) under the hood.

func GenerateCommandsGlue

func GenerateCommandsGlue(modulePath string, migrationsRel string, userCommands []string, routeVars []string, hasAuth bool, hasSchedule bool) ([]byte, error)

GenerateCommandsGlue produces app/commands/pickle_gen.go.

func GenerateConfigGlue

func GenerateConfigGlue(scan *ConfigScanResult, packageName string) ([]byte, error)

GenerateConfigGlue produces config/pickle_gen.go with Env(), public vars, Init(), and database helper methods if applicable.

func GenerateCoreConfig

func GenerateCoreConfig(packageName string) []byte

GenerateCoreConfig returns the config helpers (Env, .env loader, DatabaseConfig, etc.) with the package name set to the target package.

func GenerateCoreGraphQL

func GenerateCoreGraphQL(packageName string) []byte

GenerateCoreGraphQL returns the GraphQL executor, batch loader, ResolveContext, and gqlparser wrapper types with the package name set to the target package.

func GenerateCoreHTTP

func GenerateCoreHTTP(packageName string) []byte

GenerateCoreHTTP returns the HTTP core types (Context, Response, Router, etc.) with the package name set to the target package.

func GenerateCoreMigration

func GenerateCoreMigration(packageName string) []byte

GenerateCoreMigration returns the migration runner and SQL generators with the package name set to the target package.

func GenerateCorePolicy

func GenerateCorePolicy(packageName string) []byte

GenerateCorePolicy returns the policy runner types (PolicyRunner, GraphQLPolicyRunner, derive functions) with the package name set to the target package.

func GenerateCoreQuery

func GenerateCoreQuery(packageName string) []byte

GenerateCoreQuery returns the QueryBuilder[T] and related query types with the package name set to the target package.

func GenerateCoreScheduler

func GenerateCoreScheduler(packageName string) []byte

GenerateCoreScheduler returns the Scheduler, Job, JobEntry, and Cron types with the package name set to the target package.

func GenerateCoreSchema

func GenerateCoreSchema(packageName string) []byte

GenerateCoreSchema returns the migration schema types (Migration, Table, Column, etc.) with the package name set to the target package.

func GenerateGraphQL

func GenerateGraphQL(project *Project, tables []*schema.Table, relationships []SchemaRelationship, requests []RequestDef) error

GenerateGraphQL orchestrates the complete GraphQL layer generation.

func GenerateGraphQLCRUDResolvers

func GenerateGraphQLCRUDResolvers(cfg CRUDConfig) ([]byte, error)

GenerateGraphQLCRUDResolvers generates crud_resolver_gen.go with ownership-scoped CRUD resolvers, nested resource mutations, and constraint-based validation. This implements spec 018: zero-controller GraphQL from migrations alone.

func GenerateGraphQLDataloaders

func GenerateGraphQLDataloaders(tables []*schema.Table, relationships []SchemaRelationship, modelsImport, packageName string) ([]byte, error)

GenerateGraphQLDataloaders generates dataloader_gen.go with per-relationship batch loaders and a DataLoaderRegistry.

func GenerateGraphQLHandler

func GenerateGraphQLHandler(packageName string) ([]byte, error)

GenerateGraphQLHandler generates handler_gen.go with the net/http handler that bridges pickle auth context to GraphQL and uses structured error mapping.

func GenerateGraphQLMutations

func GenerateGraphQLMutations(tables []*schema.Table, modelsImport, packageName string, relationships ...[]SchemaRelationship) ([]byte, error)

GenerateGraphQLMutations generates mutation_gen.go with mutation dispatch and create/update/delete methods. GenerateGraphQLMutations generates mutation_gen.go with mutation dispatch and create/update/delete methods. Accepts relationships for nested mutation dispatch.

func GenerateGraphQLResolvers

func GenerateGraphQLResolvers(tables []*schema.Table, relationships []SchemaRelationship, modelsImport, packageName string) ([]byte, error)

GenerateGraphQLResolvers generates resolver_gen.go with query dispatch, per-type field resolvers, filter/sort application, and object resolution helpers.

func GenerateGraphQLSchema

func GenerateGraphQLSchema(tables []*schema.Table, relationships []SchemaRelationship, requests []RequestDef, packageName string) ([]byte, error)

GenerateGraphQLSchema generates schema_gen.go containing the SDL string constant and the parsed schema variable.

func GenerateGraphQLTypes

func GenerateGraphQLTypes(tables []*schema.Table, requests []RequestDef, packageName string) ([]byte, error)

GenerateGraphQLTypes generates types_gen.go containing GQL response structs, connection types, and input structs.

func GenerateModel

func GenerateModel(table *schema.Table, packageName string) ([]byte, error)

GenerateModel produces a Go source file containing the model struct for a table.

func GenerateNestedMutationSDL

func GenerateNestedMutationSDL(tables []*schema.Table, relationships []SchemaRelationship) string

GenerateGraphQLCRUDSchema extends the SDL with nested resource mutations. Returns additional mutation fields to append to the schema.

func GenerateQueryScopes

func GenerateQueryScopes(table *schema.Table, blocks []tickle.ScopeBlock, packageName string) ([]byte, error)

GenerateQueryScopes produces a Go source file with typed Where*/With* methods for a given table, using scope templates parsed from the cooked scopes file.

func GenerateRBACGate

func GenerateRBACGate(actionName string, allowedRoles []string, managesRoles []string, sourcePolicy string, packageName string) ([]byte, error)

GenerateRBACGate produces a gate function for the given action, allowed roles, and manages roles. The generated function checks manages roles first, then specific allowed roles.

func GenerateRegistry

func GenerateRegistry(pkg string, entries []MigrationFileEntry, localImportPath string) ([]byte, error)

GenerateRegistry produces the contents of migrations/registry_gen.go. localImportPath is the import path of the package that registry_gen.go will be written into — entries with this import path are treated as local (no import needed). Pass "" to auto-detect from the first entry.

func GenerateResponses

func GenerateResponses(table *schema.Table, packageName string) ([]byte, error)

GenerateResponses produces a Go source file with PublicResponse, OwnerResponse structs and Serialize functions for a table with ownership declared.

func GenerateSchemaInspector

func GenerateSchemaInspector(migrations []MigrationEntry) ([]byte, error)

func GenerateScopeWiring

func GenerateScopeWiring(modelName string, scopes []ScopeDef, packageName, scopeImportPath string) ([]byte, error)

GenerateScopeWiring produces a Go source file with wrapper methods on XxxQuery that delegate to user-defined scope functions.

func GenerateTxMethods

func GenerateTxMethods(tables []*schema.Table, nestingMap map[string]SchemaRelationship, modelsDir, packageName string) ([]byte, error)

GenerateTxMethods produces a tx_gen.go file with Tx.Query<Model>() methods for all tables in the models package.

func GenerateViewModel

func GenerateViewModel(view *schema.View, packageName string) ([]byte, error)

GenerateViewModel produces a Go source file containing the model struct for a view.

func GenerateViewQueryScopes

func GenerateViewQueryScopes(view *schema.View, blocks []tickle.ScopeBlock, packageName string) ([]byte, error)

GenerateViewQueryScopes produces a Go source file with typed Where* methods for a view. The query wrapper is read-only — no Create/Update/Delete.

func HasCRUDOverride

func HasCRUDOverride(graphqlDir, tableName string) bool

HasCRUDOverride checks if a user-written resolver file exists for a specific resource, implementing the per-resource override pattern.

func HasOwnership

func HasOwnership(table *schema.Table) bool

HasOwnership returns true if the table has an IsOwner column and at least one Public or OwnerSees column.

func ParseDocs

func ParseDocs() ([]tickle.DocFile, error)

ParseDocs parses the embedded documentation JSON.

func ParseDotEnv

func ParseDotEnv(path string) map[string]string

ParseDotEnv reads a .env file and returns a map of key → value.

func ResolveImportPath

func ResolveImportPath(appDir, modulePath, absDir string) string

resolveImportPath determines the Go import path for a directory. If absDir is inside the app's module (under appDir), returns modulePath + relative. Otherwise, walks up from absDir looking for go.mod to determine the external module path.

func ScanActions

func ScanActions(actionsDir string) (map[string]*ActionSet, error)

ScanActions scans database/actions/{model}/ for action and gate files.

func ScanCommands

func ScanCommands(commandsDir string) ([]string, error)

ScanCommands parses Go files in the commands directory and returns the names of exported types that implement the Command interface (Name(), Description(), Run([]string) error).

func ScanJobs

func ScanJobs(jobsDir string) ([]string, error)

ScanJobs parses Go files in the jobs directory and returns the names of exported types that have a Handle() error method.

func ScanMigrationStructs

func ScanMigrationStructs(migrationsDir string) ([]string, error)

ScanMigrationStructs parses Go files in the migrations/ directory and returns the struct names that embed Migration (sorted alphabetically).

func ScanRouteVars

func ScanRouteVars(routesDir string) ([]string, error)

ScanRouteVars scans Go files in routesDir for exported var declarations that call pickle.Routes(...) and returns their names (e.g. ["API"]).

func ScanScopes

func ScanScopes(scopesDir string) (map[string][]ScopeDef, error)

ScanScopes scans the directory database/scopes/{model}/ for exported scope functions. Returns scope definitions grouped by model name.

func SlugToPascal

func SlugToPascal(slug string) string

SlugToPascal converts a role slug to PascalCase. Examples: "compliance" → "Compliance", "support_lead" → "SupportLead"

func ValidateActions

func ValidateActions(set *ActionSet) error

ValidateActions checks that every action has a corresponding gate. Returns an error listing all ungated actions.

func WriteAuditMigrations

func WriteAuditMigrations(migrationsDir, migrationsPkg string) error

WriteAuditMigrations writes audit trail migration files into the project's database/migrations/audit/ directory. Override pattern applies.

func WriteDriverMigrations

func WriteDriverMigrations(driverName, migrationsDir, migrationsPkg string) error

WriteDriverMigrations writes migration files for a built-in auth driver into the project's database/migrations/ directory. Each migration is written as an individual _gen.go file with a proper timestamp prefix. If the user has created a .go override (same name without _gen), the _gen.go version is skipped.

func WriteGraphQLMigrations

func WriteGraphQLMigrations(migrationsDir, migrationsPkg string) error

WriteGraphQLMigrations writes GraphQL migration files into the project's database/migrations/graphql/ directory. Override pattern applies.

func WriteRBACMigrations

func WriteRBACMigrations(migrationsDir, migrationsPkg string) error

WriteRBACMigrations writes RBAC migration files into the project's database/migrations/rbac/ directory. Override pattern applies.

Types

type ActionDef

type ActionDef struct {
	Name       string // PascalCase action name, e.g. "Ban"
	StructName string // e.g. "BanAction"
	SourceFile string // relative path
	HasResult  bool   // true if Execute returns (*ResultStruct, error) instead of error
	ResultType string // e.g. "*TransferResult" (empty if HasResult is false)
}

ActionDef describes a user-defined action parsed from database/actions/.

type ActionSet

type ActionSet struct {
	Model   string // directory name / model name
	Actions []ActionDef
	Gates   []GateDef
}

ActionSet groups actions and gates for a model.

type AuthDriverInfo

type AuthDriverInfo struct {
	Name      string // directory name, e.g. "jwt", "session", "my_custom"
	IsBuiltin bool   // true if Pickle provides a built-in template for this driver
	NeedsGen  bool   // true if driver_gen.go should be written (no driver.go override)
	Dir       string // absolute path to the driver subdirectory
}

AuthDriverInfo describes a discovered auth driver.

func ScanAuthDrivers

func ScanAuthDrivers(authDir string) ([]AuthDriverInfo, error)

ScanAuthDrivers scans subdirectories of authDir for auth drivers. Each subdirectory is a driver. If driver.go exists, the user owns it. If not, and a built-in template exists, driver_gen.go will be generated.

type CRUDConfig

type CRUDConfig struct {
	Tables        []*schema.Table
	Relationships []SchemaRelationship
	ModelsImport  string
	PackageName   string
}

CRUDConfig holds the configuration for zero-controller CRUD generation.

type ConfigDef

type ConfigDef struct {
	FuncName   string // unexported function name, e.g. "database"
	ReturnType string // struct type name, e.g. "DatabaseConfig"
	VarName    string // exported var name, e.g. "Database"
}

ConfigDef describes a config function discovered in config/*.go.

type ConfigScanResult

type ConfigScanResult struct {
	Configs           []ConfigDef
	HasDatabaseConfig bool // user defined DatabaseConfig struct
}

ConfigScanResult holds everything discovered from config/*.go.

func ScanConfigs

func ScanConfigs(configDir string) (*ConfigScanResult, error)

ScanConfigs parses Go files in configDir and finds unexported functions that return a struct type ending in "Config". Also detects known struct types.

type DerivedAction

type DerivedAction struct {
	Name string
}

DerivedAction represents a registered custom controller action.

type DerivedExposure

type DerivedExposure struct {
	Model      string
	Operations []string // "list", "show", "create", "update", "delete"
}

DerivedExposure represents the computed GraphQL exposure set for a single model.

type DerivedGraphQLState

type DerivedGraphQLState struct {
	Exposures []DerivedExposure
	Actions   []DerivedAction
}

DerivedGraphQLState mirrors migration.DerivedGraphQLState for use at generation time without importing the build-constrained migration package.

type EnumDef

type EnumDef struct {
	Name   string   // e.g. "PostStatus"
	Values []string // e.g. ["DRAFT", "PUBLISHED", "ARCHIVED"]
}

EnumDef represents a GraphQL enum extracted from oneof= validation.

func ExtractEnums

func ExtractEnums(requests []RequestDef) []EnumDef

ExtractEnums parses oneof= validation tags from request fields and returns enum definitions. The enum name is derived from the struct + field name. For example: UpdatePostRequest.Status with oneof=draft published archived → enum PostStatus { DRAFT PUBLISHED ARCHIVED }

type ExposedModel

type ExposedModel struct {
	Model      string
	Table      *schema.Table
	Operations []string
}

ExposedModel pairs a model with its table definition and the GraphQL operations that should be generated for it.

func FilterExposedModels

func FilterExposedModels(tables []*schema.Table, state DerivedGraphQLState) []*ExposedModel

FilterExposedModels returns only the tables that have been exposed via GraphQL policy, matched by model name to table name. Each returned ExposedModel includes the operations defined in the policy.

type GateDef

type GateDef struct {
	Name        string // e.g. "CanBan"
	ActionName  string // e.g. "Ban"
	SourceFile  string
	IsGenerated bool // true if from _gate_gen.go
}

GateDef describes a gate function for an action.

type Layout

type Layout struct {
	HTTPDir       string         // absolute path: where pickle_gen.go (Context, Response, Router) goes
	HTTPPkg       string         // package name for HTTPDir ("pickle")
	RequestsDir   string         // absolute path: where request structs + bindings_gen.go live
	ModelsDir     string         // absolute path: where generated models live
	MigrationsDir string         // absolute path: where migration files live
	MigrationsRel string         // relative to module root (e.g. "database/migrations")
	ConfigDir     string         // absolute path: where config files live
	CommandsDir   string         // absolute path: where app/commands/ lives
	AuthDir       string         // absolute path: where app/http/auth/ lives
	MigrationDirs []MigrationDir // monorepo: multiple migration directories (empty = use MigrationsDir)
}

Layout describes where generated and user-written files live. Follows Laravel conventions: app/http/, app/models/, database/migrations/.

type MigrationDir

type MigrationDir struct {
	Dir        string // absolute path
	ImportPath string // Go import path for this package
}

MigrationDir describes a directory containing migration files.

type MigrationEntry

type MigrationEntry struct {
	StructName string
	ImportPath string // Go import path for this migration's package
	PkgAlias   string // import alias used in generated code
}

MigrationEntry holds info needed to generate the inspector program.

type MigrationFileEntry

type MigrationFileEntry struct {
	ID         string // "2026_02_21_100000_create_users_table"
	StructName string // "CreateUsersTable_2026_02_21_100000"
	ImportPath string // Go import path if from an external package (empty = local)
}

MigrationFileEntry pairs a migration ID (filename stem) with the struct name.

func ScanAllMigrationFiles

func ScanAllMigrationFiles(dirs []MigrationDir) ([]MigrationFileEntry, error)

ScanAllMigrationFiles scans multiple migration directories and returns a merged, timestamp-sorted list of migration entries.

func ScanMigrationFiles

func ScanMigrationFiles(migrationsDir string) ([]MigrationFileEntry, error)

ScanMigrationFiles scans the migrations directory and returns entries sorted by timestamp (filename order), pairing each filename stem with its struct name.

type Project

type Project struct {
	Dir        string // project root
	ModulePath string // Go module path from go.mod
	Layout     Layout
	Services   []ServiceLayout // populated in multi-service mode; empty = single-service
}

Project represents a Pickle project layout rooted at a directory.

func DetectProject

func DetectProject(dir string) (*Project, error)

DetectProject finds the project layout from the given directory.

type RBACGateInput

type RBACGateInput struct {
	ActionName   string
	AllowedRoles []string
	ManagesRoles []string
	SourcePolicy string
	PackageName  string
}

RBACGateInput holds the parameters for generating an RBAC gate function.

type RequestDef

type RequestDef struct {
	Name   string         // e.g. CreateUserRequest
	Fields []RequestField // struct fields in order
	File   string         // source file path (for diagnostics)
}

RequestDef describes a request struct parsed from the requests/ directory.

func ScanRequests

func ScanRequests(dir string) ([]RequestDef, error)

ScanRequests parses all Go files in a directory and extracts request struct definitions.

type RequestField

type RequestField struct {
	Name     string // Go field name
	Type     string // Go type as source string
	JSONTag  string // json struct tag value (e.g. "name")
	Validate string // validate struct tag value (e.g. "required,min=1,max=255")
}

RequestField describes a single field in a request struct.

type RequestValidationMap

type RequestValidationMap map[string]string

RequestValidationMap maps GraphQL input struct field names to their validation tags from the matching request struct. Key format: "CreateUserInput.Name" → "required,min=1,max=255".

func BuildColumnValidationMap

func BuildColumnValidationMap(tables []*schema.Table) RequestValidationMap

BuildColumnValidationMap derives validation tags from column constraints for GraphQL input types when no request struct exists (zero-controller mode). Key format: "CreateUserInput.Name" → "required,max=255".

func BuildRequestValidationMap

func BuildRequestValidationMap(requests []RequestDef) RequestValidationMap

BuildRequestValidationMap builds a map from request defs to validation tags for GraphQL input types. Matches CreateXxxRequest → CreateXxxInput, UpdateXxxRequest → UpdateXxxInput.

func MergeValidationMaps

func MergeValidationMaps(requestMap, columnMap RequestValidationMap) RequestValidationMap

MergeValidationMaps merges request-based and column-based validation maps. Request-based tags take precedence over column-derived tags.

type RoleAnnotation

type RoleAnnotation struct {
	Slug       string // e.g. "compliance", "support_lead"
	PascalName string // e.g. "Compliance", "SupportLead"
}

RoleAnnotation describes a role that should generate a column annotation method.

type SchemaRelationship

type SchemaRelationship struct {
	Type        string // "has_many" or "has_one"
	ParentTable string
	ChildTable  string
	Collection  bool
	TopLevel    bool
}

SchemaRelationship describes a parent-child nesting from the inspector output.

func RunSchemaInspector

func RunSchemaInspector(project *Project) ([]*schema.Table, []*schema.View, []SchemaRelationship, error)

RunSchemaInspector generates a temp inspector program, compiles and runs it, and returns the parsed schema tables, views, and relationships.

type ScopeDef

type ScopeDef struct {
	Name        string       // exported function name, e.g. "Active"
	ExtraParams []ScopeParam // parameters beyond the first ScopeBuilder param
	SourceFile  string       // relative path to the source file
}

ScopeDef describes a user-defined scope function parsed from database/scopes/.

type ScopeParam

type ScopeParam struct {
	Name string
	Type string
}

ScopeParam describes an additional parameter on a scope function.

type ServiceLayout

type ServiceLayout struct {
	Name        string // "api", "worker"
	Dir         string // absolute path to service dir
	HTTPDir     string // {serviceDir}/http
	HTTPPkg     string // package name for HTTPDir ("pickle")
	RequestsDir string // {serviceDir}/http/requests
	CommandsDir string // {serviceDir}/commands
}

ServiceLayout describes per-service paths in a multi-service project.

Jump to

Keyboard shortcuts

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