dynamodb

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package dynamodb provides helpers for Amazon DynamoDB operations.

Features

  • Item operations: Get, Put, Delete, Update with automatic marshaling
  • Batch operations: BatchGet, BatchWrite with automatic chunking
  • Scan and Query with pagination support
  • Table operations: Create, Delete, WaitForActive

Client Creation

Create a client using AWS configuration:

cfg, err := aws.LoadConfig(ctx, aws.WithRegion("us-west-2"))
if err != nil {
    return err
}

client := dynamodb.NewClient(cfg)

Basic Operations

// Define a struct for your items
type User struct {
    ID    string `dynamodbav:"pk"`
    Email string `dynamodbav:"email"`
    Name  string `dynamodbav:"name"`
}

// Put an item
user := User{ID: "user-123", Email: "[email protected]", Name: "Alice"}
err := client.PutItem(ctx, "users", user)

// Get an item
var result User
err := client.GetItem(ctx, "users", dynamodb.Key{"pk": "user-123"}, &result)

// Delete an item
err := client.DeleteItem(ctx, "users", dynamodb.Key{"pk": "user-123"})

Testing

For testing, use the interface-based client:

mock := &MockDynamoDBAPI{}
client := dynamodb.NewClientWithAPI(mock)

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrItemNotFound is returned when an item does not exist.
	ErrItemNotFound = errors.New("dynamodb: item not found")

	// ErrTableNotFound is returned when a table does not exist.
	ErrTableNotFound = errors.New("dynamodb: table not found")

	// ErrConditionalCheckFailed is returned when a condition check fails.
	ErrConditionalCheckFailed = errors.New("dynamodb: conditional check failed")

	// ErrProvisionedThroughputExceeded is returned when throughput is exceeded.
	ErrProvisionedThroughputExceeded = errors.New("dynamodb: provisioned throughput exceeded")
)

Common DynamoDB errors.

Functions

This section is empty.

Types

type API added in v1.0.0

type API 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)
	BatchGetItem(ctx context.Context, params *dynamodb.BatchGetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.BatchGetItemOutput, error)
	BatchWriteItem(ctx context.Context, params *dynamodb.BatchWriteItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.BatchWriteItemOutput, 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)
}

API defines the DynamoDB operations used by this package. This interface enables testing with mocks.

type Client added in v1.0.0

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

Client provides DynamoDB operations.

func NewClient added in v1.0.0

func NewClient(cfg *aws.Config) (*Client, error)

NewClient creates a new DynamoDB client with the given configuration.

Example:

cfg, err := aws.LoadConfig(ctx)
if err != nil {
    return err
}
client := dynamodb.NewClient(cfg)

func NewClientWithAPI added in v1.0.0

func NewClientWithAPI(api API) *Client

NewClientWithAPI creates a client with a custom API implementation. Useful for testing with mocks.

Example:

mock := &MockDynamoDBAPI{}
client := dynamodb.NewClientWithAPI(mock)

func (*Client) API added in v1.0.0

func (c *Client) API() API

API returns the underlying DynamoDB API for direct SDK access.

func (*Client) BatchDeleteItems added in v1.0.0

func (c *Client) BatchDeleteItems(ctx context.Context, tableName string, keys []Key) ([]Key, error)

BatchDeleteItems deletes multiple items from a table. Automatically handles the 25-item limit per batch.

Example:

keys := []dynamodb.Key{{"pk": "user-1"}, {"pk": "user-2"}}
unprocessed, err := client.BatchDeleteItems(ctx, "users", keys)

func (*Client) BatchWriteItems added in v1.0.0

func (c *Client) BatchWriteItems(ctx context.Context, tableName string, items []any) ([]any, error)

BatchWriteItems writes multiple items to one or more tables. Automatically handles the 25-item limit per batch.

Example:

items := []User{user1, user2, user3}
unprocessed, err := client.BatchWriteItems(ctx, "users", items)

func (*Client) DeleteItem added in v1.0.0

func (c *Client) DeleteItem(ctx context.Context, tableName string, key Key) error

DeleteItem deletes an item from a DynamoDB table.

Example:

err := client.DeleteItem(ctx, "users", dynamodb.Key{"pk": "user-123"})

func (*Client) DeleteItemIfExists added in v1.0.0

func (c *Client) DeleteItemIfExists(ctx context.Context, tableName string, key Key, pkAttribute string) error

