cooked

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: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeBadUserInput            = "BAD_USER_INPUT"
	CodeUnauthenticated         = "UNAUTHENTICATED"
	CodeForbidden               = "FORBIDDEN"
	CodeNotFound                = "NOT_FOUND"
	CodeInternalServerError     = "INTERNAL_SERVER_ERROR"
	CodeGraphQLParseFailed      = "GRAPHQL_PARSE_FAILED"
	CodeGraphQLValidationFailed = "GRAPHQL_VALIDATION_FAILED"
)

Error code constants following the GraphQL community conventions.

Variables

View Source
var AuditHook func(ctx *Context, actionTypeID int, resourceID, resourceVersionID, roleID interface{}) error

AuditHook is the function type for audit trail integration. The generator wires this to the database-backed audit package when audit tables are present. Default: no-op (log-only audit above handles it).

View Source
var ConfigReloadFunc func() (any, []string, error)

ConfigReloadFunc is the function called to reload configuration. Set this during app initialization to wire up config reloading. It should return the new config (for logging), a list of changed env var names, and any validation error.

View Source
var ConnectionNamesFunc func() []string

ConnectionNamesFunc returns the names of all managed connections. Set by the models package during initialization.

View Source
var ConnectionSwapFunc func(name, driver, dsn string) error

ConnectionSwapFunc is called during config reload when a database DSN changes. It receives the connection name, driver, and new DSN. Set by the models package to wire up ManagedConnection swapping.

View Source
var Connections = map[string]*sql.DB{}

Connections holds named database connections for multi-connection support. Keyed by connection name from config/database.go. Deprecated: Use ManagedConnections and WrapConnection for hot-reloadable connections.

View Source
var DB *sql.DB

DB is the package-level database connection. Set during app initialization.

View Source
var EncryptionKey []byte

EncryptionKey is the decoded current encryption key (set at app startup).

View Source
var EncryptionKeyNext []byte

EncryptionKeyNext is the decoded next encryption key for rotation (nil if not rotating).

View Source
var ErrNoVisibilityScope = fmt.Errorf("no visibility scope set — call SelectPublic(), SelectOwner(), or SelectAll()")

ErrNoVisibilityScope is returned when a fetch method is called without setting a visibility scope.

View Source
var ErrUnauthorized = &UnauthorizedActionError{}

ErrUnauthorized is returned by gated action methods when the gate denies access.

View Source
var GenesisHash = make([]byte, 32)

GenesisHash is the prev_hash for the first row in a chain: 32 zero bytes.

View Source
var ManagedConnections = &connectionMap{m: map[string]*ManagedConnection{}}

ManagedConnections holds named database connections with atomic swap support. Keyed by connection name from config/database.go.

Functions

func AuditDenied

func AuditDenied(ctx *Context, action, model string, resourceID any, reason string)

AuditDenied logs a denied action. Called when a gate check fails.

func AuditFailed

func AuditFailed(ctx *Context, action, model string, resourceID any, err error)

AuditFailed logs a failed action. Called when an action errors after authorisation.

func AuditPerformed

func AuditPerformed(ctx *Context, action, model string, resourceID any)

AuditPerformed logs a successful action. Called after a gate check passes and the action is executed.

func Env

func Env(key, fallback string) string

Env returns the value of the environment variable named by key, or fallback if the variable is not set. On first call, loads .env file if it exists.

func InitRuntimeConfig

func InitRuntimeConfig()

InitRuntimeConfig reads environment variables and initializes the runtime config. Call once at startup.

func OpenDB

func OpenDB(conn ConnectionConfig) *sql.DB

OpenDB opens a database connection using the given ConnectionConfig, pings it, and returns *sql.DB. Fatals on failure — call at startup.

func PlaygroundHandler

func PlaygroundHandler(endpoint string) http.Handler

PlaygroundHandler returns an http.Handler that serves a GraphQL playground UI. Mount it at /playground in debug mode.

func RegisterPickleEndpoints

func RegisterPickleEndpoints(mux *http.ServeMux)

RegisterPickleEndpoints registers Pickle's internal operations endpoints on the given ServeMux. These are infrastructure endpoints, not application routes.

WARNING: /pickle/health, /pickle/config/reload, and /pickle/metrics are operations endpoints. They must be network-restricted to internal traffic only (e.g., VPC, localhost, internal load balancer). Do not expose these to the public internet.

func SetIntrospection

func SetIntrospection(allow bool)

SetIntrospection enables or disables GraphQL introspection queries.

func TransactionOn

func TransactionOn(db *sql.DB, fn func(tx *Tx) error) error

TransactionOn runs fn inside a transaction on the specified database connection.

func VerifyProof

func VerifyProof(proof *MerkleProof) bool

VerifyProof checks a Merkle inclusion proof. This is a pure function — it needs no database access. It can run on a client, auditor, or third party.

func WithTransaction

