crud

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrMessageProcessorMustReturnSlice = "processor_must_return_slice"
	ErrCodeProcessorInvalidReturn      = 2400
)

Error message keys and codes.

View Source
const (
	RPCActionCreate          = "create"
	RPCActionUpdate          = "update"
	RPCActionDelete          = "delete"
	RPCActionCreateMany      = "create_many"
	RPCActionUpdateMany      = "update_many"
	RPCActionDeleteMany      = "delete_many"
	RPCActionFindOne         = "find_one"
	RPCActionFindAll         = "find_all"
	RPCActionFindPage        = "find_page"
	RPCActionFindOptions     = "find_options"
	RPCActionFindTree        = "find_tree"
	RPCActionFindTreeOptions = "find_tree_options"
	RPCActionImport          = "import"
	RPCActionExport          = "export"
)

RPC action names (snake_case identifiers).

View Source
const (
	RESTActionCreate          = "post /"
	RESTActionUpdate          = "put /:" + IDColumn
	RESTActionDelete          = "delete /:" + IDColumn
	RESTActionCreateMany      = "post /many"
	RESTActionUpdateMany      = "put /many"
	RESTActionDeleteMany      = "delete /many"
	RESTActionFindOne         = "get /:" + IDColumn
	RESTActionFindAll         = "get /"
	RESTActionFindPage        = "get /page"
	RESTActionFindOptions     = "get /options"
	RESTActionFindTree        = "get /tree"
	RESTActionFindTreeOptions = "get /tree/options"
	RESTActionImport          = "post /import"
	RESTActionExport          = "get /export"
)

REST action names in "<method> <path>" format, supporting Fiber route patterns (e.g., /:id).

View Source
const (
	IDColumn          = orm.ColumnID
	ParentIDColumn    = "parent_id"
	LabelColumn       = "label"
	ValueColumn       = "value"
	DescriptionColumn = "description"
)

Well-known column names.

Variables

View Source
var ErrAuditUserCompositePK = errors.New("audit user model has composite primary key, only single primary key is supported")

ErrAuditUserCompositePK indicates the audit user model has a composite primary key which is not supported.

View Source
var ErrColumnNotFound = errors.New("column does not exist in model")

ErrColumnNotFound indicates a column does not exist in the model.

View Source
var ErrModelNoPrimaryKey = errors.New("model has no primary key")

ErrModelNoPrimaryKey indicates the model schema has no primary key.

View Source
var ErrSearchTypeMismatch = errors.New("search type mismatch")

ErrSearchTypeMismatch indicates a type mismatch in search parameter conversion.

Functions

func ApplyDataPermission

func ApplyDataPermission(query orm.SelectQuery, ctx fiber.Ctx) error

ApplyDataPermission applies data permission filtering to a SelectQuery.

func GetAuditUserNameRelations

func GetAuditUserNameRelations(userModel any, nameColumn ...string) []*orm.RelationSpec

GetAuditUserNameRelations returns RelationSpecs for creator and updater joins.

func QueryError

func QueryError(ctx fiber.Ctx) error

QueryError retrieves the query error stored in the context during CTE building. Returns nil if no error has been stored.

func SetQueryError

func SetQueryError(ctx fiber.Ctx, err error)

SetQueryError stores a query error in the context during CTE building. This is used by tree APIs to propagate errors from within WithRecursive closures.

Types

type Builder

type Builder[T any] interface {
	// ResourceKind sets the resource kind (RPC or REST) for this endpoint.
	ResourceKind(kind api.Kind) T
	// Action sets the action name for this endpoint.
	Action(action string) T
	// EnableAudit enables audit logging for this endpoint.
	EnableAudit() T
	// Timeout sets the request timeout for this endpoint.
	Timeout(timeout time.Duration) T
	// Public marks this endpoint as publicly accessible without authentication.
	Public() T
	// PermToken sets the permission token required to access this endpoint.
	PermToken(token string) T
	// RateLimit configures rate limiting for this endpoint.
	RateLimit(maxRequests int, period time.Duration) T
	// Build creates an OperationSpec with the configured settings and the given handler.
	Build(handler any) api.OperationSpec
}

