tabletheory

package module
v7.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 9 Imported by: ? modules, 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

TableTheory

DynamoDB-first multi-language data contract.
One specification. Three runtimes. Verified on every commit.

Release License Docs Quality gates

Go TypeScript Python

Get started → · API reference · Contract scenarios · DMS spec


TableTheory is a DynamoDB-first ORM and schema contract designed to keep data access consistent across languages and reliable in generative coding workflows (humans + AI assistants). It ships peer implementations in Go, TypeScript, and Python — not a Go library with bindings, but three independent runtimes that pass the same P0 contract scenarios on every commit.

            FaceTheory (client delivery)
                      │
            AppTheory (serverless runtime)
                      │
      TableTheory (data layer)  ← you are here
                      │
                  DynamoDB

TableTheory is the foundation of the Theory Cloud stack — used in production by Pay Theory.

Install

TableTheory is distributed exclusively through immutable GitHub Releases — no PyPI, no npm. The single distribution path keeps versions aligned across all three runtimes.

Runtime Install
Go go get github.com/theory-cloud/tabletheory/v7@vX.Y.Z
TypeScript install the npm pack release asset — see TypeScript getting started
Python install the wheel/sdist release asset — see Python getting started

At a glance

P0 contract scenarios 9 — CRUD, omit-empty, lifecycle, locking, TTL, and release-state fixtures
Runtimes Go · TypeScript · Python (peers, not ports)
Supported lines Node 22 (deprecated, EOL 2027-04-30), Node 24, Node 26 · Python 3.12, 3.14, 3.15 — see runtime support
Distribution Immutable GitHub Releases — version-aligned across all runtimes
License Apache-2.0 — open source, production use
Status Post-1.0 stable API across all three runtimes

Why TableTheory?

Use TableTheory when you want DynamoDB-backed systems that are:

  • Serverless-first — patterns that work well in AWS Lambda: cold-start aware LambdaInit, batching with Lambda timeout awareness, transactions, streams, optional KMS-backed field encryption that's fail-closed by design.
  • Cross-language consistent — one table, multiple services, multiple runtimes — without schema or behavior drift. Verified on every commit by the P0 contract scenarios.
  • Generative-coding friendly — explicit schema, canonical patterns, strict verification, and downloadable LLM artifacts (llms.txt, vocabulary JSON, rules template, prompt recipes) so AI-generated code stays correct and maintainable.

✅ Treat schema + semantics as a contract ❌ Don't redefine "the same" table shape independently per service/language

Documentation

The full documentation site lives at tabletheory.theorycloud.ai — branded with the Theory Cloud design system, with a ⌘K search palette, runtime tabs, and surface-tinted pages.

Most-used entry points:

Section Link
Getting started tabletheory.theorycloud.ai/getting-started/
API reference tabletheory.theorycloud.ai/api-reference/
Struct definition guide tabletheory.theorycloud.ai/struct-definition-guide/
Core patterns tabletheory.theorycloud.ai/core-patterns/
Architecture patterns tabletheory.theorycloud.ai/architecture-patterns/
Testing tabletheory.theorycloud.ai/testing-guide/
Troubleshooting tabletheory.theorycloud.ai/troubleshooting/
Generative coding artifacts tabletheory.theorycloud.ai/ai/

Per-runtime entry points:

P0 contract reference and related feature pages:

Integrations — how downstream Theory Cloud frameworks use TableTheory:

Repository layout

Path What
docs/ Public documentation site (Jekyll) — also the canonical doc tree
ts/ TypeScript SDK — TS docs index
py/ Python SDK — Py docs index
contract-tests/ Cross-language P0 fixtures + runners
examples/cdk-multilang/ Deployable demo: one DynamoDB table, three Lambdas (Go, Node.js 24, Python 3.14)
.github/workflows/ CI: rubric, language gates, release-please, Pages publish

Serverless data demo (CDK)

The CDK demo deploys one DynamoDB table + three Lambda Function URLs (Go, Node.js 24, Python 3.14) that read/write the same item shape and exercise portability-sensitive features (encryption, batching, transactions):

→ examples/cdk-multilang/README.md

For infrastructure patterns, see the CDK integration guide.

DMS — the language-neutral schema

TableTheory's drift-prevention story centers on a shared, language-neutral schema document: TableTheory Spec (DMS).

dms_version: "0.2"
models:
  - name: "Note"
    table: { name: "notes_contract" }
    keys:
      partition: { attribute: "PK", type: "S" }
      sort:      { attribute: "SK", type: "S" }
    attributes:
      - { attribute: "PK",    type: "S", required: true, roles: ["pk"] }
      - { attribute: "SK",    type: "S", required: true, roles: ["sk"] }
      - { attribute: "value", type: "N" }

DMS is authored independently of any runtime — Go, TypeScript, and Python all validate against the same spec. See the DMS Specification v0.2 for the public summary.

