tigris

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 9, 2023 License: Apache-2.0 Imports: 20 Imported by: 10

Documentation

Overview

Package tigris provides an interface for accessing Tigris data-platform. This is the main client package you are looking for.

Index

Examples

Constants

View Source
const DefaultBranch = "main"

Variables

View Source
var ErrNotFound = NewError(code.NotFound, "document not found")
View Source
var ErrNotTransactional = fmt.Errorf("incorrect use of non-transactional operation in a transaction context")

ErrNotTransactional returned if not transactional call is called in a transactional context.

View Source
var SchemaVersion int

Functions

This section is empty.

Types

type Client

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

Client responsible for connecting to the server and opening a database.

func NewClient

func NewClient(ctx context.Context, cfg ...*Config) (*Client, error)

NewClient creates a connection to the Tigris server.

func (*Client) Close

func (c *Client) Close() error

Close terminates client connections and release resources.

func (*Client) GetDatabase

func (c *Client) GetDatabase() *Database

GetDatabase gets the Database for this project.

func (*Client) GetSearch

func (c *Client) GetSearch() *search.Search

GetSearch gets the Search for this project.

Example
package main

import (
	"context"

	"github.com/tigrisdata/tigris-client-go/search"
	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string
	}

	c, err := tigris.NewClient(ctx, &tigris.Config{Project: "db1"})
	if err != nil {
		panic(err)
	}

	s := c.GetSearch()

	if err := s.CreateIndexes(ctx, &Coll1{}); err != nil {
		panic(err)
	}

	idx := search.GetIndex[Coll1](s)

	if _, err = idx.Create(ctx, &Coll1{"aaa"}); err != nil {
		panic(err)
	}
}
Output:

func (*Client) InitializeBranch

func (c *Client) InitializeBranch(ctx context.Context) (*driver.CreateBranchResponse, error)

InitializeBranch will create a database branch provided in config, if not existing already.

func (*Client) OpenDatabase

func (c *Client) OpenDatabase(ctx context.Context, models ...schema.Model) (*Database, error)

OpenDatabase initializes Database from given collection models. It creates Database if necessary. Creates and migrates schemas of the collections which constitutes the Database.

type Collation

type Collation struct {
	// Case is case-sensitive by default, to perform case-insensitive query override it and set
	// this to 'ci'.
	Case string
}

Collation allows you to specify string comparison rules. Default is case-sensitive.

type Collection

type Collection[T schema.Model] struct {
	// contains filtered or unexported fields
}

Collection provides an interface for documents manipulation. Such as Insert, Update, Delete, Read.

func GetCollection

func GetCollection[T schema.Model](db *Database) *Collection[T]

GetCollection returns collection object corresponding to collection model T.

func (*Collection[T]) Count

func (c *Collection[T]) Count(ctx context.Context, filter filter.Filter) (int64, error)

Count returns documents which satisfies the filter. Only field from the give fields are populated in the documents. By default, all fields are populated.

func (*Collection[T]) Delete

func (c *Collection[T]) Delete(ctx context.Context, filter filter.Filter) (*DeleteResponse, error)

Delete removes documents from the collection according to the filter.

func (*Collection[T]) DeleteAll

func (c *Collection[T]) DeleteAll(ctx context.Context) (*DeleteResponse, error)

DeleteAll removes all the documents from the collection.

func (*Collection[T]) DeleteOne

func (c *Collection[T]) DeleteOne(ctx context.Context, filter filter.Filter) (*DeleteResponse, error)

func (*Collection[T]) Describe

func (c *Collection[T]) Describe(ctx context.Context) (*DescribeCollectionResponse, error)

Describe returns information about the collection.

func (*Collection[T]) Drop

func (c *Collection[T]) Drop(ctx context.Context) error

Drop drops the collection.

func (*Collection[T]) Explain

func (c *Collection[T]) Explain(ctx context.Context, filter filter.Filter, fields *fields.Read, options *ReadOptions) (*ExplainResponse, error)

