datastore

package
v0.15.0 Latest Latest
Warning

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

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

Documentation

Overview

Package datastore provides database abstraction and generic CRUD operations for different database backends including PostgreSQL and SQLite.

Index

Constants

View Source
const (
	DefaultPostgresTimeout = 30 * time.Second
	DefaultSQLiteTimeout   = 5 * time.Second
)

Default per-query timeouts applied when WithTimeout is not given.

Variables

This section is empty.

Functions

func BeginTenantTx added in v0.9.0

func BeginTenantTx(ctx context.Context, db *bun.DB, tenantID string) (bun.Tx, error)

BeginTenantTx begins a transaction on db and scopes it to tenantID with SELECT set_config('app.tenant_id', tenantID, true), so PostgreSQL row-level security policies apply to every statement on the returned transaction. The setting is transaction-local and dies with the transaction. If scoping fails the transaction is rolled back and the error returned, so a caller never receives an unscoped transaction.

func Cleanup

func Cleanup()

Cleanup cleans up the datastore singleton Call this when shutting down the application

func ColumnName added in v0.6.0

func ColumnName(tType reflect.Type, goName string) (string, error)

ColumnName resolves a Go struct field name to its SQL column name using Bun's schema.

func FieldIsUnique added in v0.13.0

func FieldIsUnique(tType reflect.Type, fieldName string) bool

FieldIsUnique reports whether a model's field is declared unique in its bun tag.

func FieldName added in v0.6.0

func FieldName(tType reflect.Type, colName string) (string, error)

FieldName resolves a SQL column name back to its Go struct field name using Bun's schema.

func Initialize

func Initialize(store Store) error

Initialize sets the global datastore singleton This must be called during application startup before any handlers are used It is safe to call from multiple goroutines, but only the first call will take effect

func PrimaryKeyField added in v0.12.0

func PrimaryKeyField(tType reflect.Type) string

PrimaryKeyField returns the Go field name of a model's single primary key, or "" when the model does not have exactly one.

func ResolveKeyByField added in v0.13.0

func ResolveKeyByField(ctx context.Context, meta *metadata.TypeMetadata, field, value, tenantID string) (string, error)

ResolveKeyByField returns the primary key, as a string, of the one row of meta's type whose field equals value. On a tenant route the row must belong to tenantID, and on an RLS route the lookup runs in a transaction scoped to it. ErrNotFound when no row, or more than one, matches.

func ResolveRelationPath added in v0.12.0

func ResolveRelationPath(tType reflect.Type, relations []string) ([]metadata.RelationStep, reflect.Type, error)

ResolveRelationPath resolves a path of belongs-to relation names starting at tType, such as ["Task", "Project"], into relation steps. It returns the model type at the end of the path. Every step must be a belongs-to relation with a single join column.

func ResolveSingleRouteKey added in v0.13.0

func ResolveSingleRouteKey(ctx context.Context, meta *metadata.TypeMetadata, parentID string) (string, error)

ResolveSingleRouteKey returns the key of a nested single route's row: the value of the parent's ParentFKField on the parent row whose key is parentID, as a string. ErrNotFound when the parent row does not exist or does not point at a row. Access to the parent is not checked here; requests that use the key still scope every level of the parent chain.

func RunAfterCommit added in v0.9.0

func RunAfterCommit(ctx context.Context)

RunAfterCommit runs, in order, every after-commit hook queued on ctx and clears the queue. It is a no-op when ctx carries no queue.

func TableName added in v0.6.0

func TableName(tType reflect.Type) string

TableName returns the SQL table name for a model type using Bun's schema.

func WithAfterCommitQueue added in v0.9.0

func WithAfterCommitQueue(ctx context.Context) context.Context

WithAfterCommitQueue returns a context carrying a queue for after-commit hooks. Whoever places a transaction in context under metadata.RLSTxKey owns that transaction and must also call this, then call RunAfterCommit once the transaction has committed. Hooks queued on a transaction that rolls back are simply never run.

Types

type Option added in v0.10.0

type Option func(*storeConfig)

Option configures a Store constructor.

func WithTimeout added in v0.10.0

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-query timeout the datastore applies to every operation on the store. Values of zero or less are ignored and the store's default applies: DefaultPostgresTimeout for PostgreSQL, DefaultSQLiteTimeout for SQLite.

type PostgreSQL

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

PostgreSQL implements Store for PostgreSQL databases

