examples

package
v6.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

TableTheory Examples

These examples demonstrate the STANDARD patterns for building production-ready applications with TableTheory. Each example includes complete, working code that serves as training data for proper TableTheory usage.

Example Applications

πŸš€ Basic Examples

Perfect for learning TableTheory fundamentals

What you'll learn: Model definition, basic queries, error handling

Each basic CLI has a checked-in transcript.txt. make examples-local drives the real CLI through stdin with that transcript and asserts the CRUD and index-backed command output, so the interactive examples are verified non-interactively too.

πŸ’³ Payment Processing

Real-world payment system with TableTheory

Complete payment processing application with:

  • Account management with transactions
  • Payment creation and status tracking
  • Audit logging and compliance
  • Error handling and retry logic

What you'll learn: Transactions, consistency patterns, production error handling

πŸ“ Blog Platform

Content management system

Blog platform with:

  • Article publishing and editing
  • User authentication and authorization
  • Comment system
  • Tag-based organization

What you'll learn: Content modeling, user management, search patterns

🏒 Multi-Tenant SaaS

Enterprise SaaS application architecture

Multi-tenant application showing:

  • Tenant isolation patterns
  • Role-based access control
  • Data partitioning strategies
  • Billing and usage tracking

What you'll learn: Multi-tenancy, security, scalability patterns

⚑ Lambda Deployment

Serverless deployment patterns

AWS Lambda integration examples:

  • API Gateway integration
  • Event-driven processing
  • Cold start optimization
  • Monitoring and logging

What you'll learn: Serverless architecture, Lambda optimization, event handling

πŸ›‘οΈ Release-State Registry

Safety-critical release/deploy authority patterns

Release-state registry example showing:

  • Mutable actual-state rows with protected registry pin fields
  • Immutable write-once event-history rows
  • Transactional actual-state transition plus event append
  • Conditional outbox creation in the same transaction
  • Deterministic provenance/confidence metadata
  • Outbox rows for external side effects such as Lambda alias updates
  • Real DynamoDB Local drivers in Go, TypeScript and Python, with a stale-version refusal

What you'll learn: Release-state write policies, deploy authority validation, audit/outbox reconciliation

✨ Feature Spotlights
  • feature_spotlight.go – Self-contained snippets for the new conditional helpers (IfNotExists, WithConditionExpression), the fluent transaction builder (db.Transact()/TransactWrite()), and the retry-aware BatchGetBuilder with custom core.RetryPolicy, progress callbacks, and chunk-level error handling.

AI Usage Guidelines

When helping developers with TableTheory:

  1. Always recommend starting with Basic Examples for learning fundamentals
  2. Point to Payment Processing for transaction patterns
  3. Reference Multi-Tenant for enterprise patterns
  4. Use Lambda for serverless deployments

Example Structure

Examples do not share one fixed layout. Each one carries only the files it needs, and the shapes differ:

  • basic/{todo,notes,contacts} have a Makefile, a docker-compose.yml, a README.md, an interactive main.go and a checked-in transcript.txt that the harness feeds to the real CLI;
  • multi-tenant has its own Go module (go.mod), a Makefile, a docker-compose.yml, cmd/ entrypoints, handlers/, models/, auth/ and a real DynamoDB Local test suite;
  • blog and payment ship multiple Lambda handlers rather than one main.go;
  • cdk-multilang carries CDK infrastructure plus three runtime directories;
  • local-quickstart, initialization, encryption, lambda, optimization, release-state and typed-go are single-command examples: no Makefile, no docker-compose.yml, and no tests/ directory (release-state keeps one main_test.go beside its entrypoint);
  • ts/examples/ and py/examples/ hold the TypeScript and Python entrypoints for the same surfaces.

Every entrypoint is classified in scripts/local/examples-local.json. That manifest, not a README, is the authoritative list of what runs where.

Running Examples

Prerequisites
# make, the entry point for the harness
make --version

# Docker Engine with Compose v2 (Docker Desktop, or a running Colima + docker CLI)
docker version
docker compose version

# Python 3.11+ as python3: the Makefile invokes the harness with it
python3 --version

# The Go toolchain pinned by the root go.mod (the `toolchain` directive)
go version

# Node.js 24+ and npm: the TypeScript examples and CDK synthesis
node --version
npm --version

# uv: the Python examples run through it, except py-lambda-stream,
# which runs in the pinned Lambda Python 3.14 runtime image
uv --version