Explain describes the given query execution plan.

func (*Collection[T]) Insert

func (c *Collection[T]) Insert(ctx context.Context, docs ...*T) (*InsertResponse, error)

Insert inserts documents into the collection. Returns an error if the documents with the same primary key exists already.

func (*Collection[T]) InsertOrReplace

func (c *Collection[T]) InsertOrReplace(ctx context.Context, docs ...*T) (*InsertOrReplaceResponse, error)

InsertOrReplace inserts new documents and in the case of duplicate key replaces existing documents with the new document.

func (*Collection[T]) Read

func (c *Collection[T]) Read(ctx context.Context, filter filter.Filter, fields ...*fields.Read) (*Iterator[T], error)

Read returns documents which satisfies the filter. Only field from the give fields are populated in the documents. By default, all fields are populated.

func (*Collection[T]) ReadAll

func (c *Collection[T]) ReadAll(ctx context.Context, fields ...*fields.Read) (*Iterator[T], error)

ReadAll returns Iterator which iterates over all the documents in the collection.

func (*Collection[T]) ReadOne

func (c *Collection[T]) ReadOne(ctx context.Context, filter filter.Filter, fields ...*fields.Read) (*T, error)

ReadOne reads one document from the collection satisfying the filter.

func (*Collection[T]) ReadWithOptions

func (c *Collection[T]) ReadWithOptions(ctx context.Context, filter filter.Filter, fields *fields.Read, options *ReadOptions) (*Iterator[T], error)

ReadWithOptions returns specific fields of the documents according to the filter. It allows further configure returned documents by providing options:

Limit - only returned first "Limit" documents from the result
Skip - start returning documents after skipping "Skip" documents from the result

func (*Collection[T]) Search

func (c *Collection[T]) Search(ctx context.Context, req *search.Request) (*SearchIterator[T], error)

Search returns Iterator which iterates over matched documents in the collection.

func (*Collection[T]) Update

func (c *Collection[T]) Update(ctx context.Context, filter filter.Filter, update *fields.Update) (*UpdateResponse, error)

Update partially updates documents based on the provided filter and provided document mutation.

func (*Collection[T]) UpdateOne

func (c *Collection[T]) UpdateOne(ctx context.Context, filter filter.Filter, update *fields.Update) (*UpdateResponse, error)

UpdateOne partially updates first document matching the filter.

type Config

type Config struct {
	TLS          *tls.Config `json:"tls,omitempty"`
	ClientID     string      `json:"client_id,omitempty"`
	ClientSecret string      `json:"client_secret,omitempty"`
	Token        string      `json:"token,omitempty"`
	URL          string      `json:"url,omitempty"`
	Protocol     string      `json:"protocol,omitempty"`
	Project      string      `json:"project,omitempty"`
	Branch       string      `json:"branch,omitempty"`
	// MustExist if set skips implicit database creation
	MustExist bool
}

type Database

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

Database is the interface for interacting with a Tigris Database Due to the limitations of Golang generics instantiations of the collections should be done using GetCollection[Model](ctx, db) top level function instead of method of this interface. Similarly to get access to collection APIs in a transaction top level GetTxCollection(ctx, tx) function should be used instead of method of Tx interface.

func MustOpenDatabase

func MustOpenDatabase(ctx context.Context, cfg *Config, models ...schema.Model,
) *Database

func OpenDatabase

func OpenDatabase(ctx context.Context, cfg *Config, models ...schema.Model,
) (*Database, error)

OpenDatabase initializes Database from given collection models. It creates Database if necessary. Creates and migrates schemas of the collections which constitutes the Database. This is identical to calling:

client := tigris.NewClient(...)
client.OpenDatabase(...)
Example
package main

