ddb

package module
v2.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

README

GoDoc Go Report Card Coverage Status

ddb

ddb is a high level library for accessing DynamoDB.

✅ You're on the v2 branch - This is the current and recommended version!

Installation: go get github.com/savaki/ddb/v2

What's New in V2

🚀 Performance (20-60% faster)

  • Fast-path marshaling for all Go primitive types (17 types - no reflection!)
  • O(1) attribute name deduplication (was O(n) in v1)
  • Pre-allocated maps reduce allocations by 10-45%
  • Optimized expression assembly
  • Real-world benchmarks: 20-60% faster for typical workloads

🔧 AWS SDK v2

  • Modern AWS SDK with improved performance
  • Context-aware APIs throughout
  • Better error handling and type safety

Quality

  • Fixed race conditions
  • Comprehensive benchmark suite (30+ benchmarks)
  • All tests pass with race detector
  • 100% API compatible with v1 (except SDK types)

Upgrading from v1 to v2

Version 2.0.0 migrates from AWS SDK v1 to AWS SDK v2. This introduces some breaking changes:

Breaking Changes

  1. Module Path: Update your imports from github.com/savaki/ddb to github.com/savaki/ddb/v2

  2. DynamoDB Client: The New() function now accepts the AWS SDK v2 client:

    // v1
    import "github.com/aws/aws-sdk-go/service/dynamodb"
    api := dynamodb.New(session.Must(session.NewSession()))
    db := ddb.New(api)
    
    // v2
    import "github.com/aws/aws-sdk-go-v2/service/dynamodb"
    cfg, _ := config.LoadDefaultConfig(context.TODO())
    api := dynamodb.NewFromConfig(cfg)
    db := ddb.New(api)
    
  3. Billing Mode: WithBillingMode() now accepts a typed constant instead of string:

    // v1
    ddb.WithBillingMode(dynamodb.BillingModePayPerRequest)
    
    // v2
    import "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
    ddb.WithBillingMode(types.BillingModePayPerRequest)
    

What Hasn't Changed

  • All table operations (Get, Put, Query, Scan, Update, Delete) work exactly the same
  • Struct tags (ddb and dynamodbav) remain unchanged
  • Transaction support is unchanged
  • DynamoDB Streams support is unchanged

QuickStart

type Example struct {
  PlayerID string `ddb:"hash"`
  Date     string `ddb:"range"`
}

func example() {
  var (
    ctx       = context.Background()
    s         = session.Must(session.NewSession(aws.NewConfig()))
    api       = dynamodb.New(s)
    tableName = "examples"
    model     = Example{}
    db        = ddb.New(api)
  )  
  
  table := db.MustTable(tableName, model)
  err := table.CreateTableIfNotExists(ctx)
  // handle err ...
  
  record := Example {
    PlayerID: "abc",
    Date:     "2019-01-01",
  }
  err = table.Put(record).RunWithContext(ctx) 
  // handle err ...
  
  var got Example
  err = table.Get(String(record.PlayerID)). // with hash key
    Range(String(record.Date)).             // and range key 
    ScanWithContext(ctx, &got)
  // handle err ...
  
  err = table.DeleteTableIfExists(ctx)
  // handle err ...
}

Models

ddb leverages the github.com/aws/aws-sdk-go-v2 package for encoding and decoding DynamoDB records to and from structs.

  • Use dynamodbav tag option for encoding information
  • Use ddb tag option to provide meta data about table
  • Use ; to separate multiple tag options within a tag e.g. a;b;c
Hash Key

Use the hash tag to define the hash (e.g. partition) key.

type Example struct {
  ID string `ddb:"hash"`
}
Range Key

Use the range tag to define the range (e.g. sort) key.

type Example struct {
  ID   string `ddb:"hash"`
  Date string `ddb:"range"`
}
Local Secondary Indexes (LSI)

To setup local secondary indexes, use the following tags:

  • lsi_range:{index-name} define the range (e.g. sort) key of the LSI
  • lsi_range:{index-name},keys_only - same as above, but indicate LSI should contains KEYS_ONLY
  • lsi:{index-name} include specific attribute within the LSI

In this example, we define a local secondary index with index name, blah, whose range key is Alt that includes Field1.

type Example struct {
  ID     string `ddb:"hash"`
  Date   string `ddb:"range"`
  Alt    string `ddb:"lsi_range:blah"`
  Field1 string `ddb:"lsi:blah"`
  Field2 string
}
Global Secondary Indexes (GSI)

To setup global secondary indexes, use the following tags:

  • gsi_hash:{index-name} define the hash (e.g. partition) key of the GSI
  • gsi_range:{index-name} define the range (e.g. sort) key of the GSI
  • gsi_range:{index-name},keys_only - same as above, but indicate GSI should contains KEYS_ONLY
  • gsi:{index-name} include specific attribute within the GSI

In this example, we define a global secondary index with index name, blah, whose hash key is VerifiedAt and whose range key is ID.