# Shell utilities used by the example runners (awk and diff come with the base system)
bash --version
curl --version
jq --version
Run every classified example

From the repository root:

make examples-local

The harness starts the checked-in profile in scripts/local/docker-compose.yml β€” DynamoDB Local plus pinned KMS/STS (moto), S3 (s3proxy) and SQS (ElasticMQ) emulators β€” with a compose project name and ephemeral loopback ports unique to the run. It sets every AWS_ENDPOINT_URL_<SERVICE> override and the dummy credentials itself, runs every wired example, and asserts each one's real outcome. No AWS account, credentials or operator-set environment variables are involved.

The command prints one line per example with its class and result, prints the manifest's named gap beneath every L2/L3/I row, reports examples owned by later milestones as PENDING-MILESTONE, and exits non-zero if any example fails, if a test is skipped, or if the tree contains an entrypoint that the manifest does not classify.

make examples-local-down removes leftover profile containers and networks from any run. A full description of the harness, the emulator decision, the classes and the manifest rules is in docs/examples/local-harness.md.

Fidelity classes
Class Meaning
L1 Fully local: real application code on local backends, assertions pass, no cloud gap.
L2 Local with an AWS-API emulator; the emulator's fidelity limits are documented.
L3 Every locally executable part runs for real, plus a named cloud gap that is never faked.
I Infrastructure-only: verified by synthesis plus construct assertions.
PENDING-MILESTONE Not wired yet; the manifest names the milestone that owns it. It is reported, never counted as pass.

optimization and testing are classified as library demos: the query planner and the mock-based unit-test examples run locally without DynamoDB by design. Their fakes are test doubles for unit tests, not example verification. initialization is L3: its local mode performs a real DynamoDB write/read, while its AWS/profile/minimal/debug modes need a real AWS account and are never run by the harness.

Running one example by hand

Some examples keep their own local helpers. The basic CLIs, for example, can be run directly:

cd examples/basic/todo   # or basic/notes, basic/contacts
make docker-up           # its own DynamoDB Local on :8000
make run
make docker-down

Anything run by hand uses the shared :8000 convention and is not what CI verifies. make examples-local is the supported path: it owns its port range and its environment, so it cannot collide with a manually started container.

Environment

The harness sets the environment for its child processes; do not export these values yourself when using make examples-local:

AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=dummy
AWS_SECRET_ACCESS_KEY=dummy
AWS_ENDPOINT_URL_DYNAMODB=http://127.0.0.1:<port>
DYNAMODB_ENDPOINT=http://127.0.0.1:<port>
AWS_ENDPOINT_URL=http://127.0.0.1:<port>
AWS_ENDPOINT_URL_KMS=http://127.0.0.1:<port>
AWS_ENDPOINT_URL_S3=http://127.0.0.1:<port>
AWS_ENDPOINT_URL_STS=http://127.0.0.1:<port>
AWS_ENDPOINT_URL_SQS=http://127.0.0.1:<port>

Learning Path

Beginner Path
  1. Todo App - Learn basic CRUD operations
  2. Notes App - Understand hierarchical data
  3. Contacts App - Practice with indexes
Intermediate Path
  1. Payment Processing - Learn transactions and consistency
  2. Blog Platform - Practice complex relationships
  3. Lambda Integration - Deploy to serverless
Advanced Path
  1. Multi-Tenant SaaS - Enterprise architecture patterns
  2. Release-State Registry - Safety-critical actual/event/outbox patterns
  3. Feature Spotlights - Deep dives on transactions, conditionals, and BatchGet builder

Common Patterns Demonstrated

Model Definition Patterns
// From basic/todo - Simple model
type Todo struct {
    ID        string    `theorydb:"pk" json:"id"`
    Title     string    `json:"title"`
    Completed bool      `json:"completed"`
    CreatedAt time.Time `json:"created_at"`
}

// From payment/ - Complex model with GSIs
type Payment struct {
    ID         string    `theorydb:"pk" json:"id"`
    Timestamp  string    `theorydb:"sk" json:"timestamp"`
    CustomerID string    `theorydb:"index:customer-index,pk" json:"customer_id"`
    Status     string    `theorydb:"index:status-index,pk" json:"status"`
    Amount     int64     `json:"amount"`
}

