database

package
v0.0.0-...-e769803 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package database provides the framework database facade built on top of GORM.

The package exposes a model-scoped Database handle for CRUD operations, query options, caching, dry-run SQL generation, SQL capture, cleanup, health checks, and transactions. Each independent operation must start from Database[M](ctx); reusing a handle after a terminal operation can retain GORM clauses from the previous chain.

Tables used by Database[M](ctx), WithDB, and WithTable are expected to exist before an operation chain runs. Framework startup prepares registered tables through the internal database runtime; callers using custom database instances are responsible for preparing their schemas before using them.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidDB           = errors.New("invalid database, maybe not initialized")
	ErrUnknowDBType        = errors.New("unknow database type, only support mysql or sqlite")
	ErrNotPtrStruct        = errors.New("model is not pointer to structure")
	ErrNotPtrSlice         = errors.New("not pointer to slice")
	ErrNotPtrInt64         = errors.New("not pointer to int64")
	ErrNilCount            = errors.New("count parameter cannot be nil")
	ErrNilDest             = errors.New("dest parameter cannot be nil")
	ErrEmptyFieldName      = errors.New("field name cannot be empty")
	ErrNilValue            = errors.New("value cannot be nil")
	ErrNotAddressableModel = errors.New("model is not addressable")
	ErrNotAddressableSlice = errors.New("slice is not addressable")
	ErrNotSetSlice         = errors.New("slice cannot set")
	ErrIDRequired          = errors.New("id is required")
	ErrRecordNotFound      = gorm.ErrRecordNotFound
	ErrNilSQLBuilder       = errors.New("sql statement collector cannot be nil")
	ErrNilTransactionFunc  = errors.New("transaction function cannot be nil")
	ErrBuildSQLTransaction = errors.New("build sql does not support transaction operations")
)

Functions

func DB

func DB() *gorm.DB

DB returns the framework-managed default GORM database handle.

The returned handle exposes the current runtime connection for advanced integrations, but framework initialization owns the underlying pointer. Callers should use Database[M](ctx) for normal CRUD operations.

func Database

func Database[M types.Model](ctx context.Context) types.Database[M]

Database creates and returns a generic database manipulator implementing types.Database interface. Provides comprehensive CRUD capabilities with advanced features like caching, hooks, and query building. Automatically enables debug mode when log level is set to debug. Required tables must exist before executing operations with the returned manipulator.

Type Parameters:

  • M: Model type that implements types.Model interface

Parameters:

  • ctx: Required context for cancellation, tracing, and request metadata. In service layer operations, pass the ServiceContext directly. For non-service layer operations, pass nil.

Returns a database manipulator with full CRUD and query capabilities.

Features:

  • Generic type safety for model operations
  • Automatic debug mode based on configuration
  • Context-aware operations for tracing
  • Default query limit protection
  • Panic protection for uninitialized database
  • Transaction inheritance when ctx was produced by a model-hook write or WithTx

Transaction propagation:

Database[M](ctx) checks whether ctx carries an internal GORM transaction.
When present, the returned operation chain uses that transaction instead of
the package-level DB. This is how model hooks remain atomic without changing
their public signature: Create/Update/Delete create a transaction, place it in
the hook context, and hook code keeps calling Database[*OtherModel](ctx).

This inheritance is strictly context-scoped. Passing context.Background()
or any unrelated context starts a normal non-transactional operation chain.

Required usage:

You must call Database[M](ctx) again for each separate operation chain. Assigning the return
value to a variable and running another independent operation on it afterward (e.g.
WithQuery(...).List(...) then Get(...) or Update(...) on the same variable) is incorrect:
after each method, reset() clears this wrapper's options but the underlying GORM session
keeps prior clauses, so later calls can combine wrong WHERE conditions, return empty models,
or corrupt data.

Example:

var users []*User
// Service layer: one Database() call per operation chain (required; anything else is wrong).
_ = Database[*User](ctx).WithQuery(&User{Name: "John"}).List(&users)
u := new(User)
_ = Database[*User](ctx).Get(u, id)

// Non-service layer
_ = Database[*User](context.Background()).WithQuery(&User{Name: "John"}).List(&users)

func InstallGormTracingPlugin

func InstallGormTracingPlugin(db *gorm.DB) error

InstallGormTracingPlugin installs the GORM tracing plugin to the given database instance.

Types

type GormTracingPlugin

type GormTracingPlugin struct{}

GormTracingPlugin is a GORM plugin that adds distributed tracing to database operations.

func (*GormTracingPlugin) Initialize

func (p *GormTracingPlugin) Initialize(db *gorm.DB) error

Initialize initializes the plugin.

func (*GormTracingPlugin) Name

func (p *GormTracingPlugin) Name() string

Name returns the plugin name.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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