generator

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Code generated by tickle. DO NOT EDIT.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildSDL added in v0.2.0

func BuildSDL(tables []*schema.Table, relationships []SchemaRelationship, requests []RequestDef) string

BuildSDL constructs the GraphQL SDL string from tables, relationships, and requests.

func BuildSDLWithPlans added in v0.2.0

func BuildSDLWithPlans(plans []GraphQLModelPlan, relationships []SchemaRelationship, requests []RequestDef) string

BuildSDLWithPlans constructs SDL from operation-level model plans.

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, httpImportPath string) ([]byte, error)

GenerateActionWiring produces a Go source file with gated action methods on the model struct. httpImportPath is the import path for the HTTP package (e.g. "myapp/app/http") which provides Context.

func GenerateActionWiringWithAudit added in v0.2.0

func GenerateActionWiringWithAudit(set *ActionSet, packageName, actionImportPath, httpImportPath, auditImportPath string) ([]byte, error)

GenerateActionWiringWithAudit produces gated action methods that include transactional audit trail writes. The action and its audit row are written in the same database transaction — both succeed or both roll back. This implements specs 040 and 045.

func GenerateAssignRoleGate added in v0.2.0

func GenerateAssignRoleGate(packageName, httpImport string) ([]byte, error)

GenerateAssignRoleGate produces the default AssignRole gate that requires ctx.IsAdmin().

func GenerateAuditConstants added in v0.2.0

func GenerateAuditConstants(reg *IDRegistry, packageName string) ([]byte, error)

GenerateAuditConstants produces a Go source file with constants for each action type ID, e.g. ActionTypeUserBan = 1.

func GenerateAuditSeed added in v0.2.0

func GenerateAuditSeed(reg *IDRegistry, packageName string) ([]byte, error)

GenerateAuditSeed produces the seed migration Go source that inserts model_types and action_types rows via idempotent INSERT ON CONFLICT DO NOTHING statements.

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, exposureState *DerivedGraphQLState) error

GenerateGraphQL orchestrates the complete GraphQL layer generation. If exposureState is non-nil, only models explicitly exposed in GraphQL policies are included, with per-operation filtering. If nil, all tables with a primary key are included (legacy/no-policy mode).

func GenerateGraphQLAdapterResolvers added in v0.2.0

func GenerateGraphQLAdapterResolvers(cfg AdapterConfig) ([]byte, error)

GenerateGraphQLAdapterResolvers generates adapter_resolver_gen.go with resolvers that bridge GraphQL mutations to existing controller methods. Each ControllerAction("name", handler) becomes a mutation resolver that: 1. Extracts input from the GraphQL request 2. Builds a pickle.Context 3. Calls the controller method 4. Adapts the response

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

func GenerateGraphQLMutationsWithPlans(plans []GraphQLModelPlan, modelsImport, packageName string, relationships ...[]SchemaRelationship) ([]byte, error)

GenerateGraphQLMutationsWithPlans generates mutation dispatch using exact operation-level exposure plans.

func GenerateGraphQLPolicyRegistry added in v0.2.0

func GenerateGraphQLPolicyRegistry(pkg string, entries []PolicyFileEntry) ([]byte, error)

GenerateGraphQLPolicyRegistry produces the contents of database/policies/graphql/registry_gen.go.

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

func GenerateGraphQLResolversWithPlans(plans []GraphQLModelPlan, relationships []SchemaRelationship, modelsImport, packageName string) ([]byte, error)

GenerateGraphQLResolversWithPlans generates resolver_gen.go using exact operation-level exposure plans.

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

func GenerateGraphQLSchemaWithPlans(plans []GraphQLModelPlan, relationships []SchemaRelationship, requests []RequestDef, packageName string) ([]byte, error)

GenerateGraphQLSchemaWithPlans generates schema_gen.go using exact operation-level exposure plans.

func GenerateGraphQLTypes

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

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

func GenerateGraphQLTypesWithPlans added in v0.2.0

func GenerateGraphQLTypesWithPlans(plans []GraphQLModelPlan, requests []RequestDef, packageName string, relationships ...[]SchemaRelationship) ([]byte, error)

GenerateGraphQLTypesWithPlans generates GraphQL types and field cost metadata using operation-level model plans.

func GenerateLoadRolesMiddleware added in v0.2.0