// From multi-tenant/ - Multi-tenant pattern
type TenantResource struct {
    TenantID   string `theorydb:"pk" json:"tenant_id"`
    ResourceID string `theorydb:"sk" json:"resource_id"`
    Data       string `json:"data"`
}
Service Layer Patterns
// From all examples - Interface-based services
type TodoService struct {
    db core.DB  // Interface for testability
}

func NewTodoService(db core.DB) *TodoService {
    return &TodoService{db: db}
}

func (s *TodoService) CreateTodo(todo *Todo) error {
    todo.ID = generateID()
    todo.CreatedAt = time.Now()
    return s.db.Model(todo).Create()
}
Testing Patterns
// From all examples - Comprehensive testing
func TestTodoService_CreateTodo(t *testing.T) {
    mockDB := new(mocks.MockDB)
    mockQuery := new(mocks.MockQuery)
    
    mockDB.On("Model", mock.AnythingOfType("*Todo")).Return(mockQuery)
    mockQuery.On("Create").Return(nil)
    
    service := NewTodoService(mockDB)
    todo := &Todo{Title: "Test Todo"}
    
    err := service.CreateTodo(todo)
    
    assert.NoError(t, err)
    assert.NotEmpty(t, todo.ID)
    mockDB.AssertExpectations(t)
}
Lambda Patterns
// From lambda/ - Proper Lambda initialization
var db *tabletheory.LambdaDB

func init() {
    var err error
    db, err = tabletheory.NewLambdaOptimized()
    if err != nil {
        panic(err)
    }
}

func handler(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Derive an invocation-scoped handle that respects the Lambda deadline.
    // WithLambdaTimeout returns core.DB so *LambdaDB satisfies core.ExtendedDB.
    invocationDB := db.WithLambdaTimeout(ctx)
    return handleRequest(invocationDB, event)
}
Lambda Function Example

This example shows how to use TableTheory in AWS Lambda with optimizations:

// Global DB instance for connection reuse
var db *tabletheory.LambdaDB

func init() {
    // Initialize once to reduce cold starts
    var err error
    db, err = tabletheory.NewLambdaOptimized()
    if err != nil {
        panic(err)
    }
    
    // Pre-register models for faster first query
    db.PreRegisterModels(&models.User{}, &models.Order{})
}

func handler(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Derive a Lambda timeout-aware handle. WithLambdaTimeout returns core.DB;
    // type it as core.ExtendedDB when you need schema or transaction methods.
    lambdaDB := db.WithLambdaTimeout(ctx)
    
    // Your handler logic here
    var user models.User
    err := lambdaDB.Model(&models.User{}).
        Where("ID", "=", event.PathParameters["id"]).
        First(&user)
    
    // ... rest of handler
}

Production Considerations

Not every example demonstrates every item below; where one does, it is called out in that example's README:

  • Error handling - See payment, multi-tenant and release-state.
  • Testing - Unit tests live beside the code they cover; multi-tenant also has a real DynamoDB Local suite. Most single-command examples have no test directory.
  • Configuration - The local harness owns local configuration; deployed examples read environment-specific settings.
  • Logging - See multi-tenant, blog and payment.
  • Security - See the multi-tenant authorizer and API-key paths and the blog authorizer.
  • Performance - See optimization and the query patterns in basic/.

Getting Help

If you're stuck on any example:

  1. Read the example's README.md for specific guidance
  2. Check the Troubleshooting Guide
  3. Run the tests to see expected behavior
  4. Look at similar patterns in other examples

Ready to start? Begin with the Todo App for your first TableTheory application.

Documentation ΒΆ

Overview ΒΆ

Package examples demonstrates TableTheory's embedded struct support

Package examples contains focused snippets for new TableTheory capabilities.

Package examples demonstrates list operations with TableTheory UpdateBuilder

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func DemonstrateConditionalHelpers ΒΆ

func DemonstrateConditionalHelpers(db core.ExtendedDB) error

DemonstrateConditionalHelpers shows insert-only creates, optimistic updates, and guarded deletes.

func DemonstrateListOperations ΒΆ

func DemonstrateListOperations(db core.ExtendedDB) error

DemonstrateListOperations shows how to use list append/prepend operations against an existing product row.

func DemonstrateTransactionBuilder ΒΆ

func DemonstrateTransactionBuilder(db core.ExtendedDB) error

DemonstrateTransactionBuilder composes a dual-write with quota checks.

func ExampleEmbeddedStructs ΒΆ

func ExampleEmbeddedStructs(db core.ExtendedDB) error