func WithTransaction(fn func(tx *Tx) error) error

WithTransaction runs fn inside a database transaction. If fn returns nil, the transaction is committed. If fn returns an error or panics, the transaction is rolled back.

Usage:

WithTransaction(func(tx *Tx) error { ... })

The Tx object provides query builders scoped to the transaction via generated methods like tx.QueryUser(), tx.QueryTransfer(), etc.

func WrapConnection

func WrapConnection(name string, db *sql.DB)

WrapConnection wraps an existing *sql.DB as a ManagedConnection and stores it.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is the application lifecycle manager. It handles initialization, command dispatch, and HTTP serving.

func BuildApp

func BuildApp(initFn func(), serveFn func(), cmds ...Command) *App

BuildApp creates a new App with the given init, serve, and command functions.

func (*App) PrintCommands

func (a *App) PrintCommands()

PrintCommands prints available commands to stderr.

func (*App) Run

func (a *App) Run(args []string)

Run initializes the app, then either dispatches a command or starts HTTP.

type AuthClaims

type AuthClaims struct {
	UserID string
	Role   string
}

AuthClaims holds authentication state for a GraphQL request.

type AuthInfo

type AuthInfo struct {
	UserID string
	Role   string
	Claims any
}

AuthInfo holds authentication state set by middleware.

type AuthRateLimitConfig

type AuthRateLimitConfig struct {
	// contains filtered or unexported fields
}

AuthRateLimitConfig is the builder for identity-aware rate limiting. Each config owns its own rateLimiterStore instance.

func AuthRateLimit

func AuthRateLimit() *AuthRateLimitConfig

AuthRateLimit returns a middleware that rate-limits by authenticated identity. Uses ctx.Auth().UserID as the default key. Call builder methods to customize. Reads defaults from AUTH_RATE_LIMIT_RPS (default 30) and AUTH_RATE_LIMIT_BURST (default 60).

func (*AuthRateLimitConfig) Burst

func (c *AuthRateLimitConfig) Burst(burst int) *AuthRateLimitConfig

Burst sets the burst size.

func (*AuthRateLimitConfig) KeyFunc

func (c *AuthRateLimitConfig) KeyFunc(fn func(*Context) string) *AuthRateLimitConfig

KeyFunc sets a custom key extraction function. If the function returns "", the middleware falls back to IP-based limiting.

func (*AuthRateLimitConfig) Middleware

func (c *AuthRateLimitConfig) Middleware() MiddlewareFunc

Middleware returns the MiddlewareFunc for this config. Implements MiddlewareProvider.

func (*AuthRateLimitConfig) RPS

RPS sets the requests-per-second limit.

func (*AuthRateLimitConfig) Tiers

Tiers configures per-role rate limits. When tiers are set, the middleware reads ctx.Auth().Role and applies the matching tier. Unknown roles get the global default.

type ChainError

type ChainError struct {
	Table    string
	RowID    string
	Expected []byte // recomputed hash
	Actual   []byte // stored row_hash
	Position int    // row position in chain (0-based)
}

ChainError is returned when VerifyChain detects a broken hash chain link.

func (*ChainError) Error

func (e *ChainError) Error() string

type ColumnMeta

type ColumnMeta struct {
	Name    string
	TypeTag byte
}

ColumnMeta carries column name and type tag for canonical serialization. The generator emits a slice of these for each integrity-enabled table.

type Command

type Command interface {
	Name() string
	Description() string
	Run(args []string) error
}

Command represents a CLI subcommand that the compiled binary can run.

type ConnectionConfig

type ConnectionConfig struct {
	Driver   string
	Host     string
	Port     string
	Name     string
	User     string
	Password string
	Region   string            // AWS region (DynamoDB), GCP region, etc.
	Options  map[string]string // Driver-specific options (sslmode, charset, etc.)
}

ConnectionConfig describes a single database connection.

func (ConnectionConfig) DSN

func (c ConnectionConfig) DSN() string

DSN returns the driver-specific data source name.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context wraps an HTTP request and response, providing helpers for controllers and middleware.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext creates a Context from an HTTP request/response pair.

func (*Context) Auth

func (c *Context) Auth() *AuthInfo

Auth returns the authenticated user info. Panics if no auth middleware ran — calling Auth() on an unauthenticated route is a programming error.

func (*Context) BadRequest

func (c *Context) BadRequest(msg string) Response

BadRequest returns a 400 response with a message.

func (*Context) BearerToken

func (c *Context) BearerToken() string

BearerToken extracts the token from the Authorization: Bearer header.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie returns the value of the named cookie, or an error if not present.

func (*Context) Error

func (c *Context) Error(err error) Response

Error maps an error to an appropriate HTTP response. Errors that implement httpStatusError produce their own status code; unknown errors return 500.

func (*Context) Forbidden

func (c *Context) Forbidden(msg string) Response

