Documentation
¶
Overview ¶
lambda.go
multiaccount.go
Package theorydb provides a type-safe ORM for Amazon DynamoDB in Go
Index ¶
- Variables
- func AtVersion(version int64) core.TransactCondition
- func Condition(field, operator string, value any) core.TransactCondition
- func ConditionExpression(expression string, values map[string]any) core.TransactCondition
- func ConditionVersion(version int64) core.TransactCondition
- func DefaultBatchGetOptions() *core.BatchGetOptions
- func EnableXRayTracing() bool
- func GetLambdaMemoryMB() int
- func GetPartnerFromContext(ctx context.Context) string
- func GetRemainingTimeMillis(ctx context.Context) int64
- func IfExists() core.TransactCondition
- func IfNotExists() core.TransactCondition
- func IsLambdaEnvironment() bool
- func New(config session.Config) (core.ExtendedDB, error)
- func NewBasic(config session.Config) (core.DB, error)
- func NewKeyPair(partitionKey any, sortKey ...any) core.KeyPair
- func NewWithClient(config session.Config, client session.DynamoDBAPI) (core.ExtendedDB, error)
- func PartnerContext(ctx context.Context, partnerID string) context.Context
- func UnmarshalItem(item map[string]types.AttributeValue, dest interface{}) error
- func UnmarshalItems(items []map[string]types.AttributeValue, dest interface{}) error
- func UnmarshalStreamImage(streamImage map[string]events.DynamoDBAttributeValue, dest interface{}) error
- type AccountConfig
- type AutoMigrateOption
- type BatchGetOptions
- type ColdStartMetrics
- type Config
- type DB
- func (db *DB) AutoMigrate(models ...any) error
- func (db *DB) AutoMigrateWithOptions(model any, opts ...schema.AutoMigrateOption) error
- func (db *DB) AutoMigrateWithTypedOptions(model any, opts ...schema.AutoMigrateOption) error
- func (db *DB) Close() error
- func (db *DB) CreateTable(model any, opts ...schema.TableOption) error
- func (db *DB) CreateTableWithOptions(model any, opts ...schema.TableOption) error
- func (db *DB) DeleteTable(model any) error
- func (db *DB) DescribeTable(model any) (any, error)
- func (db *DB) EnsureTable(model any) error
- func (db *DB) Migrate() error
- func (db *DB) Model(model any) core.Query
- func (db *DB) RegisterTypeConverter(typ reflect.Type, converter pkgTypes.CustomConverter) error
- func (db *DB) Transact() core.TransactionBuilder
- func (db *DB) TransactGet(ctx context.Context, requests []core.TransactGetRequest) ([]core.TransactGetResult, error)
- func (db *DB) TransactWrite(ctx context.Context, fn func(core.TransactionBuilder) error) error
- func (db *DB) WithContext(ctx context.Context) core.DB
- func (db *DB) WithLambdaTimeout(ctx context.Context) core.DB
- func (db *DB) WithLambdaTimeoutBuffer(buffer time.Duration) core.DB
- type KeyPair
- type LambdaDB
- func (ldb *LambdaDB) GetMemoryStats() LambdaMemoryStats
- func (ldb *LambdaDB) IsModelRegistered(model any) bool
- func (ldb *LambdaDB) OptimizeForColdStart()
- func (ldb *LambdaDB) OptimizeForMemory()
- func (ldb *LambdaDB) PreRegisterModels(models ...any) error
- func (ldb *LambdaDB) RegisterTypeConverter(typ reflect.Type, converter pkgTypes.CustomConverter) error
- func (ldb *LambdaDB) WithLambdaTimeout(ctx context.Context) *LambdaDB
- func (ldb *LambdaDB) WithLambdaTimeoutConfig(config LambdaTimeoutConfig) *LambdaDB
- type LambdaMemoryStats
- type LambdaTimeoutConfig
- type MultiAccountDB
- func (mdb *MultiAccountDB) AddPartner(partnerID string, config AccountConfig)
- func (mdb *MultiAccountDB) Close() error
- func (mdb *MultiAccountDB) Partner(partnerID string) (*LambdaDB, error)
- func (mdb *MultiAccountDB) RemovePartner(partnerID string)
- func (mdb *MultiAccountDB) WithContext(ctx context.Context) *MultiAccountDB
Constants ¶
This section is empty.
Variables ¶
var ( WithBackupTable = schema.WithBackupTable WithDataCopy = schema.WithDataCopy WithTargetModel = schema.WithTargetModel WithTransform = schema.WithTransform WithBatchSize = schema.WithBatchSize )
Re-export AutoMigrate options for convenience.
Functions ¶
func AtVersion ¶
func AtVersion(version int64) core.TransactCondition
AtVersion enforces an optimistic locking check on the model's version field.
func Condition ¶
func Condition(field, operator string, value any) core.TransactCondition
Condition creates a simple field comparison condition for transactional writes.
func ConditionExpression ¶
func ConditionExpression(expression string, values map[string]any) core.TransactCondition
ConditionExpression registers a raw condition expression for transactional writes.
func ConditionVersion ¶
func ConditionVersion(version int64) core.TransactCondition
ConditionVersion is an alias for AtVersion for API parity with UpdateBuilder helpers.
func DefaultBatchGetOptions ¶
func DefaultBatchGetOptions() *core.BatchGetOptions
DefaultBatchGetOptions returns the library defaults for BatchGet operations.
func EnableXRayTracing ¶
func EnableXRayTracing() bool
EnableXRayTracing enables AWS X-Ray tracing for DynamoDB calls
func GetLambdaMemoryMB ¶
func GetLambdaMemoryMB() int
GetLambdaMemoryMB returns the allocated memory in MB
func GetPartnerFromContext ¶
GetPartnerFromContext retrieves partner ID from context
func GetRemainingTimeMillis ¶
GetRemainingTimeMillis returns milliseconds until Lambda timeout
func IfExists ¶
func IfExists() core.TransactCondition
IfExists guards a write with attribute_exists on the item's primary key.
func IfNotExists ¶
func IfNotExists() core.TransactCondition
IfNotExists guards a write with attribute_not_exists on the item's primary key.
func IsLambdaEnvironment ¶
func IsLambdaEnvironment() bool
IsLambdaEnvironment detects if running in AWS Lambda
func New ¶
func New(config session.Config) (core.ExtendedDB, error)
New creates a new TableTheory instance with the given configuration
func NewBasic ¶
NewBasic creates a new TableTheory instance that returns the basic DB interface Use this when you only need core functionality and want easier mocking
func NewKeyPair ¶
NewKeyPair constructs a composite key helper for BatchGet operations.
func NewWithClient ¶
func NewWithClient(config session.Config, client session.DynamoDBAPI) (core.ExtendedDB, error)
NewWithClient creates a TableTheory instance backed by an injected DynamoDB API implementation. This is intended for deterministic consumer tests and local fakes; production callers should continue to use New.
func PartnerContext ¶
PartnerContext adds partner information to context for tracing
func UnmarshalItem ¶
func UnmarshalItem(item map[string]types.AttributeValue, dest interface{}) error
UnmarshalItem unmarshals a DynamoDB AttributeValue map into a Go struct. This is the recommended way to unmarshal DynamoDB stream records or any DynamoDB items when using TableTheory.
The function respects TableTheory struct tags (theorydb:"pk", theorydb:"attr:name", etc.) and handles all DynamoDB attribute types correctly.
Example usage with DynamoDB Streams:
func processDynamoDBStream(record events.DynamoDBEventRecord) (*MyModel, error) {
image := record.Change.NewImage
if image == nil {
return nil, nil
}
var model MyModel
if err := theorydb.UnmarshalItem(image, &model); err != nil {
return nil, fmt.Errorf("failed to unmarshal: %w", err)
}
return &model, nil
}
func UnmarshalItems ¶
func UnmarshalItems(items []map[string]types.AttributeValue, dest interface{}) error
UnmarshalItems unmarshals a slice of DynamoDB AttributeValue maps into a slice of Go structs. This is useful for batch operations or when processing multiple items from a query result.
func UnmarshalStreamImage ¶
func UnmarshalStreamImage(streamImage map[string]events.DynamoDBAttributeValue, dest interface{}) error
UnmarshalStreamImage unmarshals a DynamoDB stream image (from Lambda events) into a Go struct. This function handles the conversion from Lambda's events.DynamoDBAttributeValue to the standard types.AttributeValue and then unmarshals into your TableTheory model.
Example usage:
func handleStream(record events.DynamoDBEventRecord) error {
var order Order
if err := theorydb.UnmarshalStreamImage(record.Change.NewImage, &order); err != nil {
return err
}
// Process order...
}
Types ¶
type AccountConfig ¶
type AccountConfig struct {
RoleARN string
ExternalID string
Region string
// Optional: Custom session duration (default is 1 hour)
SessionDuration time.Duration
}
AccountConfig holds configuration for a partner account
type AutoMigrateOption ¶
type AutoMigrateOption = schema.AutoMigrateOption
Re-export types for convenience.
type ColdStartMetrics ¶
type ColdStartMetrics struct {
Phases map[string]time.Duration
TotalDuration time.Duration
MemoryMB int
IsLambda bool
}
ColdStartMetrics contains cold start performance data
func BenchmarkColdStart ¶
func BenchmarkColdStart(models ...any) ColdStartMetrics
BenchmarkColdStart measures cold start performance
func (ColdStartMetrics) String ¶
func (m ColdStartMetrics) String() string
String returns a formatted string of the metrics
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is the main TableTheory database instance
func (*DB) AutoMigrate ¶
AutoMigrate creates or updates tables based on the given models
func (*DB) AutoMigrateWithOptions ¶
func (db *DB) AutoMigrateWithOptions(model any, opts ...schema.AutoMigrateOption) error
AutoMigrateWithOptions performs enhanced auto-migration with data copy support using concrete schema.AutoMigrateOption values.
func (*DB) AutoMigrateWithTypedOptions ¶
func (db *DB) AutoMigrateWithTypedOptions(model any, opts ...schema.AutoMigrateOption) error
AutoMigrateWithTypedOptions preserves the v1.x typed-option method name.
func (*DB) CreateTable ¶
func (db *DB) CreateTable(model any, opts ...schema.TableOption) error
CreateTable creates a DynamoDB table for the given model using concrete schema.TableOption values.
func (*DB) CreateTableWithOptions ¶
func (db *DB) CreateTableWithOptions(model any, opts ...schema.TableOption) error
CreateTableWithOptions preserves the v1.x typed-option method name.
func (*DB) DeleteTable ¶
DeleteTable deletes the DynamoDB table for the given model
func (*DB) DescribeTable ¶
DescribeTable returns the table description for the given model
func (*DB) EnsureTable ¶
EnsureTable checks if a table exists for the model and creates it if not
func (*DB) RegisterTypeConverter ¶
RegisterTypeConverter registers a custom converter for a specific Go type. This allows callers to control how values are marshaled to and unmarshaled from DynamoDB without forking the internal marshaler. Registering a converter clears any cached marshalers so subsequent operations use the new logic.
func (*DB) Transact ¶
func (db *DB) Transact() core.TransactionBuilder
Transact returns a fluent transaction builder for composing TransactWriteItems requests.
func (*DB) TransactGet ¶
func (db *DB) TransactGet(ctx context.Context, requests []core.TransactGetRequest) ([]core.TransactGetResult, error)
TransactGet executes a DynamoDB TransactGetItems request through the additive core.TransactGetter extension interface.
func (*DB) TransactWrite ¶
TransactWrite executes the supplied function with a transaction builder and automatically commits it.
func (*DB) WithContext ¶
WithContext returns a new DB instance with the given context
func (*DB) WithLambdaTimeout ¶
WithLambdaTimeout sets a deadline based on Lambda context
type LambdaDB ¶
type LambdaDB struct {
core.ExtendedDB
// contains filtered or unexported fields
}
LambdaDB wraps DB with Lambda-specific optimizations
func LambdaInit ¶
LambdaInit should be called in the init() function of your Lambda handler. It performs one-time initialization to reduce cold start latency.
LambdaInit is synchronous and starts no background work: every step it runs completes before it returns, so nothing is left running once the execution environment is frozen. It requires no IAM permissions beyond the ones your handler's DynamoDB operations already need.
func NewLambdaOptimized ¶
NewLambdaOptimized creates a Lambda-optimized DB instance
func (*LambdaDB) GetMemoryStats ¶
func (ldb *LambdaDB) GetMemoryStats() LambdaMemoryStats
GetMemoryStats returns current memory usage statistics
func (*LambdaDB) IsModelRegistered ¶
IsModelRegistered checks if a model is already registered
func (*LambdaDB) OptimizeForColdStart ¶
func (ldb *LambdaDB) OptimizeForColdStart()
OptimizeForColdStart reduces Lambda cold start time using only synchronous, local work.
Lambda freezes the execution environment as soon as the handler returns, so work started in a goroutine during init is not guaranteed to run: it may be frozen mid-flight, and any network call it made is billed to an invocation that has already completed. This method therefore starts no goroutines and makes no network calls. Everything it does finishes before it returns, inside the init or invocation that called it.
It deliberately does not pre-warm the DynamoDB connection with an API call. A connection pre-warm only has value when the call succeeds, which requires IAM permissions beyond item access (the previous implementation issued ListTables) and adds that round trip to every cold start. Model metadata is still pre-compiled locally, which needs no extra IAM and no network.
func (*LambdaDB) OptimizeForMemory ¶
func (ldb *LambdaDB) OptimizeForMemory()
OptimizeForMemory adjusts internal buffers based on available Lambda memory
func (*LambdaDB) PreRegisterModels ¶
PreRegisterModels registers models at init time to reduce cold starts
func (*LambdaDB) RegisterTypeConverter ¶
func (ldb *LambdaDB) RegisterTypeConverter(typ reflect.Type, converter pkgTypes.CustomConverter) error
RegisterTypeConverter registers a custom converter on the underlying DB and clears any cached marshalers so the converter takes effect immediately.
func (*LambdaDB) WithLambdaTimeout ¶
WithLambdaTimeout creates a new DB instance with Lambda timeout handling
func (*LambdaDB) WithLambdaTimeoutConfig ¶
func (ldb *LambdaDB) WithLambdaTimeoutConfig(config LambdaTimeoutConfig) *LambdaDB
WithLambdaTimeoutConfig returns a LambdaDB configured with Lambda invocation timeout settings while preserving Lambda-specific caches and metadata.
type LambdaMemoryStats ¶
type LambdaMemoryStats struct {
Alloc uint64 // Bytes allocated and still in use
TotalAlloc uint64 // Bytes allocated (even if freed)
Sys uint64 // Bytes obtained from system
NumGC uint32 // Number of GC cycles
AllocatedMB float64 // MB currently allocated
SystemMB float64 // MB obtained from system
LambdaMemoryMB int // Total Lambda memory allocation
MemoryPercent float64 // Percentage of Lambda memory used
}
LambdaMemoryStats contains memory usage information
type LambdaTimeoutConfig ¶
LambdaTimeoutConfig configures Lambda invocation timeout handling for LambdaDB.
A positive Buffer leaves that much time before the Lambda deadline for caller cleanup and error reporting. A zero or negative Buffer preserves the LambdaDB default timeout buffer.
type MultiAccountDB ¶
type MultiAccountDB struct {
// contains filtered or unexported fields
}
MultiAccountDB manages DynamoDB connections across multiple AWS accounts
func NewMultiAccount ¶
func NewMultiAccount(accounts map[string]AccountConfig) (*MultiAccountDB, error)
NewMultiAccount creates a multi-account aware DB.
NewMultiAccount starts no background work. Partner sessions are created and refreshed synchronously on the Partner() call path, inside the invocation that needs them, because Lambda freezes the execution environment when the handler returns.
func (*MultiAccountDB) AddPartner ¶
func (mdb *MultiAccountDB) AddPartner(partnerID string, config AccountConfig)
AddPartner dynamically adds a new partner configuration
func (*MultiAccountDB) Close ¶
func (mdb *MultiAccountDB) Close() error
Close releases the base connection. It starts no background work, so there is nothing else to stop.
func (*MultiAccountDB) Partner ¶
func (mdb *MultiAccountDB) Partner(partnerID string) (*LambdaDB, error)
Partner returns a DB instance for the specified partner account
func (*MultiAccountDB) RemovePartner ¶
func (mdb *MultiAccountDB) RemovePartner(partnerID string)
RemovePartner removes a partner and clears its cached connection
func (*MultiAccountDB) WithContext ¶
func (mdb *MultiAccountDB) WithContext(ctx context.Context) *MultiAccountDB
WithContext returns a new MultiAccountDB with the given context