import (
	"context"

	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string `tigris:"primary_key"`
	}

	// Connects to the Tigris server. Creates or opens database "db1".
	// Creates or migrate &Coll1{}. Returns a "db" object, which provides
	// access to the collections of the database, Coll1 in this example.
	db, err := tigris.OpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})
	if err != nil {
		panic(err)
	}

	c := tigris.GetCollection[Coll1](db)

	if _, err := c.Insert(ctx, &Coll1{"aaa"}); err != nil {
		panic(err)
	}
}
Output:

func TestOpenDatabase

func TestOpenDatabase(ctx context.Context, d driver.Driver,
	project string, models ...schema.Model,
) (*Database, error)

TestOpenDatabase allows to provide mocked driver in tests.

func (*Database) CreateBranch

func (db *Database) CreateBranch(ctx context.Context, name string) (*driver.CreateBranchResponse, error)

CreateBranch creates a branch of this database.

func (*Database) CreateCollections

func (db *Database) CreateCollections(ctx context.Context, model schema.Model, models ...schema.Model) error

CreateCollections creates collections in the Database using provided collection models This method is only needed if collections need to be created dynamically, all static collections are created by OpenDatabase.

func (*Database) DeleteBranch

func (db *Database) DeleteBranch(ctx context.Context, name string) (*driver.DeleteBranchResponse, error)

DeleteBranch deletes a branch of this database, throws an error if "main" branch is being deleted.

func (*Database) DropAllCollections

func (db *Database) DropAllCollections(ctx context.Context) error

DropAllCollections allows to drop all database collections.

func (*Database) Tx

func (db *Database) Tx(ctx context.Context, fn func(ctx context.Context) error, options ...TxOptions) error

Tx executes given set of operations in a transaction

All operation in the "fn" closure is executed atomically in a transaction. If the closure returns no error the changes are applied to the database, when error is returned then changes just discarded, database stays intact.

Example
package main

import (
	"context"

	"github.com/tigrisdata/tigris-client-go/filter"
	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string `tigris:"primary_key"`
	}

	db, err := tigris.OpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})
	if err != nil {
		panic(err)
	}

	err = db.Tx(ctx, func(ctx context.Context) error {
		c := tigris.GetCollection[Coll1](db)

		if _, err := c.Insert(ctx, &Coll1{"aaa"}); err != nil {
			panic(err)
		}

		if _, err := c.Delete(ctx, filter.Eq("Key1", "bbb")); err != nil {
			panic(err)
		}

		return nil
	})
	if err != nil {
		panic(err)
	}
}
Output:

type DeleteResponse

type DeleteResponse struct{}

DeleteResponse includes metadata about just deleted documents. Returned by Delete-documents collection API.

type DescribeCollectionResponse

type DescribeCollectionResponse = driver.DescribeCollectionResponse

ExplainResponse includes the query plan Tigris would run for a query.

type Error

type Error driver.Error

Error contains Tigris server error.

Example
package main

import (
	"context"
	"errors"

	"github.com/tigrisdata/tigris-client-go/code"
	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string `tigris:"primary_key"`
	}

	db, err := tigris.OpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})
	if err != nil {
		panic(err)
	}

	coll := tigris.GetCollection[Coll1](db)

	// Insert document into collection
	_, err = coll.Insert(ctx, &Coll1{"aaa"})
	if err != nil {
		panic(err)
	}

	// Insert of the same object causes duplicate key error
	_, err = coll.Insert(ctx, &Coll1{"aaa"})

	// Unwrap tigris.Error and check the code
	var ep *tigris.Error
	if errors.As(err, &ep) {
		if ep.Code == code.AlreadyExists {
			// handle duplicate key
		}
	}
}
Output:

func NewError

func NewError(c code.Code, format string, a ...interface{}) *Error

func (*Error) AsTigrisError

func (e *Error) AsTigrisError(de *driver.Error) bool

type ExplainResponse

type ExplainResponse = driver.ExplainResponse

ExplainResponse includes the query plan Tigris would run for a query.

type InsertOrReplaceResponse