type Example struct {
  ID         string `ddb:"hash;gsi_range:blah"`
  Date       string `ddb:"range"`
  VerifiedAt int64  `ddb:"gsi_hash:blah"`
}
Using dynamodbav to specify attribute values

This example illustrates using the dynamodbav in conjunction with the ddb to define the schema. Here the hash key of the table will be set to id (not ID)

type Example struct {
  ID string `ddb:"hash" dynamodbav:"id"`
}

Testing

The ddbtest package provides utilities for testing with DynamoDB tables. The WithTable helper manages test resource lifecycle with automatic cleanup.

Using WithTable

WithTable takes a setup function and a test callback, ensuring cleanup occurs even if the test fails or panics:

import (
    "context"
    "testing"
    "github.com/savaki/ddb/v2"
    "github.com/savaki/ddb/v2/ddbtest"
)

type User struct {
    ID   string `ddb:"hash"`
    Name string
}

// Define a reusable setup function
func setupUserTable(t *testing.T) (context.Context, *ddb.Table, func()) {
    ctx := context.Background()
    cfg, _ := config.LoadDefaultConfig(ctx)
    api := dynamodb.NewFromConfig(cfg)
    db := ddb.New(api)

    tableName := "users-" + generateRandomID()
    table := db.MustTable(tableName, User{})

    if err := table.CreateTableIfNotExists(ctx); err != nil {
        t.Fatalf("failed to create table: %v", err)
    }

    cleanup := func() {
        table.DeleteTableIfExists(ctx)
    }

    return ctx, table, cleanup
}

func TestUserOperations(t *testing.T) {
    ddbtest.WithTable(t, setupUserTable, func(t *testing.T, ctx context.Context, table *ddb.Table) {
        // Your test logic here
        user := User{ID: "123", Name: "Alice"}

        err := table.Put(user).RunWithContext(ctx)
        if err != nil {
            t.Fatalf("failed to put user: %v", err)
        }

        var got User
        err = table.Get(ddb.String("123")).ScanWithContext(ctx, &got)
        if err != nil {
            t.Fatalf("failed to get user: %v", err)
        }

        if got.Name != "Alice" {
            t.Errorf("expected name 'Alice', got '%s'", got.Name)
        }

        // Table cleanup happens automatically after this function returns
    })
}

The setup function returns:

  • ctx: A context for the test
  • data: Test-specific data (e.g., *ddb.Table, table name, etc.)
  • cleanup: A function to clean up resources (called via defer)

This pattern ensures:

  • Resources are properly cleaned up even if tests fail
  • Setup code is reusable across multiple tests
  • Test isolation through automatic teardown

Documentation

Index

Constants

View Source
const (
	// DefaultBillingMode specifies the default billing mode for DynamoDB tables as provisioned capacity
	DefaultBillingMode = types.BillingModeProvisioned
	// DefaultReadCapacity specifies the default read capacity units for provisioned tables
	DefaultReadCapacity = int64(3)
	// DefaultWriteCapacity specifies the default write capacity units for provisioned tables
	DefaultWriteCapacity = int64(3)
)
View Source
const (
	// ErrInvalidFieldName is returned when an invalid field name is specified in an expression
	ErrInvalidFieldName = "InvalidFieldName"
	// ErrItemNotFound is returned when a requested item does not exist in the table
	ErrItemNotFound = "ItemNotFound"
	// ErrMismatchedValueCount is returned when the number of values doesn't match placeholders in an expression
	ErrMismatchedValueCount = "MismatchedValueCount"
	// ErrUnableToMarshalItem is returned when an item cannot be marshaled to DynamoDB format
	ErrUnableToMarshalItem = "UnableToMarshalItem"
)

DynamoDB Streams event name constants (re-exported from AWS SDK for convenience)

Variables

This section is empty.

Functions

func IsInvalidFieldNameError

func IsInvalidFieldNameError(err error) bool

IsInvalidFieldNameError returns true if any error in the cause chain contains the code ErrInvalidFieldName

func IsItemNotFoundError

func IsItemNotFoundError(err error) bool

IsItemNotFoundError returns true if any error in the cause chain contains the code ErrItemNotFound

func IsMismatchedValueCountError

func IsMismatchedValueCountError(err error) bool

IsMismatchedValueCountError returns true if any error in the cause chain contains the code ErrMismatchedValueCount

func TableName

func TableName(eventSourceARN string) (string, bool)

TableName extracts and returns the table name from a DynamoDB stream event source ARN. Returns the table name and true if successful, or empty string and false if the ARN format is invalid.

Types

type Change