Development & verification

make rubric        # full repo verification (the all-gates gate)
make docker-up     # start DynamoDB Local
make test          # full suite incl. integration

Run the examples locally

make examples-local        # run every classified example
make examples-local-down   # remove leftover containers and networks

The harness starts DynamoDB Local plus pinned KMS/STS, S3 and SQS emulators on ephemeral loopback ports, sets dummy credentials and endpoint overrides itself, and asserts each example's real outcome. No AWS account, AWS credentials or operator-set environment variables are involved. Prerequisites are Docker or Colima with Compose v2, Python 3.11+ as python3, the Go toolchain pinned by go.mod, Node.js 24+ with npm, uv, and bash/curl/jq. See examples/README.md for the per-example classes and named gaps, and docs/examples/local-harness.md for the harness design.

For multi-language work:

cd ts && npm run lint && npm run typecheck && npm run test:unit
uv --directory py run pytest -q tests/unit

See CONTRIBUTING.md for full contributor docs, including the Authoring documentation section if you're updating the docs site.

Theory Cloud

TableTheory is the data foundation of the Theory Cloud stack. Nothing in Theory Cloud precedes it.

  • AppTheory (serverless runtime) → depends on TableTheory
  • FaceTheory (client delivery) → depends on TableTheory
  • KnowledgeTheory (platform state + knowledge graph) → depends on TableTheory
  • Autheory (identity) → depends on TableTheory
  • theory-mcp-server → depends on TableTheory

The single-path philosophy starts here: one way to define a table, one way to access data, one way to handle encryption — enforced by the framework, not by convention. When generative coding tools produce TableTheory code, the constrained API surface means the output converges on correct implementations instead of drifting across equivalent-but-incompatible patterns.

License & contributing

Made with Theory Cloud · docs

Documentation

Overview

Package tabletheory provides a type-safe ORM for Amazon DynamoDB in Go.

Import path:

import "github.com/theory-cloud/tabletheory/v7"

Implementation lives in `internal/theorydb` so the repo root stays minimal.

Index

Constants

This section is empty.

Variables

View Source
var (
	WithBackupTable = schema.WithBackupTable
	WithDataCopy    = schema.WithDataCopy
	WithTargetModel = schema.WithTargetModel
	WithTransform   = schema.WithTransform
	WithBatchSize   = schema.WithBatchSize
)

Re-export AutoMigrate options for convenience.

Functions

func Advance

func Advance(ctx context.Context, db core.DB, model any, attribute string, value int64) (core.AdvanceResult, error)

Advance moves attribute to value only when that moves it forward, and reports whether this call moved it.

It is the ergonomic entry point for core.AtomicCounter. A retention floor advanced from several writers converges on the highest value any of them proposed and never moves backwards: a call that would not move the attribute reports Advanced=false instead of failing.

floor, err := tabletheory.Advance(ctx, db, &tenant{PK: "T1", SK: "retention"}, "floor", 100)
if floor.Advanced { /* this call moved the floor to floor.Value */ }

func AtVersion

func AtVersion(version int64) core.TransactCondition

func Condition

func Condition(field, operator string, value any) core.TransactCondition

func ConditionExpression

func ConditionExpression(expression string, values map[string]any) core.TransactCondition

func ConditionVersion

func ConditionVersion(version int64) core.TransactCondition

func DefaultBatchGetOptions

func DefaultBatchGetOptions() *core.BatchGetOptions

func EnableXRayTracing

func EnableXRayTracing() bool

func GetLambdaMemoryMB

func GetLambdaMemoryMB() int

func GetPartnerFromContext

func GetPartnerFromContext(ctx context.Context) string

func GetRemainingTimeMillis

func GetRemainingTimeMillis(ctx context.Context) int64

func IfExists

func IfExists() core.TransactCondition

func IfNotExists

func IfNotExists() core.TransactCondition

func Increment

func Increment(ctx context.Context, db core.DB, model any, attribute string, by int64) (int64, error)

Increment atomically adds by to attribute on the item identified by model's primary key and returns the value the write produced.

This is the ergonomic entry point for core.AtomicCounter, which is a separate interface so adding it never widened core.DB. An absent attribute is a counter that has not been incremented yet, so the first increment of a fresh item yields by. DynamoDB performs the addition in one UpdateItem, so concurrent increments cannot lose each other.

next, err := tabletheory.Increment(ctx, db, &session{PK: "T1", SK: "seq"}, "counter", 1)

func IsLambdaEnvironment

func IsLambdaEnvironment() bool

func ModelOf

func ModelOf[T any](db core.DB) typed.Model[T]

func New

func New(config session.Config) (core.ExtendedDB, error)

func NewBasic

func NewBasic(config session.Config) (core.DB, error)

func NewKeyPair