Forbidden returns a 403 response with a message.

func (*Context) HasAnyRole

func (c *Context) HasAnyRole(slugs ...string) bool

HasAnyRole returns true if the user has any of the given roles.

func (*Context) HasRole

func (c *Context) HasRole(slug string) bool

HasRole returns true if the user has the given role.

func (*Context) IsAdmin

func (c *Context) IsAdmin() bool

IsAdmin returns true if the user has any role with Manages() set.

func (*Context) JSON

func (c *Context) JSON(status int, data any) Response

JSON returns a JSON response with the given status code and data.

func (*Context) NoContent

func (c *Context) NoContent() Response

NoContent returns a 204 No Content response.

func (*Context) NotFound

func (c *Context) NotFound(msg string) Response

NotFound returns a 404 response with a message.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns a URL path parameter by name (e.g. :id).

func (*Context) ParamUUID

func (c *Context) ParamUUID(name string) (uuid.UUID, error)

ParamUUID returns a URL path parameter parsed as a UUID. Returns the parsed UUID and an error if the param is not a valid UUID.

func (*Context) PeekJSON

func (c *Context) PeekJSON(field string) string

PeekJSON reads a top-level string field from a JSON request body without consuming the body. The body is buffered so subsequent reads (Bind, etc.) still work. Returns "" if the field is missing or the body isn't JSON.

func (*Context) Query

func (c *Context) Query(name string) string

Query returns a query string parameter by name.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the underlying *http.Request.

func (*Context) Resource

func (c *Context) Resource(q ResourceQuery) Response

Resource executes a query that returns a single record, serialized based on the authenticated user's ownership. Returns 404 if the record is not found.

func (*Context) Resources

func (c *Context) Resources(q ResourceListQuery) Response

Resources executes a query that returns a collection of records, serialized based on the authenticated user's ownership.

func (*Context) ResponseWriter

func (c *Context) ResponseWriter() http.ResponseWriter

ResponseWriter returns the underlying http.ResponseWriter.

func (*Context) Role

func (c *Context) Role() string

Role returns the primary role slug (first role). Returns "" if no roles.

func (*Context) Roles

func (c *Context) Roles() []string

Roles returns all role slugs for the authenticated user.

func (*Context) SetAuth

func (c *Context) SetAuth(claims any)

SetAuth stores authentication info (called by auth middleware). Panics if claims is not *AuthInfo — use &AuthInfo{UserID: ..., Claims: ...} instead of a raw type.

func (*Context) SetParam

func (c *Context) SetParam(name, value string)

SetParam sets a URL path parameter. Used by the generated route handler.

func (*Context) SetRoles

func (c *Context) SetRoles(roles []RoleInfo)

SetRoles stores the user's role memberships on the context. Called by LoadRoles middleware after querying the role_user table.

func (*Context) Unauthorized

func (c *Context) Unauthorized(msg string) Response

Unauthorized returns a 401 response with a message.

type Controller

type Controller struct{}

Controller is the base type embedded by all controllers. It exists so the generator can identify controller types.

type DeadlockError

type DeadlockError struct {
	Table  string
	Detail string
}

DeadlockError is returned when Postgres detects a deadlock and kills the transaction.

func (*DeadlockError) Error

func (e *DeadlockError) Error() string

func (*DeadlockError) HTTPStatus

func (e *DeadlockError) HTTPStatus() int

type Document

type Document struct {
	Operation string         // "query" | "mutation"
	Name      string         // operation name, may be empty
	Fields    []Field        // top-level field selections
	Variables map[string]any // variable values from the request
}

Document represents a parsed GraphQL request.

type EncryptionConfig

type EncryptionConfig struct {
	CurrentKeyEnv string // env var name for the active encryption key
	NextKeyEnv    string // env var name for the rotation target key (optional)
}

EncryptionConfig holds the environment variable names for encryption keys.

type ErrorReporter

type ErrorReporter func(ctx *Context, err error)

ErrorReporter is called when ctx.Error() handles an unrecoverable error or when panic recovery catches a panic. Use it to report to Sentry, Datadog, etc.

type Field

type Field struct {
	Name       string
	Alias      string // empty if no alias
	Args       map[string]any
	Selections []Field // nested selections
}

Field represents a selected field with arguments and sub-selections.

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

FieldError is a single field validation error.

type FilterOp

type FilterOp struct {
	Column   string
	Operator string
	Value    string
}

FilterOp represents a filter with an operator: filter[column][op]=value.

type GraphQLError

type GraphQLError struct {
	Message    string
	Code       string
	Field      string // optional: the field path that caused the error
	Extensions map[string]any
}

GraphQLError is an error with a GraphQL error code for structured error responses.

func BadInput

func BadInput(msg string) *GraphQLError

BadInput returns a GraphQL error for invalid user input.

func Forbidden

func Forbidden(msg string) *GraphQLError

