Documentation
¶
Index ¶
- Constants
- Variables
- func AutoMigrate(models ...interface{}) error
- func Configure(args ...interface{}) error
- func ConfigureWithConfig(cfg Config) error
- func GenerateCacheKey(prefix, tableName string, params QueryParams) string
- func GenerateMigrationSQL(models ...interface{}) ([]string, error)
- func GenerateQueryHash(params QueryParams) string
- func GetCacheVersion() int64
- func NewThingByType(modelType reflect.Type, db DBAdapter, cache CacheClient) (interface{}, error)
- func RegisterIntrospectorFactory(dialect string, factory IntrospectorFactory)
- func RegisterListener(eventType EventType, listener EventListener)
- func ResetListeners()
- func UnregisterListener(eventType EventType, listenerToRemove EventListener)
- func WithLock(ctx context.Context, cache CacheClient, lockKey string, ...) error
- type BaseModel
- type CacheClient
- type CacheKeyLockManagerInternal
- type CacheStats
- type CachedResult
- func (cr *CachedResult[T]) All() ([]T, error)
- func (cr *CachedResult[T]) Count() (int64, error)
- func (cr *CachedResult[T]) Fetch(offset, limit int) ([]T, error)
- func (cr *CachedResult[T]) First() (T, error)
- func (cr *CachedResult[T]) Order(order string) *CachedResult[T]
- func (cr *CachedResult[T]) Preload(preloads ...string) *CachedResult[T]
- func (cr *CachedResult[T]) Where(where string, args ...interface{}) *CachedResult[T]
- func (cr *CachedResult[T]) WithDeleted() *CachedResult[T]
- type ChannelLock
- type Config
- type DBAdapter
- type Dialector
- type EventListener
- type EventType
- type FieldRule
- type IntrospectorFactory
- type JSONOption
- type JSONOptions
- type Model
- type QueryParams
- type RelationshipOpts
- type SQLBuilder
- type Thing
- func (t *Thing[T]) All() ([]T, error)
- func (t *Thing[T]) ByID(id int64) (T, error)
- func (t *Thing[T]) ByIDs(ids []int64, preloads ...string) (map[int64]T, error)
- func (t *Thing[T]) CacheStats(ctx context.Context) CacheStats
- func (t *Thing[T]) ClearCacheByID(ctx context.Context, id int64) error
- func (t *Thing[T]) DB() *sql.DB
- func (t *Thing[T]) Delete(value T) error
- func (t *Thing[T]) Load(model T, relations ...string) error
- func (t *Thing[T]) Order(order string) *CachedResult[T]
- func (t *Thing[T]) Preload(preloads ...string) *CachedResult[T]
- func (t *Thing[T]) Query(params QueryParams) *CachedResult[T]
- func (t *Thing[T]) Save(value T) error
- func (t *Thing[T]) SoftDelete(value T) error
- func (t *Thing[T]) ToJSON(model interface{}, opts ...JSONOption) ([]byte, error)
- func (t *Thing[T]) Where(where string, args ...interface{}) *CachedResult[T]
- func (t *Thing[T]) WithContext(ctx context.Context) *Thing[T]
- type Tx
Constants ¶
const ( LockDuration = 5 * time.Second LockRetryDelay = 50 * time.Millisecond LockMaxRetries = 5 )
Lock duration constants for cache locking
const (
ByIDBatchSize = 100 // Size of batches for fetching by ID from DB
)
--- Constants used internally ---
Variables ¶
var AllowDropColumn = false
AllowDropColumn controls whether AutoMigrate will execute 'DROP COLUMN' statements. Defaults to false (columns will not be dropped).
Functions ¶
func AutoMigrate ¶
func AutoMigrate(models ...interface{}) error
AutoMigrate 生成并执行建表 SQL,支持批量建表和 schema diff
func Configure ¶
func Configure(args ...interface{}) error
Configure sets up the package-level database and cache clients, and the global cache TTL. Usage:
Configure(db) // uses provided DB, default local cache Configure(db, cache) // uses provided DB and cache Configure(db, cache, ttl) // uses all provided
This MUST be called once during application initialization before using Use[T].
func ConfigureWithConfig ¶
ConfigureWithConfig sets up the package-level database and cache clients using a Config struct.
func GenerateCacheKey ¶
func GenerateCacheKey(prefix, tableName string, params QueryParams) string
GenerateCacheKey generates a cache key for list or count queries with normalized arguments. Includes cache version to isolate keys across application restarts.
func GenerateMigrationSQL ¶
GenerateMigrationSQL 生成建表 SQL,但不执行,支持批量模型
func GenerateQueryHash ¶
func GenerateQueryHash(params QueryParams) string
GenerateQueryHash generates a unique hash for a given query.
func GetCacheVersion ¶ added in v0.1.25
func GetCacheVersion() int64
GetCacheVersion returns the current cache version for query cache key generation. This version changes on each application restart, ensuring stale cache keys are ignored.
func NewThingByType ¶
func NewThingByType(modelType reflect.Type, db DBAdapter, cache CacheClient) (interface{}, error)
NewThingByType creates a *Thing for a given model type (reflect.Type)
func RegisterIntrospectorFactory ¶
func RegisterIntrospectorFactory(dialect string, factory IntrospectorFactory)
RegisterIntrospectorFactory registers a factory for a given dialect (e.g. "sqlite", "mysql", "postgres").
func RegisterListener ¶
func RegisterListener(eventType EventType, listener EventListener)
RegisterListener adds a listener function for a specific event type.
func ResetListeners ¶
func ResetListeners()
ResetListeners clears all registered event listeners. Primarily intended for use in tests.
func UnregisterListener ¶
func UnregisterListener(eventType EventType, listenerToRemove EventListener)
UnregisterListener removes a specific listener function for a specific event type. It compares function pointers to find the listener to remove.
Types ¶
type BaseModel ¶
type BaseModel struct {
ID int64 `json:"id" db:"id,pk"` // Primary key (Added pk tag)
CreatedAt time.Time `json:"created_at" db:"created_at"` // Timestamp for creation
UpdatedAt time.Time `json:"updated_at" db:"updated_at"` // Timestamp for last update
Deleted bool `json:"deleted" db:"deleted"` // Soft delete flag
// contains filtered or unexported fields
}
BaseModel provides common fields and functionality for database models. It should be embedded into specific model structs.
func (*BaseModel) IsNewRecord ¶
IsNewRecord returns whether this is a new record.
func (*BaseModel) SetNewRecordFlag ¶
SetNewRecordFlag sets the internal isNewRecord flag.
type CacheClient ¶
type CacheClient interface {
Get(ctx context.Context, key string) (string, error)
Set(ctx context.Context, key string, value string, expiration time.Duration) error
Delete(ctx context.Context, key string) error
GetModel(ctx context.Context, key string, dest interface{}) error
SetModel(ctx context.Context, key string, model interface{}, fieldsToCache []string, expiration time.Duration) error
DeleteModel(ctx context.Context, key string) error
GetQueryIDs(ctx context.Context, queryKey string) ([]int64, error)
SetQueryIDs(ctx context.Context, queryKey string, ids []int64, expiration time.Duration) error
DeleteQueryIDs(ctx context.Context, queryKey string) error
AcquireLock(ctx context.Context, lockKey string, expiration time.Duration) (bool, error)
ReleaseLock(ctx context.Context, lockKey string) error
Incr(ctx context.Context, key string) (int64, error)
Expire(ctx context.Context, key string, expiration time.Duration) error
GetCacheStats(ctx context.Context) CacheStats
}
CacheClient defines the interface for cache drivers.
var DefaultLocalCache CacheClient = &localCache{}
DefaultLocalCache is the default in-memory cache client for Thing ORM.
func Cache ¶ added in v0.1.17
func Cache() CacheClient
Cache returns the underlying CacheClient associated with this Thing instance.
type CacheKeyLockManagerInternal ¶
type CacheKeyLockManagerInternal struct {
// contains filtered or unexported fields
}
CacheKeyLockManagerInternal manages a map of mutexes, one for each cache key. It uses sync.Map for efficient concurrent access.
func NewCacheKeyLockManagerInternal ¶
func NewCacheKeyLockManagerInternal() *CacheKeyLockManagerInternal
NewCacheKeyLockManagerInternal creates a new lock manager.
func (*CacheKeyLockManagerInternal) Lock ¶
func (m *CacheKeyLockManagerInternal) Lock(key string)
Lock acquires the mutex associated with the given cache key. If the mutex does not exist, it is created. This operation blocks until the lock is acquired.
func (*CacheKeyLockManagerInternal) Unlock ¶
func (m *CacheKeyLockManagerInternal) Unlock(key string)
Unlock releases the mutex associated with the given cache key.
type CacheStats ¶
CacheStats holds cache operation counters for monitoring.
type CachedResult ¶
type CachedResult[T Model] struct { Err error // New: holds error if Query failed to initialize // contains filtered or unexported fields }
CachedResult represents a cached query result with lazy loading capabilities. It allows for efficient querying with pagination and caching.
func (*CachedResult[T]) All ¶
func (cr *CachedResult[T]) All() ([]T, error)
All retrieves all records matching the query. It first gets the total count and then fetches all records using Fetch.
func (*CachedResult[T]) Count ¶
func (cr *CachedResult[T]) Count() (int64, error)
Count returns the total number of records matching the query. It utilizes caching to avoid redundant database calls.
func (*CachedResult[T]) Fetch ¶
func (cr *CachedResult[T]) Fetch(offset, limit int) ([]T, error)
Fetch returns a subset of records starting from the given offset with the specified limit. It filters out soft-deleted items and triggers cache updates if inconsistencies are found. This implementation closely follows the CachedResult.fetch() logic: - It iteratively fetches batches from cache or DB - It filters items using KeepItem() - It dynamically calculates how many more items to fetch based on filtering results
func (*CachedResult[T]) First ¶
func (cr *CachedResult[T]) First() (T, error)
func (*CachedResult[T]) Order ¶ added in v0.1.2
func (cr *CachedResult[T]) Order(order string) *CachedResult[T]
Order on CachedResult: returns a new instance with updated Order
func (*CachedResult[T]) Preload ¶ added in v0.1.2
func (cr *CachedResult[T]) Preload(preloads ...string) *CachedResult[T]
Preload on CachedResult: returns a new instance with updated Preloads
func (*CachedResult[T]) Where ¶ added in v0.1.2
func (cr *CachedResult[T]) Where(where string, args ...interface{}) *CachedResult[T]
Where on CachedResult: returns a new instance with updated Where/Args
func (*CachedResult[T]) WithDeleted ¶
func (cr *CachedResult[T]) WithDeleted() *CachedResult[T]
WithDeleted returns a new CachedResult instance that will include soft-deleted records in its results.
type ChannelLock ¶ added in v0.1.19
type ChannelLock struct {
// contains filtered or unexported fields
}
ChannelLock implements a mutex using channel semantics
func NewChannelLock ¶ added in v0.1.19
func NewChannelLock() *ChannelLock
NewChannelLock creates a new channel-based lock
type Config ¶
type Config struct {
DB DBAdapter // User must initialize and provide
Cache CacheClient // User must initialize and provide
TTL time.Duration
}
Config holds configuration for the Thing ORM.
type DBAdapter ¶
type DBAdapter interface {
Get(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
GetCount(ctx context.Context, tableName string, where string, args []interface{}) (int64, error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (Tx, error)
Close() error
DB() *sql.DB
Builder() SQLBuilder
DialectName() string
}
DBAdapter defines the interface for database drivers.
type Dialector ¶
type Dialector interface {
Quote(identifier string) string // Quote a SQL identifier (table/column name)
Placeholder(index int) string // Bind variable placeholder (e.g. ?, $1)
}
Dialector defines how to quote identifiers and bind variables for a specific SQL dialect.
type EventListener ¶
type EventListener func(ctx context.Context, eventType EventType, model interface{}, eventData interface{}) error
EventListener defines the signature for functions that can listen to events.
type EventType ¶
type EventType string
EventType defines the type for lifecycle events.
const ( EventTypeBeforeSave EventType = "BeforeSave" EventTypeAfterSave EventType = "AfterSave" EventTypeBeforeCreate EventType = "BeforeCreate" EventTypeAfterCreate EventType = "AfterCreate" EventTypeBeforeDelete EventType = "BeforeDelete" EventTypeAfterDelete EventType = "AfterDelete" EventTypeBeforeSoftDelete EventType = "BeforeSoftDelete" EventTypeAfterSoftDelete EventType = "AfterSoftDelete" )
Standard lifecycle event types
type FieldRule ¶
type FieldRule struct {
Name string
Nested *JSONOptions // Nested options for this specific field
}
FieldRule represents a single included field and its potential nested options.
type IntrospectorFactory ¶
type IntrospectorFactory func(DBAdapter) schema.Introspector
IntrospectorFactory is a function that returns a schema.Introspector for a given DBAdapter.
type JSONOption ¶
type JSONOption func(*JSONOptions)
JSONOption defines the function signature for JSON serialization options.
func Exclude ¶
func Exclude(fields ...string) JSONOption
Exclude specifies fields to exclude from the JSON output (now supports nested DSL via WithFields logic).
func Include ¶
func Include(fields ...string) JSONOption
Include specifies fields to include in the JSON output (now supports nested DSL via WithFields logic).
func WithFields ¶
func WithFields(dsl string) JSONOption
WithFields specifies fields to include/exclude using a DSL string (supports nested, exclude, etc.).
type JSONOptions ¶
type JSONOptions struct {
OrderedInclude []*FieldRule // Ordered list of fields to include (with possible nested rules)
OrderedExclude []string // Ordered list of fields to exclude
NestedRules map[string]*JSONOptions // Stores nested rules for any field, regardless of include/exclude status
}
JSONOptions holds the options for JSON serialization.
func ParseFieldsDSL ¶
func ParseFieldsDSL(dsl string) (*JSONOptions, error)
ParseFieldsDSL parses a DSL string and returns populated jsonOptions representing the rules.
type QueryParams ¶
type QueryParams struct {
Where string
Args []interface{}
Order string
Preloads []string
IncludeDeleted bool
}
QueryParams is the public query parameter type for Thing ORM queries.
type RelationshipOpts ¶
type RelationshipOpts struct {
RelationType string // "belongsTo", "hasMany", "manyToMany"
ForeignKey string // FK field name in the *owning* struct (for belongsTo) or *related* struct (for hasMany)
LocalKey string // PK field name in the *owning* struct (defaults to info.pkName)
RelatedModel string // Optional: Specify related model name if different from field type
JoinTable string // For manyToMany: join table name
JoinLocalKey string // For manyToMany: join table column for local model
JoinRelatedKey string // For manyToMany: join table column for related model
}
RelationshipOpts defines the configuration for a relationship based on struct tags.
type SQLBuilder ¶
type SQLBuilder interface {
BuildSelectSQL(tableName string, columns []string) string
BuildSelectIDsSQL(tableName string, pkName string, where string, args []interface{}, order string) (string, []interface{})
BuildInsertSQL(tableName string, columns []string) string
BuildUpdateSQL(tableName string, setClauses []string, pkName string) string
BuildDeleteSQL(tableName, pkName string) string
BuildCountSQL(tableName string, whereClause string) string
Rebind(query string) string
}
SQLBuilder defines the contract for SQL generation with dialect-specific identifier quoting.
type Thing ¶
type Thing[T Model] struct { // contains filtered or unexported fields }
Thing is the central access point for ORM operations, analogous to gorm.DB. It holds database/cache clients and the context for operations.
func New ¶
func New[T Model](db DBAdapter, cache CacheClient) (*Thing[T], error)
New creates a new Thing instance with default context.Background(). Accepts one or more CacheClient; if none provided, uses defaultLocalCache.
func Use ¶
Use returns a Thing instance for the specified type T, using the globally configured DBAdapter and CacheClient. The package MUST be configured using Configure() before calling Use[T].
func (*Thing[T]) All ¶ added in v0.1.3
All is a convenience method to query and fetch all records matching the default QueryParams. It's equivalent to calling thingInstance.Query(QueryParams{}).All().
func (*Thing[T]) ByIDs ¶
ByIDs retrieves multiple records by their primary keys and optionally preloads relations.
func (*Thing[T]) CacheStats ¶
func (t *Thing[T]) CacheStats(ctx context.Context) CacheStats
CacheStats returns cache operation statistics for monitoring and hit/miss analysis.
func (*Thing[T]) ClearCacheByID ¶
ClearCacheByID removes the cache entry for a specific model instance by its ID. Note: This is now a Thing[T] method.
func (*Thing[T]) Order ¶ added in v0.1.2
func (t *Thing[T]) Order(order string) *CachedResult[T]
Order on Thing: starts a new query chain
func (*Thing[T]) Preload ¶ added in v0.1.2
func (t *Thing[T]) Preload(preloads ...string) *CachedResult[T]
Preload on Thing: starts a new query chain
func (*Thing[T]) Query ¶
func (t *Thing[T]) Query(params QueryParams) *CachedResult[T]
Query prepares a query based on QueryParams and returns a *CachedResult[T] for lazy execution. The actual database query happens when Count() or Fetch() is called on the result. Error handling for query execution is done within CachedResult methods.
func (*Thing[T]) SoftDelete ¶
SoftDelete performs a soft delete on the record by setting the 'deleted' flag to true and updating the 'updated_at' timestamp. It uses saveInternal to persist only these changes.
func (*Thing[T]) ToJSON ¶
func (t *Thing[T]) ToJSON(model interface{}, opts ...JSONOption) ([]byte, error)
ToJSON serializes the provided model instance (single or collection) to JSON based on the given options.
func (*Thing[T]) Where ¶ added in v0.1.2
func (t *Thing[T]) Where(where string, args ...interface{}) *CachedResult[T]
Where on Thing: starts a new query chain
type Tx ¶
type Tx interface {
Get(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
Commit() error
Rollback() error
}
Tx defines the interface for transaction operations.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
drivers
|
|
|
examples
|
|
|
01_basic_crud
command
Standalone example: Basic CRUD operations with Thing ORM Note: Only one main.go can be run at a time in the examples directory.
|
Standalone example: Basic CRUD operations with Thing ORM Note: Only one main.go can be run at a time in the examples directory. |
|
04_hooks
command
|
|
|
05_relationships
command
|
|
|
internal
|
|