dga

package module
v0.31.1 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2020 License: MIT Imports: 12 Imported by: 0

README

dgraph-access

Build Status Go Report Card GoDoc

This is a helper package to work with github.com/dgraph-io/dgo (v2), a Go client for accessing a DGraph cluster. See the examples folder for complete programs.

status

This package is under development (see commits); the API and scope may change before a v1.0.0 release.

motivation

This package was created to reduce the boilerplate code required to use the raw dgraph Go client. dgraph-access adds the following features to the standard Go client:

  • type UID and NQuad to create RDF triples w/o facets
  • type Node to encapsulate an uid and graph.type for your own entities
  • type DgraphAccess to handle transactions, JSON marshalling and populating entities
  • type Mutation to encapsulate a dgraph mutations that contains a list of RDF triples (NQuad values)
  • UpsertNode, CreateNode, CreateEdge, RunQuery, FindEquals model common dgraph operations
  • DgraphAccess can trace the queries, mutations and responses for debugging
  • DgraphAccess also provides a fluent interface for the operations

usage

import (
    dga "github.com/emicklei/dgraph-access"
)

example

See documented code examples

See examples

© 2019-2020, ernestmicklei.com. MIT License. Contributions welcome.

Documentation

Overview

Package dga is a helper package to work with `github.com/dgraph-io/dgo` (v2), a Go client for accessing a DGraph cluster.

Index

Examples

Constants

View Source
const (
	// Star is used to model any predicate or any object in an NQuad.
	Star = "*"

	// DateTimeFormat is the format used by Dgraph for facet values of type dateTime.
	DateTimeFormat = "2006-01-02T15:04:05"

	// DgraphType is a reserved predicate name to refer to a type definition.
	DgraphType = "dgraph.type"
)
View Source
const (
	// RDFString is a RDF type
	RDFString   = RDFDatatype("<xs:string>")
	RDFDateTime = RDFDatatype("<xs:dateTime>")
	RDFDate     = RDFDatatype("<xs:date>")
	RDFInt      = RDFDatatype("<xs:int>")
	RDFInteger  = RDFDatatype("<xs:integer>")
	RDFBoolean  = RDFDatatype("<xs:boolean>")
	RDFDouble   = RDFDatatype("<xs:double>")
	RDFFloat    = RDFDatatype("<xs:float>")
)

see https://docs.dgraph.io/mutations/#language-and-rdf-types

Variables

View Source
var (
	// ErrNoClient is a DGraphAccess state error
	ErrNoClient = errors.New("dgo client not initialized")

	// ErrNoTransaction is a DGraphAccess state error
	ErrNoTransaction = errors.New("dgo transaction not created")

	// ErrNoContext is a DGraphAccess state error
	ErrNoContext = errors.New("dgo transaction context not created")

	// ErrUnmarshalQueryResult is returned when the result of a query cannot be unmarshalled from JSON
	ErrUnmarshalQueryResult = errors.New("failed to unmarshal query result")
)

Functions

func IsZeroOfUnderlyingType added in v0.31.0

func IsZeroOfUnderlyingType(x interface{}) bool

Types

type AlterSchema added in v0.26.0

type AlterSchema struct {
	Source string
}

AlterSchema represents a Dgraph operation.

func (AlterSchema) Do added in v0.26.0

func (a AlterSchema) Do(d *DGraphAccess) error

Do performs the alert operation on the client.

type CreateEdge added in v0.26.0

type CreateEdge struct {
	Subject   HasUID
	Predicate string
	Object    interface{}
	Facets    map[string]interface{}
}

CreateEdge represents a Dgraph operation.

func (CreateEdge) Do added in v0.26.0

func (c CreateEdge) Do(d *DGraphAccess) (created bool, fail error)

Do creates a new Edge (using an NQuad). If Subject is a non-created Node than create it first ; abort if error If Object is a non-created Node than create it first ; abort if error Returns an error if the mutation fails. Returns whether the edge was created when the absent check was requested. Requires a DGraphAccess with a Write transaction.

type CreateNode added in v0.26.0