Forbidden returns a GraphQL error for insufficient permissions.

func InternalError

func InternalError(msg string) *GraphQLError

InternalError returns a GraphQL error for unexpected server errors.

func NotFound

func NotFound(resource string) *GraphQLError

NotFound returns a GraphQL error for a missing resource.

func Unauthenticated

func Unauthenticated(msg string) *GraphQLError

Unauthenticated returns a GraphQL error for missing or invalid authentication.

func (*GraphQLError) Error

func (e *GraphQLError) Error() string

type HandlerFunc

type HandlerFunc func(ctx *Context) Response

HandlerFunc is a resolved handler that takes a Context and returns a Response.

type ImmutableQueryBuilder

type ImmutableQueryBuilder[T any] struct {
	// contains filtered or unexported fields
}

ImmutableQueryBuilder is the query builder for immutable (versioned) tables. It is completely separate from QueryBuilder — no embedding, no inherited methods. All queries dedup to the latest version_id per id.

func ImmutableQuery

func ImmutableQuery[T any](table string, softDeletes bool, connection ...string) *ImmutableQueryBuilder[T]

ImmutableQuery starts a new immutable query for the given model type.

func (*ImmutableQueryBuilder[T]) All

func (q *ImmutableQueryBuilder[T]) All() ([]T, error)

All returns the latest version of all matching records.

func (*ImmutableQueryBuilder[T]) AllVersions

func (q *ImmutableQueryBuilder[T]) AllVersions() *ImmutableQueryBuilder[T]

AllVersions bypasses deduplication and returns the full version history.

func (*ImmutableQueryBuilder[T]) AnyOwner

func (q *ImmutableQueryBuilder[T]) AnyOwner() *ImmutableQueryBuilder[T]

func (*ImmutableQueryBuilder[T]) Count

func (q *ImmutableQueryBuilder[T]) Count() (int64, error)

Count returns the number of distinct records matching conditions.

func (*ImmutableQueryBuilder[T]) Create

func (q *ImmutableQueryBuilder[T]) Create(record *T) error

Create inserts a new record.

func (*ImmutableQueryBuilder[T]) EagerLoad

func (q *ImmutableQueryBuilder[T]) EagerLoad(relation string) *ImmutableQueryBuilder[T]

func (*ImmutableQueryBuilder[T]) First

func (q *ImmutableQueryBuilder[T]) First() (*T, error)

First returns the latest version of the first matching record.

func (*ImmutableQueryBuilder[T]) Limit

func (q *ImmutableQueryBuilder[T]) Limit(n int) *ImmutableQueryBuilder[T]

func (*ImmutableQueryBuilder[T]) Lock

Lock adds FOR UPDATE to the query. Must be used inside a Transaction.

func (*ImmutableQueryBuilder[T]) LockForShare

func (q *ImmutableQueryBuilder[T]) LockForShare() *ImmutableQueryBuilder[T]

LockForShare adds FOR SHARE to the query.

func (*ImmutableQueryBuilder[T]) LockForUpdate

func (q *ImmutableQueryBuilder[T]) LockForUpdate() *ImmutableQueryBuilder[T]

LockForUpdate is an alias for Lock().

func (*ImmutableQueryBuilder[T]) NoWait

func (q *ImmutableQueryBuilder[T]) NoWait() *ImmutableQueryBuilder[T]

NoWait adds NOWAIT to the lock clause.

func (*ImmutableQueryBuilder[T]) Offset

func (q *ImmutableQueryBuilder[T]) Offset(n int) *ImmutableQueryBuilder[T]

func (*ImmutableQueryBuilder[T]) OrderBy

func (q *ImmutableQueryBuilder[T]) OrderBy(column, direction string) *ImmutableQueryBuilder[T]

func (*ImmutableQueryBuilder[T]) SkipLocked

func (q *ImmutableQueryBuilder[T]) SkipLocked() *ImmutableQueryBuilder[T]

SkipLocked adds SKIP LOCKED to the lock clause.

func (*ImmutableQueryBuilder[T]) Timeout

Timeout sets a per-query lock timeout.

type Job

type Job interface {
	Handle() error
}

Job is the interface all Pickle jobs must satisfy.

type JobEntry

type JobEntry struct {
	Schedule string
	Job      Job
	// contains filtered or unexported fields
}

JobEntry is a registered job with its schedule and options.

func (*JobEntry) AllowOverlap

func (e *JobEntry) AllowOverlap() *JobEntry

AllowOverlap permits a job to start even if the previous run hasn't finished.

func (*JobEntry) MaxRetries

func (e *JobEntry) MaxRetries(n int) *JobEntry

MaxRetries sets the maximum number of retries on failure.

func (*JobEntry) RetryDelay

func (e *JobEntry) RetryDelay(d time.Duration) *JobEntry

RetryDelay sets the delay between retries.

func (*JobEntry) SkipIfRunning