type Change struct {
	// The approximate date and time when the stream record was created, in UNIX
	// epoch time (http://www.epochconverter.com/) format.
	ApproximateCreationDateTime EpochSeconds `json:"ApproximateCreationDateTime,omitempty"`

	// Keys for dynamodb modified dynamodb item
	Keys Image `json:"Keys,omitempty"`

	// NewImage holds dynamodb item AFTER modification
	NewImage Image `json:"NewImage,omitempty"`

	// OldImage holds dynamodb item BEFORE modification
	OldImage Image `json:"OldImage,omitempty"`

	// SequenceNumber of stream record
	SequenceNumber string `json:"SequenceNumber"`

	// SizeBytes contains size of record
	SizeBytes int64 `json:"SizeBytes"`

	// StreamViewType indicates what type of information is being held
	// https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_StreamSpecification.html
	StreamViewType string `json:"StreamViewType"`
}

Change represents a modification to a DynamoDB item, including the keys, old image, and new image of the item.

type ConsumedCapacity

type ConsumedCapacity struct {
	ReadUnits  int64
	WriteUnits int64
	// contains filtered or unexported fields
}

ConsumedCapacity tracks DynamoDB capacity units consumed by operations. It maintains separate counters for read and write capacity units, as well as total capacity units. The struct is safe for concurrent use.

func (*ConsumedCapacity) CapacityUnits

func (c *ConsumedCapacity) CapacityUnits() float64

CapacityUnits returns the total capacity units consumed. This is thread-safe and returns the accumulated capacity units from operations that reported CapacityUnits (as opposed to ReadCapacityUnits or WriteCapacityUnits).

type DDB

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

DDB is the main entry point for DynamoDB operations. It wraps the AWS SDK DynamoDB client and provides a higher-level API with automatic schema inspection, expression parsing, and capacity tracking.

func New

func New(api DynamoDBAPI) *DDB

New creates a new DDB instance with the provided DynamoDB API client. The client can be created using dynamodb.NewFromConfig(cfg) where cfg is obtained from config.LoadDefaultConfig().

func (*DDB) MustTable

func (d *DDB) MustTable(tableName string, model interface{}) *Table

MustTable is like Table but panics if there is an error creating the table. Use this for initialization where the model schema is known to be valid.

func (*DDB) Table

func (d *DDB) Table(tableName string, model interface{}) (*Table, error)

Table creates a Table instance for the specified table name and model. The model parameter should be a struct with DDB tags that define the table's hash key, range key, and indexes. Returns an error if the model cannot be inspected or has invalid schema tags.

func (*DDB) TransactGetItems

func (d *DDB) TransactGetItems(items ...GetTx) error

TransactGetItems allows TransactGetItems to be called without a context

func (*DDB) TransactGetItemsWithContext

func (d *DDB) TransactGetItemsWithContext(ctx context.Context, gets ...GetTx) (err error)

TransactGetItemsWithContext wraps the get operations using a TransactGetItems

func (*DDB) TransactWriteItems

func (d *DDB) TransactWriteItems(items ...WriteTx) (*dynamodb.TransactWriteItemsOutput, error)

TransactWriteItems executes a transactional write operation with multiple items. This is a convenience wrapper around TransactWriteItemsWithContext using the default context. See TransactWriteItemsWithContext for more details.

func (*DDB) TransactWriteItemsWithContext

func (d *DDB) TransactWriteItemsWithContext(ctx context.Context, items ...WriteTx) (*dynamodb.TransactWriteItemsOutput, error)

TransactWriteItemsWithContext applies the provided operations in a dynamodb transaction. Subject to the limits of of TransactWriteItems.

func (*DDB) WithTokenFunc

func (d *DDB) WithTokenFunc(fn func() string) *DDB

WithTokenFunc allows the generator func for dynamodb transactions to be overwritten

func (*DDB) WithTransactAttempts

func (d *DDB) WithTransactAttempts(n int) *DDB

WithTransactAttempts overrides the number of times to attempt a Transact before giving up. Defaults to 4

func (*DDB) WithTransactTimeout

func (d *DDB) WithTransactTimeout(fn func(i int) time.Duration) *DDB

WithTransactTimeout allows the timeout progression to be customized. By default uses exponential backoff e.g. attempt^2 * duration

type Delete

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

Delete represents a DynamoDB DeleteItem operation with support for conditions and consumed capacity tracking

func (*Delete) Condition

func (d *Delete) Condition(expr string, values ...interface{}) *Delete

