API Reference

Complete reference for the alosdbclient Go client library — every type, interface, and method.

Connect

Establish a connection to an ALOS DB server using functional options:

func Connect(addr string, opts ...ClientOption) (DatabaseInterface, error)

Connects to the server at addr (e.g. "localhost:6900"), authenticates, and returns a DatabaseInterface. The connection uses TCP with MessagePack serialization and AES-256-GCM encryption.

go
db, err := alosdbclient.Connect("localhost:6900",
    alosdbclient.WithCredentials("admin", "secret"),
    alosdbclient.WithDatabase("myapp"),
)
if err != nil {
    log.Fatal(err)
}
defer db.Close()

Alternatively, use ConnectWithConfig for struct-based configuration:

func ConnectWithConfig(cfg *ClientConfig) (DatabaseInterface, error)
go
cfg := alosdbclient.DefaultClientConfig("localhost:6900")
cfg.Username = "admin"
cfg.Password = "secret"

db, err := alosdbclient.ConnectWithConfig(cfg)

Document

type Document map[string]interface{}

The core data type — a schemaless map of string keys to arbitrary values, equivalent to a JSON object. All CRUD operations accept and return Document.

GetID()

func (d Document) GetID() string

Returns the _id field as a string, or "" if not set. Convenience helper for accessing the auto-generated document ID.

go
doc := alosdbclient.Document{
    "name":    "Alice",
    "age":     30,
    "active":  true,
    "tags":    []string{"admin", "user"},
    "address": alosdbclient.Document{
        "city":  "Sydney",
        "state": "NSW",
    },
}

DatabaseInterface

Returned by Connect(). Provides access to collections, transactions, stats, and import/export.

Collection(name string) CollectionInterface

Collection(name string) CollectionInterface

Returns a handle to the named collection. Collections are created on first use — no explicit creation needed.

ListCollections() []string

ListCollections() []string

Returns the names of all collections in the database.

GetStats() map[string]interface{}

GetStats() map[string]interface{}

Returns server statistics including memory usage, document counts, and uptime.

DBExists(name string) (bool, error)

DBExists(name string) (bool, error)

Returns true if the named database exists on the server (loaded or discovered on disk).

go
exists, _ := db.DBExists("analytics")
if exists {
    fmt.Println("database exists")
}

Close() error

Close() error

Flushes pending batches and closes the connection. Always defer this after Connect().

BeginTransaction() TransactionInterface

BeginTransaction() TransactionInterface

Starts a manual transaction. You must call Commit() or Rollback() explicitly. Prefer Transaction() for automatic lifecycle management.

Transaction(fn func(tx TransactionInterface) error) error

Transaction(fn func(tx TransactionInterface) error) error

Executes fn inside a transaction. Commits if fn returns nil; rolls back on error. This is the recommended pattern.

go
err := db.Transaction(func(tx alosdbclient.TransactionInterface) error {
    users := tx.Collection("users")
    _, err := users.InsertOne(alosdbclient.Document{"name": "Alice"})
    return err  // commit on nil, rollback on error
})

Export(w io.Writer, collections []string) error

Export(w io.Writer, collections []string) error

Exports the specified collections (or all if nil) to the writer in ALOS DB binary format.

Import(r io.Reader) (*ImportResult, error)

Import(r io.Reader) (*ImportResult, error)

Imports data from the reader. Returns an ImportResult with total and error counts.

CollectionInterface

Returned by db.Collection("name"). All CRUD, aggregation, and index operations are on this interface.

InsertOne(doc Document) (string, error)

InsertOne(doc Document) (string, error)

Inserts a single document. Returns the auto-generated _id. ~14.3 µs/op (70K ops/sec remote), ~446 ns/op (2.2M ops/sec embedded).

InsertMany(docs []Document) ([]string, error)

InsertMany(docs []Document) ([]string, error)

Inserts multiple documents in a single batch. Returns all generated IDs. ~91 µs per 50 docs (548K docs/sec remote), ~109 µs per 100 docs (917K docs/sec embedded).

InsertManyRaw(rawDataMap map[string][]byte) error

InsertManyRaw(rawDataMap map[string][]byte) error

Inserts pre-serialized documents by ID. Use for bulk imports where you already have the raw data.

FindOne(query Document) (Document, error)

FindOne(query Document) (Document, error)

Returns the first document matching the query. ~11.1 µs/op (90K ops/sec remote), ~149 ns/op by ID (6.7M ops/sec embedded).

go
// By ID (fastest)
doc, _ := coll.FindOne(alosdbclient.Document{"_id": "abc123"})

// By field
doc, _ = coll.FindOne(alosdbclient.Document{"email": "alice@example.com"})

// With operators
doc, _ = coll.FindOne(alosdbclient.Document{
    "age": alosdbclient.Document{"$gte": 21},
})

FindOneReadonly(query Document) (Document, error)

FindOneReadonly(query Document) (Document, error)

Same as FindOne but returns a read-only document. Faster because it skips the copy — do not modify the returned document.

FindMany(query Document) ([]Document, error)

FindMany(query Document) ([]Document, error)

Returns all documents matching the query. Supports all query operators. See Queries.

FindManyReadonly(query Document) ([]Document, error)

FindManyReadonly(query Document) ([]Document, error)

Read-only variant of FindMany. Do not modify the returned documents.

UpdateOne(filter Document, update Document) error

UpdateOne(filter Document, update Document) error

Updates the first document matching filter. Use $set, $add, $sub, $inc, $push, $pushAll, $pull, $unset, or $rename for partial updates, or pass a full document for replacement. ~18.3 µs/op (55K ops/sec remote), ~239 ns/op (4.2M ops/sec embedded).