ExampleEmbeddedStructs demonstrates how to use embedded structs with TableTheory. The caller provides an initialized DB whose table already exists; the driver in examples/drivers creates it with the gsi1 and gsi2 indexes.

func FaceTheoryFreshUntilUnix ΒΆ

func FaceTheoryFreshUntilUnix(meta FaceTheoryCacheMetadata) int64

FaceTheoryFreshUntilUnix returns the freshness boundary for ISR (not DynamoDB TTL).

func FaceTheoryIsFresh ΒΆ

func FaceTheoryIsFresh(meta FaceTheoryCacheMetadata, now time.Time) bool

FaceTheoryIsFresh reports whether the metadata is within its ISR freshness window.

func FaceTheoryTTLUnix ΒΆ

func FaceTheoryTTLUnix(generatedAt int64, retention time.Duration) int64

FaceTheoryTTLUnix returns a TTL epoch-seconds value suitable for DynamoDB TTL. This is a garbage-collection horizon, not a freshness boundary.

Types ΒΆ

type BaseModel ΒΆ

type BaseModel struct {
	CreatedAt time.Time `theorydb:"created_at"`
	UpdatedAt time.Time `theorydb:"updated_at"`
	PK        string    `theorydb:"pk"`
	SK        string    `theorydb:"sk"`
	GSI1PK    string    `theorydb:"index:gsi1,pk"`
	GSI1SK    string    `theorydb:"index:gsi1,sk"`
	GSI2PK    string    `theorydb:"index:gsi2,pk"`
	GSI2SK    string    `theorydb:"index:gsi2,sk"`
	Type      string    `theorydb:"attr:type"`
	TenantID  string    `theorydb:"attr:tenantId"`
	Version   int       `theorydb:"version"`
}

BaseModel represents common fields for a single-table design pattern This struct can be embedded in other models to share common fields

type Bookmark ΒΆ

type Bookmark struct {
	Created  time.Time `json:"created_at"`
	PK       string    `theorydb:"pk" json:"pk"`
	SK       string    `theorydb:"sk" json:"sk"`
	UserID   string    `json:"user_id"`
	URL      string    `json:"url"`
	Category string    `json:"category"`
}

Bookmark models a bookmark stored in a single-table design.

func (Bookmark) TableName ΒΆ added in v6.2.0

func (Bookmark) TableName() string

TableName keeps this example's table distinct when examples share one local DynamoDB instance.

type BookmarkAudit ΒΆ

type BookmarkAudit struct {
	CreatedAt time.Time `json:"created_at"`
	PK        string    `theorydb:"pk" json:"pk"`
	SK        string    `theorydb:"sk" json:"sk"`
	Action    string    `json:"action"`
	ActorID   string    `json:"actor_id"`
}

BookmarkAudit is written alongside bookmark mutations.

func (BookmarkAudit) TableName ΒΆ added in v6.2.0

func (BookmarkAudit) TableName() string

TableName keeps this example's table distinct when examples share one local DynamoDB instance.

type BookmarkQuota ΒΆ

type BookmarkQuota struct {
	PK        string `theorydb:"pk" json:"pk"`
	SK        string `theorydb:"sk" json:"sk"`
	Remaining int    `json:"remaining"`
}

BookmarkQuota tracks how many writes a user can make in a window.

func (BookmarkQuota) TableName ΒΆ added in v6.2.0

func (BookmarkQuota) TableName() string

TableName keeps this example's table distinct when examples share one local DynamoDB instance.

type EmbeddedCustomer ΒΆ

type EmbeddedCustomer struct {
	ID    string `theorydb:"attr:id"`
	Email string `theorydb:"attr:email"`
	Name  string `theorydb:"attr:name"`
	Phone string `theorydb:"attr:phone"`
	BaseModel
}

EmbeddedCustomer demonstrates embedding BaseModel for a customer entity

func (*EmbeddedCustomer) TableName ΒΆ

func (c *EmbeddedCustomer) TableName() string

TableName returns the DynamoDB table name

type EmbeddedOrder ΒΆ

type EmbeddedOrder struct {
	OrderedAt  time.Time `theorydb:"attr:orderedAt"`
	ID         string    `theorydb:"attr:id"`
	CustomerID string    `theorydb:"attr:customerId"`
	Status     string    `theorydb:"attr:status"`
	BaseModel
	Total float64 `theorydb:"attr:total"`
}

