Skip to content
spaceport / docs
The Spaceport handbook

Documents (CouchDB ORM) — API Reference

Complete API reference for the Document system: Document, ViewDocument, View, Operation, and CouchHandler. All classes are in the spaceport.computer.memory.physical package.


Document

spaceport.computer.memory.physical.Document

The base ORM class for CouchDB. Provides get-or-create semantics, automatic JSON serialization via Jackson, revision-based conflict detection, file attachments, state tracking, and lifecycle alerts.

Static Methods

get(String id, String database)

Retrieves the document with the given _id from the specified database. If the document does not exist, it is created in CouchDB and the on document created alert is fired.

Returns are cached — subsequent calls with the same id and database return the same in-memory object.

def doc = Document.get('settings', 'my-app')

getUncached(String id, String database)

Same as get(), but always fetches a fresh copy from CouchDB, bypassing the in-memory cache. If the document does not exist, it is created.

def fresh = Document.getUncached('settings', 'my-app')

getAs(Class documentType, String id, String database)

Retrieves the document and deserializes it as the specified type. Useful when calling from Document directly rather than a subclass.

def job = Document.getAs(Job, 'job-123', 'jobs')

getNew(String database)

Creates a new document with a randomly generated UUID (hyphens removed) and returns it.

def doc = Document.getNew('articles')
// doc._id is something like "a3f8b2c1d4e5..."

getNewAs(Class documentType, String database)

Creates a new document with a random UUID and deserializes it as the specified type.

def job = Document.getNewAs(Job, 'jobs')

getIfExists(String id, String database)

Retrieves the document if it exists, or returns null if it does not. Does not create the document.

def doc = Document.getIfExists('maybe-exists', 'my-app')
if (doc) {
    // document exists
}

exists(String id, String database)

Checks whether a document exists in the database without returning the full document. Always bypasses the cache.

if (Document.exists('settings', 'my-app')) {
    // document is present
}

Persisted Properties

These properties are serialized to and from CouchDB automatically.

Property Type Description
_id String Unique identifier within the database. Managed by CouchDB.
_rev String Revision identifier. Updated on every save. Used for conflict detection.
_attachments Map CouchDB file attachments keyed by a generated file-UUID. Holds inline base64 before save() and CouchDB attachment stubs (content_type, digest, length, revpos, stub: true) afterward.
fields Map General-purpose key-value store. Intended for data exposed to HTTP requests.
cargo Cargo Built-in Cargo object. Can be mirrored with Cargo.fromDocument() for reactivity.
updates Map Timestamped log of save operations (keyed by System.currentTimeMillis()).
states Map State tracking with current value and history per key.
type def Application-defined type tag. Used in CouchDB views to filter documents by type.

Transient Properties

These properties exist only in memory and are not saved to CouchDB.

Property Type Description
database String The database this document was loaded from. Set automatically.
additionalProperties Map<String, Object> Catch-all for JSON properties not mapped to explicit fields. Managed by Jackson's @JsonAnySetter/@JsonAnyGetter.

Custom Properties

When subclassing Document, declare a customProperties list to specify which additional properties should be persisted to CouchDB. Properties not in this list (and not in the base set) will not be saved.

class Article extends Document {
    def customProperties = ['title', 'author', 'body']

    String title
    String author
    String body
}

The base set of persisted properties is: _id, _rev, type, fields, states, cargo, updates, _attachments. Everything in customProperties is added to this set during save().


Instance Methods

save()

Persists the document to CouchDB. This method is synchronized to prevent concurrent saves of the same document instance.

doc.fields.counter = 42
Operation result = doc.save()

remove()

Deletes the document from CouchDB.

Operation result = doc.remove()

close()

Removes the document from the in-memory cache. The next get() call for this document will fetch a fresh copy from CouchDB. Changes made to the object after close() will not be reflected in the cache, and any unsaved changes will be lost.

doc.close()

asType(Class type)

Supports Groovy's as operator for type coercion between Document subclasses. If the target type is compatible, returns the cached instance. If conversion is needed, evicts the cache entry and re-fetches as the new type.

def job = doc as Job

Attachment Methods

Adding an attachment (whether from a File or from base64) stages inline base64 in _attachments on the in-memory Document. You must call save() afterward to persist the attachment to CouchDB.

CouchDB strips extra keys (attname, created, details) from _attachments[fileId] when saving and keeps only its own stub fields (content_type, digest, length, revpos, stub: true). Extra keys in details are recorded in updates[timestamp].details, so store attachment IDs and any metadata you need to query or display (such as filenames or roles) in your own customProperties fields or fields.

addAttachment(File file, Map details = [:])

Attaches a local java.io.File to the document as a base64-encoded inline attachment under a generated file-UUID key, and records the operation in updates.

def fileId = doc.addAttachment(new File('/path/to/image.png'), [label: 'Profile Photo'])
doc.save()

You can also pass explicit type (MIME type) or name overrides in details:

def fileId = doc.addAttachment(tempFile, [name: 'photo.webp', type: 'image/webp'])
doc.save()

addBase64Attachment(String base64, Map details = [:])