go
// Partial update with $set
coll.UpdateOne(
    alosdbclient.Document{"_id": id},
    alosdbclient.Document{"$set": alosdbclient.Document{"age": 31}},
)

// Numeric operations
coll.UpdateOne(
    alosdbclient.Document{"_id": id},
    alosdbclient.Document{"$inc": alosdbclient.Document{"counter": 1}},
)

// Array operations
coll.UpdateOne(
    alosdbclient.Document{"_id": id},
    alosdbclient.Document{"$push": alosdbclient.Document{"tags": "new"}},
)

// Full replacement
coll.UpdateOne(
    alosdbclient.Document{"_id": id},
    alosdbclient.Document{"name": "Alice", "age": 31},
)

UpdateMany(filter Document, update Document) (int, error)

UpdateMany(filter Document, update Document) (int, error)

Updates all matching documents. Returns the count of modified documents.

DeleteOne(filter Document) error

DeleteOne(filter Document) error

Deletes the first document matching filter. ~20.4 µs/op (49K ops/sec remote), ~1,108 ns/op (903K ops/sec embedded).

DeleteMany(filter Document) (int, error)

DeleteMany(filter Document) (int, error)

Deletes all matching documents. Returns the count of deleted documents.

UpsertOne(filter Document, update Document) (bool, error)

UpsertOne(filter Document, update Document) (bool, error)

Inserts the document if no match is found, otherwise updates. Returns true if a new document was inserted.

UpsertMany(filter Document, update Document) (int, int, error)

UpsertMany(filter Document, update Document) (int, int, error)

Bulk upsert. Returns (inserted count, updated count, error).

Aggregate(pipeline []Document) ([]Document, error)

Aggregate(pipeline []Document) ([]Document, error)

Executes an aggregation pipeline. Supports $match, $group, $sort, $project, $limit. See Aggregation.

go
results, _ := coll.Aggregate([]alosdbclient.Document{
    {"$match": alosdbclient.Document{"active": true}},
    {"$group": alosdbclient.Document{
        "_id":   "$department",
        "count": alosdbclient.Document{"$sum": 1},
    }},
    {"$sort": alosdbclient.Document{"count": -1}},
})

Count() int64

Count() int64

Returns the total number of documents. ~62.7 µs/op (16K ops/sec remote), sub-2ns embedded (~608M ops/sec) — reads an atomic counter.

Drop()

Drop()

Drops the entire collection and all its data. This is irreversible.

GetName() string

GetName() string

Returns the collection name.

HasCollection() (bool, error)

HasCollection() (bool, error)

Returns true if the collection exists in the current database. Checks both in-memory and persisted collections.

go
coll := db.Collection("users")
exists, _ := coll.HasCollection()
if exists {
    fmt.Println("users collection exists")
}

TransactionInterface

Returned by db.BeginTransaction() or passed to the closure in db.Transaction(fn). Provides ACID isolation using MVCC snapshots.

Collection(name string) TxCollectionInterface

Collection(name string) TxCollectionInterface

Returns a transaction-scoped collection handle. All reads and writes through this handle participate in the transaction.

Commit() error

Commit() error

Atomically commits all operations in the transaction. Only needed for manual transactions — the closure pattern auto-commits.

Rollback() error

Rollback() error

Discards all operations in the transaction.

GetID() string

GetID() string

Returns the unique identifier for this transaction.

TxCollectionInterface

Returned by tx.Collection("name"). A subset of CollectionInterface that operates within a transaction.

Method Signature Description
FindOne (query Document) (Document, error) Reads with snapshot isolation
InsertOne (doc Document) (string, error) Insert within transaction
UpdateOne (filter, update Document) error Update within transaction
DeleteOne (filter Document) error Delete within transaction
go
db.Transaction(func(tx alosdbclient.TransactionInterface) error {
    users := tx.Collection("users")

    // Read, write, update, delete — all within this transaction
    user, _ := users.FindOne(alosdbclient.Document{"name": "Alice"})
    users.UpdateOne(
        alosdbclient.Document{"_id": user["_id"]},
        alosdbclient.Document{"$set": alosdbclient.Document{"verified": true}},
    )
    return nil
})

Client Options

Functional options passed to Connect():

Option Default Description
WithCredentials(user, pass string) Server authentication credentials (required)
WithDatabase(name string) "default" Target database for all operations
WithTimeout(d time.Duration) 15s Per-request timeout
WithBatchSize(n int) 100 Max requests per batch
WithFlushInterval(d time.Duration) 1ms Max wait before flushing a batch
go
db, _ := alosdbclient.Connect("localhost:6900",
    alosdbclient.WithCredentials("admin", "secret"),
    alosdbclient.WithDatabase("myapp"),
    alosdbclient.WithTimeout(5 * time.Second),
    alosdbclient.WithBatchSize(50),
    alosdbclient.WithFlushInterval(2 * time.Millisecond),
)

ClientConfig

Struct-based alternative to functional options, used with ConnectWithConfig():

go
type ClientConfig struct {
    ServerAddr     string        // TCP address (e.g. "localhost:6900")
    PoolSize       int           // Connection pool size (default: 10)
    Username       string        // Auth username
    Password       string        // Auth password
    RequestTimeout time.Duration  // Per-request timeout (default: 15s)
    FireAndForget  bool          // Don't wait for server ACK
}

DefaultClientConfig(addr string) *ClientConfig

func DefaultClientConfig(addr string) *ClientConfig

Returns a ClientConfig with sensible defaults: pool size 10, 15s timeout.

ImportResult

go
type ImportResult struct {
    Total  int64  // Total documents imported
    Errors int64  // Number of failed imports
}

Returned by db.Import(). Check Errors to see if any documents failed to import.

ESC