ndgo

package module
v5.0.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2021 License: MIT Imports: 7 Imported by: 0

README

ndgo Build Status codecov Go Report Card Maintainability GoDoc

ndgo provides dgraph dgo txn abstractions and helpers.

Why

  • Reduce txn related boilerplate, thus making code more readable,
  • Make using ratel like queries easier,
  • Get query execution times the easy way, even for multi-query txns,
  • Be low level - don't do magic, keep dgo things exposed for them to be usable, if necessary,
  • No performance overhead compared to dgo, if possible.

Install

go get -u github.com/ppp225/ndgo
import (
  "github.com/ppp225/ndgo/v5"
)

Common uses

Run transactions the same way one would do in ratel:

q := QueryDQL(fmt.Sprintf(`
  {
    %s(func: eq(%s, "%s")) {
      uid
      name
    }
  }
  `, "favActor", "name", "Keanu Reeves"))

resp, err := q.Run(txn)

Or marshal structs:

jsonBytes, err := json.Marshal(myObj)
if err != nil {
  return nil, err
}
resp, err := txn.Setb(jsonBytes, nil)

Or don't:

resp, err := txn.Seti(myObj, myObj2, myObj3)

Do Upserts:

q := `{ a as var(func: eq(name, "Keanu")) }`
myObj := personStruct{
	UID:  "uid(a)",
	Type: "Person",
	Name: "Keanu",
}
resp, err := txn.DoSeti(q, myObj)

See TestBasic and TestComplex and TestTxnUpsert in ndgo_test.go for a complete example.

ndgo.Txn

Create a transaction:
dg := NewDgraphClient()
txn := ndgo.NewTxn(ctx, dg.NewTxn()) // or dg.NewReadOnlyTxn(), you can use any available dgo.txn options. You can also use ndgo.NewTxnWithoutContext(txn)
defer txn.Discard()
...
err = txn.Commit()
Do mutations and queries:
resp, err := txn.Mutate(*api.Mutation)
resp, err := txn.Setb(jsonBytes, rdfBytes)
resp, err := txn.Seti(myObjs...)
resp, err := txn.Setnq(nquads)
resp, err := txn.Deleteb(jsonBytes, deleteRdfBytes)
resp, err := txn.Deletei(myObjs...)
resp, err := txn.Deletenq(nquads)

resp, err := txn.Query(queryString)
resp, err := txn.QueryWithVars(queryWithVarsString, vars...)

resp, err := txn.Do(req *api.Request)
resp, err := txn.DoSetb(queryString, jsonBytes)
resp, err := txn.DoSeti(queryString, myObjs...)
resp, err := txn.DoSetnq(queryString, nquads)
Get diagnostics:
dbms := txn.GetDatabaseTime()
nwms := txn.GetNetworkTime()

ndgo.Set/Delete JSON/RDF

Define and run txns through json, rdf or predefined helpers

Set:
set := ndgo.SetJSON(fmt.Sprintf(`
  {
    "name": "%s",
    "age": "%s"
  }`, "L", "25"))
// or
set := ndgo.SetRDF(`<_:new> <name> "L" .
                    <_:new> <age> "25" .`)
// or
set := ndgo.Query{}.SetPred("_:new", name, "L") + 
       ndgo.Query{}.SetPred("_:new", age, "25")

resp, err := set.Run(txn)
Delete:
del := ndgo.DeleteJSON(fmt.Sprintf(`
  {
    "uid": "%s"
  }
  `, uid))
// or
del := ndgo.Query{}.DeleteNode("0x420") + 
       ndgo.Query{}.DeleteEdge("0x420", "edgeName", "0x42") +
       ndgo.Query{}.DeletePred("0x42", "name")

resp, err := del.Run(txn)
Query:
q := ndgo.QueryDQL(fmt.Sprintf(`
  {
    %s(func: eq(%s, "%s")) {
      uid
    }
  }
  `, "favActor", "name", "Keanu Reeves"))

response, err := q.Run(txn)
Join:

You can chain queries and JSON mutations with Join, RDF mutations with + operator, assuming they are the same type:

