aranGO

package module
v0.0.0-...-50b71e9 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2020 License: Apache-2.0 Imports: 10 Imported by: 2

README

aranGO

go get github.com/diegogub/aranGO

Golang driver for ArangoDB.

Here are the things you can do until now:

  • Databases : create
  • Collections : drop, create, list, truncate
  • Documents : save, replace,patch, query (simple query,AQL,Transactions)
  • Edges : Relate documents, save, patch, replace
  • Execute transactions
  • Execute AQL
  • Replication config

Additional Features

Any ideas for the driver or bug fixes please feel free to create a issue or pull-request to dev :)

Documentation

https://gowalker.org/github.com/diegogub/aranGO

Basic Usage

import ara "github.com/diegogub/aranGO"

type DocTest struct {
  ara.Document // Must include arango Document in every struct you want to save id, key, rev after saving it
  Name     string
  Age      int
  Likes    []string
}

Connect and create collections

    //change false to true if you want to see every http request
    //Connect(host, user, password string, log bool) (*Session, error) {
    s,err := ara.Connect("http://localhost:8529","diego","test",false) 
    if err != nil{
        panic(err)
    }

    // CreateDB(name string,users []User) error
    s.CreateDB("test",nil)

    // create Collections test if exist
    if !s.DB("test").ColExist("docs1"){
        // CollectionOptions has much more options, here we just define name , sync
        docs1 := NewCollectionOptions("docs1",true)
        s.DB("test").CreateCollection(docs1)
    }

    if !s.DB("test").ColExist("docs2"){
        docs2 := NewCollectionOptions("docs2",true)
        s.DB("test").CreateCollection(docs2)
    }

    if !s.DB("test").ColExist("ed"){
        edges := NewCollectionOptions("ed",true)
        edges.IsEdge() // set to Edge
        s.DB("test").CreateCollection(edges)
    }

Create and Relate documents

  var d1,d2 DocTest
  d1.Name = "Diego"
  d1.Age = 22
  d1.Likes = []string { "arangodb", "golang", "linux" }
  
  d2.Name = "Facundo"
  d2.Age = 25
  d2.Likes = []string { "php", "linux", "python" }


  err =s.DB("test").Col("docs1").Save(&d1)
  err =s.DB("test").Col("docs1").Save(&d2)
  if err != nil {
    panic(err)
  }

  // could also check error in document
  /*
  if d1.Error {
    panic(d1.Message)
  }
  */

  // update document
  d1.Age = 23
  err =s.DB("test").Col("docs1").Replace(d1.Key,d1)
  if err != nil {
    panic(err)
  }
  
  // Relate documents
  s.DB("test").Col("ed").Relate(d1.Id,d2.Id,map[string]interface{}{ "is" : "friend" })

AQL

// query query 
  q := ara.NewQuery("FOR i in docs1 RETURN i")
  c ,err:=s.DB("test").Execute(q)
  if err != nil {
    panic(err)
  }
  var doc DocTest

  for c.FetchOne(&doc){
    log.Println(doc)
  }

Transactions

// saving document with transaction
func TranSave(db *ara.Database,doc interface{},col string,counter string) (*ara.Transaction,error){
  if  col == "" || counter == ""{
    return nil,errors.New("Collection or counter must not be nil")
  }

  write := []string { col }
  q := `function(params){
                var db = require('internal').db;
                try {
                  var c = db.`+col+`.document('c');
                }catch(error){
                  var tmp = db.`+col+`.save( { '_key' : 'c' , '`+counter+`' : 0 });
                }
                var c = db.`+col+`.document('c');
                var co = c.`+counter+` || 0;
                co = co + 1 ;
                // update counter
                db.`+col+`.update(c, { '`+counter+`' : co }) ;
                params.doc.s = -1 * co ;
                params.doc.created = new Date().toISOString();
                var res = db.`+col+`.save(params.doc) ;
                return res._key
        }
  `
  t := ara.NewTransaction(q,write,nil)
  t.Params = map[string]interface{}{ "doc" : doc }

  err := t.Execute(db)

  return t,err
}

Models

To be a model, any struct must implement Modeler Interface.

type Modeler interface {
    // Returns current model key
    GetKey() string
    // Returns collection where I should save the model
    GetCollection() string
    // Error
    GetError() (string, bool)
}

Implement Modeler and add tags to struct..