func NewKeyPair(partitionKey any, sortKey ...any) core.KeyPair

func NewTypedKey

func NewTypedKey[T any](partitionKey any, sortKey ...any) typed.Key[T]

func NewWithClient

func NewWithClient(config session.Config, client session.DynamoDBAPI) (core.ExtendedDB, error)

NewWithClient creates a TableTheory instance backed by an injected DynamoDBAPI. It is intended for deterministic consumer tests and local fakes.

func PartnerContext

func PartnerContext(ctx context.Context, partnerID string) context.Context

func UnmarshalItem

func UnmarshalItem(item map[string]types.AttributeValue, dest interface{}) error

func UnmarshalItems

func UnmarshalItems(items []map[string]types.AttributeValue, dest interface{}) error

func UnmarshalStreamImage

func UnmarshalStreamImage(streamImage map[string]events.DynamoDBAttributeValue, dest interface{}) error

Types

type AccountConfig

type AccountConfig = internaltheorydb.AccountConfig

type AdvanceResult

type AdvanceResult = core.AdvanceResult

type AtomicCounter

type AtomicCounter = core.AtomicCounter

type AutoMigrateOption

type AutoMigrateOption = schema.AutoMigrateOption

type BatchGetOptions

type BatchGetOptions = core.BatchGetOptions

type ColdStartMetrics

type ColdStartMetrics = internaltheorydb.ColdStartMetrics

func BenchmarkColdStart

func BenchmarkColdStart(models ...any) ColdStartMetrics

type Config

type Config = session.Config

Re-export types for convenience.

type DB

type DB = internaltheorydb.DB

type DynamoDBAPI

type DynamoDBAPI = session.DynamoDBAPI

type KeyPair

type KeyPair = core.KeyPair

type LambdaDB

type LambdaDB = internaltheorydb.LambdaDB

func LambdaInit

func LambdaInit(models ...any) (*LambdaDB, error)

func NewLambdaOptimized

func NewLambdaOptimized() (*LambdaDB, error)

type LambdaMemoryStats

type LambdaMemoryStats = internaltheorydb.LambdaMemoryStats

type MultiAccountDB

type MultiAccountDB = internaltheorydb.MultiAccountDB

func NewMultiAccount

func NewMultiAccount(accounts map[string]AccountConfig) (*MultiAccountDB, error)

type TypedExtendedDB

type TypedExtendedDB = core.TypedExtendedDB

Directories