DeleteItemIfExists deletes an item only if it exists. Returns ErrConditionalCheckFailed if the item doesn't exist.

Example:

err := client.DeleteItemIfExists(ctx, "users", dynamodb.Key{"pk": "user-123"}, "pk")

func (*Client) GetItem added in v1.0.0

func (c *Client) GetItem(ctx context.Context, tableName string, key Key, dest any) error

GetItem retrieves an item from a DynamoDB table. The result is unmarshaled into the provided destination.

Example:

var user User
err := client.GetItem(ctx, "users", dynamodb.Key{"pk": "user-123"}, &user)
if errors.Is(err, dynamodb.ErrItemNotFound) {
    // Handle not found
}

func (*Client) GetItemRaw added in v1.0.0

func (c *Client) GetItemRaw(ctx context.Context, tableName string, key Key) (map[string]types.AttributeValue, error)

GetItemRaw retrieves an item and returns the raw attribute value map. Useful when you don't want to unmarshal into a struct.

Example:

item, err := client.GetItemRaw(ctx, "users", dynamodb.Key{"pk": "user-123"})

func (*Client) PutItem added in v1.0.0

func (c *Client) PutItem(ctx context.Context, tableName string, item any) error

PutItem writes an item to a DynamoDB table. The item is automatically marshaled from the provided struct.

Example:

user := User{ID: "user-123", Email: "[email protected]", Name: "Alice"}
err := client.PutItem(ctx, "users", user)

func (*Client) PutItemIfNotExists added in v1.0.0

func (c *Client) PutItemIfNotExists(ctx context.Context, tableName string, item any, pkAttribute string) error

PutItemIfNotExists writes an item only if it doesn't already exist. Returns ErrConditionalCheckFailed if the item exists.

Example:

user := User{ID: "user-123", Email: "[email protected]"}
err := client.PutItemIfNotExists(ctx, "users", user, "pk")
if errors.Is(err, dynamodb.ErrConditionalCheckFailed) {
    // Item already exists
}

func (*Client) Query added in v1.0.0

func (c *Client) Query(ctx context.Context, tableName string, keyCondition expression.KeyConditionBuilder, opts ...QueryOption) (*QueryResult, error)

Query performs a query operation on a DynamoDB table.

Example:

// Query by partition key
keyExpr := expression.Key("pk").Equal(expression.Value("user-123"))
result, err := client.Query(ctx, "users", keyExpr)

// Query with sort key condition
keyExpr := expression.KeyAnd(
    expression.Key("pk").Equal(expression.Value("user-123")),
    expression.Key("sk").BeginsWith("order-"),
)
result, err := client.Query(ctx, "orders", keyExpr)

func (*Client) QueryAll added in v1.0.0

func (c *Client) QueryAll(ctx context.Context, tableName string, keyCondition expression.KeyConditionBuilder, dest any, opts ...QueryOption) error

QueryAll performs a query and automatically paginates through all results. Use with caution on large datasets.

Example:

keyExpr := expression.Key("pk").Equal(expression.Value("user-123"))
var users []User
err := client.QueryAll(ctx, "users", keyExpr, &users)

func (*Client) Scan added in v1.0.0

func (c *Client) Scan(ctx context.Context, tableName string, opts ...ScanOption) (*ScanResult, error)

Scan performs a scan operation on a DynamoDB table. Scans read every item in the table - use Query when possible.

Example:

result, err := client.Scan(ctx, "users")
var users []User
err = result.Unmarshal(&users)

func (*Client) ScanAll added in v1.0.0

func (c *Client) ScanAll(ctx context.Context, tableName string, dest any, opts ...ScanOption) error

ScanAll performs a scan and automatically paginates through all results. Use with extreme caution on large tables.

Example:

var users []User
err := client.ScanAll(ctx, "users", &users)

func (*Client) ScanCallback added in v1.0.0

func (c *Client) ScanCallback(ctx context.Context, tableName string, callback func([]map[string]types.AttributeValue) error, opts ...ScanOption) error

ScanCallback iterates through all items in a table and calls a callback for each batch. Return an error from the callback to stop scanning.

Example:

err := client.ScanCallback(ctx, "users", func(items []map[string]types.AttributeValue) error {
    var users []User
    attributevalue.UnmarshalListOfMaps(items, &users)
    for _, user := range users {
        process(user)
    }
    return nil
})