Attaches base64-encoded data directly. Accepts either bare base64 or a base64 data URL (data:<mime>;base64,<data>, such as the value sent by HUD-Core server actions).

def fileId = doc.addBase64Attachment(encodedData, [name: 'photo.jpg', type: 'image/jpeg'])
doc.save()

getAttachment(String fileId, OutputStream o)

Retrieves an attachment from CouchDB and writes it to the provided OutputStream.

def out = new ByteArrayOutputStream()
def meta = doc.getAttachment('file-a3f8b2c1-...', out)

removeAttachment(String attachment)

Removes an attachment from the document directly in CouchDB. Updates _rev automatically on success.

doc.removeAttachment('file-a3f8b2c1-...')

State Management Methods

Documents have a built-in state machine via the states map. Each state key tracks a current value, a history of previous values, and a last-updated timestamp.

setState(String id, def value, def details)

Sets the current state for the given key, pushing the previous state into history.

doc.setState('status', 'approved', [approvedBy: 'admin'])

setState(String id, Closure closure)

Sets the state using a closure that receives the current state and returns the new state.

doc.setState('counter') { current ->
    [value: (current?.value ?: 0) + 1]
}

setState(String id, String state) / setState(String id, Number state)

Convenience overloads that set the state with an empty details map.

doc.setState('phase', 'review')
doc.setState('retryCount', 3)

getState(String key)

Returns the current state map for the given key. The map contains value and details. If the key does not exist, it is initialized with empty defaults.

def status = doc.getState('status')
println status.value   // 'approved'
println status.details // [approvedBy: 'admin']

getStateHistory(String key)

Returns the history map for the given key, keyed by timestamp. Each entry contains the previous state value and details.

def history = doc.getStateHistory('status')
history.each { timestamp, state ->
    println "At ${new Date(timestamp as Long)}: ${state}"
}

Document Features

The features list controls optional behavior. Add features in your subclass constructor or initializer.

Feature Description
DocumentFeature.CREATE_DIFF Computes a property-level diff on every save(). The diff is passed to lifecycle alerts.
DocumentFeature.KEEP_HISTORY Records a summary of changes in the updates map on every save() when diffs are non-empty.
class AuditedDocument extends Document {
    {
        features = [DocumentFeature.CREATE_DIFF, DocumentFeature.KEEP_HISTORY]
    }
}

Document Lifecycle Alerts

These alerts are fired during document operations. Listen for them with @Alert on static methods in any source module.

Alert Timing Context Map Keys
on document created After a new document is created in CouchDB id, database, doc, classType
on document save Before writing to CouchDB (synchronous) type, old, document, difference
on document saved After writing to CouchDB (asynchronous, new thread) type, old, document, difference, operation
on document modified After save or remove (synchronous) type, action ('saved' or 'removed'), old, document, difference, operation
on document remove Before deleting from CouchDB (synchronous) type, document
on document removed After deleting from CouchDB (synchronous) type, document, operation
on document conflict During save when _rev mismatch is detected type, action, document, conflicted, changes, differences
import spaceport.computer.alerts.Alert
import spaceport.computer.alerts.results.Result

class AuditLog {

    @Alert('on document saved')
    static _logSave(Result r) {
        def doc = r.context.document
        def type = r.context.type
        println "Document saved: ${doc._id} (type: ${type})"
    }
}

ViewDocument

spaceport.computer.memory.physical.ViewDocument

Wraps a CouchDB design document (_design/...) that contains JavaScript map/reduce view functions.

Static Methods

get(String id, String database)

Retrieves the design document _design/{id} from the specified database. Creates it if it does not exist.

def viewDoc = ViewDocument.get('my-views', 'articles')

getIfExists(String id, String database)

Retrieves the design document or returns null if it does not exist.


exists(String id, String database)

Checks whether the design document exists.


Instance Methods

setView(String id, def map)

Sets a view with the given map function and saves the design document immediately.

viewDoc.setView('by-author', '''
    function(doc) {
        if (doc.type === 'article') {
            emit(doc.author, null);
        }
    }
''')

setView(String id, def map, def reduce, boolean save = true)

Sets a view with both map and reduce functions. Optionally defers saving for chaining.

viewDoc.setView('count-by-author', '''
    function(doc) {
        if (doc.type === 'article') emit(doc.author, 1);
    }
''', '_count', false)

setViewIfNeeded(String id, def map)

Sets the view only if it does not already exist or if the map function has changed. This is the preferred method for view initialization at startup, since it avoids unnecessary writes to CouchDB.

ViewDocument.get('views', 'articles')
    .setViewIfNeeded('all', '''
        function(doc) {
            if (doc.type === 'article') {
                emit(doc._id, { title: doc.title });
            }
        }
    ''')

containsView(String id)

Checks whether the design document contains a view with the given name.


getView(String id)

Queries the named view and returns the results.


save()

Saves the design document to CouchDB. Synchronized.


remove()

Deletes the design document from CouchDB.


Persisted Properties

Property Type Default Description
_id def Design document ID (e.g., _design/my-views).
_rev def CouchDB revision string.
language def 'javascript' The language for view functions.
views Map [:] Map of view names to their map/reduce function definitions.