func NewPostgres

func NewPostgres(dsn string, opts ...Option) (*PostgreSQL, error)

NewPostgres creates a new PostgreSQL datastore. The datastore owns the connection and Cleanup() will close it. Pass WithTimeout to override the default per-query timeout.

func NewPostgresWithDB added in v0.5.2

func NewPostgresWithDB(sqlDB *sql.DB, opts ...Option) *PostgreSQL

NewPostgresWithDB creates a PostgreSQL datastore from an existing *sql.DB. Use this when you need to manage the database connection externally, such as with Vault rotating credentials or custom connection pooling. Pass WithTimeout to override the default per-query timeout.

IMPORTANT: The caller retains ownership of the *sql.DB connection. Cleanup() is a no-op for a datastore created this way; it closes neither the bun.DB wrapper nor the underlying *sql.DB. Close the *sql.DB yourself when done.

func (*PostgreSQL) Cleanup

func (p *PostgreSQL) Cleanup()

func (*PostgreSQL) GetDB

func (p *PostgreSQL) GetDB() *bun.DB

func (*PostgreSQL) GetTimeout

func (p *PostgreSQL) GetTimeout() time.Duration

func (*PostgreSQL) IlikeOp added in v0.6.1

func (p *PostgreSQL) IlikeOp() string

type Relation added in v0.6.0

type Relation struct {
	ForeignKeyCol string // FK column name (e.g., "author_id")
	ParentJoinCol string // Parent join column name (e.g., "id")
	FieldName     string // Struct field name for the relation (e.g., "Author")
}

Relation holds the result of finding a parent-child relationship via Bun schema.

func FindRelation added in v0.6.0

func FindRelation(childType, parentType reflect.Type) (Relation, error)

FindRelation uses Bun's schema to find the relationship between child and parent types. Checks for: 1. Child has belongs-to Parent (e.g., Article belongs-to User) — FK is on child 2. Parent has has-many/has-one Child — extract join columns from parent's relation 3. Parent has belongs-to Child (inverted) — FK is on parent

type SQLite

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

SQLite implements Store for SQLite databases

func NewSQLite

func NewSQLite(dsn string, opts ...Option) (*SQLite, error)

NewSQLite creates a new SQLite datastore. Use ":memory:" for in-memory database, or provide a file path. The datastore owns the connection and Cleanup() will close it. Pass WithTimeout to override the default per-query timeout.

func NewSQLiteWithDB added in v0.5.2

func NewSQLiteWithDB(sqlDB *sql.DB, opts ...Option) *SQLite

NewSQLiteWithDB creates a SQLite datastore from an existing *sql.DB. Use this when you need to manage the database connection externally, such as with Vault rotating credentials or custom connection pooling. Pass WithTimeout to override the default per-query timeout.

IMPORTANT: The caller retains ownership of the *sql.DB connection. Cleanup() is a no-op for a datastore created this way; it closes neither the bun.DB wrapper nor the underlying *sql.DB. Close the *sql.DB yourself when done.

func (*SQLite) Cleanup

func (s *SQLite) Cleanup()

func (*SQLite) GetDB

func (s *SQLite) GetDB() *bun.DB

func (*SQLite) GetTimeout

func (s *SQLite) GetTimeout() time.Duration

func (*SQLite) IlikeOp added in v0.6.1

func (s *SQLite) IlikeOp() string

type Store

type Store interface {
	GetDB() *bun.DB
	GetTimeout() time.Duration
	IlikeOp() string
	Cleanup()
}

Store defines the contract for any data store implementation

func Get

func Get() (Store, error)

Get returns the singleton datastore instance Returns an error if Initialize() hasn't been called

type Wrapper

type Wrapper[T any] struct {
	Store Store
}

Wrapper is a generic struct that wraps a Store interface to provide CRUD operations

func (*Wrapper[T]) BatchCreate

func (w *Wrapper[T]) BatchCreate(ctx context.Context, items []T) ([]*T, error)

BatchCreate creates multiple items in a single transaction. All-or-nothing: if any item fails, the entire batch is rolled back. Parent is validated once (all items share the same URL-derived parent). FK, ownership, tenant, and validation are applied per-item.

func (*Wrapper[T]) BatchDelete

func (w *Wrapper[T]) BatchDelete(ctx context.Context, items []T) error

