dynamitedb

package module
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 22 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

banner

Simple ST database engine running entirely on S3.

go get github.com/megakuul/dynamitedb
// define schemas via KeyField and DataField:
type OrderItem struct {
	OrderId     dynamitedb.KeyField          `pk:"order" cbor:"-"`
	ItemId      dynamitedb.KeyField          `sk:"item" cbor:"-"`
    ETag        dynamitedb.ETagField         `etag:"true" cbor:"-"`
	Hidden      dynamitedb.DataField[bool]   `cbor:"hidden,omitempty"`
	Name        dynamitedb.DataField[string] `cbor:"name,omitempty"`
	Description dynamitedb.DataField[string] `cbor:"description,omitempty"`
	Count       dynamitedb.DataField[int]    `cbor:"count,omitempty"`
	Price       dynamitedb.DataField[int]    `cbor:"price,omitempty"`
}

// do something with it:
func example() error {
	// create a bucket client to e.g. RustFS
	bucket, err := dynamitedb.New(context.TODO(), "http://127.0.0.1:9000", "test",
		dynamitedb.WithCredentials("rustfsadmin", "rustfsadmin"),
		dynamitedb.WithRegion("us-east-1"),
	)
	if err != nil {
		return err
	}

	err = dynamitedb.Create(context.TODO(), bucket, &OrderItem{
		OrderId:     dynamitedb.Key("1"), // order 1
		ItemId:      dynamitedb.Key("3"), // item 3 on order 1
		Name:        dynamitedb.Set("CNC Machine"),
		Description: dynamitedb.Set("The flagship of our store"),
		Count:       dynamitedb.Set(1),
		Price:       dynamitedb.Set(1_000_000),
		Hidden:      dynamitedb.Set(true),
	})
	if err != nil {
		if errors.Is(err, dynamitedb.ErrAlreadyExists) {
			// do something special
		}
		return err
	}

	err = dynamitedb.Update(context.TODO(), bucket, &OrderItem{
		OrderId: dynamitedb.Key("1"),
		ItemId:  dynamitedb.Key("3"),
		Count:   dynamitedb.Multiply(2),
		Price:   dynamitedb.Increment(1_000),
		Hidden:  dynamitedb.Toggle(),
	})
	if err != nil {
		return err
	}

	item, err := dynamitedb.Get(context.TODO(), bucket, &OrderItem{
		OrderId: dynamitedb.Key("1"),  // order 1
		ItemId:  dynamitedb.Key("3"),  // item 3 on order 1
		Hidden:  dynamitedb.Eq(false), // must be active
	})
	if err != nil {
		if errors.Is(err, dynamitedb.ErrNotFound) {
			// do something special
		}
		return err
	}

	fmt.Println(item.Name.Value())  // CNC Machine
	fmt.Println(item.Count.Value()) // 2
	fmt.Println(item.Price.Value()) // 1_001_000
	return nil
}

Schemas

DynamiteDB schemas are defined as basic go structs using KeyField and DataField interfaces.

Serialization is done transparently by tagging fields with cbor:"" tags 💡

[!TIP] It is recommended to always use omitempty. Otherwise fields that are explicitly unset on deserialization and cannot be checked with e.g. dynamitedb.Eq("").

KeyFields

KeyFields are only used to define the ST partition and sort key (for ST concept see concept).

Use the tag pk and sk to define their respective names. The sort key is optional.

type OrderItem struct {
    OrderId dynamitedb.KeyField `pk:"order" cbor:"-"` // equivalent to a dynamodb pk ORDER#<id>
    ItemId  dynamitedb.KeyField `sk:"item" cbor:"-"`  // equivalent to a dynamodb sk ITEM#<id>
}

ETagField

ETagField is automatically populated if you retrieve data and can be set on updates to ensure the object didn't change in the meantime.

deliveryNote, err := dynamitedb.Get(ctx, bucket, &DeliveryNote{
    DeliveryNoteID: dynamitedb.Key("019ffc9b-6bdb-7983-a78f-4b98f55ea7ef"),
})
if err != nil {
    return err
}

time.Sleep(time.Hour)

