Documentation
¶
Overview ¶
Package fauna provides a driver for Fauna FQL X
Index ¶
- Constants
- type Client
- type ClientConfigFn
- func AdditionalHeaders(headers map[string]string) ClientConfigFn
- func Context(ctx context.Context) ClientConfigFn
- func DefaultTypecheck(enabled bool) ClientConfigFn
- func HTTPClient(client *http.Client) ClientConfigFn
- func Linearized(enabled bool) ClientConfigFn
- func MaxAttempts(attempts int) ClientConfigFn
- func MaxBackoff(backoff time.Duration) ClientConfigFn
- func MaxContentionRetries(i int) ClientConfigFn
- func QueryTags(tags map[string]string) ClientConfigFn
- func QueryTimeout(d time.Duration) ClientConfigFn
- func URL(url string) ClientConfigFn
- type Document
- type ErrAbort
- type ErrAuthentication
- type ErrAuthorization
- type ErrConstraintFailure
- type ErrContendedTransaction
- type ErrFauna
- type ErrInvalidRequest
- type ErrNetwork
- type ErrQueryCheck
- type ErrQueryRuntime
- type ErrQueryTimeout
- type ErrServiceInternal
- type ErrServiceTimeout
- type ErrThrottling
- type Module
- type NamedDocument
- type NamedRef
- type NullDocument
- type NullNamedDocument
- type Page
- type Query
- type QueryInfo
- type QueryIterator
- type QueryOptFn
- type QuerySuccess
- type Ref
- type Stats
- type Timeouts
Examples ¶
Constants ¶
const ( // EndpointDefault constant for Fauna Production endpoint EndpointDefault = "https://db.fauna.com" // EndpointLocal constant for local (Docker) endpoint EndpointLocal = "http://localhost:8443" // EnvFaunaEndpoint environment variable for Fauna Client HTTP endpoint EnvFaunaEndpoint = "FAUNA_ENDPOINT" // EnvFaunaSecret environment variable for Fauna Client authentication EnvFaunaSecret = "FAUNA_SECRET" HeaderLastTxnTs = "X-Last-Txn-Ts" HeaderLinearized = "X-Linearized" HeaderMaxContentionRetries = "X-Max-Contention-Retries" HeaderTags = "X-Query-Tags" HeaderQueryTimeoutMs = "X-Query-Timeout-Ms" HeaderTraceparent = "Traceparent" HeaderTypecheck = "X-Typecheck" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the Fauna Client.
func NewClient ¶
func NewClient(secret string, timeouts Timeouts, configFns ...ClientConfigFn) *Client
NewClient initialize a new fauna.Client with custom settings
Example ¶
ExampleNewClient query fauna running in a local Docker instance:
docker run --rm -p 8443:8443 fauna/faunadb:latest
client := fauna.NewClient(
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
"secret",
fauna.DefaultTimeouts(),
fauna.HTTPClient(http.DefaultClient),
fauna.URL(fauna.EndpointLocal),
fauna.Context(context.Background()),
fauna.QueryTimeout(time.Minute*3),
)
query, qErr := fauna.FQL(`Math.abs(12e5)`, nil)
if qErr != nil {
log.Fatalf("query failed: %s", qErr)
}
res, queryErr := client.Query(query)
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
var result float32
if err := res.Unmarshal(&result); err != nil {
log.Fatalf("%s", queryErr)
}
fmt.Printf("%0.f", result)
Output: 1200000
func NewDefaultClient ¶
NewDefaultClient initialize a fauna.Client with recommend default settings
Example ¶
ExampleNewDefaultClient query fauna running in a local Docker instance:
docker run --rm -p 8443:8443 fauna/faunadb:latest
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
query, qErr := fauna.FQL(`Math.abs(12e5)`, nil)
if qErr != nil {
log.Fatalf("query failed: %s", qErr)
}
res, queryErr := client.Query(query)
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
var result float32
if err := res.Unmarshal(&result); err != nil {
log.Fatalf("%s", err)
}
fmt.Printf("%0.f", result)
Output: 1200000
func (*Client) GetLastTxnTime ¶
GetLastTxnTime gets the last txn timestamp seen by the fauna.Client
func (*Client) Paginate ¶ added in v0.7.0
func (c *Client) Paginate(fql *Query, opts ...QueryOptFn) *QueryIterator
Paginate invoke fql with pagination optionally set multiple QueryOptFn
Example ¶
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
collectionName := "pagination_sandbox"
// create a collection
deleteQuery, deleteQueryErr := fauna.FQL(`Collection.byName(${coll})?.delete()`, map[string]any{"coll": collectionName})
if deleteQueryErr != nil {
log.Fatalf("failed to construct delete query")
}
if _, deleteErr := client.Query(deleteQuery); deleteErr != nil {
log.Fatalf("failed to clean up collection: %t", deleteErr)
}
createQuery, createQueryErr := fauna.FQL(`Collection.create({ name: ${name} })`, map[string]any{"name": collectionName})
if createQueryErr != nil {
log.Fatalf("failed to construct create query")
}
if _, createErr := client.Query(createQuery); createErr != nil {
log.Fatalf("failed to create collection: %t", createErr)
}
// seed collection
collectionModule := &fauna.Module{Name: collectionName}
// update Output comment at the bottom if you change this
totalTestItems := 20
for i := 0; i < totalTestItems; i++ {
createCollectionQuery, createItemQueryErr := fauna.FQL(`${mod}.create({ value: ${i} })`, map[string]any{
"mod": collectionModule,
"i": i,
})
if createItemQueryErr != nil {
log.Fatalf("failed to construct create item query: %t", createItemQueryErr)
}
if _, createItemErr := client.Query(createCollectionQuery); createItemErr != nil {
log.Fatalf("failed to create seed item: %t", createItemErr)
}
}
// paginate collection
paginationQuery, paginationQueryErr := fauna.FQL(`${mod}.all()`, map[string]any{"mod": collectionModule})
if paginationQueryErr != nil {
log.Fatalf("failed to construct pagination query: %t", paginationQueryErr)
}
type Item struct {
Value int `fauna:"value"`
}
var items []Item
paginator := client.Paginate(paginationQuery)
for {
page, pageErr := paginator.Next()
if pageErr != nil {
log.Fatalf("pagination failed: %t", pageErr)
}
var pageItems []Item
if marshalErr := page.Unmarshal(&pageItems); marshalErr != nil {
log.Fatalf("failed to unmarshal page: %t", marshalErr)
}
items = append(items, pageItems...)
if !paginator.HasNext() {
break
}
}
fmt.Printf("%d", len(items))
Output: 20
func (*Client) Query ¶
func (c *Client) Query(fql *Query, opts ...QueryOptFn) (*QuerySuccess, error)
Query invoke fql optionally set multiple QueryOptFn
func (*Client) SetLastTxnTime ¶
SetLastTxnTime update the last txn time for the fauna.Client This has no effect if earlier than stored timestamp.
WARNING: This should be used only when coordinating timestamps across multiple clients. Moving the timestamp arbitrarily forward into the future will cause transactions to stall.
func (*Client) String ¶
String fulfil Stringify interface for the fauna.Client only returns the URL to prevent logging potentially sensitive headers.
type ClientConfigFn ¶
type ClientConfigFn func(*Client)
ClientConfigFn configuration options for the fauna.Client
func AdditionalHeaders ¶
func AdditionalHeaders(headers map[string]string) ClientConfigFn
AdditionalHeaders specify headers for the fauna.Client
func Context ¶
func Context(ctx context.Context) ClientConfigFn
Context specify the context to be used for the fauna.Client
func DefaultTypecheck ¶
func DefaultTypecheck(enabled bool) ClientConfigFn
DefaultTypecheck set header on the fauna.Client Enable or disable typechecking of the query before evaluation. If not set, Fauna will use the value of the "typechecked" flag on the database configuration.
func HTTPClient ¶
func HTTPClient(client *http.Client) ClientConfigFn
HTTPClient set the http.Client for the fauna.Client
func Linearized ¶
func Linearized(enabled bool) ClientConfigFn
Linearized set header on the fauna.Client If true, unconditionally run the query as strictly serialized. This affects read-only transactions. Transactions which write will always be strictly serialized.
func MaxAttempts ¶ added in v1.1.0
func MaxAttempts(attempts int) ClientConfigFn
MaxAttempts sets the maximum number of times the fauna.Client will attempt to run a query, retrying if appropriate.
func MaxBackoff ¶ added in v1.1.0
func MaxBackoff(backoff time.Duration) ClientConfigFn
MaxBackoff sets the maximum duration the fauna.Client will wait before retrying.
func MaxContentionRetries ¶
func MaxContentionRetries(i int) ClientConfigFn
MaxContentionRetries set header on the fauna.Client The max number of times to retry the query if contention is encountered.
func QueryTags ¶
func QueryTags(tags map[string]string) ClientConfigFn
QueryTags sets header on the fauna.Client Set tags to associate with the query. See logging
func QueryTimeout ¶
func QueryTimeout(d time.Duration) ClientConfigFn
QueryTimeout set header on the fauna.Client
type ErrAbort ¶ added in v0.6.0
type ErrAbort struct {
*ErrFauna
}
An ErrAbort is returned when the `abort()` function was called, which will return custom abort data in the error response.
type ErrAuthentication ¶ added in v0.1.1
type ErrAuthentication struct {
*ErrFauna
}
An ErrAuthentication is returned when Fauna is unable to authenticate the request due to an invalid or missing authentication token.
type ErrAuthorization ¶ added in v0.1.1
type ErrAuthorization struct {
*ErrFauna
}
An ErrAuthorization is returned when a query attempts to access data the secret is not allowed to access.
type ErrConstraintFailure ¶ added in v0.6.0
type ErrContendedTransaction ¶ added in v0.7.0
type ErrContendedTransaction struct {
*ErrFauna
}
ErrContendedTransaction is returned when a transaction is aborted due to concurrent modification.
type ErrFauna ¶ added in v0.1.1
type ErrFauna struct {
*QueryInfo
StatusCode int `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Abort any `json:"abort"`
ConstraintFailures []ErrConstraintFailure `json:"constraint_failures"`
}
An ErrFauna is the base of all errors and provides the underlying `code`, `message`, and any fauna.QueryInfo.
type ErrInvalidRequest ¶ added in v0.6.0
type ErrInvalidRequest struct {
*ErrFauna
}
An ErrInvalidRequest is returned when the request body is not valid JSON, or does not conform to the API specification
type ErrNetwork ¶ added in v0.1.1
type ErrNetwork error
An ErrNetwork is returned when an unknown error is encountered when attempting to send a request to Fauna.
type ErrQueryCheck ¶ added in v0.1.1
type ErrQueryCheck struct {
*ErrFauna
}
An ErrQueryCheck is returned when the query fails one or more validation checks.
type ErrQueryRuntime ¶ added in v0.1.1
type ErrQueryRuntime struct {
*ErrFauna
}
An ErrQueryRuntime is returned when the query fails due to a runtime error. The `code` field will vary based on the specific error cause.
type ErrQueryTimeout ¶ added in v0.1.1
type ErrQueryTimeout struct {
*ErrFauna
}
An ErrQueryTimeout is returned when the client specified timeout was exceeded, but the timeout was set lower than the query's expected processing time. This response is distinguished from fauna.ServiceTimeoutError by the fact that a fauna.QueryTimeoutError response is considered a successful response for the purpose of determining the service's availability.
type ErrServiceInternal ¶ added in v0.1.1
type ErrServiceInternal struct {
*ErrFauna
}
An ErrServiceInternal is returned when an unexpected error occurs.
type ErrServiceTimeout ¶ added in v0.1.1
type ErrServiceTimeout struct {
*ErrFauna
}
An ErrServiceTimeout is returned when an unexpected timeout occurs.
type ErrThrottling ¶ added in v0.1.1
type ErrThrottling struct {
*ErrFauna
}
An ErrThrottling is returned when the query exceeded some capacity limit.
type NamedDocument ¶
type NullDocument ¶ added in v0.7.0
type NullNamedDocument ¶ added in v0.7.0
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query represents a query to be sent to Fauna.
func FQL ¶
FQL creates a fauna.Query from an FQL string and set of arguments.
args are optional. If provided their keys must match with `${name}` sigils in the query. FQL `${value} + 1` must have an argument called "value" in the args map.
The values of args can be any type, including fauna.Query to allow for query composition.
Example ¶
ExampleFQL query fauna running in a local Docker instance:
docker run --rm -p 8443:8443 fauna/faunadb:latest
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
query, fqlErr := fauna.FQL(`2 + 2`, nil)
if fqlErr != nil {
log.Fatalf("query failed: %s", fqlErr)
}
res, queryErr := client.Query(query)
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
fmt.Printf("%d", res.Data)
Output: 4
Example (Arguments) ¶
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
query, fqlErr := fauna.FQL(`${num} + 2`, map[string]any{"num": 2})
if fqlErr != nil {
log.Fatalf("query failed: %s", fqlErr)
}
res, queryErr := client.Query(query)
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
fmt.Printf("%d", res.Data)
Output: 4
Example (Composed) ¶
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
type myObj struct {
Value int `fauna:"value"`
}
arg := &myObj{Value: 4}
// Build a query to pull a value from some object. This could be document already
// in Fauna.
getValQuery, gvqErr := fauna.FQL(`${obj}["value"]`, map[string]any{"obj": arg})
if gvqErr != nil {
log.Fatalf("query failed: %s", gvqErr)
}
// Compose the value query with a multiplier to multiply the value we pulled by
// some number.
query, fqlErr := fauna.FQL("${multiplier} * ${value}", map[string]any{
"value": getValQuery,
"multiplier": 4,
})
if fqlErr != nil {
log.Fatalf("query failed: %s", fqlErr)
}
res, queryErr := client.Query(query, fauna.Typecheck(true))
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
fmt.Printf("%+v", res.Data)
Output: 16
Example (Structs) ¶
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
type myObj struct {
Value int `fauna:"value"`
}
arg := &myObj{Value: 2}
query, fqlErr := fauna.FQL(`${obj}["value"] + 2`, map[string]any{"obj": arg})
if fqlErr != nil {
log.Fatalf("query failed: %s", fqlErr)
}
res, queryErr := client.Query(query)
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
fmt.Printf("%d", res.Data)
Output: 4
Example (Unmarshal) ¶
// IMPORTANT: just for the purpose of example, don't actually hardcode secret
_ = os.Setenv(fauna.EnvFaunaSecret, "secret")
_ = os.Setenv(fauna.EnvFaunaEndpoint, fauna.EndpointLocal)
client, clientErr := fauna.NewDefaultClient()
if clientErr != nil {
log.Fatalf("client should have been initialized: %s", clientErr)
}
type myObj struct {
Value int `fauna:"value"`
}
// Mock out an object that looks like our struct `myObj`.
query, fqlErr := fauna.FQL(`{"value": 4}`, nil)
if fqlErr != nil {
log.Fatalf("query failed: %s", fqlErr)
}
res, queryErr := client.Query(query)
if queryErr != nil {
log.Fatalf("request failed: %s", queryErr)
}
// Unmarshal the resulting object into a `myObj` object.
var result myObj
if err := res.Unmarshal(&result); err != nil {
log.Fatalf("unmarshal failed: %s", queryErr)
}
fmt.Printf("%+v", result)
Output: {Value:4}
type QueryInfo ¶
type QueryInfo struct {
// TxnTime is the transaction commit time in micros since epoch. Used to
// populate the x-last-txn-ts request header in order to get a consistent
// prefix RYOW guarantee.
TxnTime int64
// SchemaVersion that was used for the query execution.
SchemaVersion int64
// Summary is a comprehensive, human readable summary of any errors, warnings
// and/or logs returned from the query.
Summary string
// QueryTags is the value of [fauna.Tags] provided with the query, if there
// were any.
QueryTags map[string]string
// Stats provides access to stats generated by the query.
Stats *Stats
}
QueryInfo provides access to information about the query.
type QueryIterator ¶ added in v0.7.0
type QueryIterator struct {
// contains filtered or unexported fields
}
QueryIterator is a fauna.Client iterator for paginated queries
func (*QueryIterator) HasNext ¶ added in v0.7.0
func (q *QueryIterator) HasNext() bool
HasNext returns whether there is another page of results
func (*QueryIterator) Next ¶ added in v0.7.0
func (q *QueryIterator) Next() (*Page, error)
Next returns the next page of results
type QueryOptFn ¶
type QueryOptFn func(req *fqlRequest)
QueryOptFn function to set options on the Client.Query
func QueryContext ¶
func QueryContext(ctx context.Context) QueryOptFn
QueryContext set the context.Context for a single Client.Query
func Tags ¶
func Tags(tags map[string]string) QueryOptFn
Tags set the tags header on a single Client.Query
func Timeout ¶
func Timeout(dur time.Duration) QueryOptFn
Timeout set the query timeout on a single Client.Query
func Traceparent ¶
func Traceparent(id string) QueryOptFn
Traceparent sets the header on a single Client.Query
func Typecheck ¶
func Typecheck(enabled bool) QueryOptFn
Typecheck sets the header on a single Client.Query
type QuerySuccess ¶
type QuerySuccess struct {
*QueryInfo
// Data is the raw result returned by the query.
Data any
// StaticType is the query's inferred static result type, if the query was
// typechecked.
StaticType string
}
QuerySuccess is the response returned from fauna.Client.Query when the query runs successfully.
func (*QuerySuccess) Unmarshal ¶
func (r *QuerySuccess) Unmarshal(into any) error
Unmarshal will unmarshal the raw fauna.QuerySuccess.Data value into a known type provided as `into`. `into` must be a pointer to a map or struct.
type Stats ¶
type Stats struct {
// ComputeOps is the amount of Transactional Compute Ops consumed by the query.
ComputeOps int `json:"compute_ops"`
// ReadOps is the amount of Transactional Read Ops consumed by the query.
ReadOps int `json:"read_ops"`
// WriteOps is amount of Transactional Write Ops consumed by the query.
WriteOps int `json:"write_ops"`
// QueryTimeMs is the query run time in milliseconds.
QueryTimeMs int `json:"query_time_ms"`
// ContentionRetries is the number of times the transaction was retried due
// to write contention.
ContentionRetries int `json:"contention_retries"`
// StorageBytesRead is the amount of data read from storage, in bytes.
StorageBytesRead int `json:"storage_bytes_read"`
// StorageBytesWrite is the amount of data written to storage, in bytes.
StorageBytesWrite int `json:"storage_bytes_write"`
// Attempts is the number of times the client attempted to run the query.
Attempts int `json:"_"`
}
Stats provides access to stats generated by the query.
type Timeouts ¶ added in v0.8.0
type Timeouts struct {
// The timeout of each query. This controls the maximum amount of time Fauna will
// execute your query before marking it failed.
QueryTimeout time.Duration
// Time beyond `QueryTimeout` at which the client will abort a request if it has not received a response.
// The default is 5s, which should account for network latency for most clients. The value must be greater
// than zero. The closer to zero the value is, the more likely the client is to abort the request before the
// server can report a legitimate response or error.
ClientBufferTimeout time.Duration
// ConnectionTimeout amount of time to wait for the connection to complete.
ConnectionTimeout time.Duration
// IdleConnectionTimeout is the maximum amount of time an idle (keep-alive) connection will
// remain idle before closing itself.
IdleConnectionTimeout time.Duration
}
func DefaultTimeouts ¶ added in v0.8.0
func DefaultTimeouts() Timeouts
DefaultTimeouts suggested timeouts for the default fauna.Client