type CreateNode struct {
	Node HasUID
	// contains filtered or unexported fields
}

CreateNode models the operation to (conditionally) create a Dgraph node.

func (*CreateNode) CreateUnless added in v0.31.0

func (c *CreateNode) CreateUnless(predicate string, object interface{})

CreateUnless is a means to conditionally create the node. Create unless [predicate=object] for uids of the same type is true.

func (CreateNode) Do added in v0.26.0

func (c CreateNode) Do(d *DGraphAccess) (created bool, fail error)

Do creates a new Node. Return an error if the mutation fails. Requires a DGraphAccess with a Write transaction.

type DGraphAccess

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

DGraphAccess is a decorator for a dgo.Client that holds a Context and Transaction to perform queries and mutations.

func NewDGraphAccess

func NewDGraphAccess(client *dgo.Dgraph) *DGraphAccess

NewDGraphAccess returns a new DGraphAccess using a client.

func (*DGraphAccess) CheckState added in v0.27.0

func (d *DGraphAccess) CheckState() error

CheckState verifies that the Access can be used for a transaction (write | read only)

func (*DGraphAccess) Commit added in v0.21.0

func (d *DGraphAccess) Commit() error

Commit completes the current transaction. Return an error if the DGraphAccess is in the wrong state or if the Commit fails. Requires a DGraphAccess with a Write transaction.

func (*DGraphAccess) Discard added in v0.21.0

func (d *DGraphAccess) Discard() error

Discard aborts the current transaction (unless absent).

func (*DGraphAccess) Do added in v0.26.0

func (d *DGraphAccess) Do(o Operation) (hadEffect bool, err error)

Do executes the operation. Return whether the operation had effect or an error.

func (*DGraphAccess) Fluent added in v0.26.0

func (d *DGraphAccess) Fluent() Fluent

Fluent gives access to the fluent interface of DGraphAccess.

func (*DGraphAccess) ForReadOnly

func (d *DGraphAccess) ForReadOnly(ctx context.Context) *DGraphAccess

ForReadOnly returns a copy of DGraphAccess ready to perform read operations only.

func (*DGraphAccess) ForReadWrite

func (d *DGraphAccess) ForReadWrite(ctx context.Context) *DGraphAccess

ForReadWrite returns a copy of DGraphAccess ready to perform mutations.

func (*DGraphAccess) InTransactionDo

func (d *DGraphAccess) InTransactionDo(ctx context.Context, do func(da *DGraphAccess) error) error

InTransactionDo calls a function with a prepared DGraphAccess with a Write transaction. The encapsulated transaction is available from the receiver using Transaction(). Return an error if the Commit fails.

func (*DGraphAccess) Transaction added in v0.21.0

func (d *DGraphAccess) Transaction() *dgo.Txn

Transaction returns the encapsulated transaction (if present).

func (*DGraphAccess) WithTraceLogging

func (d *DGraphAccess) WithTraceLogging() *DGraphAccess

WithTraceLogging returns a copy of DGraphAccess that will trace parts of its internals.

type DGraphTransaction added in v0.12.0

type DGraphTransaction interface {
	Mutate(ctx context.Context, mu *api.Mutation) (*api.Response, error)
	Commit(ctx context.Context) error
	Discard(ctx context.Context) error
	Do(ctx context.Context, req *api.Request) (*api.Response, error)
	Query(ctx context.Context, q string) (*api.Response, error)
}

DGraphTransaction exists for testing. It has only the methods this package needs from a *dgo.Txn

type FindEquals added in v0.26.0

type FindEquals struct {
	Predicate string
	Object    interface{}
	Result    interface{}
}

FindEquals populates the result with the result of matching a predicate with a value.

func (FindEquals) Do added in v0.26.0

func (f FindEquals) Do(d *DGraphAccess) (hadEffect bool, err error)

Do populates the result with the result of matching a predicate with a value.

type Fluent added in v0.26.0

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

Fluent gives access to the fluent interface of DGraphAccess.

func (Fluent) AlterSchema added in v0.26.0