Builder defines the interface for building API endpoints.

func NewBuilder

func NewBuilder[T any](self T, kind ...api.Kind) Builder[T]

NewBuilder creates a new base API builder instance.

type Create

type Create[TModel, TParams any] interface {
	api.OperationsProvider
	Builder[Create[TModel, TParams]]

	// WithPreCreate registers a processor that is called before the model is saved to the database.
	WithPreCreate(processor PreCreateProcessor[TModel, TParams]) Create[TModel, TParams]
	// WithPostCreate registers a processor that is called after the model is saved within the same transaction.
	WithPostCreate(processor PostCreateProcessor[TModel, TParams]) Create[TModel, TParams]
}

Create provides a fluent interface for building create endpoints. Supports pre/post processing hooks and transaction-based model creation.

func NewCreate

func NewCreate[TModel, TParams any](kind ...api.Kind) Create[TModel, TParams]

NewCreate creates a new Create instance for single record creation.

type CreateMany

type CreateMany[TModel, TParams any] interface {
	api.OperationsProvider
	Builder[CreateMany[TModel, TParams]]

	// WithPreCreateMany registers a processor that is called before the models are saved to the database.
	WithPreCreateMany(processor PreCreateManyProcessor[TModel, TParams]) CreateMany[TModel, TParams]
	// WithPostCreateMany registers a processor that is called after the models are saved within the same transaction.
	WithPostCreateMany(processor PostCreateManyProcessor[TModel, TParams]) CreateMany[TModel, TParams]
}

CreateMany provides a fluent interface for building batch create endpoints. Creates multiple models atomically in a single transaction with pre/post hooks.

func NewCreateMany

func NewCreateMany[TModel, TParams any](kind ...api.Kind) CreateMany[TModel, TParams]

NewCreateMany creates a new CreateMany instance for batch creation.

type CreateManyParams

type CreateManyParams[TParams any] struct {
	api.P

	List []TParams `json:"list" validate:"required,min=1,dive" label_i18n:"batch_create_list"`
}

CreateManyParams is a wrapper type for batch create parameters.

type DataOption

type DataOption struct {
	// Display text shown to users
	Label string `json:"label" bun:"label"`
	// Underlying value used in form submissions
	Value string `json:"value" bun:"value"`
	// Additional descriptive text (optional)
	Description string `json:"description,omitempty" bun:"description"`
	// Custom metadata for extended functionality (optional)
	Meta map[string]any `json:"meta,omitempty" bun:"meta"`
}

DataOption represents a selectable item with display text and underlying value. Commonly used for dropdown lists, radio buttons, and select components.

type DataOptionColumnMapping

type DataOptionColumnMapping struct {
	// Column name for label (default: "name")
	LabelColumn string `json:"labelColumn"`
	// Column name for value (default: "id")
	ValueColumn string `json:"valueColumn"`
	// Column name for description
	DescriptionColumn string `json:"descriptionColumn"`
	// Additional columns to include in meta field
	// Supports simple column names or "column AS alias" format
	// Examples: ["status", "role_name as role"]
	MetaColumns []string `json:"metaColumns"`
}

DataOptionColumnMapping defines the mapping between database columns and option fields.

type DataOptionConfig

type DataOptionConfig struct {
	api.M

	DataOptionColumnMapping
}

DataOptionConfig is the API request meta for querying options.

type Delete

type Delete[TModel any] interface {
	api.OperationsProvider
	Builder[Delete[TModel]]

	// WithPreDelete registers a processor that is called before the model is deleted from the database.
	WithPreDelete(processor PreDeleteProcessor[TModel]) Delete[TModel]
	// WithPostDelete registers a processor that is called after the model is deleted within the same transaction.
	WithPostDelete(processor PostDeleteProcessor[TModel]) Delete[TModel]
	// DisableDataPerm disables automatic data permission filtering for delete queries.
	DisableDataPerm() Delete[TModel]
}

Delete provides a fluent interface for building delete endpoints. Validates primary key, loads model, and supports pre/post processing hooks.

func NewDelete

func NewDelete[TModel any](kind ...api.Kind) Delete[TModel]

NewDelete creates a new Delete operation instance for single record deletion.