type DocTest struct {
  ara.Document // Must include arango Document in every struct you want to save id, key, rev after saving it
// required tag for strings.
  Name     string `required:"-"`
// unique tag validate within collection users, if username is unique
  Username string `unique:"users"`
// enum tag checks string value
  Type     string `enum:"A,M,S"`
// Next release I will be implementing some other tags to validate int
and arrays
  Age      int
  Likes    []string
}

func (d *DocTest) GetKey() string{
  return d.Key
}

func (d *DocTest) GetCollection() string {
  return "testcollection"
}

func (d *DocTest) GetError()(string,error){
    // default error bool and messages. Could be any kind of error
    return d.Message,d.Error
}

// pass ArangoDB database as context
ctx, err :=  NewContext(db)

// save model, returns map of errors or empty map
e := ctx.Save(d1)

// check errors, also Error is saved in Context struct
if len(e) > 1 {
  panic(e)
}

// get other document
d2.Key = "d2key"
ctx.Get(d2)
log.Println(d2)

We can implement hooks to execute when saving,updating or deleting model..

// execute before saving
func (d *DocTest) PreSave(c *ara.Context) {
   var e error
  // Any extra validation
  // ......
  // ......
  if e != nil {
    // errors should be set into context struct
    c.Err["presave"] = "failed to validate doctest"
  }

  return
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Collections

func Collections(db *Database) error

Collections gets list of collections from any database

func Inc

func Inc(field string, n int64) error

increase value by n

func Tag

func Tag(obj interface{}, fname, key string) string

func Tags

func Tags(obj interface{}, key string) map[string]string

func Unique

func Unique(m interface{}, db *Database, update bool, err Error)

func Validate

func Validate(m interface{}, db *Database, col string, update bool, err Error)

Types

type Applier

type Applier struct {
	State    ApplierState `json:"state"`
	Server   ServerInfo   `json:"server"`
	Endpoint string       `json:"endpoint"`
	Database string       `json:"database"`
}

type ApplierConf

type ApplierConf struct {
	Endpoint string `json:"endpoint,omitempty"`
	Database string `json:"database,omitempty"`
	Username string `json:"username,omitempty"`

	Ssl            int  `json:"sslProtocol,omitempty"`
	ReConnect      int  `json:"maxConnectRetries,omitempty"`
	ConnectTimeout int  `json:"connectTimeOut,omitempty"`
	RequestTimeout int  `json:"requestTimeOut,omitempty"`
	Chunk          int  `json:"chunkSize,omitempty"`
	AutoStart      bool `json:"autoStart,omitempty"`
	AdaptPolling   bool `json:"adaptivePolling,omitempty"`
	// contains filtered or unexported fields
}

type ApplierProgress

type ApplierProgress struct {
	Time    time.Time `json:"time"`
	Message string    `json:"message"`
	Fails   int       `json:"failedConnects"`
}

type ApplierState

type ApplierState struct {
	Running       bool            `json:"running"`
	Progress      ApplierProgress `json:"progress"`
	TotalRequests int             `json:"totalRequests"`
	FailConnects  int             `json:"totalFailedConnects"`
	TotalEvents   int             `json:"totalEvents"`
	Time          time.Time       `json:"time"`
}

type AqlCollect

type AqlCollect struct {
	Sentence string `json:"collect"`
}

func (AqlCollect) Generate

func (aqc AqlCollect) Generate() string

type AqlFilter

type AqlFilter struct {
	DefaultKey string `json:"key"`
	// never include in json parsing
	Custom string `json:"-"`
	// Function filters
	Functions []AqlFunction `json:"functions"`
	// Filters
	Filters []Filter `json:"filters"`
	// Match all the filters or any of them
	Any bool `json:"any"`
}

func FilterJSON

func FilterJSON(s string) AqlFilter

FilterJSON returns AqlFilter parsing valid json string

func (AqlFilter) Generate

func (aqf AqlFilter) Generate() string

type AqlFunction

type AqlFunction struct {
	Name   string
	Params []interface{}
}

Aql functions

func Fun

func Fun(name string, i ...interface{}) AqlFunction

Creates a AqlFunction to use into AqlStruct

func (AqlFunction) Generate

func (f AqlFunction) Generate() string

type AqlInsert

type AqlInsert struct {
	Data Obj
	Col  string
}

func (AqlInsert) Generate

func (aqi AqlInsert) Generate() string

type AqlLet

type AqlLet struct {
	Var string
	Exp interface{}
}

func (AqlLet) Generate

func (aql AqlLet) Generate() string

type AqlLimit

type AqlLimit struct {
	Skip  int64 `json:"skip"`
	Limit int64 `json:"limit"`
	// contains filtered or unexported fields
}

func (AqlLimit) Generate

func (l AqlLimit) Generate() string

type AqlRemove

type AqlRemove struct {
	Id      interface{}
	Col     string
	Options interface{}
}

func (AqlRemove) Generate

func (aqr AqlRemove) Generate() string

type AqlReplace

type AqlReplace struct {
	Id      interface{}
	Repl    Obj
	Col     string
	Options interface{}
}

func (AqlReplace) Generate

func (aqr AqlReplace) Generate() string

type AqlSort

type AqlSort struct {
	List []Sort `json:"sort"`
}

func (AqlSort) Generate

func (aqs AqlSort) Generate() string

type AqlStruct

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

Basic Aql struct to build Aql Query

func NewAqlStruct

func NewAqlStruct() *AqlStruct

func (*AqlStruct) Collect

func (aq *AqlStruct) Collect(sentence string) *AqlStruct

Aql Collect Usage: Collect("first = u.firstName, age = u.age INTO g")

func (*AqlStruct) Execute

func (aq *AqlStruct) Execute(db *Database) (*Cursor, error)

Execute AqlStuct into database

func (*AqlStruct) Filter

func (aq *AqlStruct) Filter(f ...interface{}) *AqlStruct

Aql filter add Filter() to AqlQuery Could be use like:

  • Filter(custom ... string) example: Filter("u.name == 'Diego' && u.age > 21") out: FILTER u.name == 'Diego' && u.age > 21
  • Filter(key string,fil ... Filter || AqlFunction, any bool) example: Filter("u",Fil("sum","eq",213),Fil("age","gt",21),true) out: FILTER u.sum == 213 || u.age > 21 Filter("u",Fil("sum","eq",213),FilField("id","==","adm.id"),false) out: FILTER u.sum == 213 FILTER u.id == adm.id Filter("u",Fil("sum","eq",213),FilField("id","==","adm.id"),false) out: FILTER u.sum == 213 FILTER u.id == adm.id Filter("u",Fun("LIKE",Atr("u","name"),"di%",true) out: FILTER u.age > 21 || LIKE(u.name,'di%',true) -FILTER(jsonFilter string) example: Filter(`{ "key" : "u" , "filters": [{ "name": "name", "like": "gt", "val": "die%" },{ "name": "status", "op": "eq", "val":"A"}] }`) out: FILTER (IS_NULL(u.name) == false && LIKE(u.name,'die%',true)) && u.status == 'A' Filter(`{ "key" : "u" , "filters": [{ "name": "status", "op": "==", "val": "P" },{ "name": "status", "op": "eq", "val":"A"}], "any" : true }`) out: FILTER u.status == 'P' || u.status == 'A' Filter(`{ "key" : "u" , "filters": [{ "name": "id", "op": "==", "field": "adm.id" },{ "name": "status", "op": "eq", "val":"A"}], "any" : true }`) out: FILTER u.id == adm.id || u.status == 'A'

func (*AqlStruct) For

func (aq *AqlStruct) For(v string, in interface{}) *AqlStruct

func (*AqlStruct) Generate

func (aq *AqlStruct) Generate() string

Generate Aql query string

func (*AqlStruct) Insert

func (aq *AqlStruct) Insert(obj Obj, col string) *AqlStruct

Aql INSERT Usage:

Insert(Obj{ "name" : Atr("u","name") , "test" : 2},"backup")

func (*AqlStruct) Let

func (aq *AqlStruct) Let(v string, i interface{}) *AqlStruct

Aql Let

func (*AqlStruct) Limit

func (aq *AqlStruct) Limit(s ...int64) *AqlStruct

Aql Limit Usage:

Limit(10)
out: LIMIT 10
Limit(5,15)
out: LIMIT 5,15

func (*AqlStruct) Remove

func (aq *AqlStruct) Remove(id interface{}, col string, options interface{}) *AqlStruct

Aql Remove Usage: Remove("u._id","users",nil)

func (*AqlStruct) Replace

func (aq *AqlStruct) Replace(id interface{}, replace Obj, col string, options interface{}) *AqlStruct

Aql Replace Usage:

Replace("u._id",Obj{ "name" : "Diego" },"users",nil)

func (*AqlStruct) Return

func (aq *AqlStruct) Return(view interface{}) *AqlStruct

func (*AqlStruct) Sort

func (aq *AqlStruct) Sort(i ...interface{}) *AqlStruct

Aql Sort Usage:

Sort("u.name","u.age","ASC","u.created","DESC")

or

Sort(Atr("u","name),Atr("u","age"),"ASC",Var("u","created"),"DESC")

func (*AqlStruct) Update

func (aq *AqlStruct) Update(doc interface{}, with Obj, col string, options interface{}) *AqlStruct

Aql UPDATE Usage:

type AqlStructer

type AqlStructer interface {
	Generate() string
}

type AqlUpdate

type AqlUpdate struct {
	Doc     interface{}
	Col     string
	With    Obj
	Options interface{}
}

func (AqlUpdate) Generate

func (aqu AqlUpdate) Generate() string

type Collection

type Collection struct {
	Name   string `json:"name"`
	System bool   `json:"isSystem"`
	Status int    `json:"status"`
	// 3 = Edges , 2 =  Documents
	Type int `json:"type"`
	// contains filtered or unexported fields
}

Basic Collection struct

func (*Collection) All

func (c *Collection) All(skip, limit int) (*Cursor, error)

func (*Collection) Any

func (c *Collection) Any(doc interface{}) error

Any returns random number

func (*Collection) ConditionBitArray

func (c *Collection) ConditionBitArray(condition string, skip int, limit int, index string) (*Cursor, error)

Coditional query using bitarray index

func (*Collection) ConditionSkipList

func (c *Collection) ConditionSkipList(condition string, skip int, limit int, index string) (*Cursor, error)

Coditional query using skiplist index

func (*Collection) Count

func (col *Collection) Count() int64

Count all documents in collection

func (*Collection) CreateFullText

func (c *Collection) CreateFullText(min int, fields ...string) error

func (*Collection) CreateGeoIndex

func (c *Collection) CreateGeoIndex(unique bool, geojson bool, fields ...string) error

func (*Collection) CreateHash

func (c *Collection) CreateHash(unique bool, fields ...string) error

func (*Collection) CreateSkipList

func (c *Collection) CreateSkipList(unique bool, fields ...string) error

func (*Collection) Delete

func (col *Collection) Delete(key string) error

func (*Collection) DeleteIndex

func (c *Collection) DeleteIndex(id string) error

Delete Index

func (*Collection) Edges

func (col *Collection) Edges(start string, direction string, result interface{}) error

Edges gets vertex relations

func (*Collection) Example

func (c *Collection) Example(doc interface{}, skip, limit int) (*Cursor, error)

Simple query by example

func (*Collection) First

func (c *Collection) First(example, doc interface{}) error

First returns first document in example query

func (*Collection) FullText

func (c *Collection) FullText(q string, atr string, skip, limit int) (*Cursor, error)

func (*Collection) Get

func (col *Collection) Get(key string, doc interface{}) error

Get Document

func (*Collection) Indexes

func (c *Collection) Indexes() (map[string]Index, error)

Indexes gets all indexs

func (*Collection) Load

func (col *Collection) Load() error

Load collection

func (*Collection) Near

func (c *Collection) Near(lat float64, lon float64, distance bool, geo string, skip, limit int) (*Cursor, error)

func (*Collection) Patch

func (col *Collection) Patch(key string, doc interface{}) error

func (*Collection) Relate

func (col *Collection) Relate(from string, to string, label interface{}) error

Relate documents in edge collection

func (*Collection) Replace

func (col *Collection) Replace(key string, doc interface{}) error

Replace document

func (*Collection) Save

func (col *Collection) Save(doc interface{}) error

Save saves doc into collection, doc should have Document Embedded to retrieve error and Key later.

func (*Collection) SaveEdge

func (col *Collection) SaveEdge(doc interface{}, from string, to string) error

Save Edge into Edges collection

func (*Collection) SetCap

func (c *Collection) SetCap(size int64, bysize int64) error

Create cap constraint

func (*Collection) Unique

func (c *Collection) Unique(key string, value interface{}, update bool, index string) (bool, error)

Unique checks if a key is unique

func (*Collection) WithIn

func (c *Collection) WithIn(radius float64, lat float64, lon float64, distance bool, geo string, skip, limit int) (*Cursor, error)

type CollectionDump

type CollectionDump struct {
	Parameters CollectionParameters `json:"parameters"`
	Indexes    []Index
}

type CollectionOptions

type CollectionOptions struct {
	Name        string                 `json:"name"`
	Type        uint                   `json:"type"`
	Sync        bool                   `json:"waitForSync,omitempty"`
	Compact     bool                   `json:"doCompact,omitempty"`
	JournalSize int                    `json:"journalSize,omitempty"`
	System      bool                   `json:"isSystem,omitempty"`
	Volatile    bool                   `json:"isVolatile,omitempty"`
	Keys        map[string]interface{} `json:"keyOptions,omitempty"`
	// Count
	Count int64 `json:"count"`
	// Cluster
	Shards    int      `json:"numberOfShards,omitempty"`
	ShardKeys []string `json:"shardKeys,omitempty"`
}

Options to create collection

func NewCollectionOptions

func NewCollectionOptions(name string, sync bool) *CollectionOptions

func (*CollectionOptions) IsDocument

func (opt *CollectionOptions) IsDocument()

func (*CollectionOptions) IsEdge

func (opt *CollectionOptions) IsEdge()

func (*CollectionOptions) IsVolatile

func (opt *CollectionOptions) IsVolatile()

Sets if collection must be Volatile.

func (*CollectionOptions) Journal

func (opt *CollectionOptions) Journal(size int)

Sets custom journal size

func (*CollectionOptions) MustSync

func (opt *CollectionOptions) MustSync()

Sets always-sync to true

func (*CollectionOptions) Shard

func (opt *CollectionOptions) Shard(num int)

Sets the number of shards for a collection

func (*CollectionOptions) ShardKey

func (opt *CollectionOptions) ShardKey(keys []string)

type CollectionParameters

type CollectionParameters struct {
	CollectionOptions
	Id      string `json:"cid"`
	Version int    `json:"version"`
	Deleted bool   `json:"deleted"`
}

type Context

type Context struct {
	Keys map[string]interface{}
	Db   *Database
	Err  Error
}

Context to share state between hook and track transaction state

func NewContext

func NewContext(db *Database) (*Context, error)

func (*Context) BulkSave

func (c *Context) BulkSave(models []Modeler) map[int]Error

Saves models into database concurrently

func (*Context) Delete

func (c *Context) Delete(m Modeler) Error

func (*Context) Get

func (c *Context) Get(m Modeler) Error

Get model

func (*Context) NewRelation

func (c *Context) NewRelation(main Modeler, label map[string]interface{}, edgecol string, dierection string, rel ...Modeler) (*Relation, Error)

func (*Context) Save

func (c *Context) Save(m Modeler) Error

Updates or save new Model into database

type Cursor

type Cursor struct {
	Id string `json:"Id"`

	Index  int           `json:"-"`
	Result []interface{} `json:"result"`
	More   bool          `json:"hasMore"`
	Amount int           `json:"count"`
	Data   Extra         `json:"extra"`

	Err    bool   `json:"error"`
	ErrMsg string `json:"errorMessage"`
	Code   int    `json:"code"`

	Time time.Duration `json:"time"`
	// contains filtered or unexported fields
}

func NewCursor

func NewCursor(db *Database) *Cursor

func (Cursor) Count

func (c Cursor) Count() int

func (*Cursor) Delete

func (c *Cursor) Delete() error

Delete cursor in server and free RAM

func (Cursor) ErrCode

func (c Cursor) ErrCode() int

func (Cursor) Error

func (c Cursor) Error() bool

func (*Cursor) FetchBatch

func (c *Cursor) FetchBatch(r interface{}) error

func (*Cursor) FetchOne

func (c *Cursor) FetchOne(r interface{}) bool

FetchOne iterates over cursor, returns false when no more values into batch, fetch next batch if necesary.

func (*Cursor) FullCount

func (c *Cursor) FullCount() int

func (Cursor) HasMore

func (c Cursor) HasMore() bool

func (*Cursor) Next

func (c *Cursor) Next(r interface{}) bool

move cursor index by 1

type Database

type Database struct {
	Name        string `json:"name"`
	Id          string `json:"id"`
	Path        string `json:"path"`
	System      bool   `json:"isSystem"`
	Collections []Collection
	// contains filtered or unexported fields
}

Database struct

func (*Database) Applier

func (db *Database) Applier() (*Applier, error)

func (*Database) ApplierConf

func (db *Database) ApplierConf() (*ApplierConf, error)

func (*Database) CheckCollection

func (d *Database) CheckCollection(name string) *CollectionOptions

CheckCollection returns collection option based on name, nil otherwise

func (Database) Col

func (db Database) Col(name string) *Collection

Col returns Collection attached to current Database

func (*Database) ColExist

func (db *Database) ColExist(name string) bool

ColExist checks if collection exist

func (*Database) CreateCollection

func (d *Database) CreateCollection(c *CollectionOptions) error

Create collections

func (*Database) CreateGraph

func (db *Database) CreateGraph(name string, eds []EdgeDefinition) (*Graph, error)

Creates graphs

func (*Database) DropCollection

func (d *Database) DropCollection(name string) error

Drop Collection

func (*Database) DropGraph

func (db *Database) DropGraph(name string) error

func (*Database) Execute

func (d *Database) Execute(q *Query) (*Cursor, error)

Execute AQL query into server and returns cursor struct

func (*Database) ExecuteTran

func (d *Database) ExecuteTran(t *Transaction) error

ExecuteTran executes transaction into the database

func (*Database) Graph

func (db *Database) Graph(name string) *Graph

func (*Database) Inventory

func (db *Database) Inventory() (*ReplicationInventory, error)

Inventory returns replication inventory

func (*Database) IsValid

func (d *Database) IsValid(q *Query) bool

func (*Database) ListGraphs

func (db *Database) ListGraphs() ([]Graph, error)

func (*Database) LoggerState

func (db *Database) LoggerState() (*Logger, error)

func (*Database) ServerID

func (db *Database) ServerID() string

func (*Database) SetApplierConf

func (db *Database) SetApplierConf(appconf *ApplierConf) error

func (*Database) StartReplication

func (db *Database) StartReplication() error

func (*Database) StopReplication

func (db *Database) StopReplication() error

func (*Database) TruncateCollection

func (d *Database) TruncateCollection(name string) error

Truncate collection

type Databases

type Databases struct {
	List []string `json:"result" `
}

type Document

type Document struct {
	Id  string `json:"_id,omitempty"              `
	Rev string `json:"_rev,omitempty"             `
	Key string `json:"_key,omitempty"             `

	Error   bool   `json:"error,omitempty"`
	Message string `json:"errorMessage,omitempty"`
}

func NewDocument

func NewDocument(id string) (*Document, error)

Creates base document structure

func (*Document) Exist

func (d *Document) Exist(db *Database) (bool, error)

Exist checks if document exist

func (*Document) Map

func (d *Document) Map(db *Database) (map[string]string, error)

Map returns map[string]string of document instead of struct

func (*Document) SetKey

func (d *Document) SetKey(key string) error

func (*Document) SetRev

func (d *Document) SetRev(rev string) error

func (*Document) Updated

func (d *Document) Updated(db *Database) (bool, error)

Updated checks if a document was updated

type Edge

type Edge struct {
	Id    string `json:"_id,omitempty"  `
	From  string `json:"_from"`
	To    string `json:"_to"  `
	Error bool   `json:"error,omitempty"`
}

type EdgeDefinition

type EdgeDefinition struct {
	Collection string   `json:"collection"`
	From       []string `json:"from"`
	To         []string `json:"to"`
}

func NewEdgeDefinition

func NewEdgeDefinition(col string, from []string, to []string) *EdgeDefinition

type Error

type Error map[string]string

func NewError

func NewError() Error

type Extra

type Extra struct {
	Stats Stats `json:"stats"`
}

type Filter

type Filter struct {
	AtrR string `json:"name"`
	// compare to value or function depending on operand
	Value interface{} `json:"val,omitempty"`
	// compare to field, need to check if it's valid variable!
	Field string `json:"field,omitempty"`
	// could be AqlFunction too
	Function *AqlFunction `json:"-"`
	// Operator
	Oper string `json:"op"`
}

func Fil

func Fil(atr string, oper string, i interface{}) Filter

Fil returns filter , comparing with value

func FilField

func FilField(atr string, oper string, i string) Filter

FilField returns filter , comparing 2 fields

func (Filter) String

func (f Filter) String(key string) string

type Graph

type Graph struct {
	Id       string           `json:"_id,omitempty"`
	Key      string           `json:"_key"`
	Name     string           `json:"name"`
	EdgesDef []EdgeDefinition `json:"edgeDefinitions"`
	Orphan   []string         `json:"orphanCollections"`
	// contains filtered or unexported fields
}

Graph structure

func (*Graph) AddEdgeDef

func (g *Graph) AddEdgeDef(ed *EdgeDefinition) error

func (*Graph) AddEdgeDefinition

func (g *Graph) AddEdgeDefinition(ed EdgeDefinition) error

func (*Graph) AddVertexCol

func (g *Graph) AddVertexCol(col string) error

AddVertexCol adds vertex collections

func (*Graph) E

func (g *Graph) E(col string, edge interface{}) error

Creates a Egde

func (*Graph) GetE

func (g *Graph) GetE(col string, key string, edge interface{}) error

GetE gets Edge

func (*Graph) GetV

func (g *Graph) GetV(col string, key string, doc interface{}) error

GetV gets Vertex from collection

func (*Graph) ListEdgesDef

func (g *Graph) ListEdgesDef() ([]string, error)

func (*Graph) ListVertexCol

func (g *Graph) ListVertexCol() ([]string, error)

func (*Graph) PatchE

func (g *Graph) PatchE(col string, key string, doc interface{}, patch interface{}) error

Patch Edge

func (*Graph) PatchV

func (g *Graph) PatchV(col string, key string, doc interface{}, patch interface{}) error

Patch vertex

func (*Graph) RemoveE

func (g *Graph) RemoveE(col string, key string) error

RemoveE removes Vertex

func (*Graph) RemoveEdgeDef

func (g *Graph) RemoveEdgeDef(col string) error

RemoveEdgeDef removes edge

func (*Graph) RemoveV

func (g *Graph) RemoveV(col string, key string) error

RemoveV removes Vertex

func (*Graph) RemoveVertexCol

func (g *Graph) RemoveVertexCol(col string) error

RemoveVertexCol removes vertex collections

func (*Graph) ReplaceE

func (g *Graph) ReplaceE(col string, key string, doc interface{}, patch interface{}) error

ReplaceE replaces edge

func (*Graph) ReplaceEdgeDef

func (g *Graph) ReplaceEdgeDef(name string, ed *EdgeDefinition) error

func (*Graph) ReplaceV

func (g *Graph) ReplaceV(col string, key string, doc interface{}, patch interface{}) error

ReplaceV replaces vertex

func (*Graph) Traverse

func (g *Graph) Traverse(t *Traversal, r interface{}) error

Tranvers graph

func (*Graph) V

func (g *Graph) V(col string, doc interface{}) error

Creates a vertex in collection

type Index

type Index struct {
	Id        string   `json:"id"`
	Type      string   `json:"type"`
	Unique    bool     `json:"unique"`
	MinLength int      `json:"minLength"`
	Fields    []string `json:"fields"`
	Size      int64    `json:"size"`
}

type Indexes

type Indexes struct {
	Indexes  []Index
	IndexMap map[string]Index `json:"identifiers"`
}

type List

type List []interface{}

AqlList

func (List) String

func (l List) String() string

type Logger

type Logger struct {
	State  ReplicationState `json:"state"`
	Server ServerInfo       `json:"server"`
	Client []string         `json:"clients"`
}

type Modeler

type Modeler interface {
	// Returns current model key
	GetKey() string
	// Returns collection where I should save the model
	GetCollection() string
	// Error
	GetError() (string, bool)
}

type Obj

type Obj map[string]interface{}

AqlObject

func (Obj) String

func (ob Obj) String() string

type ObjTran

type ObjTran struct {
	Collection string      `json:"c"`
	Obj        interface{} `json:"o"`
}

func ObjT

func ObjT(m Modeler) ObjTran

type PostDeleter

type PostDeleter interface {
	PostDelete(c *Context)
}

type PostSaver

type PostSaver interface {
	PostSave(c *Context)
}

type PostUpdater

type PostUpdater interface {
	PostUpdate(c *Context)
}

type PreDeleter

type PreDeleter interface {
	PreDelete(c *Context)
}

type PreSaver

type PreSaver interface {
	PreSave(c *Context)
}

hook interfaces

type PreUpdater

type PreUpdater interface {
	PreUpdate(c *Context)
}

type Query

type Query struct {
	// mandatory
	Aql string `json:"query,omitempty"`
	//Optional values Batch    int                    `json:"batchSize,omitempty"`
	Count    bool                   `json:"count,omitempty"`
	BindVars map[string]interface{} `json:"bindVars,omitempty"`
	Options  map[string]interface{} `json:"options,omitempty"`
	// opetions fullCount bool
	// Note that the fullCount sub-attribute will only be present in the result if the query has a LIMIT clause and the LIMIT clause is actually used in the query.
	// Control
	Validate bool   `json:"-"`
	ErrorMsg string `json:"errorMessage,omitempty"`
}

Aql query

func NewQuery

func NewQuery(query string) *Query

func (*Query) Modify

func (q *Query) Modify(query string) error

func (*Query) MustCheck

func (q *Query) MustCheck()

MustCheck validates query before execution

func (*Query) SetFullCount

func (q *Query) SetFullCount(count bool)

type Relation

type Relation struct {
	Obj ObjTran `json:"obj"   `
	// Relate to map[edgeCol]obj
	EdgeCol string                 `json:"edgcol"`
	Label   map[string]interface{} `json:"label" `
	Rel     []ObjTran              `json:"rel"   `
	Error   bool                   `json:"error" `
	Update  bool                   `json:"update"`

	Db *Database
}

func (*Relation) Commit

func (a *Relation) Commit() error

type ReplicationInventory

type ReplicationInventory struct {
	Collections []CollectionDump `json:"collections"`
	State       ReplicationState `json:"state"`
	Tick        string           `json:"tick"`
}

type ReplicationState

type ReplicationState struct {
	Running     bool      `json:"running"`
	LastTick    string    `json:"lastLogTick"`
	TotalEvents int64     `json:"totalEvents"`
	Time        time.Time `json:"time"`
}

type ServerInfo

type ServerInfo struct {
	Id      string `json:"serverId"`
	Version string `json:"version"`
}

type Session

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

func Connect

func Connect(host, user, password string, log bool) (*Session, error)

Connects to Database

func (*Session) AvailableDBs

func (s *Session) AvailableDBs() ([]string, error)

List available databases

func (*Session) CreateDB

func (s *Session) CreateDB(name string, users []User) error

Create database

func (*Session) CurrentDB

func (s *Session) CurrentDB() (*Database, error)

Show current database

func (*Session) DB

func (s *Session) DB(name string) *Database

DB returns database

func (*Session) DropDB

func (s *Session) DropDB(name string) error

Drops database

func (*Session) Safe

func (s *Session) Safe(safe bool)

type Sort

type Sort struct {
	Variable  interface{} `json:"field"`
	Direction string      `json:"direction,omitempty"`
}

func (Sort) String

func (s Sort) String() string

type Stats

type Stats struct {
	FullCount int `json:"fullCount"`
}

type Transaction

type Transaction struct {
	Collections map[string][]string `json:"collections"`
	Action      string              `json:"action"`
	Result      interface{}         `json:"result,omitempty"`

	//Optional
	Sync      bool                   `json:"waitForSync,omitempty"`
	Lock      int                    `json:"lockTimeout,omitempty"`
	Replicate bool                   `json:"replicate,omitempty"`
	Params    map[string]interface{} `json:"params,omitempty"`
	Time      time.Duration          `json:"time,omitempty"`

	//ErrorInfo
	Error bool `json:"error,omitempty"`
	Code  int  `json:"code,omitempty"`
	Num   int  `json:"errorNum,omitempty"`
}

func NewTransaction

func NewTransaction(q string, write []string, read []string) *Transaction

func (*Transaction) Execute

func (t *Transaction) Execute(db *Database) error

type Traversal

type Traversal struct {
	StartVertex string     `json:"startVertex"`
	Filter      string     `json:"filter"`
	MinDepth    int        `json:"minDepth"`
	MaxDepth    int        `json:"maxDepth"`
	Visitor     string     `json:"visitor"`
	Direction   string     `json:"direction"`
	Init        string     `json:"init"`
	Expander    string     `json:"expander"`
	Sort        string     `json:"sort"`
	Strategy    string     `json:"strategy"`
	Order       string     `json:"order"`
	ItemOrder   string     `json:"itemOrder"`
	Unique      Uniqueness `json:"uniqueness"`
	MaxIter     int        `json:"maxIterations"`
	// contains filtered or unexported fields
}

type Uniqueness

type Uniqueness struct {
	Edges    string `json:"edges"`
	Vertices string `json:"vertices"`
}

type User

type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Active   bool   `json:"active"`
	Extra    string `json:"extra"`
}

type Var

type Var struct {
	Obj  string
	Name string
}

AQL Variable

func Atr

func Atr(obj, name string) Var

func Col

func Col(name string) Var

Represent AQL collection

func (Var) String

func (v Var) String() string

Jump to

Keyboard shortcuts

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