View

spaceport.computer.memory.physical.View

Represents the result of querying a CouchDB view. Contains the returned rows, total count, and offset.

Static Methods

get(String document_id, String view_id, String database)

Queries the specified view and returns the results.

def results = View.get('my-views', 'by-author', 'articles')

getWithDocuments(String document_id, String view_id, String database)

Queries the view with include_docs=true, so each row contains the full document. Use getDocuments() on the result to get Document objects.

def results = View.getWithDocuments('my-views', 'all', 'articles')
def docs = results.getDocuments()

get(String document_id, String view_id, String database, Map parameters)

Queries the view with additional CouchDB parameters (e.g., key, startkey, endkey, limit, descending, group, reduce).

def results = View.get('my-views', 'by-author', 'articles', [
    key: '"Alice"',
    limit: 10
])

getByKey(String document_id, String view_id, String database, def key, boolean includeDocs = true)

Queries the view restricted to a single key, server-side. The key is JSON-encoded automatically before being sent to CouchDB, avoiding both the manual-quoting gotcha of the Map parameters overload and the inefficient fetch-all-rows-then-filter-in-Groovy pattern.

// All sessions for one user (ids only — cheapest)
def rows = View.getByKey('views', 'by-user', 'sessions', userId, false).rows

// Same, but with the full documents attached
List<Document> docs = View.getByKey('views', 'by-user', 'sessions', userId).getDocuments()

// Compound key
def rows2 = View.getByKey('views', 'by-tenant-user', 'sessions', [tenantId, userId], false).rows

Instance Properties

Property Type Description
rows List The list of result rows. Each row is a map with id, key, and value.
total_rows Integer The total number of rows in the view (before any limit).
offset Integer The offset of the first returned row.
database def The database this view was queried from (transient, not serialized).

Instance Methods

getDocuments()

Converts the view rows into Document objects. If the view was queried with include_docs=true, deserializes the embedded documents from the row payload. Otherwise, fetches each document by _id through the document cache.

List<Document> docs = results.getDocuments()

rowsAs(Class<T> rowType)

Returns the view's rows recursively coerced into instances of the given row class. Unlike Groovy's rows as List<Row> — where the generic parameter is erased and each row stays a LinkedHashMap — this genuinely converts each row map into a typed Row, including nested typed properties such as a typed value field.

class Row {
    String key
    String id
    Value  value

    static class Value {
        String jobId
        String client
    }
}

List<Row> typed = View.get('views', 'list-jobs', 'jobs').rowsAs(Row)

Operation

spaceport.computer.memory.physical.Operation

Represents the result of a CouchDB operation (create, update, delete). Also used as a general-purpose result object throughout Spaceport.

Static Factory Methods

Operation.success(String reason = "...")

Creates a successful Operation.

def op = Operation.success('Document saved successfully.')

Operation.successWithId(String id, String reason = "...")

Creates a successful Operation with an associated document ID.


Operation.failure(String reason = "...")

Creates a failed Operation.


Operation.failureWithError(String error, String reason = "...")

Creates a failed Operation with an error code.


Instance Properties

Property Type Description
ok def true if the operation succeeded, false otherwise.
reason def A human-readable description of the outcome.
id def The document _id (on success).
rev def The new document _rev (on success).
error def An error code or identifier (on failure).

Instance Methods

wasSuccessful()

Returns true if ok == true.

def result = doc.save()
if (result.wasSuccessful()) {
    println "Saved with rev: ${result.rev}"
}

CouchHandler Configuration

CouchDB connection is configured in the .spaceport manifest file under memory cores:

memory cores:
  main:
    type: couchdb
    address: 'http://127.0.0.1:5984'

With authentication:

memory cores:
  main:
    type: couchdb
    address: 'http://127.0.0.1:5984'
    username: admin
    password: secret

If username or password are omitted but CouchDB requires authentication, Spaceport will prompt for credentials at startup.

CouchHandler Database Methods

The CouchHandler instance is accessible via Spaceport.main_memory_core and provides low-level database management:

Method Description
createDatabase(String id) Creates a new CouchDB database. Returns Operation.
createDatabaseIfNotExists(String id) Creates the database only if it does not already exist.
deleteDatabase(String id) Deletes a CouchDB database.
containsDatabase(String id) Checks whether a database exists. Returns boolean.
getAllDatabases() Returns a List<String> of all database names.
Spaceport.main_memory_core.createDatabaseIfNotExists('articles')

CouchHandler Changes Feed Methods

Method Description
getChanges(String database, Map parameters) Fetches the raw CouchDB changes feed for a database.
getNewChanges(String database, Map parameters) Fetches only changes since the last recorded sequence. Tracks sequence checkpoints automatically. Use no_store: true in parameters to skip persisting the checkpoint.

Import Summary

import spaceport.computer.memory.physical.Document
import spaceport.computer.memory.physical.ViewDocument
import spaceport.computer.memory.physical.View
import spaceport.computer.memory.physical.Operation

Make the docs better.Edit this page on GitHub