type DeleteMany

type DeleteMany[TModel any] interface {
	api.OperationsProvider
	Builder[DeleteMany[TModel]]

	// WithPreDeleteMany registers a processor that is called before the models are deleted from the database.
	WithPreDeleteMany(processor PreDeleteManyProcessor[TModel]) DeleteMany[TModel]
	// WithPostDeleteMany registers a processor that is called after the models are deleted within the same transaction.
	WithPostDeleteMany(processor PostDeleteManyProcessor[TModel]) DeleteMany[TModel]
	// DisableDataPerm disables automatic data permission filtering for batch delete queries.
	DisableDataPerm() DeleteMany[TModel]
}

DeleteMany provides a fluent interface for building batch delete endpoints. Deletes multiple models atomically with validation and pre/post hooks.

func NewDeleteMany

func NewDeleteMany[TModel any](kind ...api.Kind) DeleteMany[TModel]

NewDeleteMany creates a new DeleteMany instance for batch deletion.

type DeleteManyParams

type DeleteManyParams struct {
	api.P

	PKs []any `json:"pks" validate:"required,min=1" label_i18n:"batch_delete_pks"`
}

DeleteManyParams is a wrapper type for batch delete parameters. For single primary key models: PKs can be []any with direct values (e.g., ["id1", "id2"]) For composite primary key models: PKs should be []map[string]any with each map containing all PK fields.

type Export

type Export[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, []TModel, Export[TModel, TSearch]]

	// WithDefaultFormat sets the default export format (Excel or CSV) when not specified in the request.
	WithDefaultFormat(format TabularFormat) Export[TModel, TSearch]
	// WithExcelOptions configures Excel-specific export options (sheet name, styles, etc.).
	WithExcelOptions(opts ...excel.ExportOption) Export[TModel, TSearch]
	// WithCsvOptions configures CSV-specific export options (delimiter, encoding, etc.).
	WithCsvOptions(opts ...csv.ExportOption) Export[TModel, TSearch]
	// WithPreExport registers a processor for post-query data transformation before export.
	WithPreExport(processor PreExportProcessor[TModel, TSearch]) Export[TModel, TSearch]
	// WithFilenameBuilder sets a custom function to generate the export filename.
	WithFilenameBuilder(builder FilenameBuilder[TSearch]) Export[TModel, TSearch]
}

Export provides a fluent interface for building export endpoints. Queries data based on search conditions and exports to Excel or Csv file.

func NewExport

func NewExport[TModel, TSearch any](kind ...api.Kind) Export[TModel, TSearch]

NewExport creates a new Export instance.

type FilenameBuilder

type FilenameBuilder[TSearch any] func(search TSearch, ctx fiber.Ctx) string

FilenameBuilder generates the filename for exported Excel files based on search parameters. Allows dynamic filename generation with timestamp, filters, etc.

type Find

type Find[TModel, TSearch, TProcessorIn, TOperation any] interface {
	Builder[TOperation]

	// Setup initializes the find operation with framework-level options and validates configuration.
	// Must be called before query execution. Config specifies which QueryParts framework options apply to.
	Setup(db orm.DB, config *FindOperationConfig, opts ...*FindOperationOption) error
	// ConfigureQuery applies FindOperationOption for the specified QueryPart to the query.
	// Returns error if any option applier fails.
	ConfigureQuery(query orm.SelectQuery, search TSearch, meta api.Meta, ctx fiber.Ctx, part QueryPart) error
	// Process applies post-query processing to transform results.
	// Returns input unchanged if no Processor is configured.
	Process(input TProcessorIn, search TSearch, ctx fiber.Ctx) any

	// WithProcessor registers a post-query processor to transform or enrich results before returning.
	WithProcessor(processor Processor[TProcessorIn, TSearch]) TOperation
	// WithOptions appends custom FindOperationOption to the query configuration.
	WithOptions(opts ...*FindOperationOption) TOperation
	// WithSelect adds a column to the SELECT clause for specified query parts.
	WithSelect(column string, parts ...QueryPart) TOperation
	// WithSelectAs adds a column with an alias to the SELECT clause for specified query parts.
	WithSelectAs(column, alias string, parts ...QueryPart) TOperation
	// WithDefaultSort sets the default sort order when no dynamic sorting is provided in the request.
	WithDefaultSort(sort ...*sortx.OrderSpec) TOperation
	// WithCondition adds a WHERE condition using ConditionBuilder for specified query parts.
	WithCondition(fn func(cb orm.ConditionBuilder), parts ...QueryPart) TOperation
	// DisableDataPerm disables automatic data permission filtering for this endpoint.
	// IMPORTANT: Must be called before the API is registered (before Setup() is invoked).
	DisableDataPerm() TOperation
	// WithRelation adds a relation join to the query for specified query parts.
	WithRelation(relation *orm.RelationSpec, parts ...QueryPart) TOperation
	// WithAuditUserNames joins audit user model to populate creator/updater name fields.
	WithAuditUserNames(userModel any, nameColumn ...string) TOperation
	// WithQueryApplier adds a custom query modification function for specified query parts.
	WithQueryApplier(applier func(query orm.SelectQuery, search TSearch, ctx fiber.Ctx) error, parts ...QueryPart) TOperation
}

