Documentation
¶
Index ¶
- func GetMetadataValue(ctx context.Context, key string) any
- func SetIsInternal(ctx context.Context) context.Context
- func SetMetadataValues(ctx context.Context, data map[string]any) context.Context
- type Action
- type AggregateFunction
- type Authz
- type AuthzEffect
- type AuthzRule
- type CDC
- type CollectionSchema
- type CommitCmd
- type CreateCmd
- type DBOpt
- type Database
- type DeleteCmd
- type DocBuilder
- type Document
- func (d *Document) Bytes() []byte
- func (d *Document) Clone() *Document
- func (d *Document) Del(field string) error
- func (d *Document) DelAll(fields ...string) error
- func (d *Document) Diff(before *Document) []JSONFieldOp
- func (d *Document) Encode(w io.Writer) error
- func (d *Document) Exists(field string) bool
- func (d *Document) FieldPaths() []string
- func (d *Document) Get(field string) any
- func (d *Document) GetArray(field string) []any
- func (d *Document) GetBool(field string) bool
- func (d *Document) GetFloat(field string) float64
- func (d *Document) GetString(field string) string
- func (d *Document) GetTime(field string) time.Time
- func (d *Document) MarshalJSON() ([]byte, error)
- func (d *Document) Merge(with *Document) error
- func (d *Document) MergeJoin(with *Document, alias string) error
- func (d *Document) Overwrite(values map[string]any) error
- func (d *Document) Scan(value any) error
- func (d *Document) Set(field string, val any) error
- func (d *Document) SetAll(values map[string]any) error
- func (d *Document) String() string
- func (d *Document) UnmarshalJSON(bytes []byte) error
- func (d *Document) Valid() bool
- func (d *Document) Value() map[string]any
- func (d *Document) Where(wheres []Where) (bool, error)
- type Documents
- func (documents Documents) Filter(predicate func(document *Document, i int) bool) Documents
- func (documents Documents) ForEach(fn func(next *Document, i int))
- func (documents Documents) Map(mapper func(t *Document, i int) *Document) Documents
- func (documents Documents) Slice(start, end int) Documents
- type EventType
- type Explain
- type ForEachFunc
- type ForEachOpts
- type ForeignKey
- type GetCmd
- type Index
- type JSONFieldOp
- type JSONOp
- type Join
- type Optimizer
- type OrderBy
- type OrderByDirection
- type Page
- type PageStats
- type PropertyIndex
- type Query
- type QueryBuilder
- func (q *QueryBuilder) GroupBy(groups ...string) *QueryBuilder
- func (q *QueryBuilder) Having(where ...Where) *QueryBuilder
- func (q *QueryBuilder) Join(join ...Join) *QueryBuilder
- func (q *QueryBuilder) Limit(limit int) *QueryBuilder
- func (q *QueryBuilder) OrderBy(ob ...OrderBy) *QueryBuilder
- func (q *QueryBuilder) Page(page int) *QueryBuilder
- func (q *QueryBuilder) Query() Query
- func (q *QueryBuilder) Select(fields ...Select) *QueryBuilder
- func (q *QueryBuilder) Where(where ...Where) *QueryBuilder
- type QueryCmd
- type RollbackCmd
- type SchemaProperty
- type Select
- type SetCmd
- type Transport
- type Trigger
- type Tx
- type TxCmd
- type TxFunc
- type TxResponse
- type Txn
- type UpdateCmd
- type Where
- type WhereOp
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetMetadataValue ¶ added in v0.2.0
GetMetadataValue gets a metadata value from the context if it exists
func SetIsInternal ¶ added in v0.2.1
SetIsInternal sets a context value to indicate that the request is internal (it should only be used to bypass things like authorization, validation, etc)
Types ¶
type Action ¶
type Action string
Action is an action that causes a mutation to the database
const ( // CreateAction creates a document CreateAction Action = "create" // SetAction sets a document's values in place SetAction Action = "set" // UpdateAction updates a set of fields on a document UpdateAction Action = "update" // DeleteAction deletes a document DeleteAction Action = "delete" // QueryAction queries documents QueryAction Action = "query" // ConfigureAction configures a collection of documents ConfigureAction Action = "configure" // ChangeStreamAction creates a change stream ChangeStreamAction Action = "changeStream" )
type AggregateFunction ¶
type AggregateFunction string
AggregateFunction is an agggregate function applied to a list of documents
const AggregateFunctionCount AggregateFunction = "count"
AggregateFunctionCount gets the count of a set of documents
const AggregateFunctionMax AggregateFunction = "max"
AggregateFunctionMax gets the max value in a set of documents
const AggregateFunctionMin AggregateFunction = "min"
AggregateFunctionMin gets the min value in a set of documents
const AggregateFunctionSum AggregateFunction = "sum"
AggregateFunctionSum gets the sum of values in a set of documents
type Authz ¶ added in v0.2.0
type Authz struct {
Rules []AuthzRule `json:"rules" validate:"min=1,required"`
}
Authz is a serializable authz object which represents the x-authorization section of a collection schema
type AuthzEffect ¶ added in v0.2.0
type AuthzEffect string
AuthzEffect is an effect of an authz rule
const ( Allow AuthzEffect = "allow" Deny AuthzEffect = "deny" )
type AuthzRule ¶ added in v0.2.0
type AuthzRule struct {
Effect AuthzEffect `json:"effect" validate:"required"`
Action []Action `json:"action" validate:"min=1,required"`
Match string `json:"match" validate:"required"`
}
AuthzRule
type CDC ¶
type CDC struct {
// ID is the unique id of the cdc
ID string `json:"_id" validate:"required"`
// Collection is the collection the change was applied to
Collection string `json:"collection" validate:"required"`
// Action is the action applied to the document
Action Action `json:"action" validate:"required,oneof='create' 'update' 'delete' 'set'"`
// DocumentID is the ID of the document that was changed
DocumentID string `json:"documentID" validate:"required"`
// Diff is the difference between the previous and new version of the document
Diff []JSONFieldOp `json:"diff,omitempty"`
// Timestamp is the nanosecond timestamp the cdc was created at
Timestamp int64 `json:"timestamp" validate:"required"`
// Metadata is the context metadata when the change was made
Metadata *Document `json:"metadata" validate:"required"`
}
CDC is a change data capture object used for tracking changes to documents over time
type CollectionSchema ¶
type CollectionSchema interface {
// Collection is the collection name
Collection() string
// ValidateDocument validates the input document against the collection's JSON schema
ValidateDocument(ctx context.Context, doc *Document) error
// Indexing returns a copy the schemas indexing
Indexing() map[string]Index
// PrimaryIndex returns the collection's primary index
PrimaryIndex() Index
// PrimaryKey returns the collection's primary key
PrimaryKey() string
// GetPrimaryKey gets the document's primary key
GetPrimaryKey(doc *Document) string
// SetPrimaryKey sets the document's primary key
SetPrimaryKey(doc *Document, id string) error
// RequireQueryIndex returns whether the collection requires that queries are appropriately indexed
RequireQueryIndex() bool
// Properties returns a map of the schema's properties
Properties() map[string]SchemaProperty
// PropertyPaths returns a flattened map of the schema's properties - nested properties will be keyed in dot notation
PropertyPaths() map[string]SchemaProperty
// Triggers returns a map of triggers keyed by name that are assigned to the collection
Triggers() []Trigger
// IsReadOnly returns whether the collection is read only
IsReadOnly() bool
// Authz returns the collection's authz if it exists
Authz() Authz
// MarshalYAML returns the collection schema as yaml bytes
MarshalYAML() ([]byte, error)
// UnmarshalYAML refreshes the collection schema with the given json bytes
UnmarshalYAML(bytes []byte) error
json.Marshaler
json.Unmarshaler
}
CollectionSchema is a database collection configuration
type CreateCmd ¶ added in v0.1.4
type CreateCmd struct {
// Collection is the collection the document belongs to
Collection string `json:"collection" validate:"required"`
// Document is the document to set
Document *Document `json:"document" validate:"required"`
}
CreateCmd is a serializable create command
type DBOpt ¶
type DBOpt func(d *defaultDB)
DBOpt is an option for configuring a collection
func WithJavascriptOverrides ¶
WithJavascriptOverrides adds global variables or methods to the embedded javascript vm(s)
func WithOptimizer ¶
WithOptimizer overrides the default query optimizer provider
type Database ¶
type Database interface {
// Collections returns a list of collection names that are registered in the collection
Collections(ctx context.Context) []string
// Configure overwrites a single database collection configuration. It will create the collection if it does not exist
// and will update the collection if it does exist. The collection will be created/updated with the given schema and indexing.
Configure(ctx context.Context, collectionSchemaBytes []byte) error
// GetSchema gets a collection schema by name (if it exists)
GetSchema(ctx context.Context, collection string) CollectionSchema
// HasCollection reports whether a collection exists in the database
HasCollection(ctx context.Context, collection string) bool
// Tx executes the given function against a new transaction.
// if the function returns an error, all changes will be rolled back.
// otherwise, the changes will be commited to the database
Tx(ctx context.Context, opts kv.TxOpts, fn TxFunc) error
// NewTx returns a new transaction. a transaction must call Commit method in order to persist changes
NewTx(opts kv.TxOpts) (Txn, error)
// ChangeStream streams changes to documents in the given collection. CDC Persistence must be enabled to use this method.
ChangeStream(ctx context.Context, collection string, fn func(cdc CDC) (bool, error)) error
// Get gets a single document by id
Get(ctx context.Context, collection, id string) (*Document, error)
// ForEach scans the optimal index for a collection's documents passing its filters.
// results will not be ordered unless an index supporting the order by(s) was found by the optimizer
// Query should be used when order is more important than performance/resource-usage
ForEach(ctx context.Context, collection string, opts ForEachOpts, fn ForEachFunc) (Explain, error)
// Query queries a list of documents
Query(ctx context.Context, collection string, query Query) (Page, error)
// Get gets 1-many document by id(s)
BatchGet(ctx context.Context, collection string, ids []string) (Documents, error)
// RunScript executes a javascript function within the script
// The following global variables will be injected: 'db' - a database instance, 'ctx' - the context passed to RunScript, and 'params' - the params passed to RunScript
RunScript(ctx context.Context, function string, script string, params map[string]any) (any, error)
// RawKV returns the database key value provider - it should be used with caution and only when standard database functionality is insufficient.
RawKV() kv.DB
// Serve serves the database over the given transport
Serve(ctx context.Context, t Transport) error
// NewDoc creates a new document builder instance
NewDoc() *DocBuilder
// Close closes the database
Close(ctx context.Context) error
}
Database is a NoSQL database built on top of key value storage
type DeleteCmd ¶ added in v0.1.4
type DeleteCmd struct {
// Collection is the collection the document belongs to
Collection string `json:"collection" validate:"required"`
// ID is the unique id of the document
ID string `json:"id" validate:"required"`
}
DeleteCmd is a serializable delete command
type DocBuilder ¶ added in v0.1.0
type DocBuilder struct {
// contains filtered or unexported fields
}
DocBuilder is a builder for creating a document
func (*DocBuilder) Doc ¶ added in v0.1.0
func (b *DocBuilder) Doc() *Document
Doc returns the document
func (*DocBuilder) Err ¶ added in v0.1.0
func (b *DocBuilder) Err() error
Err returns an error if one exists
func (*DocBuilder) From ¶ added in v0.1.0
func (b *DocBuilder) From(d *Document) *DocBuilder
From creates a new document builder from the input document
func (*DocBuilder) Set ¶ added in v0.1.0
func (b *DocBuilder) Set(values map[string]any) *DocBuilder
DocBuilder sets the key value pairs on the document
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is a concurrency safe JSON document
func ExtractMetadata ¶ added in v0.2.0
ExtractMetadata extracts metadata from the context and returns it
func NewDocumentFrom ¶
NewDocumentFrom creates a new document from the given value - the value must be json compatible
Example ¶
package main
import (
"fmt"
"github.com/autom8ter/myjson"
)
func main() {
doc, _ := myjson.NewDocumentFrom(map[string]any{
"name": "autom8ter",
})
fmt.Println(doc.String())
}
Output: {"name":"autom8ter"}
func NewDocumentFromBytes ¶
NewDocumentFromBytes creates a new document from the given json bytes
func (*Document) Del ¶
Del deletes a field from the document. SJSON systax is supported For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (*Document) DelAll ¶
DelAll deletes a field from the document. SJSON systax is supported For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (*Document) Diff ¶
func (d *Document) Diff(before *Document) []JSONFieldOp
Diff calculates a json diff between the document and the input document
func (*Document) Exists ¶
Exists returns true if the fieldPath has a value in the json document. Exists has GJSON syntax support // For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) FieldPaths ¶
FieldPaths returns the paths to fields & nested fields in dot notation format
func (*Document) Get ¶
Get gets a field on the document. Get has GJSON syntax support For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) GetArray ¶
GetArray gets an array field on the document. Get has GJSON syntax support For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) GetBool ¶
GetBool gets a bool field value on the document. GetBool has GJSON syntax support For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) GetFloat ¶
GetFloat gets a float64 field value on the document. GetFloat has GJSON syntax support For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) GetString ¶
GetString gets a string field value on the document. GetString has GJSON syntax support For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) GetTime ¶
GetTime gets a time.Time field value on the document. GetTime has GJSON syntax support For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (*Document) MarshalJSON ¶
MarshalJSON satisfies the json Marshaler interface
func (*Document) MergeJoin ¶
MergeJoin merges the document with the input document with each key from the input document prefixed with the given alias
func (*Document) Overwrite ¶
Overwrite resets the document with the given values. SJSON systax is supported For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (*Document) Set ¶
Set sets a field on the document. Set has SJSON syntax support (dot notation) For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (*Document) SetAll ¶
SetAll sets all fields on the document. SJSON systax is supported For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (*Document) UnmarshalJSON ¶
UnmarshalJSON satisfies the json Unmarshaler interface
type Documents ¶
type Documents []*Document
Documents is an array of documents
type Explain ¶ added in v0.1.0
type Explain struct {
// Collection
Collection string `json:"collection"`
// Index is the index the query optimizer chose
Index Index `json:"index"`
// MatchedFields are the fields that matched the index
MatchedFields []string `json:"matched_fields"`
// MatchedValues are the values that were matched to the index
MatchedValues map[string]any `json:"matched_values,omitempty"`
// SeekFields indicates that the given fields will be seeked
SeekFields []string `json:"seek,omitempty"`
// SeekValues are the values to seek
SeekValues map[string]any `json:"seek_values,omitempty"`
// Reverse indicates that the index should be scanned in reverse
Reverse bool `json:"reverse,omitempty"`
}
Explain is the optimizer's output for a query
type ForEachFunc ¶
ForEachFunc returns false to stop scanning and an error if one occurred
type ForEachOpts ¶
type ForEachOpts struct {
Where []Where `json:"where,omitempty"`
Join []Join `json:"join,omitempty"`
}
ForEachOpts are options when executing db.ForEach against a collection
type ForeignKey ¶
type ForeignKey struct {
// Collection is the foreign collection
Collection string `json:"collection"`
// Cascade indicates that the document should be deleted when the foreign key is deleted
Cascade bool `json:"cascade"`
}
ForeignKey is a reference/relationship to another collection by primary key
type GetCmd ¶ added in v0.1.4
type GetCmd struct {
// Collection is the collection the document belongs to
Collection string `json:"collection" validate:"required"`
// ID is the unique id of the document
ID string `json:"id" validate:"required"`
}
GetCmd is a serializable get command
type Index ¶
type Index struct {
// Name is the indexes unique name in the collection
Name string `json:"name" validate:"required,min=1"`
// Fields to index - order matters
Fields []string `json:"fields" validate:"required,min=1"`
// Unique indicates that it's a unique index which will enforce uniqueness
Unique bool `json:"unique"`
// Unique indicates that it's a primary index
Primary bool `json:"primary"`
// ForeignKey indecates that it's an index for a foreign key
ForeignKey *ForeignKey `json:"foreign_key,omitempty"`
}
Index is a database index used to optimize queries against a collection
type JSONFieldOp ¶
type JSONFieldOp struct {
// Path is the path to the field within the document
Path string `json:"path"`
// Op is the operation applied
Op JSONOp `json:"op"`
// Value is the value applied with the operation
Value any `json:"value,omitempty"`
// BeforeValue is the value before the operation was applied
BeforeValue any `json:"beforeValue,omitempty"`
}
JSONFieldOp is an operation against a JSON field
type Join ¶
type Join struct {
Collection string `json:"collection" validate:"required"`
On []Where `json:"on" validate:"required,min=1"`
As string `json:"as,omitempty"`
}
Join is a join against another collection
type Optimizer ¶
type Optimizer interface {
// Optimize selects the optimal index to use based on the given where clauses
Optimize(c CollectionSchema, where []Where) (Explain, error)
}
Optimizer selects the best index from a set of indexes based on where clauses
type OrderBy ¶
type OrderBy struct {
Direction OrderByDirection `json:"direction" validate:"oneof='desc' 'asc'"`
Field string `json:"field"`
}
OrderBy indicates how to order results returned from a query
type OrderByDirection ¶
type OrderByDirection string
OrderByDirection is the direction of an order by clause
const OrderByDirectionAsc OrderByDirection = "asc"
OrderByDirectionAsc is ascending order
const OrderByDirectionDesc OrderByDirection = "desc"
OrderByDirectionDesc is descending order
type Page ¶
type Page struct {
// Documents are the documents that make up the page
Documents Documents `json:"documents"`
// Next page
NextPage int `json:"next_page"`
// Document count
Count int `json:"count"`
// Stats are statistics collected from a document aggregation query
Stats PageStats `json:"stats,omitempty"`
}
Page is a page of documents
type PageStats ¶
type PageStats struct {
// ExecutionTime is the execution time to get the page
ExecutionTime time.Duration `json:"execution_time,omitempty"`
// Explain is the optimizer's output for the query that returned a page
Explain *Explain `json:"explain,omitempty"`
}
PageStats are statistics collected from a query returning a page
type PropertyIndex ¶
type PropertyIndex struct {
AdditionalFields []string `json:"additional_fields,omitempty"`
}
PropertyIndex is an index attached to a json schema property
type Query ¶
type Query struct {
// Select selects fields - at least 1 select is required.
// 1 select with Field: * gets all fields
Select []Select `json:"select" validate:"min=1,required"`
// Join joins the results to another collection
Join []Join `json:"join,omitempty" validate:"dive"`
// Where filters results. The optimizer will select the appropriate index based on where clauses
Where []Where `json:"where,omitempty" validate:"dive"`
// GroupBy groups results by a given list of fields
GroupBy []string `json:"groupBy,omitempty"`
// Page is the page of results - it is used with Limit for pagination
Page int `json:"page" validate:"min=0"`
// Limit is used to limit the number of results returned
Limit int `json:"limit,omitempty" validate:"min=0"`
// OrderBy orders results
OrderBy []OrderBy `json:"orderBy,omitempty" validate:"dive"`
// Having applies a final filter after any aggregations have occured
Having []Where `json:"having,omitempty" validate:"dive"`
}
Query is a query against the NOSQL database
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder is a utility for creating queries via chainable methods
func Q ¶
func Q() *QueryBuilder
Q creates a new QueryBuilder instance
Example ¶
package main
import (
"fmt"
"github.com/autom8ter/myjson"
)
func main() {
query := myjson.Q().
Select(myjson.Select{
Field: "*",
}).
Where(myjson.Where{
Field: "description",
Op: myjson.WhereOpContains,
Value: "testing",
}).Query()
fmt.Println(query.String())
}
Output: {"select":[{"field":"*"}],"where":[{"field":"description","op":"contains","value":"testing"}],"page":0}
func (*QueryBuilder) GroupBy ¶
func (q *QueryBuilder) GroupBy(groups ...string) *QueryBuilder
GroupBy adds the GroupBy clause(s) to the query
func (*QueryBuilder) Having ¶
func (q *QueryBuilder) Having(where ...Where) *QueryBuilder
Having adds the Where clause(s) to the query - they execute after all other clauses have resolved
func (*QueryBuilder) Join ¶
func (q *QueryBuilder) Join(join ...Join) *QueryBuilder
Join adds the Join clause(s) to the query
func (*QueryBuilder) Limit ¶
func (q *QueryBuilder) Limit(limit int) *QueryBuilder
Limit adds the Limit clause(s) to the query
func (*QueryBuilder) OrderBy ¶
func (q *QueryBuilder) OrderBy(ob ...OrderBy) *QueryBuilder
OrderBy adds the OrderBy clause(s) to the query
func (*QueryBuilder) Page ¶
func (q *QueryBuilder) Page(page int) *QueryBuilder
Page adds the Page clause(s) to the query which controls pagination results
func (*QueryBuilder) Select ¶
func (q *QueryBuilder) Select(fields ...Select) *QueryBuilder
Select adds the SelectFiel(s) to the query
func (*QueryBuilder) Where ¶
func (q *QueryBuilder) Where(where ...Where) *QueryBuilder
Where adds the Where clause(s) to the query
type QueryCmd ¶ added in v0.1.4
type QueryCmd struct {
// Collection is the collection the document belongs to
Collection string `json:"collection" validate:"required"`
// Query is the query to execute
Query Query `json:"query,omitempty"`
}
QueryCmd is a serializable query command
type RollbackCmd ¶ added in v0.2.0
type RollbackCmd struct{}
RollbackCmd is a serializable rollback command
type SchemaProperty ¶
type SchemaProperty struct {
// Primary indicates the property is the primary key
Primary bool `json:"x-primary,omitempty"`
// Name is the name of the property
Name string `json:"name" validate:"required"`
// Description is the description of the property
Description string `json:"description,omitempty"`
// Type is the type of the property
Type string `json:"type" validate:"required"`
// Path is a dot notation path to the property
Path string `json:"path" validate:"required"`
// Unique indicates the field value is unique
Unique bool `json:"x-unique,omitempty"`
// ForeignKey is a relationship to another collection
ForeignKey *ForeignKey `json:"x-foreign,omitempty"`
// Index is a secondary index mapped by index name
Index map[string]PropertyIndex `json:"x-index,omitempty"`
// Properties are object properties
Properties map[string]SchemaProperty `json:"properties,omitempty"`
}
SchemaProperty is a property belonging to a JSON Schema
type Select ¶
type Select struct {
Aggregate AggregateFunction `json:"aggregate,omitempty" validate:"oneof='count' 'max' 'min' 'sum'"`
As string `json:"as,omitempty"`
Field string `json:"field"`
}
Select is a field to select
type SetCmd ¶ added in v0.1.4
type SetCmd struct {
// Collection is the collection the document belongs to
Collection string `json:"collection" validate:"required"`
// Document is the document to set
Document *Document `json:"document" validate:"required"`
}
SetCmd is a serializable set command
type Transport ¶ added in v0.1.0
Transport serves the database over a network (optional for integration with different transport mechanisms)
type Trigger ¶
type Trigger struct {
// Name is the unique name of the trigger
Name string `json:"name" validate:"required"`
// Order is used to sort triggers into an array where the lower order #s are executed before larger order #s
Order int `json:"order"`
// Events is an array of events that the trigger executes on
Events []EventType `json:"events" validate:"min=1,required"`
// Script is the javascript script to execute
Script string `json:"script" validate:"required"`
}
Trigger is a javasript function executed after a database event occurs
type Tx ¶
type Tx interface {
// Cmd is a generic command that can be used to execute any command against the database
Cmd(ctx context.Context, cmd TxCmd) TxResponse
// Query executes a query against the database
Query(ctx context.Context, collection string, query Query) (Page, error)
// Get returns a document by id
Get(ctx context.Context, collection string, id string) (*Document, error)
// Create creates a new document - if the documents primary key is unset, it will be set as a sortable unique id
Create(ctx context.Context, collection string, document *Document) (string, error)
// Update updates a value in the database
Update(ctx context.Context, collection, id string, document map[string]any) error
// Set sets the specified key/value in the database
Set(ctx context.Context, collection string, document *Document) error
// Delete deletes the specified key from the database
Delete(ctx context.Context, collection string, id string) error
// ForEach scans the optimal index for a collection's documents passing its filters.
// results will not be ordered unless an index supporting the order by(s) was found by the optimizer
// Query should be used when order is more important than performance/resource-usage
ForEach(ctx context.Context, collection string, opts ForEachOpts, fn ForEachFunc) (Explain, error)
// DB returns the transactions underlying database
DB() Database
}
Tx is a database transaction interface - it holds the primary methods used while using a transaction
type TxCmd ¶ added in v0.1.4
type TxCmd struct {
// Create is a create command
Create *CreateCmd `json:"create,omitempty"`
// Get is a get command
Get *GetCmd `json:"get,omitempty"`
// Set is a set command
Set *SetCmd `json:"set,omitempty"`
// Update is an update command
Update *UpdateCmd `json:"update,omitempty"`
// Delete is a delete command
Delete *DeleteCmd `json:"delete,omitempty"`
// Query is a query command
Query *QueryCmd `json:"query,omitempty"`
// Commit is a commit command - it ends the transaction
Commit *CommitCmd `json:"commit,omitempty"`
// Rollback is a rollback command - it ends the transaction
Rollback *RollbackCmd `json:"rollback,omitempty"`
}
TxCmd is a serializable transaction command
type TxFunc ¶
TxFunc is a function executed against a transaction - if the function returns an error, all changes will be rolled back. Otherwise, the changes will be commited to the database
type TxResponse ¶ added in v0.1.4
type TxResponse struct {
// Create is a create response - it returns the created document
Create *Document `json:"create,omitempty"`
// Get is a get response - it returns the document from the get request (if it exists)
Get *Document `json:"get,omitempty"`
// Set is a set response - it returns the document after the set was applied
Set *Document `json:"set,omitempty"`
// Update is an update response - it contains the document after the update was applied
Update *Document `json:"update,omitempty"`
// Delete is an empty delete response
Delete *struct{} `json:"delete,omitempty"`
// Query is a query response - it contains the documents returned from the query
Query *Page `json:"page,omitempty"`
// Commit is an empty commit response
Commit *struct{} `json:"commit,omitempty"`
// Rollback is an empty rollback response
Rollback *struct{} `json:"rollback,omitempty"`
// Error is an error response if an error was encountered
Error *errors.Error `json:"error,omitempty"`
}
TxResponse is a serializable transaction response
type Txn ¶
type Txn interface {
// Commit commits the transaction to the database
Commit(ctx context.Context) error
// Rollback rollsback all changes made to the datbase
Rollback(ctx context.Context) error
// Close closes the transaction - it should be deferred after
Close(ctx context.Context)
Tx
}
Txn is a database transaction interface - it holds the methods used while using a transaction + commit,rollback,and close functionality
type UpdateCmd ¶ added in v0.1.4
type UpdateCmd struct {
// Collection is the collection the document belongs to
Collection string `json:"collection" validate:"required"`
// ID is the unique id of the document
ID string `json:"id" validate:"required"`
// Update is the set of fields to set
Update map[string]any `json:"update,omitempty"`
}
UpdateCmd is a serializable update command
type Where ¶
type Where struct {
Field string `json:"field" validate:"required"`
Op WhereOp `json:"op" validate:"oneof='eq' 'neq' 'gt' 'gte' 'lt' 'lte' 'contains' 'containsAny' 'containsAll' 'in'"`
Value interface{} `json:"value" validate:"required"`
}
Where is a filter against documents returned from a query
type WhereOp ¶
type WhereOp string
WhereOp is an operation belonging to a where clause
const WhereOpContains WhereOp = "contains"
WhereOpContains checks if a string field contains subtext
const WhereOpContainsAll WhereOp = "containsAll"
WhereOpContainsAll is a check whether an array contains all of the given array values
const WhereOpContainsAny WhereOp = "containsAny"
WhereOpContainsAny is a check whether an array contains any of the given array values
const WhereOpEq WhereOp = "eq"
WhereOpEq is an equality check.
const WhereOpGt WhereOp = "gt"
WhereOpGt is a check whether a value is greater than another
const WhereOpGte WhereOp = "gte"
WhereOpGte is a check whether a value is greater than or equal to another
const WhereOpHasPrefix WhereOp = "hasPrefix"
WhereOpHasPrefix is a check whether a string value has a prefix
const WhereOpHasSuffix WhereOp = "hasSuffix"
WhereOpHasSuffix is a check whether a string value has a suffix
const WhereOpIn WhereOp = "in"
WhereOpIn is a check whether a value is one of a list of values
const WhereOpLt WhereOp = "lt"
WhereOpLt is a check whether a value is less than another
const WhereOpLte WhereOp = "lte"
WhereOpLte is a check whether a values is less than or equal to another
const WhereOpNeq WhereOp = "neq"
WhereOpNeq is a non-equality check
const WhereOpRegex WhereOp = "regex"
WhereOpRegex is a check whtether a string value matches a regex expression