func (f Fluent) AlterSchema(source string) error

AlterSchema uses a schema definition to change the current DGraph schema. This operation is idempotent. Requires a DGraphAccess with a Write transaction.

func (Fluent) CreateEdge added in v0.26.0

func (f Fluent) CreateEdge(subject HasUID, predicate string, object interface{}) error

CreateEdge creates a new Edge (using an NQuad). Return an error if the mutation fails. Requires a DGraphAccess with a Write transaction. If subject is a non-created Node than create it first ; abort if error If object is a non-created Node than create it first ; abort if error

func (Fluent) CreateNode added in v0.26.0

func (f Fluent) CreateNode(node HasUID) error

CreateNode creates a new Node. Return an error if the mutation fails. Requires a DGraphAccess with a Write transaction.

func (Fluent) FindEquals added in v0.26.0

func (f Fluent) FindEquals(result interface{}, predicateName string, value interface{}) (bool, error)

FindEquals populates the result with the result of matching a predicate with a value.

func (Fluent) RunQuery added in v0.26.0

func (f Fluent) RunQuery(result interface{}, query string, dataKey string) (bool, error)

RunQuery executes the raw query and populates the result with the data found using a given key.

func (Fluent) UpsertNode added in v0.31.1

func (f Fluent) UpsertNode(node HasUID, predicate string, object interface{}) (wasCreated bool, err error)

UpsertNode creates (insert) or updates a Node. The operation will update iff the predicate -> object. Return an error if the mutation fails. Requires a DGraphAccess with a Write transaction.

type HasUID

type HasUID interface {
	SetUID(uid UID)
	GetUID() UID
	SetType(typeName string)
	GetTypes() []string
}

HasUID is used in CreateNode to set the assigned UID to a typed value.

type Mutation

type Mutation struct {
	// set, delete
	Operation string
	//
	NQuads []NQuad
}

Mutation represents an action with multiple RDF Triples represented by NQuad values.

func (Mutation) RDF

func (m Mutation) RDF() string

RDF returns the string representation of the Mutation.

type NQuad

type NQuad struct {
	// Subject is the node for which the predicate must be created/modified.
	Subject UID

	// Predicate is a known schema predicate or a Star
	Predicate string

	// Object can be a primitive value or a UID or a Star (constant)
	Object interface{}

	// StorageType is used to optionally specify the type when storing the object
	// see https://docs.dgraph.io/mutations/#language-and-rdf-types
	// Example: dga.RDFString
	StorageType RDFDatatype

	// Maps to string, bool, int, float and dateTime.
	// For int and float, only 32-bit signed integers and 64-bit floats are accepted.
	Facets map[string]interface{}
}

NQuad represents an RDF S P O pair.

func BlankNQuad

func BlankNQuad(subjectName string, predicate string, object interface{}) NQuad

BlankNQuad returns an NQuad value with a Blank UID subject. Use BlankUID if you want the object also to be a Blank UID from a name.

Example
fmt.Println(BlankNQuad("subject", "predicate", 42).RDF())
Output:

_:subject <predicate> "42" .
Example (Blankobject)
fmt.Println(BlankNQuad("parent-Sylvia", "children", BlankUID("child-Max")).RDF())
Output:

_:parent-Sylvia <children> _:child-Max .

func ReflectNQuads added in v0.31.0

func ReflectNQuads(uid UID, value HasUID) (list []NQuad)

func (NQuad) Bytes

func (n NQuad) Bytes() []byte

Bytes returns the mutation line.

func (NQuad) RDF

func (n NQuad) RDF() string

RDF returns the string version of its Bytes representation.

func (NQuad) WithFacet

func (n NQuad) WithFacet(key string, value interface{}) NQuad

WithFacet returns a copy with an additional facet (key=value).

func (NQuad) WithStorageType added in v0.12.3

func (n NQuad) WithStorageType(t RDFDatatype) NQuad

WithStorageType returns a copy with its StorageType set. Use DetectStorageType(any interface{})

type Node added in v0.16.0

type Node struct {
	UID   UID      `json:"uid,omitempty"`
	DType []string `json:"dgraph.type,omitempty"`
}