Find provides a fluent interface for building find endpoints. All configuration is done through FindOperationOption passed to NewFindXxx constructors.

func NewFind

func NewFind[TModel, TSearch, TProcessor, TOperation any](self TOperation, kind ...api.Kind) Find[TModel, TSearch, TProcessor, TOperation]

NewFind creates the base Find instance used by all find-type endpoints.

type FindAll

type FindAll[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, []TModel, FindAll[TModel, TSearch]]
}

FindAll provides a fluent interface for building find all endpoints. Returns all records matching the search criteria (with a safety limit).

func NewFindAll

func NewFindAll[TModel, TSearch any](kind ...api.Kind) FindAll[TModel, TSearch]

NewFindAll creates a new FindAll instance.

type FindOne

type FindOne[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, TModel, FindOne[TModel, TSearch]]
}

FindOne provides a fluent interface for building find one endpoints. Returns a single record matching the search criteria.

func NewFindOne

func NewFindOne[TModel, TSearch any](kind ...api.Kind) FindOne[TModel, TSearch]

NewFindOne creates a new FindOne instance.

type FindOperationConfig

type FindOperationConfig struct {
	// QueryParts defines which query operations (condition, sort, audit relations) apply to different query contexts
	QueryParts *QueryPartsConfig
}

FindOperationConfig contains all configuration for find operation setup phase.

type FindOperationOption

type FindOperationOption struct {
	Parts   []QueryPart
	Applier func(query orm.SelectQuery, search any, meta api.Meta, ctx fiber.Ctx) error
}

FindOperationOption defines a configuration option for find operations. It can target specific query parts for fine-grained control, which is essential for recursive CTE queries used in tree operations.

The Applier function receives the query, search parameters, meta, and fiber context, allowing for dynamic configuration based on runtime data.

type FindOptions

type FindOptions[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, []DataOption, FindOptions[TModel, TSearch]]

	// WithDefaultColumnMapping sets fallback column mapping for value, label, and description columns.
	WithDefaultColumnMapping(mapping *DataOptionColumnMapping) FindOptions[TModel, TSearch]
}

FindOptions provides a fluent interface for building find options endpoints. Returns a simplified list of options (value, label, description) for dropdowns and selects.

func NewFindOptions

func NewFindOptions[TModel, TSearch any](kind ...api.Kind) FindOptions[TModel, TSearch]

NewFindOptions creates a new FindOptions instance.

type FindPage

type FindPage[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, []TModel, FindPage[TModel, TSearch]]

	// WithDefaultPageSize sets the fallback page size when the request's page size is zero or invalid.
	WithDefaultPageSize(size int) FindPage[TModel, TSearch]
}

FindPage provides a fluent interface for building find page endpoints. Returns paginated results with total count.

func NewFindPage

func NewFindPage[TModel, TSearch any](kind ...api.Kind) FindPage[TModel, TSearch]

NewFindPage creates a new FindPage instance.

type FindTree