func (e *JobEntry) SkipIfRunning() *JobEntry

SkipIfRunning prevents overlapping runs (default behavior; explicit for documentation).

func (*JobEntry) Timeout

func (e *JobEntry) Timeout(d time.Duration) *JobEntry

Timeout sets a maximum execution duration. Zero means no timeout.

type LockHolder

type LockHolder struct {
	PID       int           `json:"pid"`
	Duration  time.Duration `json:"duration"`
	Query     string        `json:"query"`
	WaitCount int           `json:"wait_count"`
}

LockHolder describes a single lock holder from pg_locks / pg_stat_activity.

type LockOutsideTransactionError

type LockOutsideTransactionError struct {
	Table string
}

LockOutsideTransactionError is returned when Lock() is called on a query builder that is not associated with a transaction. Locks are released immediately after the query without a transaction, which is never correct.

func (*LockOutsideTransactionError) Error

func (*LockOutsideTransactionError) HTTPStatus

func (e *LockOutsideTransactionError) HTTPStatus() int

type LockStatus

type LockStatus struct {
	Table      string       `json:"table"`
	LockedRows int          `json:"locked_rows"`
	Waiters    int          `json:"waiters"`
	Holders    []LockHolder `json:"holders"`
}

LockStatus describes the current lock state for a table.

type LockTimeoutError

type LockTimeoutError struct {
	Table    string
	LockType string // "row", "share", "advisory"
	Duration time.Duration
}

LockTimeoutError is returned when a lock acquisition exceeds the configured timeout.

func (*LockTimeoutError) Error

func (e *LockTimeoutError) Error() string

func (*LockTimeoutError) HTTPStatus

func (e *LockTimeoutError) HTTPStatus() int

type ManagedConnection

type ManagedConnection struct {
	DB   *sql.DB
	Name string
	// contains filtered or unexported fields
}

ManagedConnection wraps a *sql.DB with in-flight query tracking and graceful retirement. When a connection's DSN changes on config reload, the old pool is retired and closes itself after its last in-flight query completes.

func (*ManagedConnection) Acquire

func (mc *ManagedConnection) Acquire() bool

Acquire increments the in-flight counter. Returns false if the connection is retired — caller must re-resolve from the ManagedConnections map.

func (*ManagedConnection) Release

func (mc *ManagedConnection) Release()

Release decrements the in-flight counter. If the connection is retired and this was the last in-flight query, the pool is closed.

type MerkleCheckpoint

type MerkleCheckpoint struct {
	CheckpointID     [16]byte  `json:"checkpoint_id" db:"checkpoint_id"`
	RootHash         []byte    `json:"root_hash" db:"root_hash"`
	FirstRowID       [16]byte  `json:"first_row_id" db:"first_row_id"`
	LastRowID        [16]byte  `json:"last_row_id" db:"last_row_id"`
	RowCount         int64     `json:"row_count" db:"row_count"`
	PrevCheckpointID *[16]byte `json:"prev_checkpoint_id,omitempty" db:"prev_checkpoint_id"`
}

MerkleCheckpoint represents a snapshot of the hash chain organized as a Merkle tree.

type MerkleProof

type MerkleProof struct {
	RowHash      []byte      `json:"row_hash"`
	RootHash     []byte      `json:"root_hash"`
	CheckpointID [16]byte    `json:"checkpoint_id"`
	Siblings     []ProofNode `json:"siblings"`
}

MerkleProof is an inclusion proof for a single row within a checkpoint. It can be verified without database access — hand it to an auditor.

type MiddlewareFunc

type MiddlewareFunc func(ctx *Context, next func() Response) Response

MiddlewareFunc is the signature for middleware functions.

func RateLimit

func RateLimit(rps float64, burst int) MiddlewareFunc

RateLimit returns a middleware that applies a per-IP rate limit with the given requests-per-second and burst size. Use this for per-route or per-group overrides on top of the framework-level global rate limit.

r.Group("/api/expensive", middleware.Auth, func(r *pickle.Router) {
    r.Post("/", handler, pickle.RateLimit(2, 5))
})

func RequireRole

func RequireRole(roles ...string) MiddlewareFunc

RequireRole returns middleware that checks if the user has any of the given roles. Returns 403 Forbidden if the user lacks all specified roles.

type MiddlewareProvider

type MiddlewareProvider interface {
	Middleware() MiddlewareFunc
}

MiddlewareProvider is implemented by types that can produce a MiddlewareFunc. Route registration methods check for this interface and unwrap automatically, so builders like AuthRateLimitConfig can be passed directly as middleware.

type NoWaitError

type NoWaitError struct {
	Table string
}

NoWaitError is returned when NoWait() is used and the target row is already locked.

func (*NoWaitError) Error

func (e *NoWaitError) Error() string

func (*NoWaitError) HTTPStatus

func (e *NoWaitError) HTTPStatus() int

type PageArgs

type PageArgs struct {
	First  int
	After  string
	Last   int
	Before string
	Offset int
}

PageArgs holds parsed pagination arguments.

type Pagination

type Pagination struct {
	Total    int64 `json:"total"`
	Page     int   `json:"page"`
	PageSize int   `json:"page_size"`
	Pages    int   `json:"pages"`
}

Pagination holds pagination metadata for search results.

type ProofNode

type ProofNode struct {
	Hash []byte `json:"hash"`
	Left bool   `json:"left"` // true if this sibling is on the left
}

ProofNode is a sibling hash in a Merkle inclusion proof.

type QueryBuilder

type QueryBuilder[T any] struct {
	// contains filtered or unexported fields
}

QueryBuilder is the generic query builder for all models.

func ApplyScopeBuilder

func ApplyScopeBuilder[T any](q *QueryBuilder[T], sb *ScopeBuilder[T]) *QueryBuilder[T]

ApplyScopeBuilder merges a ScopeBuilder's state back into a QueryBuilder.

func Query

func Query[T any](table string, connection ...string) *QueryBuilder[T]

Query starts a new query for the given model type.

func (*QueryBuilder[T]) All

func (q *QueryBuilder[T]) All() ([]T, error)

All returns all matching records.

func (*QueryBuilder[T]) AnyOwner

func (q *QueryBuilder[T]) AnyOwner() *QueryBuilder[T]

AnyOwner signals that this query intentionally does not scope by ownership. It is a no-op — it exists so that Squeeze recognizes the explicit opt-out.

func (*QueryBuilder[T]) Count

func (q *QueryBuilder[T]) Count() (int64, error)

Count returns the number of matching records.

func (*QueryBuilder[T]) Create

func (q *QueryBuilder[T]) Create(record *T) error

Create inserts a new record and scans the returned row back into the struct, populating DB-generated values (UUIDs, timestamps, defaults).

func (*QueryBuilder[T]) Delete

func (q *QueryBuilder[T]) Delete(record *T) error

Delete removes matching records.

func (*QueryBuilder[T]) EagerLoad

func (q *QueryBuilder[T]) EagerLoad(relation string) *QueryBuilder[T]

EagerLoad marks a relationship for eager loading.

func (*QueryBuilder[T]) First

func (q *QueryBuilder[T]) First() (*T, error)

First returns the first matching record.

func (*QueryBuilder[T]) Limit

func (q *QueryBuilder[T]) Limit(n int) *QueryBuilder[T]

Limit sets the LIMIT clause.

func (*QueryBuilder[T]) Lock

func (q *QueryBuilder[T]) Lock() *QueryBuilder[T]

Lock adds FOR UPDATE to the query. Must be used inside a Transaction.

func (*QueryBuilder[T]) LockForShare

func (q *QueryBuilder[T]) LockForShare() *QueryBuilder[T]

LockForShare adds FOR SHARE to the query — blocks writes but allows other FOR SHARE reads.

func (*QueryBuilder[T]) LockForUpdate

func (q *QueryBuilder[T]) LockForUpdate() *QueryBuilder[T]

LockForUpdate is an alias for Lock().

func (*QueryBuilder[T]) NoWait

func (q *QueryBuilder[T]) NoWait() *QueryBuilder[T]

NoWait adds NOWAIT to the lock clause — fails immediately instead of blocking if the target row is locked.

func (*QueryBuilder[T]) Offset

func (q *QueryBuilder[T]) Offset(n int) *QueryBuilder[T]

Offset sets the OFFSET clause.

func (*QueryBuilder[T]) OrderBy

func (q *QueryBuilder[T]) OrderBy(column, direction string) *QueryBuilder[T]

OrderBy adds an ORDER BY clause. The column name must be a valid SQL identifier (letters, digits, underscores only). Direction must be ASC or DESC. Invalid values panic — this is a programming error, not user input.

Prefer the generated typed methods (OrderByEmail, OrderByCreatedAt, etc.) which are safe by construction. This method exists for generated code and internal use; calling it with unsanitized user input is a bug.

func (*QueryBuilder[T]) SkipLocked

func (q *QueryBuilder[T]) SkipLocked() *QueryBuilder[T]

SkipLocked adds SKIP LOCKED to the lock clause — skips rows that are currently locked by another transaction. Useful for work queue patterns.

func (*QueryBuilder[T]) Timeout

func (q *QueryBuilder[T]) Timeout(d time.Duration) *QueryBuilder[T]

Timeout sets a per-query lock timeout. If the lock isn't acquired within this duration, a LockTimeoutError is returned.

func (*QueryBuilder[T]) Update

func (q *QueryBuilder[T]) Update(record *T) error

Update updates an existing record.

type RateLimitEvent

