dynamodb

package
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

DynamoDB

AWS DynamoDB client utilities for Go.

Part of the AWS package collection.

Features

  • Table management (create, list, describe, update, delete)
  • Item operations (get, put, update, delete)
  • Query and scan operations
  • Pagination support
  • TTL (Time To Live) management
  • Table creation/deletion waiter support

Installation

go get -u github.com/common-library/go/aws/dynamodb

Usage

Basic Setup
import (
    "context"
    "github.com/common-library/go/aws/dynamodb"
    "github.com/aws/aws-sdk-go-v2/aws"
    aws_dynamodb "github.com/aws/aws-sdk-go-v2/service/dynamodb"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Initialize client
var client dynamodb.Client
err := client.CreateClient(
    context.TODO(),
    "us-east-1",
    "your-access-key",
    "your-secret-key",
    "",
)
Table Operations
Create Table
response, err := client.CreateTable(
    &aws_dynamodb.CreateTableInput{
        TableName: aws.String("users"),
        AttributeDefinitions: []types.AttributeDefinition{
            {
                AttributeName: aws.String("id"),
                AttributeType: types.ScalarAttributeTypeS,
            },
        },
        KeySchema: []types.KeySchemaElement{
            {
                AttributeName: aws.String("id"),
                KeyType:       types.KeyTypeHash,
            },
        },
        BillingMode: types.BillingModePayPerRequest,
    },
    true,  // wait for table to be active
    30,    // wait timeout in seconds
)
List Tables
listOutput, err := client.ListTables(&aws_dynamodb.ListTablesInput{
    Limit: aws.Int32(10),
})
Describe Table
describeOutput, err := client.DescribeTable("users")
fmt.Printf("Table status: %s\n", describeOutput.Table.TableStatus)
Update Table
updateOutput, err := client.UpdateTable(&aws_dynamodb.UpdateTableInput{
    TableName: aws.String("users"),
    // ... update specifications
})
Delete Table
deleteOutput, err := client.DeleteTable(
    "users",
    true,  // wait for deletion
    30,    // timeout seconds
)
Item Operations
Put Item
_, err = client.PutItem(&aws_dynamodb.PutItemInput{
    TableName: aws.String("users"),
    Item: map[string]types.AttributeValue{
        "id":    &types.AttributeValueMemberS{Value: "user-123"},
        "name":  &types.AttributeValueMemberS{Value: "John Doe"},
        "email": &types.AttributeValueMemberS{Value: "john@example.com"},
    },
})
Get Item
output, err := client.GetItem(&aws_dynamodb.GetItemInput{
    TableName: aws.String("users"),
    Key: map[string]types.AttributeValue{
        "id": &types.AttributeValueMemberS{Value: "user-123"},
    },
})
Update Item
updateOutput, err := client.UpdateItem(&aws_dynamodb.UpdateItemInput{
    TableName: aws.String("users"),
    Key: map[string]types.AttributeValue{
        "id": &types.AttributeValueMemberS{Value: "user-123"},
    },
    UpdateExpression: aws.String("SET #name = :name"),
    ExpressionAttributeNames: map[string]string{
        "#name": "name",
    },
    ExpressionAttributeValues: map[string]types.AttributeValue{
        ":name": &types.AttributeValueMemberS{Value: "Jane Doe"},
    },
})
Delete Item
deleteOutput, err := client.DeleteItem(&aws_dynamodb.DeleteItemInput{
    TableName: aws.String("users"),
    Key: map[string]types.AttributeValue{
        "id": &types.AttributeValueMemberS{Value: "user-123"},
    },
})
Query and Scan
Query Items
queryOutput, err := client.Query(&aws_dynamodb.QueryInput{
    TableName:              aws.String("users"),
    KeyConditionExpression: aws.String("id = :id"),
    ExpressionAttributeValues: map[string]types.AttributeValue{
        ":id": &types.AttributeValueMemberS{Value: "user-123"},
    },
})
Scan Items
scanOutput, err := client.Scan(&aws_dynamodb.ScanInput{
    TableName: aws.String("users"),
    FilterExpression: aws.String("age > :minAge"),
    ExpressionAttributeValues: map[string]types.AttributeValue{
        ":minAge": &types.AttributeValueMemberN{Value: "18"},
    },
})
Query with Pagination
// First page
output, err := client.QueryPaginatorNextPage(&aws_dynamodb.QueryInput{
    TableName:              aws.String("users"),
    KeyConditionExpression: aws.String("status = :status"),
    ExpressionAttributeValues: map[string]types.AttributeValue{
        ":status": &types.AttributeValueMemberS{Value: "active"},
    },
    Limit: aws.Int32(100),
})

// Process results
for _, item := range output.Items {
    // Process each item
}

// Check if more pages exist
if output.LastEvaluatedKey != nil {
    // More pages available
}
Scan with Pagination
for hasMorePages := true; hasMorePages; {
    output, err := client.ScanPaginatorNextPage(&aws_dynamodb.ScanInput{
        TableName: aws.String("users"),
        Limit: aws.Int32(100),
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Process output
    for _, item := range output.Items {
        // Process each item
    }
    
    hasMorePages = output.LastEvaluatedKey != nil
}
TTL Management
Enable TTL
_, err := client.UpdateTimeToLive("users", "expirationTime", true)
Check TTL Status
ttlOutput, err := client.DescribeTimeToLive("users")
fmt.Printf("TTL Status: %s\n", ttlOutput.TimeToLiveDescription.TimeToLiveStatus)
Disable TTL
_, err = client.UpdateTimeToLive("users", "expirationTime", false)

API Reference

Client Management
  • CreateClient(ctx, region, accessKey, secretKey, sessionToken, options...) - Initialize client
Table Operations
  • CreateTable(request, wait, waitTimeout, options...) - Create table with optional wait
  • ListTables(request, options...) - List all tables
  • DescribeTable(tableName, options...) - Get table information
  • UpdateTable(request, options...) - Modify table settings
  • DeleteTable(tableName, wait, waitTimeout, options...) - Delete table with optional wait
Item Operations
  • GetItem(request, options...) - Retrieve single item
  • PutItem(request, options...) - Create or replace item
  • UpdateItem(request, options...) - Modify item attributes
  • DeleteItem(request, options...) - Delete item
Query and Scan
  • Query(request, options...) - Query items by primary key
  • Scan(request, options...) - Scan all items
  • QueryPaginatorNextPage(request, options...) - Paginated query
  • ScanPaginatorNextPage(request, options...) - Paginated scan
TTL Management
  • DescribeTimeToLive(tableName, options...) - Get TTL settings
  • UpdateTimeToLive(tableName, attributeName, enabled, options...) - Enable/disable TTL

Custom Endpoint Configuration

DynamoDB Local

For local development and testing, use DynamoDB Local:

var client dynamodb.Client
err := client.CreateClient(
    context.TODO(),
    "us-east-1",
    "dummy",
    "dummy",
    "",
    func(o *aws_dynamodb.Options) {
        o.BaseEndpoint = aws.String("http://localhost:8000")
    },
)

Run DynamoDB Local with Docker:

docker run -p 8000:8000 amazon/dynamodb-local

See DynamoDB Local documentation for more details.

Implementation Details

  • Uses github.com/aws/aws-sdk-go-v2/service/dynamodb
  • AWS SDK v2 based implementation
  • Context support for all operations
  • Waiter support for table operations
  • Pagination support for large result sets
  • TTL management capabilities
  • 1MB limit per query/scan (use paginators for larger datasets)

Error Handling

All functions return errors that should be checked:

response, err := client.GetItem(&aws_dynamodb.GetItemInput{...})
if err != nil {
    var nfe *types.ResourceNotFoundException
    if errors.As(err, &nfe) {
        // Handle resource not found
        log.Printf("Table or item not found")
    } else {
        log.Fatalf("Failed to get item: %v", err)
    }
}

Common error scenarios:

  • Invalid credentials (authentication failure)
  • Table does not exist
  • Item not found
  • Insufficient permissions
  • Network connectivity issues
  • Service throttling (rate limits)
  • Validation errors (invalid attribute types, missing required fields)

Best Practices

  1. Use Context with Timeout

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    
    err := client.CreateClient(ctx, region, accessKey, secretKey, "")
    
  2. Pagination for Large Datasets

    // DynamoDB limits query/scan results to 1MB
    for hasMorePages := true; hasMorePages; {
        output, err := client.QueryPaginatorNextPage(request)
        // Process output
        hasMorePages = output.LastEvaluatedKey != nil
    }
    
  3. Conditional Writes

    _, err := client.PutItem(&aws_dynamodb.PutItemInput{
        TableName: aws.String("users"),
        Item: item,
        ConditionExpression: aws.String("attribute_not_exists(id)"),
    })
    
  4. Batch Operations

    // Use BatchWriteItem for multiple puts/deletes
    // Use BatchGetItem for multiple gets
    // Both operations support up to 25 items
    
  5. Error Handling with Retries

    if err != nil {
        var throttleErr *types.ProvisionedThroughputExceededException
        if errors.As(err, &throttleErr) {
            // Implement exponential backoff retry
        }
    }
    
  6. Credential Security

    • Never hardcode credentials in source code
    • Use environment variables or AWS IAM roles
    • Rotate credentials regularly
    • Use session tokens for temporary access

Examples

Complete Table Lifecycle
package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/common-library/go/aws/dynamodb"
    "github.com/aws/aws-sdk-go-v2/aws"
    aws_dynamodb "github.com/aws/aws-sdk-go-v2/service/dynamodb"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

func main() {
    var client dynamodb.Client
    
    // Initialize client
    err := client.CreateClient(
        context.TODO(),
        "us-east-1",
        "your-access-key",
        "your-secret-key",
        "",
    )
    if err != nil {
        log.Fatal(err)
    }
    
    // Create table
    _, err = client.CreateTable(
        &aws_dynamodb.CreateTableInput{
            TableName: aws.String("users"),
            AttributeDefinitions: []types.AttributeDefinition{
                {
                    AttributeName: aws.String("id"),
                    AttributeType: types.ScalarAttributeTypeS,
                },
            },
            KeySchema: []types.KeySchemaElement{
                {
                    AttributeName: aws.String("id"),
                    KeyType:       types.KeyTypeHash,
                },
            },
            BillingMode: types.BillingModePayPerRequest,
        },
        true,  // wait for active
        30,    // timeout seconds
    )
    if err != nil {
        log.Fatal(err)
    }
    
    // Put item
    _, err = client.PutItem(&aws_dynamodb.PutItemInput{
        TableName: aws.String("users"),
        Item: map[string]types.AttributeValue{
            "id":    &types.AttributeValueMemberS{Value: "user-123"},
            "name":  &types.AttributeValueMemberS{Value: "John Doe"},
            "email": &types.AttributeValueMemberS{Value: "john@example.com"},
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Get item
    output, err := client.GetItem(&aws_dynamodb.GetItemInput{
        TableName: aws.String("users"),
        Key: map[string]types.AttributeValue{
            "id": &types.AttributeValueMemberS{Value: "user-123"},
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Retrieved item: %+v\n", output.Item)
    
    // Delete table
    _, err = client.DeleteTable("users", true, 30)
    if err != nil {
        log.Fatal(err)
    }
}

Dependencies

  • github.com/aws/aws-sdk-go-v2/aws - Core AWS SDK
  • github.com/aws/aws-sdk-go-v2/config - Configuration loading
  • github.com/aws/aws-sdk-go-v2/credentials - Credentials management
  • github.com/aws/aws-sdk-go-v2/service/dynamodb - DynamoDB service

Further Reading

Documentation

Overview

Package dynamodb provides utilities for working with AWS DynamoDB.

This package wraps the AWS SDK v2 DynamoDB client to provide simplified functions for table management, item operations, and query/scan functionality.

Features:

  • Table operations (create, list, describe, update, delete)
  • Item operations (get, put, update, delete)
  • Query and scan with pagination support
  • TTL (Time To Live) management
  • Waiter support for table creation/deletion

Example usage:

var client dynamodb.Client
err := client.CreateClient(ctx, "us-east-1", "key", "secret", "")
response, err := client.PutItem(&dynamodb.PutItemInput{...})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client is a struct that provides client related methods.

func (*Client) CreateClient

func (c *Client) CreateClient(ctx context.Context, region, accessKey, secretAccessKey, sessionToken string, dynamodbOptionsFuncs ...func(*dynamodb.Options)) error

CreateClient creates a DynamoDB client with service-specific options.

This is the recommended way to create a DynamoDB client with custom endpoint and other service-specific configurations.

Parameters:

  • ctx: context for the client lifecycle
  • region: AWS region (e.g., "us-east-1")
  • accessKey: AWS access key ID
  • secretAccessKey: AWS secret access key
  • sessionToken: optional session token (empty string if not using temporary credentials)
  • dynamodbOptionsFuncs: optional service-specific configuration functions

Example:

err := client.CreateClient(context.TODO(), "us-east-1", "access-key", "secret-key", "",
    func(o *dynamodb.Options) {
        o.BaseEndpoint = aws.String("http://localhost:8000")
    })

func (*Client) CreateTable

func (c *Client) CreateTable(request *dynamodb.CreateTableInput, wait bool, waitTimeout time.Duration, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.CreateTableOutput, error)

CreateTable creates a new DynamoDB table.

Parameters:

  • request: CreateTableInput containing table definition
  • wait: if true, waits for table to be active before returning
  • waitTimeout: timeout duration in seconds for table creation wait
  • optionFunctions: optional service-specific configuration functions

Returns the CreateTableOutput and any error encountered. See client_test.go for detailed examples.

Example:

response, err := client.CreateTable(&dynamodb.CreateTableInput{...}, true, 10)

func (*Client) DeleteItem

func (c *Client) DeleteItem(request *dynamodb.DeleteItemInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.DeleteItemOutput, error)

DeleteItem deletes a single item from a table.

Parameters:

  • request: DeleteItemInput containing the table name and primary key
  • optionFunctions: optional service-specific configuration functions

Returns the DeleteItemOutput and any error encountered.

Example:

response, err := client.DeleteItem(&dynamodb.DeleteItemInput{...})

func (*Client) DeleteTable

func (c *Client) DeleteTable(tableName string, wait bool, waitTimeout time.Duration, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.DeleteTableOutput, error)

DeleteTable deletes a table and all of its items.

Parameters:

  • tableName: name of the table to delete
  • wait: if true, waits for table deletion to complete before returning
  • waitTimeout: timeout duration in seconds for deletion wait
  • optionFunctions: optional service-specific configuration functions

Returns the DeleteTableOutput and any error encountered.

Example:

response, err := client.DeleteTable("users", true, 10)

func (*Client) DescribeTable

func (c *Client) DescribeTable(tableName string, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.DescribeTableOutput, error)

DescribeTable retrieves information about a table.

Parameters:

  • tableName: name of the table to describe
  • optionFunctions: optional service-specific configuration functions

Returns the DescribeTableOutput containing table metadata and any error encountered.

Example:

response, err := client.DescribeTable("users")

func (*Client) DescribeTimeToLive

func (c *Client) DescribeTimeToLive(tableName string, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.DescribeTimeToLiveOutput, error)

DescribeTimeToLive retrieves the Time To Live (TTL) settings for a table.

Parameters:

  • tableName: name of the table
  • optionFunctions: optional service-specific configuration functions

Returns the DescribeTimeToLiveOutput containing TTL status and any error encountered.

Example:

response, err := client.DescribeTimeToLive("users")

func (*Client) GetItem

func (c *Client) GetItem(request *dynamodb.GetItemInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)

GetItem retrieves a single item from a table.

Parameters:

  • request: GetItemInput containing the table name and primary key
  • optionFunctions: optional service-specific configuration functions

Returns the GetItemOutput containing the item and any error encountered.

Example:

response, err := client.GetItem(&dynamodb.GetItemInput{...})

func (*Client) ListTables

func (c *Client) ListTables(request *dynamodb.ListTablesInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.ListTablesOutput, error)

ListTables retrieves the list of table names in the current region.

Parameters:

  • request: ListTablesInput with optional pagination parameters
  • optionFunctions: optional service-specific configuration functions

Returns the ListTablesOutput containing table names and any error encountered.

Example:

response, err := client.ListTables(&dynamodb.ListTablesInput{Limit: aws.Int32(10)})

func (*Client) PutItem

func (c *Client) PutItem(request *dynamodb.PutItemInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)

PutItem creates a new item or replaces an existing item.

Parameters:

  • request: PutItemInput containing the table name and item attributes
  • optionFunctions: optional service-specific configuration functions

Returns the PutItemOutput and any error encountered.

Example:

response, err := client.PutItem(&dynamodb.PutItemInput{...})

func (*Client) Query

func (c *Client) Query(request *dynamodb.QueryInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)

Query retrieves items based on primary key values.

You must provide the partition key value. You can optionally provide a sort key value and use a comparison operator to refine the search results.

Parameters:

  • request: QueryInput containing the table name and key conditions
  • optionFunctions: optional service-specific configuration functions

Returns the QueryOutput containing matching items and any error encountered.

Example:

response, err := client.Query(&dynamodb.QueryInput{...})

func (*Client) QueryPaginatorNextPage

func (c *Client) QueryPaginatorNextPage(request *dynamodb.QueryInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)

QueryPaginatorNextPage fetches the next page of results using QueryPaginator.

This is useful for processing large result sets that exceed the 1MB limit per query.

Parameters:

  • request: QueryInput containing the query parameters
  • optionFunctions: optional service-specific configuration functions

Returns the QueryOutput for the next page and any error encountered.

Example:

response, err := client.QueryPaginatorNextPage(&dynamodb.QueryInput{...})

func (*Client) Scan

func (c *Client) Scan(request *dynamodb.ScanInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error)

Scan retrieves all items in a table or a secondary index.

A Scan operation reads every item in a table or index. You can optionally apply a filter expression to return only matching items.

Parameters:

  • request: ScanInput containing the table name and optional filter expressions
  • optionFunctions: optional service-specific configuration functions

Returns the ScanOutput containing all items and any error encountered.

Example:

response, err := client.Scan(&dynamodb.ScanInput{...})

func (*Client) ScanPaginatorNextPage

func (c *Client) ScanPaginatorNextPage(request *dynamodb.ScanInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error)

ScanPaginatorNextPage fetches the next page of results using ScanPaginator.

This is useful for processing large result sets that exceed the 1MB limit per scan.

Parameters:

  • request: ScanInput containing the scan parameters
  • optionFunctions: optional service-specific configuration functions

Returns the ScanOutput for the next page and any error encountered.

Example:

response, err := client.ScanPaginatorNextPage(&dynamodb.ScanInput{...})

func (*Client) UpdateItem

func (c *Client) UpdateItem(request *dynamodb.UpdateItemInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.UpdateItemOutput, error)

UpdateItem modifies the attributes of an existing item.

Parameters:

  • request: UpdateItemInput containing the table name, key, and update expression
  • optionFunctions: optional service-specific configuration functions

Returns the UpdateItemOutput and any error encountered.

Example:

response, err := client.UpdateItem(&dynamodb.UpdateItemInput{...})

func (*Client) UpdateTable

func (c *Client) UpdateTable(request *dynamodb.UpdateTableInput, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.UpdateTableOutput, error)

UpdateTable modifies the provisioned throughput settings, global secondary indexes, or DynamoDB Streams settings for a table.

Parameters:

  • request: UpdateTableInput containing the modifications
  • optionFunctions: optional service-specific configuration functions

Returns the UpdateTableOutput and any error encountered.

Example:

response, err := client.UpdateTable(&dynamodb.UpdateTableInput{...})

func (*Client) UpdateTimeToLive

func (c *Client) UpdateTimeToLive(tableName, attributeName string, enabled bool, optionFunctions ...func(*dynamodb.Options)) (*dynamodb.UpdateTimeToLiveOutput, error)

UpdateTimeToLive enables or disables Time To Live (TTL) for a table.

TTL allows you to define a per-item timestamp to determine when an item is no longer needed.

Parameters:

  • tableName: name of the table
  • attributeName: name of the TTL attribute
  • enabled: true to enable TTL, false to disable
  • optionFunctions: optional service-specific configuration functions

Returns the UpdateTimeToLiveOutput and any error encountered.

Example:

response, err := client.UpdateTimeToLive("users", "expirationTime", true)

Jump to

Keyboard shortcuts

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