type FindTree[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, []TModel, FindTree[TModel, TSearch]]

	// WithIDColumn sets the column used to identify individual tree nodes.
	WithIDColumn(name string) FindTree[TModel, TSearch]
	// WithParentIDColumn sets the column that establishes parent-child relationships between nodes.
	WithParentIDColumn(name string) FindTree[TModel, TSearch]
}

FindTree provides a fluent interface for building find tree endpoints. Returns hierarchical data using recursive CTEs.

func NewFindTree

func NewFindTree[TModel, TSearch any](
	treeBuilder func(flatModels []TModel) []TModel,
	kind ...api.Kind,
) FindTree[TModel, TSearch]

NewFindTree creates a new FindTree for hierarchical data retrieval. The treeBuilder function converts flat database records into nested tree structures. Requires models to have id and parent_id columns for parent-child relationships.

type FindTreeOptions

type FindTreeOptions[TModel, TSearch any] interface {
	api.OperationsProvider
	Find[TModel, TSearch, []TreeDataOption, FindTreeOptions[TModel, TSearch]]

	// WithDefaultColumnMapping sets fallback column mapping for label, value, description, and sort columns.
	WithDefaultColumnMapping(mapping *DataOptionColumnMapping) FindTreeOptions[TModel, TSearch]
	// WithIDColumn sets the column used to identify individual tree nodes.
	WithIDColumn(name string) FindTreeOptions[TModel, TSearch]
	// WithParentIDColumn sets the column that establishes parent-child relationships between nodes.
	WithParentIDColumn(name string) FindTreeOptions[TModel, TSearch]
}

FindTreeOptions provides a fluent interface for building find tree options endpoints. Returns hierarchical options using recursive CTEs for tree-structured dropdowns.

func NewFindTreeOptions

func NewFindTreeOptions[TModel, TSearch any](kind ...api.Kind) FindTreeOptions[TModel, TSearch]

NewFindTreeOptions creates a new FindTreeOptions instance.

type Import

type Import[TModel any] interface {
	api.OperationsProvider
	Builder[Import[TModel]]

	// WithDefaultFormat sets the default import format (Excel or CSV) when not specified in the request.
	WithDefaultFormat(format TabularFormat) Import[TModel]
	// WithExcelOptions configures Excel-specific import options (sheet index, header row, etc.).
	WithExcelOptions(opts ...excel.ImportOption) Import[TModel]
	// WithCsvOptions configures CSV-specific import options (delimiter, encoding, etc.).
	WithCsvOptions(opts ...csv.ImportOption) Import[TModel]
	// WithPreImport registers a processor that is called before parsed models are inserted into the database.
	WithPreImport(processor PreImportProcessor[TModel]) Import[TModel]
	// WithPostImport registers a processor that is called after models are inserted within the same transaction.
	WithPostImport(processor PostImportProcessor[TModel]) Import[TModel]
}

Import provides a fluent interface for building import endpoints. Parses uploaded Excel or Csv file and creates records in database.

func NewImport

func NewImport[TModel any](kind ...api.Kind) Import[TModel]

NewImport creates a new Import instance.

type PostCreateManyProcessor

type PostCreateManyProcessor[TModel, TParams any] func(models []TModel, paramsList []TParams, ctx fiber.Ctx, tx orm.DB) error

PostCreateManyProcessor handles side effects after successful batch model creation. Runs within the same transaction. Uses: audit logging, notifications, cache updates.

type PostCreateProcessor

type PostCreateProcessor[TModel, TParams any] func(model *TModel, params *TParams, ctx fiber.Ctx, tx orm.DB) error

PostCreateProcessor handles side effects after successful model creation. Runs within the same transaction. Uses: audit logging, notifications, cache updates.

type PostDeleteManyProcessor

type PostDeleteManyProcessor[TModel any] func(models []TModel, ctx fiber.Ctx, tx orm.DB) error

PostDeleteManyProcessor handles cleanup tasks after successful batch deletion. Runs within the same transaction. Uses: cascade operations, audit logging.

type PostDeleteProcessor

type PostDeleteProcessor[TModel any] func(model *TModel, ctx fiber.Ctx, tx orm.DB) error

PostDeleteProcessor handles cleanup tasks after successful deletion. Runs within the same transaction. Uses: cascade operations, audit logging.

