The Store interface
rest.Resource.Store (rest/store.go) is the only
entry point to data that rest.Service uses — Find,
CountDocuments, FindOne, InsertMany, UpdateOne, ReplaceOne,
DeleteOne. No *mongo.Collection appears in
rest/service.go.
type Store interface {
Find(ctx context.Context, filter bson.M, skip, limit int64, sort bson.D, projection bson.M) ([]Doc, error)
CountDocuments(ctx context.Context, filter bson.M) (int64, error)
FindOne(ctx context.Context, filter bson.M, projection bson.M) (Doc, error)
InsertMany(ctx context.Context, docs []any) error
UpdateOne(ctx context.Context, filter, update bson.M) (matched int64, err error)
ReplaceOne(ctx context.Context, filter bson.M, replacement any) (matched int64, err error)
DeleteOne(ctx context.Context, filter bson.M) (deleted int64, err error)
}
The only implementation today is platform/mongodb.Store, a thin
wrapper around *mongo.Collection:
store := mongodb.NewStore(db.Collection("tags"))
res := &rest.Resource{Store: store, ...}
In a service (app.Env), use env.Store("collection-name") instead of
building the wrapper by hand.
platform/postgres.Store follows the same NewStore-wraps-a-
client, Find/FindOne/... shape, for a relational database — it just
isn't an implementation of the interface above, on purpose (see
Postgres backend for why):
store := postgres.NewStore(pool, "tags")
docs, err := store.Find(ctx, postgres.Filter{"status": "draft"}, 0, 10, nil, nil)
This Store is lower-level than what a Postgres-backed Resource
actually registers, though: restpostgres.NewAdapter wraps it (plus
a Transactor and a Schema) into a rest.Adapter — see
adapter.md for the seam Resource.Adapter is, and why
a Postgres resource sets that instead of Store.
What this decouples — and what it doesn't
This interface decides who talks to the database, not the language
the query is written in: filter/sort/update stay bson.M/bson.D,
and the errors rest checks directly (mongo.ErrNoDocuments,
mongo.IsDuplicateKeyError, timeouts) stay in the shape the Mongo driver
returns. That was an explicit decision: storage portability this round is
the interface, not the query language nor the error semantics.
In practice that means:
- Swapping the implementation of
Store(another Mongo client, an instrumentation layer, a cache) is straightforward: satisfy the interface. - Moving from Mongo to another database takes more than implementing
Store: the queries (bson.M) and the errors checked inrest/service.goassumed Mongo untilrest.Adapter(seeadapter.md) gave each backend its own implementation of that instead.platform/postgres.Store(its ownStore-shaped type, not an implementation of this interface — see Postgres backend for why) stays the low-level piecerestpostgres.postgresAdapteris built on, not something aResourceever sees directly.
Query performance today
where= (see querying.md for the filter syntax itself)
has no cost model or explain() exposed — the only lever is the index
declared for the collection it hits. Indexes are declared per service in
an indices.conf file, or added/overridden via the mongo.indexes config
key, and built at startup by platform/mongodb.EnsureIndexes
(mongo.indexes_mode: create builds them, check only logs what's
missing, off skips this entirely):
# collection keys options
settings product:1 unique
articles classification_id:1,_updated:-1 name=by_classification
articles friendly_title:1 unique sparse
sessions created:1 ttl=3600
Keys are field:direction, direction one of 1, -1, text, hashed,
2dsphere; options are unique, sparse, name=, ttl= (seconds). A
where= filter with no matching index degenerates into a full collection
scan — there is no query planner feedback surfaced today, so declaring
the right index is the whole optimization story for a Mongo-backed
resource.
This is Mongo-shaped end to end (the index directions above, ttl=, the
indices.conf format itself) and doesn't carry over to Postgres as-is:
Postgres' default index is a btree, with gin for jsonb/array/full-text
columns, gist for geometric/range types and brin for large,
naturally-ordered tables; there's no native ttl (it needs a cron job or
trigger), and EXPLAIN ANALYZE gives a real query plan where Mongo's
where= gives none. platform/postgres.EnsureIndexes/IndexSpec is the
Postgres equivalent — its own format, deliberately narrower (no TTL/
text/hashed/2dsphere), called explicitly by whoever sets up a resource's
table, same precedent as EnsureFunctions (see
adapter.md).
Explicit Postgres typed sort indexes
IndexField.Mode defaults to postgres.IndexFieldLegacy: existing JSONB DDL
is preserved, including the safe datetime helper. JSONB ordering differs from
restpostgres's typed ordering, especially for nulls and mixed JSON types.
To index the current scalar sort expression, opt in per field:
postgres.IndexSpec{
Table: "items", Name: "items_rank_typed_v1",
Fields: []postgres.IndexField{{
Field: "rank", Kind: postgres.KindInteger,
Mode: postgres.IndexFieldTypedSort,
}},
}
This produces ((doc->>'rank')::int8). Supported kinds are KindString
(text), KindInteger (int8), KindNumber (numeric) and KindBoolean
(boolean). Compound indexes and Desc are supported; the database's default
NULLS order and collation apply. Ties require an explicit sort term if a stable
page order is needed. Queries, bindings and their ordering semantics do not change.
Datetime, array/object, unknown kinds/modes, and typed indexes with Unique or
Sparse are rejected. Nested paths and meta fields are outside this mode.
Audit existing data before creation and validate future writes: invalid casts
prevent index creation and reject writes afterward. JSON null and missing keys
become SQL NULL; a numeric string may cast to the same value as a JSON number.
Each additional index costs storage and write work. Use an explicit new name;
EnsureIndexes/CREATE IF NOT EXISTS neither migrate old definitions nor prove
that an existing index with the same name has equivalent DDL.
Parameterized field names can still prevent index use with generic plans.
A typed sort index does not turn a JSONB filter into a typed index condition,
and deep offsets may still require a Sort. The manual local gate
make postgres-ha-typed-sort-test POSTGRES_HA_PORT=5540 uses real EnsureIndexes
and the SELECT captured from restpostgres.Find, checks auto/custom plans and
records generic/deep-offset controls. Artifacts are in .local/postgres-typed-sort/.
It provisions no infrastructure and is not enabled in GitHub Actions. Initial
adoption is limited to gate fixtures; no comments-api index or migration is added.
Places that still go straight to Mongo, on purpose
outbox writes to the outbox collection with a
*mongo.Collection directly — that's its own decision, separate from a
Resource's storage decision (see outbox.md). A resource
that needs a query Store doesn't expose uses Store anyway —
categories-api's GET /categories/tree
(examples/blog-apis/services/categories-api/categories.go) only needs
Find/FindOne for that — but a more complex aggregation would still
require extending the interface or dropping down to the driver.
The Mongo outbox package remains backend-specific; outboxpostgres supplies the transactional Postgres counterpart. See integration and outbox.