fauna

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2023 License: MPL-2.0 Imports: 22 Imported by: 0

README

The Official Golang Driver for Fauna.

Go Report Card Go Reference License

This driver can only be used with FQL v10, and is not compatible with earlier versions of FQL. To query your databases with earlier API versions, see the faunadb version.

See the Fauna Documentation for additional information how to configure and query your databases.

Supported Go Versions

Currently, the driver is tested on:

  • 1.19
  • 1.20

Using the Driver

For FQL templates, denote variables with ${} and pass variables as map[string]any to fauna.FQL(). You can escape a variable with by prepending an additional $.

Basic Usage
package main

import (
	"fmt"

	"github.com/fauna/fauna-go"
)

func main() {
	client, clientErr := fauna.NewDefaultClient()
	if clientErr != nil {
		panic(clientErr)
	}

	createColl, _ := fauna.FQL(`Collection.create({ name: "Dogs" })`, nil)
	if _, err := client.Query(createColl); err != nil {
		panic(err)
	}

	createDog, _ := fauna.FQL(`Dogs.create({ name: ${name}})`, map[string]any{"name": "Scout"})
	res, err := client.Query(createDog)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.Data.(*fauna.Document).Data["name"])
}
Using Structs
package main

import (
	"fmt"

	"github.com/fauna/fauna-go"
)

type Dog struct {
	Name string `fauna:"name"`
}

func main() {
	client, clientErr := fauna.NewDefaultClient()
	if clientErr != nil {
		panic(clientErr)
	}

	createColl, _ := fauna.FQL(`Collection.create({ name: "Dogs" })`, nil)
	if _, err := client.Query(createColl); err != nil {
		panic(err)
	}

	newDog := Dog{"Scout"}
	createDog, _ := fauna.FQL(`Dogs.create(${dog})`, map[string]any{"dog": newDog})
	res, err := client.Query(createDog)
	if err != nil {
		panic(err)
	}

	var scout Dog
	if err := res.Unmarshal(&scout); err != nil {
		panic(err)
	}

	fmt.Println(scout.Name)
}
Composing Multiple Queries
package main

import (
	"fmt"

	"github.com/fauna/fauna-go"
)

func addTwo(x int) *fauna.Query {
	q, _ := fauna.FQL(`${x} + 2`, map[string]any{"x": x})
	return q
}

func main() {
	client, clientErr := fauna.NewDefaultClient()
	if clientErr != nil {
		panic(clientErr)
	}

	q, _ := fauna.FQL(`${y} + 4`, map[string]any{"y": addTwo(2)})
	res, err := client.Query(q)
	if err != nil {
		panic(err)
	}

	data := res.Data.(int64)
	fmt.Println(data) // 8
}

Client Configuration

Timeouts
Query Timeout

The timeout of each query. This controls the maximum amount of time Fauna will execute your query before marking it failed.

package main

import "github.com/fauna/fauna-go"

func main() {
	client := fauna.NewClient("mysecret", fauna.Timeouts{QueryTimeout: 20 * time.Second})
}
Client Buffer Timeout

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.

package main

import "github.com/fauna/fauna-go"

func main() {
	client := fauna.NewClient("mysecret", fauna.Timeouts{ClientBufferTimeout: 20 * time.Second})
}
Connection Timeout

The amount of time to wait for the connection to complete.

package main

import "github.com/fauna/fauna-go"

func main() {
	client := fauna.NewClient("mysecret", fauna.Timeouts{ConnectionTimeout: 10 * time.Second})
}
Idle Connection Timeout

The maximum amount of time an idle (keep-alive) connection will remain idle before closing itself.

package main

import "github.com/fauna/fauna-go"

func main() {
	client := fauna.NewClient("mysecret", fauna.Timeouts{IdleConnectionTimeout: 10 * time.Second})
}
Retries

By default the client will automatically retry a query if the request results in an HTTP status code 429. Retries use an exponential backoff. The maximum number of retries and maximum wait time before a retry can be configured on the client.

Maximum Attempts

The maximum number of times the client will try a query. The default is 3.

package main

import "github.com/fauna/fauna-go"

func main() {
	client := fauna.NewClient("mysecret", fauna.DefaultTimeouts(), fauna.MaxAttempts(1))
}
Maximum Backoff Time

The maximum amount of time to wait before retrying a query. Retries will use an exponential backoff up to this value. The default is 20 seconds.

package main

import (
    "time"

    "github.com/fauna/fauna-go"
)

func main() {
	client := fauna.NewClient("mysecret", fauna.DefaultTimeouts(), fauna.MaxBackoff(10 * time.Second))
}

Contributing

GitHub pull requests are very welcome.

LICENSE

Copyright 2023 Fauna, Inc.

Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at

http://mozilla.org/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Overview

Package fauna provides a driver for Fauna FQL X

Index

Examples

Constants

View Source
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

func NewDefaultClient() (*Client, error)

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

func (c *Client) GetLastTxnTime() int64

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

func (c *Client) SetLastTxnTime(txnTime time.Time)

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

func (c *Client) String() 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

func URL

func URL(url string) ClientConfigFn

URL set the fauna.Client URL

type Document

type Document struct {
	ID   string         `fauna:"id"`
	Coll *Module        `fauna:"coll"`
	TS   *time.Time     `fauna:"ts"`
	Data map[string]any `fauna:"-"`
}

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.

func (*ErrAbort) Unmarshal added in v0.8.0

func (e *ErrAbort) Unmarshal(into any) error

Unmarshal decodes the Abort property into the provided object.

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 ErrConstraintFailure struct {
	Message string `json:"message"`
	Name    string `json:"name,omitempty"`
	Paths   []any  `json:"paths,omitempty"`
}

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.

func (ErrFauna) Error added in v0.1.1

func (e ErrFauna) Error() string

Error provides the underlying error message.

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 Module

type Module struct {
	Name string
}

type NamedDocument

type NamedDocument struct {
	Name string         `fauna:"name"`
	Coll *Module        `fauna:"coll"`
	TS   *time.Time     `fauna:"ts"`
	Data map[string]any `fauna:"-"`
}

type NamedRef

type NamedRef struct {
	Name string  `fauna:"name"`
	Coll *Module `fauna:"coll"`
}

type NullDocument added in v0.7.0

type NullDocument struct {
	Ref   *Ref   `fauna:"ref"`
	Cause string `fauna:"cause"`
}

type NullNamedDocument added in v0.7.0

type NullNamedDocument struct {
	Ref   *NamedRef `fauna:"ref"`
	Cause string    `fauna:"cause"`
}

type Page

type Page struct {
	Data  []any  `fauna:"data"`
	After string `fauna:"after"`
}

func (Page) Unmarshal added in v0.7.0

func (p Page) Unmarshal(into any) error

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query represents a query to be sent to Fauna.

func FQL

func FQL(query string, args map[string]any) (*Query, error)

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 Ref

type Ref struct {
	ID   string  `fauna:"id"`
	Coll *Module `fauna:"coll"`
}

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

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL