Documentation
¶
Index ¶
- Constants
- Variables
- func AuditDenied(ctx *Context, action, model string, resourceID any, reason string)
- func AuditFailed(ctx *Context, action, model string, resourceID any, err error)
- func AuditPerformed(ctx *Context, action, model string, resourceID any)
- func Env(key, fallback string) string
- func InitRuntimeConfig()
- func OpenDB(conn ConnectionConfig) *sql.DB
- func PlaygroundHandler(endpoint string) http.Handler
- func RegisterPickleEndpoints(mux *http.ServeMux)
- func SetIntrospection(allow bool)
- func TransactionOn(db *sql.DB, fn func(tx *Tx) error) error
- func VerifyProof(proof *MerkleProof) bool
- func WithTransaction(fn func(tx *Tx) error) error
- func WrapConnection(name string, db *sql.DB)
- type App
- type AuthClaims
- type AuthInfo
- type AuthRateLimitConfig
- func (c *AuthRateLimitConfig) Burst(burst int) *AuthRateLimitConfig
- func (c *AuthRateLimitConfig) KeyFunc(fn func(*Context) string) *AuthRateLimitConfig
- func (c *AuthRateLimitConfig) Middleware() MiddlewareFunc
- func (c *AuthRateLimitConfig) RPS(rps float64) *AuthRateLimitConfig
- func (c *AuthRateLimitConfig) Tiers(tiers map[string]RateTier) *AuthRateLimitConfig
- type ChainError
- type ColumnMeta
- type Command
- type ConnectionConfig
- type Context
- func (c *Context) Auth() *AuthInfo
- func (c *Context) BadRequest(msg string) Response
- func (c *Context) BearerToken() string
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Error(err error) Response
- func (c *Context) Forbidden(msg string) Response
- func (c *Context) HasAnyRole(slugs ...string) bool
- func (c *Context) HasRole(slug string) bool
- func (c *Context) IsAdmin() bool
- func (c *Context) JSON(status int, data any) Response
- func (c *Context) NoContent() Response
- func (c *Context) NotFound(msg string) Response
- func (c *Context) Param(name string) string
- func (c *Context) ParamUUID(name string) (uuid.UUID, error)
- func (c *Context) PeekJSON(field string) string
- func (c *Context) Query(name string) string
- func (c *Context) Request() *http.Request
- func (c *Context) Resource(q ResourceQuery) Response
- func (c *Context) Resources(q ResourceListQuery) Response
- func (c *Context) ResponseWriter() http.ResponseWriter
- func (c *Context) Role() string
- func (c *Context) Roles() []string
- func (c *Context) SetAuth(claims any)
- func (c *Context) SetParam(name, value string)
- func (c *Context) SetRoles(roles []RoleInfo)
- func (c *Context) Unauthorized(msg string) Response
- type Controller
- type DeadlockError
- type Document
- type EncryptionConfig
- type ErrorReporter
- type Field
- type FieldError
- type FilterOp
- type GraphQLError
- type HandlerFunc
- type ImmutableQueryBuilder
- func (q *ImmutableQueryBuilder[T]) All() ([]T, error)
- func (q *ImmutableQueryBuilder[T]) AllVersions() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) AnyOwner() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) Count() (int64, error)
- func (q *ImmutableQueryBuilder[T]) Create(record *T) error
- func (q *ImmutableQueryBuilder[T]) EagerLoad(relation string) *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) First() (*T, error)
- func (q *ImmutableQueryBuilder[T]) Limit(n int) *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) Lock() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) LockForShare() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) LockForUpdate() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) NoWait() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) Offset(n int) *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) OrderBy(column, direction string) *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) SkipLocked() *ImmutableQueryBuilder[T]
- func (q *ImmutableQueryBuilder[T]) Timeout(d time.Duration) *ImmutableQueryBuilder[T]
- type Job
- type JobEntry
- type LockHolder
- type LockOutsideTransactionError
- type LockStatus
- type LockTimeoutError
- type ManagedConnection
- type MerkleCheckpoint
- type MerkleProof
- type MiddlewareFunc
- type MiddlewareProvider
- type NoWaitError
- type PageArgs
- type Pagination
- type ProofNode
- type QueryBuilder
- func (q *QueryBuilder[T]) All() ([]T, error)
- func (q *QueryBuilder[T]) AnyOwner() *QueryBuilder[T]
- func (q *QueryBuilder[T]) Count() (int64, error)
- func (q *QueryBuilder[T]) Create(record *T) error
- func (q *QueryBuilder[T]) Delete(record *T) error
- func (q *QueryBuilder[T]) EagerLoad(relation string) *QueryBuilder[T]
- func (q *QueryBuilder[T]) First() (*T, error)
- func (q *QueryBuilder[T]) Limit(n int) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Lock() *QueryBuilder[T]
- func (q *QueryBuilder[T]) LockForShare() *QueryBuilder[T]
- func (q *QueryBuilder[T]) LockForUpdate() *QueryBuilder[T]
- func (q *QueryBuilder[T]) NoWait() *QueryBuilder[T]
- func (q *QueryBuilder[T]) Offset(n int) *QueryBuilder[T]
- func (q *QueryBuilder[T]) OrderBy(column, direction string) *QueryBuilder[T]
- func (q *QueryBuilder[T]) SkipLocked() *QueryBuilder[T]
- func (q *QueryBuilder[T]) Timeout(d time.Duration) *QueryBuilder[T]
- func (q *QueryBuilder[T]) Update(record *T) error
- type RateLimitEvent
- type RateTier
- type ResolveContext
- type ResourceController
- type ResourceListQuery
- type ResourceQuery
- type Response
- type RoleInfo
- type Route
- type Router
- func (r *Router) AllRoutes() []Route
- func (r *Router) Delete(path string, handler HandlerFunc, mw ...any)
- func (r *Router) Get(path string, handler HandlerFunc, mw ...any)
- func (r *Router) Group(prefix string, body func(*Router), mw ...any)
- func (r *Router) ListenAndServe(addr string) error
- func (r *Router) OnError(fn ErrorReporter)
- func (r *Router) OnRateLimit(fn func(ctx *Context, event RateLimitEvent))
- func (r *Router) Patch(path string, handler HandlerFunc, mw ...any)
- func (r *Router) Post(path string, handler HandlerFunc, mw ...any)
- func (r *Router) Put(path string, handler HandlerFunc, mw ...any)
- func (r *Router) RegisterRoutes(mux *http.ServeMux)
- func (r *Router) Resource(prefix string, c ResourceController, mw ...any)
- type RuntimeConfig
- type Scheduler
- type ScopeBuilder
- type StaleVersionError
- type Tx
- type UnauthorizedActionError
- type ValidationError
- type VisibilityTier
Constants ¶
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 ¶
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).
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.
var ConnectionNamesFunc func() []string
ConnectionNamesFunc returns the names of all managed connections. Set by the models package during initialization.
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.
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.
var DB *sql.DB
DB is the package-level database connection. Set during app initialization.
var EncryptionKey []byte
EncryptionKey is the decoded current encryption key (set at app startup).
var EncryptionKeyNext []byte
EncryptionKeyNext is the decoded next encryption key for rotation (nil if not rotating).
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.
ErrUnauthorized is returned by gated action methods when the gate denies access.
var GenesisHash = make([]byte, 32)
GenesisHash is the prev_hash for the first row in a chain: 32 zero bytes.
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 ¶
AuditDenied logs a denied action. Called when a gate check fails.
func AuditFailed ¶
AuditFailed logs a failed action. Called when an action errors after authorisation.
func AuditPerformed ¶
AuditPerformed logs a successful action. Called after a gate check passes and the action is executed.
func Env ¶
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 ¶
PlaygroundHandler returns an http.Handler that serves a GraphQL playground UI. Mount it at /playground in debug mode.
func RegisterPickleEndpoints ¶
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 ¶
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 ¶
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 ¶
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 (*App) PrintCommands ¶
func (a *App) PrintCommands()
PrintCommands prints available commands to stderr.
type AuthClaims ¶
AuthClaims holds authentication state for a GraphQL request.
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 ¶
func (c *AuthRateLimitConfig) RPS(rps float64) *AuthRateLimitConfig
RPS sets the requests-per-second limit.
func (*AuthRateLimitConfig) Tiers ¶
func (c *AuthRateLimitConfig) Tiers(tiers map[string]RateTier) *AuthRateLimitConfig
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 ¶
ColumnMeta carries column name and type tag for canonical serialization. The generator emits a slice of these for each integrity-enabled table.
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 ¶
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 ¶
BadRequest returns a 400 response with a message.
func (*Context) BearerToken ¶
BearerToken extracts the token from the Authorization: Bearer header.
func (*Context) Error ¶
Error maps an error to an appropriate HTTP response. Errors that implement httpStatusError produce their own status code; unknown errors return 500.
func (*Context) HasAnyRole ¶
HasAnyRole returns true if the user has any of the given roles.
func (*Context) ParamUUID ¶
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 ¶
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) 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) SetAuth ¶
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) SetRoles ¶
SetRoles stores the user's role memberships on the context. Called by LoadRoles middleware after querying the role_user table.
func (*Context) Unauthorized ¶
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 ¶
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 ¶
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 ¶
FieldError is a single field validation error.
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 ¶
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 ¶
func (q *ImmutableQueryBuilder[T]) Lock() *ImmutableQueryBuilder[T]
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 ¶
func (q *ImmutableQueryBuilder[T]) Timeout(d time.Duration) *ImmutableQueryBuilder[T]
Timeout sets a per-query lock timeout.
type JobEntry ¶
JobEntry is a registered job with its schedule and options.
func (*JobEntry) AllowOverlap ¶
AllowOverlap permits a job to start even if the previous run hasn't finished.
func (*JobEntry) MaxRetries ¶
MaxRetries sets the maximum number of retries on failure.
func (*JobEntry) RetryDelay ¶
RetryDelay sets the delay between retries.
func (*JobEntry) SkipIfRunning ¶
SkipIfRunning prevents overlapping runs (default behavior; explicit for documentation).
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 (e *LockOutsideTransactionError) Error() string
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 ¶
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 ¶
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 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 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 ¶
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 ¶
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 ¶
Response represents an HTTP response to be written.
func RequireAdmin ¶
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) WithCookie ¶
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 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 (*Router) AllRoutes ¶
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) ListenAndServe ¶
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 ¶
RegisterRoutes wires all routes onto the given ServeMux. Also registers Pickle's internal operations endpoints (/pickle/*).
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 (*Scheduler) Entries ¶
Entries returns the registered job entries. Used by CLI tools to inspect the schedule.
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.
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 )