Path Synopsis
cmd
tabletheory command
Package examples demonstrates TableTheory's embedded struct support
Package examples demonstrates TableTheory's embedded struct support
cdk-multilang/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).
drivers command
Package main drives the loose examples/*.go snippets against DynamoDB Local.
Package main drives the loose examples/*.go snippets against DynamoDB Local.
encryption command
initialization command
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 command
optimization command
release-state command
typed-go command
Package main drives the typed generic API against DynamoDB Local.
Package main drives the typed generic API against DynamoDB Local.
internal
dynamodbprobe
Package dynamodbprobe verifies that a local endpoint actually speaks the DynamoDB protocol instead of merely accepting HTTP connections.
Package dynamodbprobe verifies that a local endpoint actually speaks the DynamoDB protocol instead of merely accepting HTTP connections.
dynamodbprobe/cmd/dynamodb-local-check command
Command dynamodb-local-check exits 0 when the endpoint speaks the DynamoDB protocol and non-zero with a clear message otherwise.
Command dynamodb-local-check exits 0 when the endpoint speaks the DynamoDB protocol and non-zero with a clear message otherwise.
safeoutput
Package safeoutput writes generated and scaffolded files through an os.Root-confined, atomic rename so that a symlink in the destination path cannot redirect a write to an unrelated victim file outside its intended directory.
Package safeoutput writes generated and scaffolded files through an os.Root-confined, atomic rename so that a symlink in the destination path cannot redirect a write to an unrelated victim file outside its intended directory.
theorydb
lambda.go
lambda.go
pkg
consistency
Package consistency provides utilities for handling eventual consistency in DynamoDB
Package consistency provides utilities for handling eventual consistency in DynamoDB
core
Package core defines the core interfaces and types for TableTheory
Package core defines the core interfaces and types for TableTheory
dms
errors
Package errors defines error types and utilities for TableTheory
Package errors defines error types and utilities for TableTheory
interfaces
Package interfaces provides abstractions for AWS SDK operations to enable mocking
Package interfaces provides abstractions for AWS SDK operations to enable mocking
lease
Package lease provides a small, correctness-first DynamoDB lease/lock helper.
Package lease provides a small, correctness-first DynamoDB lease/lock helper.
marshal
Package marshal provides optimized marshaling for DynamoDB
Package marshal provides optimized marshaling for DynamoDB
mocks
Package mocks provides mock implementations for TableTheory interfaces and AWS SDK operations
Package mocks provides mock implementations for TableTheory interfaces and AWS SDK operations
model
Package model provides model registration and metadata management for TableTheory
Package model provides model registration and metadata management for TableTheory
query
Package query provides aggregate functionality for DynamoDB queries
Package query provides aggregate functionality for DynamoDB queries
releasestate
Package releasestate contains opt-in helpers for release-state registry records.
Package releasestate contains opt-in helpers for release-state registry records.
session
Package session provides AWS session management and DynamoDB client configuration
Package session provides AWS session management and DynamoDB client configuration
testing
Package testing provides utilities for testing applications that use TableTheory.
Package testing provides utilities for testing applications that use TableTheory.
testing/fakedb
Package fakedb provides a deterministic, state-backed DynamoDBAPI fake for consumer tests.
Package fakedb provides a deterministic, state-backed DynamoDBAPI fake for consumer tests.
transaction
Package transaction provides atomic transaction support for TableTheory
Package transaction provides atomic transaction support for TableTheory
typed
Package typed provides additive generic wrappers around the stable TableTheory core interfaces.
Package typed provides additive generic wrappers around the stable TableTheory core interfaces.
types
Package types provides type conversion between Go types and DynamoDB AttributeValues
Package types provides type conversion between Go types and DynamoDB AttributeValues
scripts
local/cmd/examples-local-cdk-fixtures command
Command examples-local-cdk-fixtures prepares and inspects the local state the cdk-multilang rows need: it provisions the shared demo table, the TTL evidence table and the archive bucket, enables the evidence table's real DynamoDB stream, reads an encrypted item back in its raw DynamoDB envelope form, and reads the archive object the deployed archive handler wrote to the local S3 emulator.
Command examples-local-cdk-fixtures prepares and inspects the local state the cdk-multilang rows need: it provisions the shared demo table, the TTL evidence table and the archive bucket, enables the evidence table's real DynamoDB stream, reads an encrypted item back in its raw DynamoDB envelope form, and reads the archive object the deployed archive handler wrote to the local S3 emulator.
local/cmd/examples-local-kms-key command
Command examples-local-kms-key provisions the KMS key the encryption examples use and proves the local KMS can wrap and unwrap a data key with the same EncryptionContext the framework's v2 envelope sends.
Command examples-local-kms-key provisions the KMS key the encryption examples use and proves the local KMS can wrap and unwrap a data key with the same EncryptionContext the framework's v2 envelope sends.
local/cmd/examples-local-lambda-preflight command
Command examples-local-lambda-preflight runs inside the Lambda runtime container before any example handler and proves the function environment cannot reach real AWS: every SDK endpoint resolves to the local profile's service, only the harness dummy credentials are available, each backend speaks its AWS protocol, and a real AWS hostname does not resolve.
Command examples-local-lambda-preflight runs inside the Lambda runtime container before any example handler and proves the function environment cannot reach real AWS: every SDK endpoint resolves to the local profile's service, only the harness dummy credentials are available, each backend speaks its AWS protocol, and a real AWS hostname does not resolve.
local/cmd/examples-local-payment-fixtures command
Command examples-local-payment-fixtures provisions the local DynamoDB tables the Lambda and payment examples use, seeds fixture rows through the real TableTheory models, configures a real moto S3 bucket notification and puts the reconciliation object, and reads the stored state back for harness assertions.
Command examples-local-payment-fixtures provisions the local DynamoDB tables the Lambda and payment examples use, seeds fixture rows through the real TableTheory models, configures a real moto S3 bucket notification and puts the reconciliation object, and reads the stored state back for harness assertions.
local/cmd/examples-local-preflight command
Command examples-local-preflight proves the environment the example harness hands to every child process resolves DynamoDB, KMS, STS, S3 and SQS to the checked-in local profile instead of the real AWS endpoints, that the SDK sees nothing but the harness's static dummy credentials, and that each local backend speaks its real AWS protocol.
Command examples-local-preflight proves the environment the example harness hands to every child process resolves DynamoDB, KMS, STS, S3 and SQS to the checked-in local profile instead of the real AWS endpoints, that the SDK sees nothing but the harness's static dummy credentials, and that each local backend speaks its real AWS protocol.
local/cmd/examples-local-stream-event command
Command examples-local-stream-event performs a real DynamoDB write (and, in ttl-remove mode, a real delete) and reads the resulting record from the table's DynamoDB stream with DescribeStream, GetShardIterator and GetRecords.
Command examples-local-stream-event performs a real DynamoDB write (and, in ttl-remove mode, a real delete) and reads the resulting record from the table's DynamoDB stream with DescribeStream, GetShardIterator and GetRecords.
local/internal/streams
Package streams reads DynamoDB Streams from the local profile.
Package streams reads DynamoDB Streams from the local profile.

Jump to

Keyboard shortcuts

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