type RateLimitEvent struct {
	Key       string  // identity key or IP
	Layer     string  // "ip" or "auth"
	Path      string  // request path
	RPS       float64 // configured limit
	Burst     int     // configured burst
	Remaining float64 // tokens remaining (0 for denied)
	Allowed   bool    // whether the request was allowed
}

RateLimitEvent contains information about a rate limit check for observability.

type RateTier

type RateTier struct {
	RPS   float64
	Burst int
}

RateTier defines rate limit parameters for a specific role or plan.

type ResolveContext

type ResolveContext struct {
	// contains filtered or unexported fields
}

ResolveContext carries auth, variables, and dataloaders for a single GraphQL request.

func (*ResolveContext) CanSeeOwnerFields

func (c *ResolveContext) CanSeeOwnerFields(ownerID string) bool

CanSeeOwnerFields returns true if the caller owns the resource or is admin.

func (*ResolveContext) HasRole

func (c *ResolveContext) HasRole(role string) bool

HasRole returns true if the authenticated user has the given role.

func (*ResolveContext) IsAuthenticated

func (c *ResolveContext) IsAuthenticated() bool

IsAuthenticated returns true if the request has valid auth.

func (*ResolveContext) UserID

func (c *ResolveContext) UserID() string

UserID returns the authenticated user's ID, or empty string.

func (*ResolveContext) Visibility

func (c *ResolveContext) Visibility() VisibilityTier

Visibility returns the visibility tier for the current request.

type ResourceController

type ResourceController interface {
	Index(*Context) Response
	Show(*Context) Response
	Store(*Context) Response
	Update(*Context) Response
	Destroy(*Context) Response
}

Resource registers standard CRUD routes for a controller.

type ResourceListQuery

type ResourceListQuery interface {
	FetchResources(ownerID string) (any, error)
}

ResourceListQuery is implemented by generated query types to support ctx.Resources(). It fetches all matching records and returns them serialized for the given owner.

type ResourceQuery

type ResourceQuery interface {
	FetchResource(ownerID string) (any, error)
}

ResourceQuery is implemented by generated query types to support ctx.Resource(). It fetches a single record and returns it serialized for the given owner.

type Response

type Response struct {
	StatusCode int
	Body       any
	Headers    map[string]string
	Cookies    []*http.Cookie
}

Response represents an HTTP response to be written.

func RequireAdmin

func RequireAdmin(ctx *Context, next func() Response) Response

RequireAdmin returns middleware that checks if the user has a Manages role. Returns 403 Forbidden if the user is not an admin.

func RunMiddleware

func RunMiddleware(ctx *Context, middleware []MiddlewareFunc, handler func() Response) Response

RunMiddleware executes a middleware stack around a handler. Middleware functions are called in order, each wrapping the next.

func (Response) Header

func (r Response) Header(key, value string) Response

Header returns a copy of the response with an additional header set.

func (Response) WithCookie

func (r Response) WithCookie(c *http.Cookie) Response

WithCookie returns a copy of the response with an additional cookie to set.

func (Response) Write

func (r Response) Write(w http.ResponseWriter)

Write serializes the response to an http.ResponseWriter.

type RoleInfo

type RoleInfo struct {
	Slug    string
	Manages bool
}

RoleInfo describes a user's role membership, used by SetRoles.

type Route

type Route struct {
	Method     string
	Path       string
	Handler    HandlerFunc
	Middleware []MiddlewareFunc
}

Route describes a single registered route.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router collects route definitions. It is a descriptor, not a runtime router.

func Routes

func Routes(fn func(r *Router)) *Router

Routes creates a new Router by invoking the given configuration function.

func (*Router) AllRoutes

func (r *Router) AllRoutes() []Route

AllRoutes returns a flattened list of all routes with prefixes and middleware fully resolved.

func (*Router) Delete

func (r *Router) Delete(path string, handler HandlerFunc, mw ...any)

Delete registers a DELETE route.

func (*Router) Get

func (r *Router) Get(path string, handler HandlerFunc, mw ...any)

Get registers a GET route.

func (*Router) Group

func (r *Router) Group(prefix string, body func(*Router), mw ...any)

Group creates a sub-router with a shared prefix and optional middleware.

func (*Router) ListenAndServe

func (r *Router) ListenAndServe(addr string) error

Convenience: register on http.DefaultServeMux

func (*Router) OnError

func (r *Router) OnError(fn ErrorReporter)

OnError registers a callback that is invoked for panics recovered during request handling. Use this to wire in external error reporting (Sentry, etc.).

func (*Router) OnRateLimit

func (r *Router) OnRateLimit(fn func(ctx *Context, event RateLimitEvent))

OnRateLimit registers a callback that is invoked on every rate limit check (both IP and auth layers). Use this for metrics and alerting.

func (*Router) Patch

func (r *Router) Patch(path string, handler HandlerFunc, mw ...any)

Patch registers a PATCH route.

func (*Router) Post

func (r *Router) Post(path string, handler HandlerFunc, mw ...any)

Post registers a POST route.

func (*Router) Put

func (r *Router) Put(path string, handler HandlerFunc, mw ...any)

Put registers a PUT route.

func (*Router) RegisterRoutes

func (r *Router) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes wires all routes onto the given ServeMux. Also registers Pickle's internal operations endpoints (/pickle/*).

func (*Router) Resource

func (r *Router) Resource(prefix string, c ResourceController, mw ...any)

type RuntimeConfig

type RuntimeConfig struct {
	EncryptionKey     []byte
	EncryptionKeyNext []byte
	DatabaseDSNs      map[string]string // connection name → DSN
}

RuntimeConfig holds configuration values that can be hot-reloaded without restarting the process. Access via Config() — never cache the pointer.

func Config

func Config() *RuntimeConfig

Config returns the current runtime config. Lock-free, safe for concurrent reads.

func ReloadConfig

func ReloadConfig() (*RuntimeConfig, []string, error)

ReloadConfig re-reads environment variables, validates them, and atomically swaps the in-memory RuntimeConfig. Returns the new config, a list of changed env var names, and any validation error.

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler collects job registrations.

func Cron

func Cron(fn func(s *Scheduler)) *Scheduler

Cron creates a new Scheduler by invoking the given configuration function.

func (*Scheduler) Entries

func (s *Scheduler) Entries() []*JobEntry

Entries returns the registered job entries. Used by CLI tools to inspect the schedule.

func (*Scheduler) Job

func (s *Scheduler) Job(schedule string, job Job) *JobEntry

Job registers a cron job with the given schedule expression.

func (*Scheduler) Start

func (s *Scheduler) Start(ctx context.Context)

Start begins the scheduler loop. It blocks until ctx is cancelled.

type ScopeBuilder

type ScopeBuilder[T any] struct {
	// contains filtered or unexported fields
}

ScopeBuilder is a restricted query builder that exposes filter/sort methods but no terminal methods (First, All, Count, Create, Update, Delete). Scopes are defined against this type to prevent data access in scope functions.

func NewScopeBuilder

func NewScopeBuilder[T any](q *QueryBuilder[T]) *ScopeBuilder[T]

NewScopeBuilder creates a ScopeBuilder from a QueryBuilder's current state.

func (*ScopeBuilder[T]) Limit

func (sb *ScopeBuilder[T]) Limit(n int) *ScopeBuilder[T]

Limit sets the LIMIT clause.

func (*ScopeBuilder[T]) Offset

func (sb *ScopeBuilder[T]) Offset(n int) *ScopeBuilder[T]

Offset sets the OFFSET clause.

func (*ScopeBuilder[T]) OrderBy

func (sb *ScopeBuilder[T]) OrderBy(column, direction string) *ScopeBuilder[T]

OrderBy adds an ORDER BY clause to the scope builder.

type StaleVersionError

type StaleVersionError struct {
	Table           string
	EntityID        string
	ExpectedVersion string
	ActualVersion   string
}

StaleVersionError is returned when an immutable table Update() detects that the entity's version_id has changed since the caller read it. This means another write occurred between the read and update — the caller must re-read and decide how to proceed.

func (*StaleVersionError) Error

func (e *StaleVersionError) Error() string

func (*StaleVersionError) HTTPStatus

func (e *StaleVersionError) HTTPStatus() int

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx wraps a database transaction and provides query builder constructors scoped to that transaction. Generated Query<Model>() methods are emitted by the scope generator for each model.

func (*Tx) Conn

func (tx *Tx) Conn() *sql.Tx

Conn returns the underlying *sql.Tx for advanced use cases.

func (*Tx) Transaction

func (tx *Tx) Transaction(fn func(tx *Tx) error) error

Transaction runs fn inside a nested savepoint. If fn returns nil, the savepoint is released. If fn returns an error, only the savepoint is rolled back — the outer transaction continues.

type UnauthorizedActionError

type UnauthorizedActionError struct{}

UnauthorizedActionError indicates an action was denied by its gate.

func (*UnauthorizedActionError) Error

func (e *UnauthorizedActionError) Error() string

func (*UnauthorizedActionError) HTTPStatus

func (e *UnauthorizedActionError) HTTPStatus() int

type ValidationError

type ValidationError struct {
	Fields []FieldError `json:"fields"`
}

ValidationError holds field-level validation errors for GraphQL responses.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type VisibilityTier

type VisibilityTier int

VisibilityTier represents the access level of a request.

const (
	// VisibilityPublic is for unauthenticated access.
	VisibilityPublic VisibilityTier = iota
	// VisibilityOwner is for authenticated users viewing their own data.
	VisibilityOwner
	// VisibilityAll is for admin access.
	VisibilityAll
)

Directories

Path Synopsis
auth
jwt

Jump to

Keyboard shortcuts

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