func GenerateLoadRolesMiddleware(httpImport, modelsImport string) ([]byte, error)

GenerateLoadRolesMiddleware produces the load_roles_gen.go file for the project's middleware package. It wires pickle.RoleLoaderFunc to a concrete implementation that queries the role_user and roles tables.

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

func GeneratePolicyRegistry(pkg string, entries []PolicyFileEntry) ([]byte, error)

GeneratePolicyRegistry produces the contents of database/policies/registry_gen.go.

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, httpImport 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 GenerateRBACGates added in v0.2.0

func GenerateRBACGates(actionsDir, policiesDir, httpImport string) (map[string][]byte, error)

GenerateRBACGates generates gate files for actions that lack user-written gates. It returns a map of filePath → generated content. actionsDir is the path to database/actions/. policiesDir is the path to database/policies/.

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

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

RunSchemaInspectorWithMigrations returns final schema state plus the recorded per-migration operations used by tools that need lossless migration lowering.

func SaveIDRegistry added in v0.2.0

func SaveIDRegistry(path string, reg *IDRegistry) error

SaveIDRegistry writes the registry to disk.

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

func WriteAuditModels(modelsDir, httpImport string) error

WriteAuditModels writes audit model files into the project's app/models/audit/ directory. Includes QueryBuilder and Context types.

func WriteAuditSeedAndConstants added in v0.2.0

func WriteAuditSeedAndConstants(project *Project, actionSets map[string]*ActionSet) error

WriteAuditSeedAndConstants scans actions, updates the ID registry, and writes the seed migration and constants files.

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, _ string) error

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

func WriteRBACMigrations

func WriteRBACMigrations(migrationsDir, _ string) error

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

func WriteRBACModels added in v0.2.0

func WriteRBACModels(modelsDir string) error

WriteRBACModels writes Role and RoleUser model structs + query scopes into app/models/auth/. 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 ActionGrant added in v0.2.0

type ActionGrant struct {
	ActionName   string
	AllowedRoles []string // roles with explicit Can() for this action
	ManagesRoles []string // roles with Manages()
	SourcePolicy string   // policy that last granted this action
}

ActionGrant maps an action name to the roles that can perform it plus manages roles.

func DeriveActionGrants added in v0.2.0

func DeriveActionGrants(roles []DerivedRole) []ActionGrant

DeriveActionGrants computes the action grants from derived roles. For each action that any role Can() do, it builds an ActionGrant with the allowed roles and manages roles.

type ActionReg added in v0.2.0

type ActionReg struct {
	ID          int    `json:"id"`
	ModelTypeID int    `json:"model_type_id"`
	Model       string `json:"model"`
	Action      string `json:"action"`
}

ActionReg stores the registered ID and model type link for an action type.

type ActionSet

type ActionSet struct {
	Model       string // directory name / model name
	Actions     []ActionDef
	Gates       []GateDef
	IsImmutable bool // true if the model's table is immutable (has VersionID)
}

ActionSet groups actions and gates for a model.

type AdapterConfig added in v0.2.0

type AdapterConfig struct {
	Actions           []DerivedAction
	ControllersImport string
	ModelsImport      string
	PackageName       string
}

AdapterConfig holds configuration for generating controller action adapter resolvers.

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
	Plans         []GraphQLModelPlan
}

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
	Handler string
}

DerivedAction represents a registered custom controller action.

type DerivedExposure

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

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.

func DeriveGraphQLStateFromDir added in v0.2.0

func DeriveGraphQLStateFromDir(dir string) DerivedGraphQLState

DeriveGraphQLStateFromDir reads GraphQL policy files from disk using string matching (policy files have //go:build ignore and can't be compiled) and derives the current exposure state by replaying operations in file order.

type DerivedRelationshipExposure added in v0.2.0

type DerivedRelationshipExposure struct {
	Name        string
	Cost        int
	MaxPageSize int
}

DerivedRelationshipExposure is optional relationship budget metadata derived from GraphQL exposure policies.

type DerivedRole added in v0.2.0

type DerivedRole struct {
	Slug           string
	DisplayName    string
	IsManages      bool
	IsDefault      bool
	Actions        []string
	BirthTimestamp string // policy ID that created this role
}

DerivedRole represents the computed state of a role after replaying all policies.

func StaticDeriveRoles added in v0.2.0

func StaticDeriveRoles(policies []StaticPolicyOps) []DerivedRole

StaticDeriveRoles replays parsed policy operations to compute the current role set. Respects birth timestamps: a dropped and recreated role loses old Can() grants.

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
	Relationships []DerivedRelationshipExposure
}

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

