Skip to content

API Reference

Complete API reference for the Dynorm package.

Package dynorm

import "github.com/go-gamma/dynorm"

Configuration

SetClient

func SetClient(client *dynamodb.Client)

Sets a custom DynamoDB client. Useful for testing or custom configuration.

SetContext

func SetContext(ctx context.Context)

Sets the global context for all operations.

SetTablePrefix

func SetTablePrefix(prefix string)

Sets the prefix added to all table names.

GetTablePrefix

func GetTablePrefix() string

Returns the current table prefix.

Reset

func Reset()

Resets all global state. For testing only.


Entity

Base type for all entities.

type Entity struct {
    ID        string
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

Methods

Method Return Description
IsNew() bool True if not yet saved
IsDeleted() bool True if soft deleted
GetID() string Entity ID
GetCreatedAt() time.Time Creation timestamp
GetUpdatedAt() time.Time Last update timestamp
SoftDelete() - Mark as deleted
Restore() - Remove delete marker
IsDirty(field) bool True if field changed
HasChanges() bool True if any field changed
DirtyFields() []string List of changed fields
Changes() map[string]any Map of changes
OriginalValue(field) (any, bool) Original value

Repository[T]

Generic repository for entity operations.

CRUD Methods

Method Signature Description
Find (id string) (*T, error) Find by ID
Save (entity *T) error Create or update
Delete (entity *T) error Delete entity
DeleteByID (id string) error Delete by ID
All () (*Collection[T], error) Get all entities
Count () (int64, error) Count all entities

Query Methods

Method Signature Description
Where (field, op string, value any) *Query[T] Start query
Select (fields ...string) *Query[T] Select fields
OrderBy (field, direction string) *Query[T] Order results
Limit (n int) *Query[T] Limit results
With (relations ...string) *Query[T] Eager load

Batch Methods

Method Signature Description
BatchGet (ids []string) ([]*T, error) Get multiple
BatchSave (entities []*T) error Save multiple
BatchDelete (ids []string) error Delete multiple
BatchDeleteEntities (entities []*T) error Delete entities

Soft Delete Methods

Method Signature Description
SoftDelete (entity *T) error Soft delete
Restore (entity *T) error Restore

Transaction Methods

Method Signature Description
Transaction () *RepositoryTransaction[T] Start transaction

Query[T]

Fluent query builder.

Filter Methods

Method Signature Description
Where (field, op string, value any) *Query[T] Add condition
WhereBeginsWith (field, prefix string) *Query[T] Prefix match
WhereBetween (field string, low, high any) *Query[T] Range
WhereIn (field string, values ...any) *Query[T] In list
WhereContains (field string, value any) *Query[T] Contains

Control Methods

Method Signature Description
Select (fields ...string) *Query[T] Projection
OrderBy (field, direction string) *Query[T] Ordering
Limit (n int) *Query[T] Limit
UseIndex (indexName string) *Query[T] Force index
With (relations ...string) *Query[T] Eager load

Execution Methods

Method Signature Description
GetAll () (*Collection[T], error) Get all
GetFirst () (*T, error) Get first
Count () (int64, error) Count
DeleteAll () error Delete all
Update (updates *UpdateBuilder) (int, error) Update all
Paginate (size int, cursor Cursor) (*Page[T], error) Paginate
Iterate (size int) *Iterator[T] Iterate

Collection[T]

Wrapper for entity slices with utility methods.

Access

Method Return Description
Items() []*T Underlying slice
Count() int Number of items
IsEmpty() bool True if empty
First() *T First item
Last() *T Last item
Get(i) *T Item at index

Filtering

Method Return Description
Filter(fn) *Collection[T] Keep matching
Reject(fn) *Collection[T] Exclude matching
Where(field, value) *Collection[T] Filter by field
Find(fn) *T First matching
Any(fn) bool Any match
All(fn) bool All match

Sorting

Method Return Description
Sort(less) *Collection[T] Custom sort
SortBy(field) *Collection[T] Sort ascending
SortByDesc(field) *Collection[T] Sort descending
Reverse() *Collection[T] Reverse order

Aggregation

Method Return Description
Pluck(field) []any Extract values
PluckStrings(field) []string Extract strings
IDs() []string All IDs
GroupBy(field) map[any]*Collection[T] Group
Unique(field) *Collection[T] Remove duplicates

Bulk Operations

Method Return Description
SaveAll() error Save all
DeleteAll() error Delete all
UpdateAll(map) error Update fields
SaveDirty() error Save changed

UpdateBuilder

Fluent update builder.

Set Operations

Method Description
Set(field, value) Set field
SetIfNotExists(field, value) Set if not exists
Remove(fields...) Remove fields

Numeric Operations

Method Description
Increment(field, n) Add to number
Decrement(field, n) Subtract from number
Add(field, value) Add to number/set

List Operations

Method Description
Append(field, values...) Append to list
Prepend(field, values...) Prepend to list
Delete(field, values...) Remove from set

Conditions

Method Description
Where(field, op, value) Add condition
WhereExists(field) Field exists
WhereNotExists(field) Field not exists
WithOptimisticLock(version) Version check
IncrementVersion() Increment version

Relationship Types

HasOne[R]

type HasOne[R RepositoryInterface] struct
Method Return Description
Get() (any, error) Get related
WithTrashed() *HasOne[R] Include deleted

HasMany[R]

type HasMany[R RepositoryInterface] struct
Method Return Description
Get() (any, error) Get all related
Count() (int, error) Count
Add(entity) error Add relation
Remove(entity) error Remove relation
WithTrashed() *HasMany[R] Include deleted

BelongsTo[R]

type BelongsTo[R RepositoryInterface] struct
Method Return Description
Get() (any, error) Get related

BelongsToMany[R]

type BelongsToMany[R RepositoryInterface] struct
Method Return Description
Get() (any, error) Get all related
Count() (int, error) Count
Attach(entity) error Add relation
Detach(entity) error Remove relation
Sync(entities) error Replace all
Toggle(entity) error Toggle relation

Constants

const (
    MaxBatchGetItems   = 100  // Max items per BatchGetItem
    MaxBatchWriteItems = 25   // Max items per BatchWriteItem
    MaxRetries         = 3    // Max retries for unprocessed items
    MaxTransactionItems = 100 // Max items per transaction
    EnvTablePrefix     = "DYNORM_TABLE_PREFIX"
)

Errors

var (
    ErrNoRepository      = errors.New("collection has no repository reference")
    ErrRepositoryNotFound = errors.New("repository not found")
    ErrPivotNotInitialized = errors.New("pivot repository not initialized")
    ErrParentNotSaved    = errors.New("parent entity must be saved first")
    ErrEntityNil         = errors.New("entity is nil")
    ErrEntityNotSaved    = errors.New("entity must be saved first")
    ErrForeignKeyNotSet  = errors.New("foreign key could not be set")
    ErrMethodNotFound    = errors.New("method not found on repository")
)