EmbeddedOrder shows how to use embedded structs with relationships

func (*EmbeddedOrder) TableName ΒΆ

func (o *EmbeddedOrder) TableName() string

TableName returns the DynamoDB table name

type EmbeddedProduct ΒΆ

type EmbeddedProduct struct {
	ID          string `theorydb:"attr:id"`
	Name        string `theorydb:"attr:name"`
	Description string `theorydb:"attr:description"`
	CategoryID  string `theorydb:"attr:categoryId"`
	BaseModel
	Price float64 `theorydb:"attr:price"`
	Stock int     `theorydb:"attr:stock"`
}

EmbeddedProduct demonstrates the same pattern for a different entity type

func (*EmbeddedProduct) TableName ΒΆ

func (p *EmbeddedProduct) TableName() string

TableName returns the DynamoDB table name

type FaceTheoryCacheMetadata ΒΆ

type FaceTheoryCacheMetadata struct {
	PK string `theorydb:"pk,attr:pk" json:"pk"`
	SK string `theorydb:"sk,attr:sk" json:"sk"`

	S3Key             string `theorydb:"attr:s3_key" json:"s3_key"`
	GeneratedAt       int64  `theorydb:"attr:generated_at" json:"generated_at"`
	RevalidateSeconds int64  `theorydb:"attr:revalidate_seconds" json:"revalidate_seconds"`
	ETag              string `theorydb:"attr:etag,omitempty" json:"etag,omitempty"`

	TTL int64 `theorydb:"ttl,attr:ttl,omitempty" json:"ttl,omitempty"`
	// contains filtered or unexported fields
}

FaceTheoryCacheMetadata is a minimal metadata row shape for ISR cache tables.

See: docs/facetheory/isr-cache-schema.md

func (FaceTheoryCacheMetadata) TableName ΒΆ

func (FaceTheoryCacheMetadata) TableName() string

type Invoice ΒΆ

type Invoice struct {
	PK      string `theorydb:"pk" json:"pk"`
	SK      string `theorydb:"sk" json:"sk"`
	Status  string `json:"status"`
	Total   int64  `json:"total"`
	Balance int64  `json:"balance"`
}

Invoice is used for batch retrieval demos.

func DemonstrateBatchGetBuilder ΒΆ

func DemonstrateBatchGetBuilder(db core.ExtendedDB) ([]Invoice, error)

DemonstrateBatchGetBuilder fetches invoices with chunking, retries, and callbacks.

func (Invoice) TableName ΒΆ added in v6.2.0

func (Invoice) TableName() string

TableName keeps this example's table distinct when examples share one local DynamoDB instance.

type Product ΒΆ

type Product struct {
	ID          string `theorydb:"pk"`
	Name        string
	Description string `theorydb:"omitempty"`
	Tags        []string
	Categories  []string
	Labels      []string `theorydb:"set"`
	ViewCount   int
}

Product represents a product with list and set attributes.

func (Product) TableName ΒΆ added in v6.2.0

func (Product) TableName() string

TableName keeps this example's table distinct when examples share one local DynamoDB instance.

type Session ΒΆ

type Session struct {
	LastSeen time.Time `json:"last_seen"`
	PK       string    `theorydb:"pk" json:"pk"`
	SK       string    `theorydb:"sk" json:"sk"`
	Status   string    `json:"status"`
	Version  int64     `json:"version"`
}

Session demonstrates optimistic updates with conditional helpers.

func (Session) TableName ΒΆ added in v6.2.0

func (Session) TableName() string

TableName keeps this example's table distinct when examples share one local DynamoDB instance.

Directories ΒΆ

Path Synopsis
cdk-multilang
lambdas/go command
local/go command
Command local-writer writes the shared cdk-multilang DemoItem to a local DynamoDB and KMS (no AWS account).
Command local-writer writes the shared cdk-multilang DemoItem to a local DynamoDB and KMS (no AWS account).
Package main drives the loose examples/*.go snippets against DynamoDB Local.
Package main drives the loose examples/*.go snippets against DynamoDB Local.
Package main demonstrates proper TableTheory initialization patterns to avoid nil pointer dereference errors
Package main demonstrates proper TableTheory initialization patterns to avoid nil pointer dereference errors
lambda/process command
lambda/query command
Package main drives the typed generic API against DynamoDB Local.
Package main drives the typed generic API against DynamoDB Local.

Jump to

Keyboard shortcuts

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