type GraphQLModelPlan struct {
	Table         *schema.Table
	Operations    map[string]bool
	Relationships map[string]DerivedRelationshipExposure
}

GraphQLModelPlan carries the exposed table plus the exact operations that generation is allowed to emit for it.

type IDRegistry added in v0.2.0

type IDRegistry struct {
	NextModelTypeID  int                  `json:"next_model_type_id"`
	NextActionTypeID int                  `json:"next_action_type_id"`
	ModelTypes       map[string]int       `json:"model_types"`  // model name → ID
	ActionTypes      map[string]ActionReg `json:"action_types"` // "Model.Action" → registration
}

IDRegistry tracks permanently assigned integer IDs for model_types and action_types. Once an ID is assigned, it is never reused, even if the corresponding model or action is removed from the codebase.

func LoadIDRegistry added in v0.2.0

func LoadIDRegistry(path string) (*IDRegistry, error)

LoadIDRegistry reads the registry from disk, or returns a fresh one.

func (*IDRegistry) EnsureActionType added in v0.2.0

func (r *IDRegistry) EnsureActionType(model, action string) int

EnsureActionType assigns a stable ID for a model+action pair.

func (*IDRegistry) EnsureModelType added in v0.2.0

func (r *IDRegistry) EnsureModelType(name string) int

EnsureModelType assigns a stable ID for a model name.

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

type MigrationOperation struct {
	Type       string
	Table      string
	OldName    string
	NewName    string
	ColumnName string
	Columns    []*schema.Column
	Index      *schema.Index
	TableDef   *schema.Table
	ViewDef    *schema.View
	SQL        string
}

MigrationOperation is a serializable schema operation captured from a migration.

type MigrationOps added in v0.2.0

type MigrationOps struct {
	Name string
	Up   []MigrationOperation
	Down []MigrationOperation
}

MigrationOps groups the Up and Down operations captured for one migration struct.

type PolicyFileEntry added in v0.2.0

type PolicyFileEntry struct {
	ID         string // "2026_03_23_100000_create_initial_roles"
	StructName string // "CreateInitialRoles_2026_03_23_100000"
}

PolicyFileEntry pairs a policy ID (filename stem) with the struct name.

func ScanGraphQLPolicyFiles added in v0.2.0

func ScanGraphQLPolicyFiles(policiesDir string) ([]PolicyFileEntry, error)

ScanGraphQLPolicyFiles scans a directory for GraphQL policy files (structs embedding GraphQLPolicy).

func ScanPolicyFiles added in v0.2.0

func ScanPolicyFiles(policiesDir string) ([]PolicyFileEntry, error)

ScanPolicyFiles scans a directory for role policy files (structs embedding Policy).

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
	HTTPImport   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.

func NonManagesRoleAnnotations added in v0.2.0

func NonManagesRoleAnnotations(policiesDir string) ([]RoleAnnotation, error)

NonManagesRoleAnnotations derives RoleAnnotation entries for all non-Manages roles from a policy directory. This is the bridge between policy parsing and column annotation generation.

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.

type StaticPolicyOps added in v0.2.0

type StaticPolicyOps struct {
	PolicyID   string // migration-style ID from filename
	SourceFile string // relative path
	Ops        []StaticRoleOp
}

StaticPolicyOps groups role operations by the policy file they came from.

func ParsePolicyOps added in v0.2.0

func ParsePolicyOps(policiesDir string) ([]StaticPolicyOps, error)

ParsePolicyOps statically parses all policy files in the given directory, extracting role operations from the Up() methods via AST analysis.

type StaticRoleOp added in v0.2.0

type StaticRoleOp struct {
	Type          string // "create", "alter", "drop"
	Slug          string
	DisplayName   string
	IsManages     bool
	RemoveManages bool
	IsDefault     bool
	RemoveDefault bool
	Actions       []string
	RevokeActions []string
}

StaticRoleOp represents a role operation extracted from the AST of a policy file.

Jump to

Keyboard shortcuts

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