Node is an abstract type that encapsulates a Dgraph identity (uid) and type (dgraph.type) Node can be used to embed in your own entity type, e.g.:

type Person struct {
   dga.Node    `json:",inline"`
   Name string `json:"name"`
}

func (Node) GetTypes added in v0.17.0

func (n Node) GetTypes() []string

GetTypes returns the graph.type value(s).

func (Node) GetUID added in v0.16.0

func (n Node) GetUID() UID

GetUID gets the dgraph uid

func (*Node) SetType added in v0.17.0

func (n *Node) SetType(typeName string)

SetType set or adds a graph.type for value that embeds the node.

func (*Node) SetUID added in v0.16.0

func (n *Node) SetUID(uid UID)

SetUID sets the dgraph uid

type Operation added in v0.26.0

type Operation interface {
	Do(d *DGraphAccess) (hadEffect bool, err error)
}

Operation is for dispatching commands using a DGraphAccess.

type RDFDatatype added in v0.12.3

type RDFDatatype string

RDFDatatype is to set the StorageType of an NQuad.

type RunQuery added in v0.26.0

type RunQuery struct {
	Result  interface{}
	Query   string
	DataKey string
}

RunQuery executes the raw query and populates the result with the data found using a given key.

func (RunQuery) Do added in v0.26.0

func (r RunQuery) Do(d *DGraphAccess) (hadEffect bool, err error)

Do executes the raw query and populates the result with the data found using a given key.

type UID

type UID struct {
	// Str is exposed for JSON marshalling. Do not use it to read/write it directly.
	Str string
	// contains filtered or unexported fields
}

UID represents a DGraph uid which can be expressed using an integer,string or undefined value.

func BlankUID

func BlankUID(name string) UID

BlankUID returns an UID with an undefined uid and a local name only valid for one write transaction. .RDF() => _:name

Example
fmt.Println(BlankUID("canada").RDF())
Output:

_:canada

func IntegerUID

func IntegerUID(i int) UID

IntegerUID returns an UID using the integer value. .RDF() => <0x...>

Example
fmt.Println(IntegerUID(42).RDF())
Output:

<0x2a>

func NewUID added in v0.12.0

func NewUID(s string) UID

NewUID returns an UID that is printed as is. .RDF() => s

func StringUID

func StringUID(id string) UID

StringUID returns an UID using a string value for uid. .RDF() => <id>

Example
fmt.Println(StringUID("name").RDF())
Output:

<name>

func (UID) Assigned added in v0.19.0

func (u UID) Assigned() string

Assigned is the actual by DGraph assigned id number as string. Also, returns the string part enclosed in <..>.

TODO not sure about the name

func (UID) IsZero

func (u UID) IsZero() bool

IsZero returns whether this UID is a zero value

func (UID) MarshalJSON

func (u UID) MarshalJSON() ([]byte, error)

MarshalJSON is part of JSON

func (UID) RDF added in v0.12.0

func (u UID) RDF() string

RDF returns a string presentation for use in an NQuad. Eg. <0x12>

func (UID) String

func (u UID) String() string

String is for debugging only. Eg. UID(<0x13>)

func (*UID) UnmarshalJSON

func (u *UID) UnmarshalJSON(data []byte) error

UnmarshalJSON is part of JSON

type UpsertNode added in v0.31.0

type UpsertNode struct {
	Node HasUID
	// contains filtered or unexported fields
}

UpsertNode models the operation to insert (create) or update a Dgraph node.

func (UpsertNode) Do added in v0.31.0

func (u UpsertNode) Do(d *DGraphAccess) (created bool, fail error)

Do creates or updates a new Node. Return an error if the mutation fails. Requires a DGraphAccess with a Write transaction.

func (*UpsertNode) InsertUnless added in v0.31.0

func (u *UpsertNode) InsertUnless(predicate string, object interface{})

InsertUnless set the condition to update versus insert the node.

Directories

Path Synopsis
cmd
dggen Module

Jump to

Keyboard shortcuts

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