type PostImportProcessor

type PostImportProcessor[TModel any] func(models []TModel, ctx fiber.Ctx, tx orm.DB) error

PostImportProcessor handles side effects after successful import. Runs within the same transaction. Uses: audit logging, notifications, cache updates.

type PostUpdateManyProcessor

type PostUpdateManyProcessor[TModel, TParams any] func(oldModels, models []TModel, paramsList []TParams, ctx fiber.Ctx, tx orm.DB) error

PostUpdateManyProcessor handles side effects after successful batch model update. Runs within the same transaction. Uses: audit trails, change notifications.

type PostUpdateProcessor

type PostUpdateProcessor[TModel, TParams any] func(oldModel, model *TModel, params *TParams, ctx fiber.Ctx, tx orm.DB) error

PostUpdateProcessor handles side effects after successful model update. Runs within the same transaction. Uses: audit trails, change notifications.

type PreCreateManyProcessor

type PreCreateManyProcessor[TModel, TParams any] func(models []TModel, paramsList []TParams, query orm.InsertQuery, ctx fiber.Ctx, tx orm.DB) error

PreCreateManyProcessor handles business logic before batch model creation. Runs within the same transaction. Common uses: batch validation, default values, related data setup.

type PreCreateProcessor

type PreCreateProcessor[TModel, TParams any] func(model *TModel, params *TParams, query orm.InsertQuery, ctx fiber.Ctx, tx orm.DB) error

PreCreateProcessor handles business logic before model creation. Runs within the same transaction. Uses: validation, default values, related data setup.

type PreDeleteManyProcessor

type PreDeleteManyProcessor[TModel any] func(models []TModel, query orm.DeleteQuery, ctx fiber.Ctx, tx orm.DB) error

PreDeleteManyProcessor handles validation and checks before batch model deletion. Runs within the same transaction. Common uses: referential integrity checks, soft delete logic.

type PreDeleteProcessor

type PreDeleteProcessor[TModel any] func(model *TModel, query orm.DeleteQuery, ctx fiber.Ctx, tx orm.DB) error

PreDeleteProcessor handles validation and checks before model deletion. Runs within the same transaction. Common uses: referential integrity checks, soft delete logic.

type PreExportProcessor

type PreExportProcessor[TModel, TSearch any] func(models []TModel, search TSearch, ctx fiber.Ctx, db orm.DB) error

PreExportProcessor handles data modification before exporting to Excel. Common uses: data formatting, field filtering, additional data loading.

type PreImportProcessor

type PreImportProcessor[TModel any] func(models []TModel, query orm.InsertQuery, ctx fiber.Ctx, tx orm.DB) error

PreImportProcessor handles validation and transformation before saving imported data. Runs within the same transaction. Common uses: data validation, default values, duplicate checking.

type PreUpdateManyProcessor

type PreUpdateManyProcessor[TModel, TParams any] func(oldModels, models []TModel, paramsList []TParams, query orm.UpdateQuery, ctx fiber.Ctx, tx orm.DB) error

PreUpdateManyProcessor handles business logic before batch model update. Runs within the same transaction. Provides both old and new model states for comparison and validation.

type PreUpdateProcessor

type PreUpdateProcessor[TModel, TParams any] func(oldModel, model *TModel, params *TParams, query orm.UpdateQuery, ctx fiber.Ctx, tx orm.DB) error

PreUpdateProcessor handles business logic before model update. Runs within the same transaction. Provides both old and new model states for comparison and validation.

type Processor

type Processor[TIn, TSearch any] func(input TIn, search TSearch, ctx fiber.Ctx) any

Processor transforms query results after execution but before JSON serialization. Commonly used for data formatting, field selection, or computed properties.

type QueryPart

type QueryPart int

QueryPart defines which part(s) of a query an option applies to. This is particularly important for tree APIs that use recursive CTEs, where different parts of the query require different configurations.