type InsertOrReplaceResponse struct {
	// JSON documents, which contain autogenerated fields
	Keys [][]byte
}

InsertOrReplaceResponse includes metadata regarding just inserted or replaced documents. Returned by InsertOrReplace-documents collection API.

type InsertResponse

type InsertResponse struct {
	// JSON documents, which contain autogenerated fields
	Keys [][]byte
}

InsertResponse includes metadata regarding just inserted documents. Returned by Insert-documents collection API.

type Iterator

type Iterator[T any] struct {
	driver.Iterator
	// contains filtered or unexported fields
}

Iterator is used to iterate documents returned by streaming APIs.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string `tigris:"primary_key"`
	}

	db, err := tigris.OpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})
	if err != nil {
		panic(err)
	}

	c := tigris.GetCollection[Coll1](db)

	it, err := c.ReadAll(ctx)
	if err != nil {
		panic(err)
	}

	defer it.Close()

	var doc Coll1
	for it.Next(&doc) {
		fmt.Printf("%+v\n", doc)
	}

	if err := it.Err(); err != nil {
		panic(err)
	}
}
Output:

func (*Iterator[T]) Array

func (it *Iterator[T]) Array() ([]T, error)

Array returns result of iteration as an array of documents.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/tigrisdata/tigris-client-go/filter"
	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string
	}

	db := tigris.MustOpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})

	coll := tigris.GetCollection[Coll1](db)

	it, err := coll.Read(ctx, filter.All)
	if err != nil {
		panic(err)
	}

	arr, err := it.Array()
	if err != nil {
		panic(err)
	}

	for k, v := range arr {
		fmt.Fprintf(os.Stderr, "doc %v = %+v\n", k, v)
	}
}
Output:

func (*Iterator[T]) Close

func (it *Iterator[T]) Close()

Close closes Iterator stream.

func (*Iterator[T]) Err

func (it *Iterator[T]) Err() error

Err returns nil if iteration was successful, otherwise return error details.

func (*Iterator[T]) Iterate

func (it *Iterator[T]) Iterate(fn func(doc *T) error) error

Iterate calls provided function for every document in the result. It's ia convenience to avoid common mistakes of not closing the iterator and not checking the error from the iterator.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/tigrisdata/tigris-client-go/filter"
	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type Coll1 struct {
		Key1 string
	}

	db := tigris.MustOpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})

	coll := tigris.GetCollection[Coll1](db)

	it, err := coll.Read(ctx, filter.All)
	if err != nil {
		panic(err)
	}

	err = it.Iterate(func(doc *Coll1) error {
		fmt.Fprintf(os.Stderr, "%+v\n", doc)
		return nil
	})
	if err != nil {
		panic(err)
	}
}
Output:

func (*Iterator[T]) Next

func (it *Iterator[T]) Next(doc *T) bool

Next populates 'doc' with the next document in the iteration order Returns false at the end of the stream or in the case of error.

type Metadata

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

func (*Metadata) GetCreatedAt

func (m *Metadata) GetCreatedAt() time.Time

GetCreatedAt returns time of document creation.

func (*Metadata) GetDeletedAt

func (m *Metadata) GetDeletedAt() time.Time

GetDeletedAt returns time of document deletion.

func (*Metadata) GetUpdatedAt

func (m *Metadata) GetUpdatedAt() time.Time

GetUpdatedAt returns time of last document update.

type Model

type Model struct {
	Metadata

	// This field is unused if user defines its own primary key
	// If no primary key is defined in the user model
	// this field is automatically populated with
	// autogenerated unique UUID
	ID uuid.UUID `tigris:"primary_key,autoGenerate"`
}

Model contains document metadata Metadata is populated automatically if embedded into user document

Example:

type User {
   tigris.Model
   // User fields
   Name string
   ...
}

type Projection

type Projection[T schema.Model, P schema.Model] struct {
	// contains filtered or unexported fields
}

func GetProjection