err = dynamitedb.Delete(ctx, bucket, &DeliveryNote{
    DeliveryNoteID: dynamitedb.Key(deliveryNote.DeliveryNoteID.Value()),
    ETag:           deliveryNote.ETag,
})
if err != nil {
    if errors.Is(err, ErrConcurrencyConflict) {
        // this happens if someone changed the document since you called Get.
    }
    return err
}

DataFields

DataFields are used for mutable data. Because serialization is handled transparently by the cbor marshaller you can also just add other fields to your object, however, those fields will become static and cannot be changed/filtered after creation!

type OrderItem struct {
    OrderId  dynamitedb.KeyField `pk:"order" cbor:"-"`
    ItemId   dynamitedb.KeyField `sk:"item" cbor:"-"`
    StaticId uuid.UUID           `cbor:"static_id,omitempty"` // <- this is allowed but immutable and non-filterable
}

Nested datafields in structs are also allowed:

type Description struct {
    Title   dynamitedb.DataField[string] `cbor:"title,omitempty"`
    Tooltip dynamitedb.DataField[string] `cbor:"tooltip,omitempty"`
    Text    dynamitedb.DataField[string] `cbor:"text,omitempty"`
}

type OrderItem struct {
    OrderId     dynamitedb.KeyField            `pk:"order" cbor:"-"`
    ItemId      dynamitedb.KeyField            `sk:"item" cbor:"-"`
    Description Description                    `cbor:"description,omitempty"` // <- this is allowed
    Invalid     []dynamitedb.DataField[string] `cbor:"invalid,omitempty"`     // <- this is NOT allowed
    Valid       dynamitedb.DataField[[]Custom] `cbor:"valid,omitempty"`
}

Operators

For data retrieval and manipulation there are two different types of "operators": filter and update.

[!TIP] DynamiteDB treats inserts (Create/Put) and updates (Update) exactly the same. Under the hood inserts just default initialize the item first and then apply the update operators.

Operators are designed to write readable queries, updates and inserts.

If you need more complex checks you can use CustomFilter and CustomUpdate:

dynamitedb.Get(context.TODO(), bucket, &OrderItem{
    Price: dynamitedb.CustomFilter(func(price int) bool {
        return value%2 == 0
    }), // check if price is even
})

(I'm open to suggestions for introducing new operators for common use cases.)

All operators are always designed to be read from left to right:

dynamitedb.Get(context.TODO(), bucket, &OrderItem{
    OrderId:    dynamitedb.Key("1"),
    ItemId:     dynamitedb.Key("3"),
    Price:      dynamitedb.GreaterThan(1337),  // database price is greater than 1337
    Expiration: dynamitedb.Before(time.Now()), // expiration is before now
})

[!WARNING]
Using filter operators on update calls like Create, Put, Update, etc will panic. Same thing for update operators on filter calls like Get, Query, etc.

dynamitedb.Get(context.TODO(), bucket, &OrderItem{
    OrderId: dynamitedb.Key("1"),
    ItemId:  dynamitedb.Key("3"),
    Hidden:  dynamitedb.Set(false), // <- this is incorrect usage on Get() therefore it will panic
})

[!NOTE]
All operators contain comments describing whether they are for filtering or updating.

Errors

DynamiteDB intentionally hides the underlying S3 errors so they are not relied upon and not part of the public API.

Instead, it provides its own set of sentinel errors in errors which can be used to check for certain conditions of the request.

Concept

DynamiteDB is based on a simplified version of the SingleTable data schema often used in DynamoDB.

Data is organized in objects which are identified by:

  • Partition Key (PK): Defines root object type and value e.g. "user/187".
  • Sort Key (SK): Defines child object type and value of root e.g. "order/69".

Notice that this effectively just supports one to many relationships. Other relations must be modelled by denormalizing data!

[!TIP]
Unlike DynamoDB, DynamiteDB supports lexically sorted partition keys (you can just omit the SK for the base model).

[!WARNING]
DynamiteDB only supports lexical ASCENDING sorting!

While DynamiteDB is schemaless, the coding pattern effectively enforces a client side data model.

Testing

DynamiteDB provides unit tests for important internal reflection functions (like update, filter and serialization).

In addition there are integration tests for all operations in the test/integration/ directory.

Backend Support

DynamiteDB requires a proper S3 compatible backend that supports Conditional Locking.

Some operational backend inspiration:

[!WARNING] The Garage s3 project cannot be used since they do not support conditional locking!

Speed Notice

While properly designed DynamiteDB schemas scale virtually forever, it will have a base latency dictated by the S3 backend. Since S3 uses randomized data, the total overhead (S3 + DynamiteDB) will also always be higher compared to classic databases like Postgres.

[!NOTE]
Since performance is not a priority, I decided to also sacrifice go performance in favor of usability (using reflection heavy operations).

Documentation

Overview

Package dynamitedb provides an embedded singletable database engine running on s3.

Index

Constants

This section is empty.

Variables

View Source
var (
	// the specified object was not found
	ErrNotFound = errors.New("not found")
	// the specified object was found but the filter blocked it
	ErrFilterMismatch = errors.New("filter mismatch")
	// the object you want to insert does already exist
	ErrAlreadyExists = errors.New("already exists")
	// optimistic locking failure (operation aborted because another writer changed object mid transaction)
	ErrConcurrencyConflict = errors.New("optimistic lock failed")
)

external error API to catch specific conditions.

Functions

func Add

func Add[T time.Time](operand time.Duration) *addUpdate[T]

Add adds the provided duration to the database time. This is an update operator.

func After

func After[T time.Time](operand T) *afterFilter[T]

After checks if the database value is after the specified time. This is a filter operator.

func Append

func Append[T any](items ...T) *appendUpdate[T]

Append appends the items to the previous slice. This is an update operator.

func Before

func Before[T time.Time](operand T) *beforeFilter[T]

Before checks if the database value is before the specified time. This is a filter operator.

func Contains

func Contains[T comparable](operands ...T) *containsFilter[T]

Contains checks if the slice contains all of the operands. This is a filter operator.

func Create

func Create[T any](ctx context.Context, bucket *Bucket, model *T, opts ...Option) error

Create inserts the provided structure to the database if not exists.

func CustomFilter

func CustomFilter[T any](check func(databaseValue T) bool) *customFilter[T]

CustomFilter allows you to perform a custom filter check on the field. This is a filter operator.

func CustomUpdate

func CustomUpdate[T any](update func(databaseValue T) (updatedValue T)) *customUpdate[T]

CustomUpdate allows you to perform a custom update action on the field. This is an update operator.

func Delete added in v0.1.0

func Delete[T any](ctx context.Context, bucket *Bucket, filter *T) error

Delete removes the specified object from database. If the object does not exist this becomes a noop returning nil.

func Emplace

func Emplace[K comparable, V any](operand map[K]V) *emplaceUpdate[K, V]

Emplace updates the previous map with the provided new kv pairs. This is an update operator.

func Eq

func Eq[T any](operand T) *eqFilter[T]

Eq checks for an exact match with the operand. For slices and map this enforces a deep equal state. This is a filter operator.

func Get

func Get[T any](ctx context.Context, bucket *Bucket, filter *T) (*T, error)

Get fetches a single entry from database based on the filter. This operation performs no ListObject call and is more efficient but only works with exact key matches.

func GreaterOrEqThan

func GreaterOrEqThan[T int | float64 | time.Duration](operand T) *greaterOrEqThanFilter[T]

GreaterOrEqThan compares exactly what it says. This is a filter operator.

func GreaterThan

func GreaterThan[T int | float64 | time.Duration](operand T) *greaterThanFilter[T]

GreaterThan compares exactly what it says. This is a filter operator.

func Has

func Has[K, V comparable](key K, value V) *hasFilter[K, V]

Has checks if the map contains the specified key value pair. This is a filter operator.

func In

func In[T any](operands ...T) inFilter[T]

In checks if the database value is inside the provided list. Functionally equivalent to Eq but just with an operand for loop. This is a filter operator.

func Includes

func Includes[T string](operand string) *includesFilter[T]

Includes checks if the string contains the operand. This is a filter operator.

func Increment

func Increment[T int | float64 | time.Duration](operand T) *incrementUpdate[T]

Increment increments the value with operand (can be positive or negative). This is an update operator.

func Key

func Key(id string) *key

Key performs an exact match on the specified key id. Since keys are immutable this can be used for query and data fields.

func KeyPrefix

func KeyPrefix(prefix string) *beginsWithQuery

KeyPrefix reads all entries with the specified prefix. Using KeyPrefix on PK and SK converts the PK to an exact match.

func LessOrEqThan

func LessOrEqThan[T int | float64 | time.Duration](operand T) *lessOrEqThanFilter[T]

LessOrEqThan compares exactly what it says. This is a filter operator.

func LessThan

func LessThan[T int | float64 | time.Duration](operand T) *lessThanFilter[T]

LessThan compares exactly what it says. This is a filter operator.

func Multiply

func Multiply[T int | float64 | time.Duration](operand T) *multiplyUpdate[T]

Multiply multiplies the value with operand. This is an update operator.

func NotEq

func NotEq[T any](operand T) *notEqFilter[T]

NotEq is just !Eq. This is a filter operator.

func NotIn

func NotIn[T any](operands ...T) notInFilter[T]

NotIn is just !In. This is a filter operator.

func Put

func Put[T any](ctx context.Context, bucket *Bucket, model *T, opts ...Option) error

Put inserts the provided structure to the database (replaces previous data).

func Query

func Query[T any](ctx context.Context, bucket *Bucket, filter *T, opts ...Option) ([]*T, error)

Query scans (by filter) and returns all database entries indexed by key prefix matches. Caution: if key prefixes are not properly organized a query can easily rawdog scan millions of entries.

func Remove

func Remove[T comparable](items ...T) *removeUpdate[T]

Remove removes the provided items from the slice. This is an update operator.

func Set

func Set[T any](operand T) *setUpdate[T]

Set simply overwrites the previous value. This is an update operator.

func Toggle

func Toggle() *toggleUpdate[bool]

Toggle changes the value to !value. This is an update operator.

func Update

func Update[T any](ctx context.Context, bucket *Bucket, update *T, opts ...Option) error

Update changes the entry on the database (identified by PK / SK). For update operations see "Field" API on the schema. Update will modify v to represent the final state of the updated entry.

func WithExpires

func WithExpires(expires time.Time) func(*options)

WithExpires can be specified to expire the updated or inserted item at a certain point in time. Notice that this relies on the S3 lifecycle and may not be immediately removed depending on implementation.

func WithLimit

func WithLimit(limit int) func(*options)

WithLimit specifies the limit of elements to return. caution: even with a limit of 10 Query() will scan million of entries if it finds no filter matches.

func WithStartAfter

func WithStartAfter[T any](filter *T) func(*options)

WithStartAfter specifies an item from where to start querying (useful for pagination). This parameter requires a filter object with an exact key match (other filter props are not checked).

Types

type Bucket

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

func New

func New(ctx context.Context, url, bucket string, opts ...BucketOption) (*Bucket, error)

New constructs a dynamitedb bucket pointing to the provided s3 url / bucket. Credentials are loaded with aws sdk (e.g. from env AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY).

func NewFromClient

func NewFromClient(client *s3.Client, bucket string) *Bucket

NewFromClient initializes a dynamitedb bucket from an existing aws s3 sdk client.

type BucketOption

type BucketOption func(*s3.Options)

func WithCredentials

func WithCredentials(accessKey, secretKey string) BucketOption

WithCredentials specifies a static access and secret key. This disables the default AWS SDK credential process.

func WithRegion

func WithRegion(region string) BucketOption

WithRegion specifies a static bucket region. This disables the default AWS SDK region process.

type DataField

type DataField[T any] interface {

	// Value returns the raw data value.
	Value() T
	// contains filtered or unexported methods
}

DataField defines a dynamite data field (initialize with dynamitedb.Data("blub")). Use Value() to retrieve the underlying value.

type ETagField added in v0.6.0

type ETagField *string

ETagField defines a dynamite OCC etag. Tag it with `etag:"true"` to mark for automatic insertion. Multiple etags are not allowed (dynamite will simply use the first in this situation).

type KeyField

type KeyField interface {
	// Value returns the raw key value.
	Value() string
	// contains filtered or unexported methods
}

KeyField defines a dynamite index key (initialize with dynamitedb.Key("123")). Tag it with `pk:"user"` to mark partition key or `sk:"order"` for sort key. Every model requires at least the partition key (sort key is optional). Multiple partition or sort keys are not allowed (dynamite will simply use the first in this situation).

type Option

type Option func(*options)

Jump to

Keyboard shortcuts

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