const (
	// QueryRoot applies the option to the root/outer query only.
	// This is the default for sorting and limiting operations.
	// For tree APIs, this is the final SELECT from the CTE.
	// For normal APIs, this is the main query.
	QueryRoot QueryPart = iota

	// QueryBase applies the option to the base/main query in recursive CTEs.
	// This is the initial SELECT inside the WITH clause before UNION ALL.
	// Use this for conditions that should only filter the starting nodes.
	QueryBase

	// QueryRecursive applies the option to the recursive query in CTEs.
	// This is the SELECT after UNION ALL that joins with the CTE itself.
	// Use this for configurations needed in the recursive traversal.
	QueryRecursive

	// QueryAll applies the option to all query parts.
	// Use this for configurations that should be consistent across all parts,
	// such as column selections or joins.
	QueryAll
)

type QueryPartsConfig

type QueryPartsConfig struct {
	// Condition specifies which queries apply WHERE clause filtering
	Condition []QueryPart
	// Sort specifies which queries apply ORDER BY sorting
	Sort []QueryPart
	// AuditUserRelation specifies which queries auto-join audit user relations (created_by, updated_by)
	AuditUserRelation []QueryPart
}

QueryPartsConfig controls which query parts are enabled for specific query contexts (e.g., FindAll, FindPage).

type Sortable

type Sortable struct {
	api.M

	Sort []sortx.OrderSpec `json:"sort"`
}

Sortable provides sorting capability for API search parameters.

type TabularFormat

type TabularFormat string

TabularFormat represents the format type for import/export operations.

const (
	FormatExcel TabularFormat = "excel"
	FormatCsv   TabularFormat = "csv"
)

Tabular format types for import/export.

type TreeDataOption

type TreeDataOption struct {
	DataOption

	// Unique identifier for the tree node
	ID string `json:"-" bun:"id"`
	// Parent node identifier (null for root nodes)
	ParentID null.String `json:"-" bun:"parent_id"`
	// Nested child options forming the tree structure
	Children []TreeDataOption `json:"children,omitempty" bun:"-"`
}

TreeDataOption represents a hierarchical selectable item that can contain child options. Used for tree-structured selections like category menus or organizational hierarchies.

type Update

type Update[TModel, TParams any] interface {
	api.OperationsProvider
	Builder[Update[TModel, TParams]]

	// WithPreUpdate registers a processor that is called before the model is updated in the database.
	WithPreUpdate(processor PreUpdateProcessor[TModel, TParams]) Update[TModel, TParams]
	// WithPostUpdate registers a processor that is called after the model is updated within the same transaction.
	WithPostUpdate(processor PostUpdateProcessor[TModel, TParams]) Update[TModel, TParams]
	// DisableDataPerm disables automatic data permission filtering for update queries.
	DisableDataPerm() Update[TModel, TParams]
}

Update provides a fluent interface for building update endpoints. Loads existing model, merges changes, and supports pre/post processing hooks.

func NewUpdate

func NewUpdate[TModel, TParams any](kind ...api.Kind) Update[TModel, TParams]

NewUpdate creates a new Update instance for single record update.

type UpdateMany

type UpdateMany[TModel, TParams any] interface {
	api.OperationsProvider
	Builder[UpdateMany[TModel, TParams]]

	// WithPreUpdateMany registers a processor that is called before the models are updated in the database.
	WithPreUpdateMany(processor PreUpdateManyProcessor[TModel, TParams]) UpdateMany[TModel, TParams]
	// WithPostUpdateMany registers a processor that is called after the models are updated within the same transaction.
	WithPostUpdateMany(processor PostUpdateManyProcessor[TModel, TParams]) UpdateMany[TModel, TParams]
	// DisableDataPerm disables automatic data permission filtering for batch update queries.
	DisableDataPerm() UpdateMany[TModel, TParams]
}

UpdateMany provides a fluent interface for building batch update endpoints. Updates multiple models atomically with validation, merge, and pre/post hooks.

func NewUpdateMany

func NewUpdateMany[TModel, TParams any](kind ...api.Kind) UpdateMany[TModel, TParams]

NewUpdateMany creates a new UpdateMany instance for batch update.

type UpdateManyParams

type UpdateManyParams[TParams any] struct {
	api.P

	List []TParams `json:"list" validate:"required,min=1,dive" label_i18n:"batch_update_list"`
}

UpdateManyParams is a wrapper type for batch update parameters.

Jump to

Keyboard shortcuts

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