q1 := ndgo.QueryDQL(`{q1(func:eq(name,"a")){uid}})`
q2 := ndgo.QueryDQL(`{q2(func:eq(name,"b")){uid}})`
resp, err := q1.Join(q2).Run(txn)

Note that query blocks have to be named uniquely.

Other helpers

FlattenResp

Sometimes, when querying dgraph, we want just 1 resulting element, instead of a nested array.

// Instead of having this:
type Queries struct {
  Q []struct {
    UID string `json:"uid"`
  } `json:"q"`
}
// We can have:
type MyObj struct {
  UID string `json:"uid"`
}
resp, _ := ndgo.QueryDQL(`{q(func:uid(0x123)){uid}}`).Run(txn)
// query block name -------^ must be one letter and only one query block must be in the query for this helper to work!
var result MyObj
if err := json.Unmarshal(ndgo.Unsafe{}.FlattenRespToObject(resp.GetJson()), &result); err != nil {
	panic(err) // will fail, if result has more than 1 element!
}
var resultSlice []MyObj
if err := json.Unmarshal(ndgo.Unsafe{}.FlattenRespToArray(resp.GetJson()), &resultSlice); err != nil {
	panic(err) // will fail, if multiple query blocks are used in Query, but can have multiple results!
}
log.Print(result)
log.Print(resultSlice)

Future plans

  • add more upsert things

Note

This project uses semantic versioning, see the changelog for details.

Documentation

Overview

Package ndgo <read iNDiGO> provides dgo abstractions and helpers - github.com/ppp225/ndgo

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug()

Debug enables logging of all requests and responses Uses the default std logger

Types

type DeleteJSON

type DeleteJSON string

DeleteJSON represents a dgraph delete mutation string with some methods defined

func (DeleteJSON) Join

func (v DeleteJSON) Join(json DeleteJSON) DeleteJSON

Join allows to join multiple json Query of same type

func (DeleteJSON) Run

func (v DeleteJSON) Run(t *Txn) (resp *api.Response, err error)

Run makes a dgraph db delete mutation (need to be in an array for Join to work)

type DeleteRDF

type DeleteRDF string

DeleteRDF represents a dgraph delete rdf mutation string with some methods defined

func (DeleteRDF) Run

func (v DeleteRDF) Run(t *Txn) (resp *api.Response, err error)

Run makes a dgraph db delete mutation

type Query

type Query struct{}

Query groups. Usage: ndgo.Query{}... It's recommended to create your own helpers, than to use the build in ones.

func (Query) DeleteEdge

func (Query) DeleteEdge(from, predicate, to string) DeleteRDF

DeleteEdge Usage: _, err = ndgo.Query{}.DeleteEdge(parentUID, "edgeName", childUID).Run(txn)

func (Query) DeleteNode

func (Query) DeleteNode(uid string) DeleteRDF

DeleteNode Usage: _, err = ndgo.Query{}.DeleteNode(UID).Run(txn)

func (Query) DeletePred

func (Query) DeletePred(uid, predicate string) DeleteRDF

DeletePred Usage: ndgo.Query{}.DeletePred(from, predicate)

func (Query) GetPredExpandType

func (Query) GetPredExpandType(blockID, fx, pred, val, funcParams, directives, dgPreds, dgTypes string) QueryDQL

GetPredExpandType constructs a complete query. It's for convenience, so formatting can be done only once. Also one liner! Usage: resp, err := ndgo.Query{}.GetPredExpandType("q", "eq", predicate, value, ",first:1", "", "uid dgraph.type", dgTypes).Run(txn)

func (Query) GetUIDExpandType

func (Query) GetUIDExpandType(blockID, fx, uid, funcParams, directives, dgPreds, dgTypes string) QueryDQL

GetUIDExpandType constructs a complete query. It's for convenience, so formatting can be done only once. Also one liner! Usage: resp, err := ndgo.Query{}.GetUIDExpandType("q", "uid", uid, "", "", "", "_all_").Run(txn)

func (Query) SetEdge

func (Query) SetEdge(from, predicate, to string) SetRDF

SetEdge Usage: ndgo.Query{}.SetEdge(from, predicate, to)

func (Query) SetPred

func (Query) SetPred(uid, predicate, value string) SetRDF

SetPred Usage: ndgo.Query{}.SetPred(uid, predicate, value)

type QueryDQL

type QueryDQL string

QueryDQL represents a dgraph query string with some methods defined

func (QueryDQL) Join

func (v QueryDQL) Join(json QueryDQL) QueryDQL

Join allows to join multiple json Query of same type

func (QueryDQL) Run

func (v QueryDQL) Run(t *Txn) (resp *api.Response, err error)

Run makes a dgraph db query

type SetJSON

type SetJSON string

SetJSON represents a dgraph set mutation string with some methods defined

func (SetJSON) Join

func (v SetJSON) Join(json SetJSON) SetJSON

Join allows to join multiple json Query of same type

func (SetJSON) Run

func (v SetJSON) Run(t *Txn) (resp *api.Response, err error)

Run makes a dgraph db set mutation (need to be in an array for Join to work)

type SetRDF

type SetRDF string

SetRDF represents a dgraph set rdf mutation string with some methods defined

func (SetRDF) Run

func (v SetRDF) Run(t *Txn) (resp *api.Response, err error)

Run makes a dgraph db set mutation

type Txn

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

Txn is a dgo.Txn wrapper with additional diagnostic data Helps with Queries, by providing abstractions for dgraph Query and Mutation

func NewTxn

func NewTxn(ctx context.Context, txn *dgo.Txn) *Txn

NewTxn creates new Txn (with ctx)

func NewTxnWithoutContext

func NewTxnWithoutContext(txn *dgo.Txn) *Txn

NewTxnWithoutContext creates new Txn (without ctx)

func (*Txn) Commit

func (v *Txn) Commit() (err error)

Commit commits dgo.Txn

func (*Txn) Deleteb

func (v *Txn) Deleteb(json, rdf []byte) (resp *api.Response, err error)

Deleteb is equivalent to Mutate using DeleteJson or DelNquads

func (*Txn) Deletei

func (v *Txn) Deletei(jsonMutations ...interface{}) (resp *api.Response, err error)

Deletei is equivalent to Deleteb, but it marshalls structs into one slice of mutations

func (*Txn) Deletenq

func (v *Txn) Deletenq(rdf string) (resp *api.Response, err error)

Deletenq is equivalent to Mutate using DelNquads

func (*Txn) Discard

func (v *Txn) Discard()

Discard cleans up dgo.Txn resources. Always defer this on creation.

func (*Txn) Do

func (v *Txn) Do(req *api.Request) (resp *api.Response, err error)

Do executes a query followed by one or more mutations. Possible to run query without mutations, or vice versa

func (*Txn) DoSetb

func (v *Txn) DoSetb(query, cond string, json, rdf []byte) (resp *api.Response, err error)

DoSetb is equivalent to Do using mutation with SetJson or SetNquads

func (*Txn) DoSeti

func (v *Txn) DoSeti(query string, jsonMutations ...interface{}) (resp *api.Response, err error)

DoSeti is equivalent to Do, but it marshalls structs into mutations

func (*Txn) DoSetnq

func (v *Txn) DoSetnq(query, nquads string) (resp *api.Response, err error)

DoSetnq is equivalent to Do using mutation with SetNquads

func (*Txn) GetDatabaseTime

func (v *Txn) GetDatabaseTime() float64

GetDatabaseTime gets time txn spend in db

func (*Txn) GetNetworkTime

func (v *Txn) GetNetworkTime() float64

GetNetworkTime gets total time until response

func (*Txn) Mutate

func (v *Txn) Mutate(mu *api.Mutation) (resp *api.Response, err error)

Mutate performs dgraph mutation

func (*Txn) Query

func (v *Txn) Query(q string) (resp *api.Response, err error)

Query performs dgraph query

func (*Txn) QueryWithVars

func (v *Txn) QueryWithVars(q string, vars map[string]string) (resp *api.Response, err error)

QueryWithVars performs dgraph query with vars

func (*Txn) Setb

func (v *Txn) Setb(json, rdf []byte) (resp *api.Response, err error)

Setb is equivalent to Mutate using SetJson or SetNquads

func (*Txn) Seti

func (v *Txn) Seti(jsonMutations ...interface{}) (resp *api.Response, err error)

Seti is equivalent to Setb, but it marshalls structs into one slice of mutations

func (*Txn) Setnq

func (v *Txn) Setnq(rdf string) (resp *api.Response, err error)

Setnq is equivalent to Mutate using SetNquads

type Unsafe

type Unsafe struct{}

Unsafe collects helpers, which require knowledge of how they work to operate correctly

func (Unsafe) FlattenRespToArray

func (Unsafe) FlattenRespToArray(bytes []byte) []byte

FlattenRespToArray flattens resp.GetJson() to only contain array without query block. i.e. transforms `{"q":[...]}` to `[...]`. QueryBlockID must be single letter. One QueryBlock supported, otherwise will return gibberish and unmarshal will error.

func (Unsafe) FlattenRespToObject

func (Unsafe) FlattenRespToObject(toFlatten []byte) []byte

FlattenRespToObject flattens resp.GetJson() to only contain a single object, without array or query block. i.e. transforms `{"q":[{...}]}` to `{...}`. QueryBlockID must be single letter. One QueryBlock supported. Response array should only have 0 or 1 object, otherwise will return gibberish and unmarshal will error.

Jump to

Keyboard shortcuts

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