Condition adds a condition expression to the delete operation. The expression uses placeholders (#field for attribute names, ? for values). Multiple conditions are combined with AND.

func (*Delete) ConsumedCapacity

func (d *Delete) ConsumedCapacity(capture *ConsumedCapacity) *Delete

ConsumedCapacity captures consumed capacity to the property provided

func (*Delete) DeleteItemInput

func (d *Delete) DeleteItemInput() (*dynamodb.DeleteItemInput, error)

DeleteItemInput constructs and returns the underlying DynamoDB DeleteItemInput that will be used for the delete operation

func (*Delete) Range

func (d *Delete) Range(rangeKey interface{}) *Delete

Range specifies the range key value for the item to delete. This is required for tables that have a composite primary key.

func (*Delete) ReturnValuesOnConditionCheckFailure

func (d *Delete) ReturnValuesOnConditionCheckFailure(value types.ReturnValuesOnConditionCheckFailure) *Delete

ReturnValuesOnConditionCheckFailure specifies what values to return when the delete condition fails. Valid values are types.ReturnValuesOnConditionCheckFailureNone and types.ReturnValuesOnConditionCheckFailureAllOld. This setting is only used when the delete is part of a transaction via Tx().

func (*Delete) Run

func (d *Delete) Run() error

Run executes the delete operation using the default context. Returns an error if the delete fails or if a condition is not met.

func (*Delete) RunWithContext

func (d *Delete) RunWithContext(ctx context.Context) error

RunWithContext executes the delete operation using the provided context. Returns an error if the delete fails or if a condition is not met.

func (*Delete) Tx

func (d *Delete) Tx() (*types.TransactWriteItem, error)

Tx converts the delete operation into a TransactWriteItem for use in transactions. Returns an error if the delete configuration is invalid.

type DynamoDBAPI

type DynamoDBAPI interface {
	GetItem(ctx context.Context, params *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
	PutItem(ctx context.Context, params *dynamodb.PutItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
	DeleteItem(ctx context.Context, params *dynamodb.DeleteItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DeleteItemOutput, error)
	UpdateItem(ctx context.Context, params *dynamodb.UpdateItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.UpdateItemOutput, error)
	Query(ctx context.Context, params *dynamodb.QueryInput, optFns ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)
	Scan(ctx context.Context, params *dynamodb.ScanInput, optFns ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error)
	TransactGetItems(ctx context.Context, params *dynamodb.TransactGetItemsInput, optFns ...func(*dynamodb.Options)) (*dynamodb.TransactGetItemsOutput, error)
	TransactWriteItems(ctx context.Context, params *dynamodb.TransactWriteItemsInput, optFns ...func(*dynamodb.Options)) (*dynamodb.TransactWriteItemsOutput, error)
	CreateTable(ctx context.Context, params *dynamodb.CreateTableInput, optFns ...func(*dynamodb.Options)) (*dynamodb.CreateTableOutput, error)
	DeleteTable(ctx context.Context, params *dynamodb.DeleteTableInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DeleteTableOutput, error)
	DescribeTable(ctx context.Context, params *dynamodb.DescribeTableInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DescribeTableOutput, error)
}

DynamoDBAPI defines the interface for DynamoDB operations

type EpochSeconds

type EpochSeconds int64

EpochSeconds represents a timestamp as Unix seconds (seconds since January 1, 1970 UTC). This type is used for DynamoDB stream timestamps.

func (EpochSeconds) MarshalJSON

func (e EpochSeconds) MarshalJSON() ([]byte, error)

MarshalJSON marshals EpochSeconds to JSON as a floating-point number. This implements the json.Marshaler interface.

func (EpochSeconds) Time

func (e EpochSeconds) Time() time.Time

Time converts EpochSeconds to a time.Time value.

func (*EpochSeconds) UnmarshalJSON

func (e *EpochSeconds) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals JSON into EpochSeconds from a floating-point number. This implements the json.Unmarshaler interface.

type Error

type Error interface {
	error
	Cause() error
	Code() string
	Keys() (hashKey, rangeKey types.AttributeValue)
	Message() string
	TableName() string
}

Error provides a unified error definition that includes a code and message along with an optional original error.

type Event

type Event struct {
	// EventSourceARN holds the arn of the resource that generated the record
	EventSourceARN string `json:"eventSourceARN,omitempty"`

	// IsFinalInvokeForWindow - indicates if this is the last invocation for the tumbling window. This only occurs once per window period. [Tumbling Window]
	IsFinalInvokeForWindow bool `json:"isFinalInvokeForWindow,omitempty"`

	// IsWindowTerminatedEarly - a window ends early only if the state exceeds the maximum allowed size of 1 MB [Tumbling Window]
	IsWindowTerminatedEarly bool `json:"isWindowTerminatedEarly,omitempty"`

	// Records contains the modified records in order
	Records []Record `json:"Records"`

	// ShardId uniquely identifies the shard
	ShardId string `json:"shardId,omitempty"`

	// State holds optional tumbling window state [Tumbling Window]
	State json.RawMessage `json:"state,omitempty"`

	// Window holds the endpoints of this window [Tumbling Window]
	Window *Window `json:"window,omitempty"`
}

Event represents a DynamoDB stream event that can be processed by AWS Lambda. This type addresses the incompatibility between github.com/aws/aws-lambda-go and github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue, allowing DynamoDB records to be properly unmarshaled.

type Get

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

Get represents a DynamoDB GetItem operation with support for consistent reads and consumed capacity tracking

func (*Get) ConsistentRead

func (g *Get) ConsistentRead(enabled bool) *Get

ConsistentRead enables strongly consistent reads for the get operation. By default, DynamoDB uses eventually consistent reads which may not reflect recent writes.

func (*Get) ConsumedCapacity

func (g *Get) ConsumedCapacity(capture *ConsumedCapacity) *Get

ConsumedCapacity captures consumed capacity to the property provided

func (*Get) GetItemInput

func (g *Get) GetItemInput() (*dynamodb.GetItemInput, error)

GetItemInput constructs and returns the underlying DynamoDB GetItemInput that will be used for the get operation

func (*Get) Range

func (g *Get) Range(value interface{}) *Get

Range specifies the range key value for the item to retrieve. This is required for tables that have a composite primary key.

func (*Get) Scan

func (g *Get) Scan(v interface{}) error

Scan retrieves the item and unmarshals it into the provided value using the default context. Returns ErrItemNotFound if the item does not exist.

func (*Get) ScanTx

func (g *Get) ScanTx(v interface{}) GetTx

ScanTx prepares the get operation for use in a transaction. The provided value will be populated when the transaction executes successfully.

func (*Get) ScanWithContext

func (g *Get) ScanWithContext(ctx context.Context, v interface{}) error

ScanWithContext retrieves the item and unmarshals it into the provided value using the given context. Returns ErrItemNotFound if the item does not exist.

type GetAPI

type GetAPI interface {
	GetItem(ctx context.Context, params *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
}

GetAPI defines the interface for Get operations

type GetTx

type GetTx interface {
	// Decode the response from AWS
	Decode(v *types.ItemResponse) error
	// Tx generates the get input
	Tx() (*types.TransactGetItem, error)
}

GetTx encapsulates a transactional get operation

type Image added in v2.0.3

type Image map[string]types.AttributeValue

Image represents a DynamoDB item (a map of attribute names to values). This type properly unmarshals AttributeValue data from JSON stream events.

func (*Image) UnmarshalJSON added in v2.0.3

func (img *Image) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for DynamoDB AttributeValue maps.

type Int64Set

type Int64Set []int64

Int64Set represents a DynamoDB Number Set (NS) type, storing a collection of int64 values. This is distinct from a List (L) type which would be the default for slices.

func (Int64Set) MarshalDynamoDBAttributeValue

func (ii Int64Set) MarshalDynamoDBAttributeValue() (types.AttributeValue, error)

MarshalDynamoDBAttributeValue marshals the Int64Set into a DynamoDB Number Set attribute. This implements the Marshaler interface for the AWS SDK v2.

func (*Int64Set) UnmarshalDynamoDBAttributeValue

func (ii *Int64Set) UnmarshalDynamoDBAttributeValue(item types.AttributeValue) error

UnmarshalDynamoDBAttributeValue unmarshals a DynamoDB Number Set attribute into an Int64Set. This implements the Unmarshaler interface for the AWS SDK v2.

type Item

type Item interface {
	// Raw returns the raw value of the element
	Raw() map[string]types.AttributeValue

	// Unmarshal the record into the provided interface
	Unmarshal(v interface{}) error
}

Item provides handle to each record that can be unmarshalled

type Put

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

Put represents a DynamoDB PutItem operation with support for conditions and consumed capacity tracking

func (*Put) Condition

func (p *Put) Condition(expr string, values ...interface{}) *Put

Condition adds a condition expression to the put operation. The expression uses placeholders (#field for attribute names, ? for values). Multiple conditions are combined with AND.

func (*Put) ConsumedCapacity

func (p *Put) ConsumedCapacity(capture *ConsumedCapacity) *Put

ConsumedCapacity captures consumed capacity to the property provided

func (*Put) PutItemInput

func (p *Put) PutItemInput() (*dynamodb.PutItemInput, error)

PutItemInput constructs and returns the underlying DynamoDB PutItemInput that will be used for the put operation

func (*Put) ReturnValuesOnConditionCheckFailure

func (p *Put) ReturnValuesOnConditionCheckFailure(value types.ReturnValuesOnConditionCheckFailure) *Put

ReturnValuesOnConditionCheckFailure specifies what values to return when the put condition fails. Valid values are types.ReturnValuesOnConditionCheckFailureNone and types.ReturnValuesOnConditionCheckFailureAllOld. This setting is only used when the put is part of a transaction via Tx().

func (*Put) Run

func (p *Put) Run() error

Run executes the put operation using the default context. Returns an error if the put fails or if a condition is not met.

func (*Put) RunWithContext

func (p *Put) RunWithContext(ctx context.Context) error

RunWithContext executes the put operation using the provided context. Returns an error if the put fails or if a condition is not met.

func (*Put) Tx

func (p *Put) Tx() (*types.TransactWriteItem, error)

Tx converts the put operation into a TransactWriteItem for use in transactions. Returns an error if the put configuration is invalid.

type PutAPI

type PutAPI interface {
	PutItem(ctx context.Context, params *dynamodb.PutItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
}

PutAPI defines the interface for Put operations

type Query

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

Query represents a DynamoDB Query operation with support for filtering, pagination, and consumed capacity tracking

func (*Query) ConsistentRead

func (q *Query) ConsistentRead(enabled bool) *Query

ConsistentRead enables strongly consistent reads for the query operation. By default, DynamoDB uses eventually consistent reads which may not reflect recent writes.

func (*Query) ConsumedCapacity

func (q *Query) ConsumedCapacity(capture *ConsumedCapacity) *Query

ConsumedCapacity captures consumed capacity to the property provided

func (*Query) Each

func (q *Query) Each(fn func(item Item) (bool, error)) error

Each iterates over all items matching the query, invoking the callback for each. The callback should return true to continue iteration or false to stop.

func (*Query) EachWithContext

func (q *Query) EachWithContext(ctx context.Context, fn func(item Item) (bool, error)) (err error)

EachWithContext iterates over all items matching the query using the provided context. The callback should return true to continue iteration or false to stop.

func (*Query) Filter

func (q *Query) Filter(expr string, values ...interface{}) *Query

Filter allows for the query to be conditionally filtered

func (*Query) FindAll

func (q *Query) FindAll(v interface{}) error

FindAll returns all record

func (*Query) FindAllWithContext

func (q *Query) FindAllWithContext(ctx context.Context, v interface{}) error

FindAllWithContext returns all record using context provided

func (*Query) First

func (q *Query) First(v interface{}) error

First binds the first value and returns

func (*Query) FirstWithContext

func (q *Query) FirstWithContext(ctx context.Context, v interface{}) error

FirstWithContext binds the first value and returns

func (*Query) IndexName

func (q *Query) IndexName(indexName string) *Query

IndexName specifies the name of a secondary index to query. If not specified, the query operates on the base table.

func (*Query) KeyCondition

func (q *Query) KeyCondition(expr string, values ...interface{}) *Query

KeyCondition sets the key condition expression for the query. The expression uses placeholders (#field for attribute names, ? for values).

func (*Query) LastEvaluatedKey

func (q *Query) LastEvaluatedKey(lastEvaluatedKey *map[string]types.AttributeValue) *Query

LastEvaluatedKey stores the last evaluated key into the provided value

func (*Query) LastEvaluatedToken

func (q *Query) LastEvaluatedToken(lastEvaluatedToken *string) *Query

LastEvaluatedToken stores the last evaluated key as a base64 encoded string

func (*Query) Limit

func (q *Query) Limit(limit int64) *Query

Limit returns at most N elements; 0 indicates return all elements

func (*Query) QueryInput

func (q *Query) QueryInput() (*dynamodb.QueryInput, error)

QueryInput constructs and returns the underlying DynamoDB QueryInput that will be submitted to DynamoDB

func (*Query) ScanIndexForward

func (q *Query) ScanIndexForward(enabled bool) *Query

ScanIndexForward when true returns the values in reverse sort key order https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html

func (*Query) Select

func (q *Query) Select(s types.Select) *Query

Select specifies which attributes to return. Defaults to types.SelectAllAttributes if not specified.

func (*Query) StartKey

func (q *Query) StartKey(startKey map[string]types.AttributeValue) *Query

StartKey sets the exclusive start key for query pagination. Use the last evaluated key from a previous query to continue pagination.

func (*Query) StartToken

func (q *Query) StartToken(token string) *Query

StartToken sets the exclusive start key using a base64 encoded token. This provides a more portable way to handle pagination than raw keys.

type Record

type Record struct {
	// AWSRegion update occurred within
	AWSRegion string `json:"awsRegion"`
	// Change holds the modification to the dynamodb record
	Change Change `json:"dynamodb"`
	// EventID holds a unique identifier for event
	EventID string `json:"eventID"`
	// EventName will be one of INSERT, MODIFY, or REMOVE
	// https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html
	EventName string `json:"eventName"`
	// EventSource for record.  Will generally be aws:dynamodb
	EventSource string `json:"eventSource"`
	// EventSourceARN holds the arn of the resource that generated the record
	EventSourceARN string `json:"eventSourceARN"`
	// EventVersion number of the stream format
	EventVersion string `json:"eventVersion"`
}

Record represents a single DynamoDB stream record containing metadata about a change to an item in the table.

type Scan

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

Scan represents a DynamoDB Scan operation with support for parallel scanning, filtering, and consumed capacity tracking

func (*Scan) ConsistentRead

func (s *Scan) ConsistentRead(enabled bool) *Scan

ConsistentRead enables or disables consistent reading

func (*Scan) ConsumedCapacity

func (s *Scan) ConsumedCapacity(capture *ConsumedCapacity) *Scan

ConsumedCapacity captures consumed capacity to the property provided

func (*Scan) Debug

func (s *Scan) Debug(w io.Writer) *Scan

Debug dynamodb request

func (*Scan) Each

func (s *Scan) Each(callback func(item Item) (bool, error)) error

Each is identical to EachWithContext except that it does not allow for cancellation via the context.

func (*Scan) EachWithContext

func (s *Scan) EachWithContext(ctx context.Context, callback func(item Item) (bool, error)) error

EachWithContext iterates invokes the callback for each record that matches the scan. So long as the callback returns `true, nil`, the scan will continue. If the callback either returns an error OR false, the scan will stop. The scan will also stop if the context has been canceled.

func (*Scan) Filter

func (s *Scan) Filter(expr string, values ...interface{}) *Scan

Filter allows for the scan record to be conditionally filtered

func (*Scan) First

func (s *Scan) First(v interface{}) error

First returns the first scanned record

func (*Scan) FirstWithContext

func (s *Scan) FirstWithContext(ctx context.Context, v interface{}) error

FirstWithContext returns the first scanned record and allows for cancellation

func (*Scan) IndexName

func (s *Scan) IndexName(indexName string) *Scan

IndexName specifies the name of a secondary index to scan. If not specified, the scan operates on the base table.

func (*Scan) TotalSegments

func (s *Scan) TotalSegments(n int64) *Scan

TotalSegments enables parallel scanning by dividing the table into segments. Each segment is scanned concurrently. Defaults to 1 (sequential scan).

type StringSet

type StringSet []string

StringSet represents a DynamoDB String Set (SS) type, storing a collection of string values. This is distinct from a List (L) type which would be the default for slices.

func (StringSet) Contains

func (ss StringSet) Contains(want string) bool

Contains returns true if the specified string is found in the StringSet.

func (StringSet) ContainsRegexp

func (ss StringSet) ContainsRegexp(re *regexp.Regexp) bool

ContainsRegexp returns true if the provided regular expression matches any element in the StringSet.

func (StringSet) MarshalDynamoDBAttributeValue

func (ss StringSet) MarshalDynamoDBAttributeValue() (types.AttributeValue, error)

MarshalDynamoDBAttributeValue marshals the StringSet into a DynamoDB String Set attribute. This implements the Marshaler interface for the AWS SDK v2.

func (StringSet) StringSlice

func (ss StringSet) StringSlice() []string

StringSlice converts the StringSet to a standard []string slice.

func (StringSet) Sub

func (ss StringSet) Sub(that StringSet) StringSet

Sub returns a new StringSet containing elements from the original set that are not present in the provided set (set difference operation).

func (*StringSet) UnmarshalDynamoDBAttributeValue

func (ss *StringSet) UnmarshalDynamoDBAttributeValue(item types.AttributeValue) error

UnmarshalDynamoDBAttributeValue unmarshals a DynamoDB String Set attribute into a StringSet. This implements the Unmarshaler interface for the AWS SDK v2.

type Table

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

Table represents a DynamoDB table and provides methods for CRUD operations. It maintains table metadata and tracks consumed capacity for all operations performed on the table.

func (*Table) ConsumedCapacity

func (t *Table) ConsumedCapacity() ConsumedCapacity

ConsumedCapacity returns a snapshot of the capacity units consumed by all operations performed on this table. The returned value is a copy and safe to use without synchronization.

func (*Table) CreateTableIfNotExists

func (t *Table) CreateTableIfNotExists(ctx context.Context, opts ...TableOption) error

CreateTableIfNotExists creates a DynamoDB table if it does not already exist. If the table already exists, this method returns nil without error. Options can be provided to configure billing mode, capacity, and stream settings.

func (*Table) DDB

func (t *Table) DDB() *DDB

DDB returns the underlying DDB instance that created this table.

func (*Table) Delete

func (t *Table) Delete(hashKey interface{}) *Delete

Delete creates a new Delete operation for the item with the specified hash key. Use Range() to specify the range key if the table has a composite primary key.

func (*Table) DeleteTableIfExists

func (t *Table) DeleteTableIfExists(ctx context.Context) error

DeleteTableIfExists deletes a DynamoDB table if it exists. If the table does not exist, this method returns nil without error.

func (*Table) Get

func (t *Table) Get(hashKey interface{}) *Get

Get creates a new Get operation for the item with the specified hash key. Use Range() to specify the range key if the table has a composite primary key.

func (*Table) Put

func (t *Table) Put(v interface{}) *Put

Put creates a new Put operation to insert or replace the specified item in the table. The item will be marshaled to DynamoDB format automatically.

func (*Table) Query

func (t *Table) Query(expr string, values ...interface{}) *Query

Query creates a new Query operation with the specified key condition expression. The expression uses placeholders (#field for attribute names, ? for values). Use IndexName() to query a secondary index instead of the base table.

func (*Table) Scan

func (t *Table) Scan() *Scan

Scan creates a new Scan operation to retrieve all items in the table. Use Filter() to conditionally filter results and TotalSegments() for parallel scanning.

func (*Table) Update

func (t *Table) Update(hashKey interface{}) *Update

Update creates a new Update operation for the item with the specified hash key. Use Range() to specify the range key if the table has a composite primary key. Use Set(), Add(), Remove(), and Delete() to specify the updates.

type TableIndexOption

type TableIndexOption interface {
	TableOption
}

TableIndexOption defines an interface for options that can be applied to both tables and indexes

func WithReadCapacity

func WithReadCapacity(rcap int64) TableIndexOption

WithReadCapacity sets the read capacity units for provisioned tables and indexes. This setting is only used when billing mode is set to provisioned capacity.

func WithWriteCapacity

func WithWriteCapacity(wcap int64) TableIndexOption

WithWriteCapacity sets the write capacity units for provisioned tables and indexes. This setting is only used when billing mode is set to provisioned capacity.

type TableOption

type TableOption interface {
	ApplyTable(o *tableOptions)
}

TableOption defines an interface for applying configuration options to table creation

func WithBillingMode

func WithBillingMode(mode types.BillingMode) TableOption

WithBillingMode configures the billing mode for a DynamoDB table. Common modes are types.BillingModeProvisioned and types.BillingModePayPerRequest.

func WithStreamSpecification

func WithStreamSpecification(streamViewType string) TableOption

WithStreamSpecification enables DynamoDB streams for the table with the specified view type. Valid values include KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, and NEW_AND_OLD_IMAGES.

type Update

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

Update represents a DynamoDB UpdateItem operation with support for SET, ADD, DELETE, REMOVE expressions, conditions, and consumed capacity tracking

func (*Update) Add

func (u *Update) Add(expr string, values ...interface{}) *Update

Add increments a number attribute or adds elements to a set attribute. For numbers, adds the specified value. For sets, adds the specified elements.

func (*Update) Condition

func (u *Update) Condition(expr string, values ...interface{}) *Update

Condition adds a condition expression to the update operation. Multiple conditions are combined with AND. The update only succeeds if all conditions are met.

func (*Update) ConsumedCapacity

func (u *Update) ConsumedCapacity(capture *ConsumedCapacity) *Update

ConsumedCapacity captures consumed capacity information to the provided variable.

func (*Update) Delete

func (u *Update) Delete(expr string, values ...interface{}) *Update

Delete removes elements from a set attribute. The specified elements are removed from the set.

func (*Update) NewValues

func (u *Update) NewValues(v interface{}) *Update

NewValues captures the updated attribute values after the update completes. The provided variable will be populated with the new values.

func (*Update) OldValues

func (u *Update) OldValues(v interface{}) *Update

OldValues captures the original attribute values before the update. The provided variable will be populated with the old values.

func (*Update) Range

func (u *Update) Range(rangeKey interface{}) *Update

Range specifies the range key value for the item to update. This is required for tables that have a composite primary key.

func (*Update) Remove

func (u *Update) Remove(expr string, values ...interface{}) *Update

Remove deletes an attribute from the item. The specified attributes are completely removed from the item.

func (*Update) ReturnValuesOnConditionCheckFailure

func (u *Update) ReturnValuesOnConditionCheckFailure(value types.ReturnValuesOnConditionCheckFailure) *Update

ReturnValuesOnConditionCheckFailure specifies what values to return when the update condition fails. Valid values are types.ReturnValuesOnConditionCheckFailureNone and types.ReturnValuesOnConditionCheckFailureAllOld. This setting is only used when the update is part of a transaction via Tx().

func (*Update) Run

func (u *Update) Run() error

Run executes the update operation using the default context. Returns an error if the update fails or if a condition is not met.

func (*Update) RunWithContext

func (u *Update) RunWithContext(ctx context.Context) error

RunWithContext executes the update operation using the provided context. Returns an error if the update fails or if a condition is not met.

func (*Update) Set

func (u *Update) Set(expr string, values ...interface{}) *Update

Set sets the value of an attribute or creates a new attribute if it doesn't exist. This is the most common update operation for modifying attribute values.

func (*Update) Tx

func (u *Update) Tx() (*types.TransactWriteItem, error)

Tx converts the update operation into a TransactWriteItem for use in transactions. Returns an error if the update configuration is invalid.

func (*Update) UpdateItemInput

func (u *Update) UpdateItemInput() (*dynamodb.UpdateItemInput, error)

UpdateItemInput constructs and returns the underlying DynamoDB UpdateItemInput that will be used for the update operation

type Window

type Window struct {
	Start string `json:"start,omitempty"`
	End   string `json:"end,omitempty"`
}

Window represents a tumbling window for Lambda stream processing. See https://aws.amazon.com/blogs/compute/using-aws-lambda-for-streaming-analytics/

type WriteTx

type WriteTx interface {
	Tx() (*types.TransactWriteItem, error)
}

WriteTx converts ddb operations into instances of *types.TransactWriteItem

Directories

Path Synopsis
Package ddbtest provides testing utilities for working with DynamoDB tables.
Package ddbtest provides testing utilities for working with DynamoDB tables.

Jump to

Keyboard shortcuts

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