BatchDelete deletes multiple items in a single transaction. All-or-nothing: if any item fails, the entire batch is rolled back. Items must have at least an ID field set.

func (*Wrapper[T]) BatchPatch added in v0.6.0

func (w *Wrapper[T]) BatchPatch(ctx context.Context, items []T) ([]*T, error)

BatchPatch partially updates multiple items in a single transaction. Identical to BatchUpdate but passes OpPatch to validators and auditors.

func (*Wrapper[T]) BatchUpdate

func (w *Wrapper[T]) BatchUpdate(ctx context.Context, items []T) ([]*T, error)

BatchUpdate updates multiple items in a single transaction. All-or-nothing: if any item fails, the entire batch is rolled back. Ownership validation is applied per-item via Get before the transaction starts.

func (*Wrapper[T]) ComputeIncludeCounts added in v0.6.0

func (w *Wrapper[T]) ComputeIncludeCounts(ctx context.Context, items []*T, includeCounts []string) (map[string]map[string]int, error)

ComputeIncludeCounts computes per-item child relation counts for the given items. Returns a map of relation name → {pk_string → count}. Items with zero counts are omitted. Auth is checked via AllowedIncludes from context.

func (*Wrapper[T]) Create

func (w *Wrapper[T]) Create(ctx context.Context, item T) (*T, error)

Create inserts a new item of type T into the datastore

func (*Wrapper[T]) Delete

func (w *Wrapper[T]) Delete(ctx context.Context, id string) error

Delete removes an item of type T from the datastore by ID The id parameter is a string to support both integer and UUID primary keys

func (*Wrapper[T]) Get

func (w *Wrapper[T]) Get(ctx context.Context, id string) (*T, error)

Get retrieves a single item of type T by ID from the datastore Filters from context (parent IDs) are applied automatically Relations can be loaded via ?include= query parameter (parsed into QueryOptions.Include) The id parameter is a string to support both integer and UUID primary keys

func (*Wrapper[T]) GetAll

func (w *Wrapper[T]) GetAll(ctx context.Context) ([]*T, int, map[string]float64, *metadata.CursorInfo, error)

GetAll retrieves all items of type T from the datastore Filters from context are applied automatically Relations can be loaded via ?include= query parameter (parsed into QueryOptions.Include) Returns items, total count (0 if not requested), sums (nil if not requested), cursor info (nil if not cursor mode), and error

func (*Wrapper[T]) GetByParentRelation

func (w *Wrapper[T]) GetByParentRelation(ctx context.Context, parentID string) (*T, error)

GetByParentRelation retrieves a single item of type T via the parent's foreign key field Fetches the parent, extracts the FK value, then calls normal Get (preserving security checks)

func (*Wrapper[T]) GetMany added in v0.10.0

func (w *Wrapper[T]) GetMany(ctx context.Context, ids []string) ([]*T, error)

GetMany fetches the rows for ids in a single query, applying the same parent, ownership, tenant, and include handling as Get. Results are in the order of ids. Any ID that is missing or not visible to the caller yields ErrNotFound.

func (*Wrapper[T]) Patch added in v0.6.0

func (w *Wrapper[T]) Patch(ctx context.Context, id string, item T) (*T, error)

Patch partially updates an existing item of type T in the datastore. Identical to Update but passes OpPatch to validators and auditors so they can distinguish partial updates from full replacements.

func (*Wrapper[T]) PatchByParentRelation added in v0.6.0

func (w *Wrapper[T]) PatchByParentRelation(ctx context.Context, parentID string, item T) (*T, error)

PatchByParentRelation patches a single item of type T via the parent's foreign key field. Fetches the parent, extracts the FK value, sets it on the item struct (so WherePK targets the correct row), then calls normal Patch (preserving security checks and OpPatch propagation).

func (*Wrapper[T]) Update

func (w *Wrapper[T]) Update(ctx context.Context, id string, item T) (*T, error)

Update updates an existing item of type T in the datastore The id parameter is a string to support both integer and UUID primary keys

func (*Wrapper[T]) UpdateByParentRelation

func (w *Wrapper[T]) UpdateByParentRelation(ctx context.Context, parentID string, item T) (*T, error)

UpdateByParentRelation updates a single item of type T via the parent's foreign key field Fetches the parent, extracts the FK value, sets it on the item struct (so WherePK targets the correct row), then calls normal Update (preserving security checks).

Jump to

Keyboard shortcuts

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