func GetProjection[T schema.Model, P schema.Model](db *Database, keyPath ...string) *Projection[T, P]

GetProjection returns collection object corresponding to collection model T.

func (*Projection[T, P]) Read

func (p *Projection[T, P]) Read(ctx context.Context, filter filter.Filter) (*Iterator[P], error)

Read returns documents which satisfies the filter. Only field from the give fields are populated in the documents. By default, all fields are populated.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tigrisdata/tigris-client-go/filter"
	"github.com/tigrisdata/tigris-client-go/tigris"
)

func main() {
	ctx := context.TODO()

	type NestedColl1 struct {
		Key2 string
	}

	type Coll1 struct {
		Key1   string
		Nested NestedColl1
	}

	db := tigris.MustOpenDatabase(ctx, &tigris.Config{Project: "db1"}, &Coll1{})

	coll := tigris.GetCollection[Coll1](db)

	_, err := coll.Insert(ctx, &Coll1{Key1: "k1", Nested: NestedColl1{Key2: "k2"}})
	if err != nil {
		panic(err)
	}

	proj := tigris.GetProjection[Coll1, NestedColl1](db, "Nested")

	it, err := proj.Read(ctx, filter.All)
	if err != nil {
		panic(err)
	}

	var Nested NestedColl1
	for it.Next(&Nested) {
		fmt.Printf("%+v\n", Nested)
	}

	// Projection with only top level key included
	type Proj2 struct {
		Key1 string
	}

	proj2 := tigris.GetProjection[Coll1, Proj2](db)

	it2, err := proj2.Read(ctx, filter.All)
	if err != nil {
		panic(err)
	}

	var p2 Proj2
	for it2.Next(&p2) {
		fmt.Printf("%+v\n", p2)
	}
}
Output:

func (*Projection[T, P]) ReadAll

func (p *Projection[T, P]) ReadAll(ctx context.Context) (*Iterator[P], error)

ReadAll reads all the documents from the collection.

func (*Projection[T, P]) ReadOne

func (p *Projection[T, P]) ReadOne(ctx context.Context, filter filter.Filter) (*P, error)

ReadOne returns first documents which satisfies the filter.

func (*Projection[T, P]) ReadWithOptions

func (p *Projection[T, P]) ReadWithOptions(ctx context.Context, filter filter.Filter, options *ReadOptions) (*Iterator[P], error)

ReadWithOptions returns specific fields of the documents according to the filter. It allows further configure returned documents by providing options:

Limit - only returned first "Limit" documents from the result
Skip - start returning documents after skipping "Skip" documents from the result

type ReadOptions

type ReadOptions struct {
	// Limit the number of documents returned by the read operation.
	Limit int64
	// Number of documents to skip before starting to return resulting documents.
	Skip int64
	// A cursor for use in pagination. The next streams will return documents after this offset.
	Offset []byte
	// Collation allows you to specify string comparison rules. Default is case-sensitive.
	Collation *driver.Collation
	// Sort order
	Sort sort.Order
}

ReadOptions modifies read request behavior.

type SearchIterator

type SearchIterator[T interface{}] struct {
	Iterator driver.SearchResultIterator
	// contains filtered or unexported fields
}

SearchIterator is used to iterate search documents.

func (*SearchIterator[T]) Close

func (it *SearchIterator[T]) Close()

Close closes Iterator stream.

func (*SearchIterator[T]) Err

func (it *SearchIterator[T]) Err() error

Err returns nil if iteration was successful, otherwise return error details.

func (*SearchIterator[T]) Next

func (it *SearchIterator[T]) Next(res *search.Result[T]) bool

type Tx

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

Tx is the interface for accessing APIs in a transactional way.

type TxOptions

type TxOptions struct {
	AutoRetry bool
}

type UpdateResponse

type UpdateResponse struct{}

UpdateResponse includes metadata about just updated documents. Returned by Update-documents collection API.

Jump to

Keyboard shortcuts

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