type Key added in v1.0.0

type Key map[string]any

Key represents a DynamoDB item key. Keys should use string, number, or binary attribute values.

Example:

// Simple partition key
:= dynamodb.Key{"pk": "user-123"}

// Composite key (partition + sort)
key := dynamodb.Key{"pk": "user-123", "sk": "profile"}

type QueryOption added in v1.0.0

type QueryOption func(*queryOptions)

QueryOption configures a Query operation.

func WithConsistentRead added in v1.0.0

func WithConsistentRead() QueryOption

WithConsistentRead enables consistent reads.

Example:

results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithConsistentRead())

func WithFilter added in v1.0.0

func WithFilter(filter expression.ConditionBuilder) QueryOption

WithFilter adds a filter expression to the query.

Example:

filter := expression.Name("status").Equal(expression.Value("active"))
results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithFilter(filter))

func WithIndex added in v1.0.0

func WithIndex(indexName string) QueryOption

WithIndex specifies a secondary index to query.

Example:

results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithIndex("email-index"))

func WithLimit added in v1.0.0

func WithLimit(limit int32) QueryOption

WithLimit limits the number of items returned.

Example:

results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithLimit(10))

func WithProjection added in v1.0.0

func WithProjection(attrs ...string) QueryOption

WithProjection specifies which attributes to return.

Example:

results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithProjection("id", "name", "email"))

func WithScanForward added in v1.0.0

func WithScanForward(forward bool) QueryOption

WithScanForward sets the scan direction. true = ascending, false = descending.

Example:

results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithScanForward(false))

func WithStartKey added in v1.0.0

func WithStartKey(key map[string]types.AttributeValue) QueryOption

WithStartKey sets the exclusive start key for pagination.

Example:

results, err := client.Query(ctx, "users", keyExpr, dynamodb.WithStartKey(lastKey))

type QueryResult added in v1.0.0

type QueryResult struct {
	Items            []map[string]types.AttributeValue
	Count            int32
	ScannedCount     int32
	LastEvaluatedKey map[string]types.AttributeValue
}

QueryResult contains the results of a Query operation.

func (*QueryResult) HasMorePages added in v1.0.0

func (r *QueryResult) HasMorePages() bool

HasMorePages returns true if there are more results to fetch.

func (*QueryResult) Unmarshal added in v1.0.0

func (r *QueryResult) Unmarshal(dest any) error

Unmarshal unmarshals the query results into a slice of the provided type.

Example:

result, err := client.Query(ctx, "users", keyExpr)
var users []User
err = result.Unmarshal(&users)

type ScanOption added in v1.0.0

type ScanOption func(*scanOptions)

ScanOption configures a Scan operation.

func WithParallelScan added in v1.0.0

func WithParallelScan(segment, totalSegments int32) ScanOption

WithParallelScan configures parallel scanning.

Example:

// Scan segment 0 of 4 total segments
result, err := client.Scan(ctx, "users", dynamodb.WithParallelScan(0, 4))

func WithScanFilter added in v1.0.0

func WithScanFilter(filter expression.ConditionBuilder) ScanOption

WithScanFilter adds a filter expression to the scan.

func WithScanLimit added in v1.0.0

func WithScanLimit(limit int32) ScanOption

WithScanLimit limits the number of items scanned.

func WithScanProjection added in v1.0.0

func WithScanProjection(attrs ...string) ScanOption

WithScanProjection specifies which attributes to return.

func WithScanStartKey added in v1.0.0

func WithScanStartKey(key map[string]types.AttributeValue) ScanOption

WithScanStartKey sets the exclusive start key for pagination.

type ScanResult added in v1.0.0

type ScanResult struct {
	Items            []map[string]types.AttributeValue
	Count            int32
	ScannedCount     int32
	LastEvaluatedKey map[string]types.AttributeValue
}

ScanResult contains the results of a Scan operation.

func (*ScanResult) HasMorePages added in v1.0.0

func (r *ScanResult) HasMorePages() bool

HasMorePages returns true if there are more results to fetch.

func (*ScanResult) Unmarshal added in v1.0.0

func (r *ScanResult) Unmarshal(dest any) error

Unmarshal unmarshals the scan results into a slice of the provided type.

Jump to

Keyboard shortcuts

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