gogm

package module
v2.3.10 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2022 License: MIT Imports: 19 Imported by: 0

README

Go Report Card Actions Status GoDoc

GoGM Golang Object Graph Mapper v2

Installation

go get github.com/mindstand/gogm/v2

Note: Do not use -u when installing. If you do, gogm will not compile.

This is caused by a dependency being updated to go1.18 making it incompatable with go1.17. In a future update, gogm will be updated to go1.18 eliminating this issue.

Features

  • Struct Mapping through the gogm struct decorator
  • Full support for ACID transactions
  • Underlying connection pooling
  • Support for HA Casual Clusters using bolt+routing through the Official Neo4j Go Driver
  • Custom queries in addition to built in functionality
  • Builder pattern cypher queries using MindStand's cypher dsl package
  • CLI to generate link and unlink functions for gogm structs.
  • Multi database support with Neo4j v4

What's new in V2

  • GoGM is an object now! This means you can have multiple instances of GoGM at a time
  • OpenTracing and Context Support
  • Driver has been updated from v1.6 to v4
  • Log interface, so anyone can use the logger of their choice instead of being forced to use logrus
  • Primary Key strategies to use any type of primary key. GoGM is no longer UUID only!
  • TLS now supported

| Note: GoGM v1 has been deprecated.

Usage

Primary Key Strategy

Primary key strategies allow more customization over primary keys. A strategy is provided to gogm on initialization.
Built in primary key strategies are:

  • gogm.DefaultPrimaryKeyStrategy -- just use the graph id from neo4j as the primary key
  • gogm.UUIDPrimaryKeyStrategy -- uuid's as primary keys
// Example of the internal UUID strategy
PrimaryKeyStrategy{
	// StrategyName is the name to reference the strategy
    StrategyName: "UUID",
    // DBName is the name of the field in the database
    DBName:       "uuid",
    // FieldName is the name of the field in go, this will validate to make sure all pk's use the same field name
    FieldName:    "UUID",
    // Type is the reflect type of the primary key, in this case it's a string but it can be any primitive
    Type:         reflect.TypeOf(""),
    // GenIDFunc defines how new ids are generated, in this case we're using googles uuid library
    GenIDFunc: func() (id interface{}) {
        return uuid.New().String()
    },
}
Load Strategy

Load strategies allow control over the queries generated by Load operations. Different strategies change the size of the queries sent to the database as well as the amount of work the database has to do. A load strategy is provided to gomg on initialization.

The defined load strategies are:

  • gogm.PATH_LOAD_STRATEGY -- Use cypher path queries to generate simple queries for load operations.
  • gogm.SCHEMA_LOAD_STRATEGY -- Leverage the GoGM schema to generate more complex queries for load operations which results in less work for the database.

Depending on your use case, PATH_LOAD_STRATEGY may result in higher latency.

Struct Configuration
text notates deprecation

Decorators that can be used

  • name=<name> -- used to set the field name that will show up in neo4j.
  • relationship=<edge_name> -- used to set the name of the edge on that field.
  • direction=<INCOMING|OUTGOING|BOTH|NONE> -- used to specify direction of that edge field.
  • index -- marks field to have an index applied to it.
  • unique -- marks field to have unique constraint.
  • pk=<strategy_name> -- marks field as a primary key and specifies which pk strategy to use. Can only have one pk, composite pk's are not supported.
  • properties -- marks that field is using a map. GoGM only supports properties fields of map[string]interface{}, map[string]<primitive>, map[string][]<primitive> and []<primitive>
  • - -- marks that field will be ignored by the ogm
Not on relationship member variables

All relationships must be defined as either a pointer to a struct or a slice of struct pointers *SomeStruct or []*SomeStruct

Use ; as delimiter between decorator tags.

Ex.

type TdString string

type MyNeo4jObject struct {
  // provides required node field
  // use gogm.BaseUUIDNode if you want to use UUIDs
  gogm.BaseNode

  Field string `gogm:"name=field"`
  Props map[string]interface{} `gogm:"properties;name=props"` //note that this would show up as `props.<key>` in neo4j
  IgnoreMe bool `gogm="-"`
  UniqueTypeDef TdString `gogm:"name=unique_type_def"`
  Relation *SomeOtherStruct `gogm="relationship=SOME_STRUCT;direction=OUTGOING"`
  ManyRelation []*SomeStruct `gogm="relationship=MANY;direction=INCOMING"`
}

GOGM Usage
package main

import (
	"github.com/mindstand/gogm/v2"
	"time"
)

type tdString string
type tdInt int

//structs for the example (can also be found in decoder_test.go)
type VertexA struct {
	// provides required node fields
	gogm.BaseNode

    TestField         string                `gogm:"name=test_field"`
	TestTypeDefString tdString          `gogm:"name=test_type_def_string"`
	TestTypeDefInt    tdInt             `gogm:"name=test_type_def_int"`
	MapProperty       map[string]string `gogm:"name=map_property;properties"`
	SliceProperty     []string          `gogm:"name=slice_property;properties"`
    SingleA           *VertexB          `gogm:"direction=incoming;relationship=test_rel"`
	ManyA             []*VertexB        `gogm:"direction=incoming;relationship=testm2o"`
	MultiA            []*VertexB        `gogm:"direction=incoming;relationship=multib"`
	SingleSpecA       *EdgeC            `gogm:"direction=outgoing;relationship=special_single"`
	MultiSpecA        []*EdgeC          `gogm:"direction=outgoing;relationship=special_multi"`
}

type VertexB struct {
	// provides required node fields
	gogm.BaseNode

	TestField  string     `gogm:"name=test_field"`
	TestTime   time.Time  `gogm:"name=test_time"`
	Single     *VertexA   `gogm:"direction=outgoing;relationship=test_rel"`
	ManyB      *VertexA   `gogm:"direction=outgoing;relationship=testm2o"`
	Multi      []*VertexA `gogm:"direction=outgoing;relationship=multib"`
	SingleSpec *EdgeC     `gogm:"direction=incoming;relationship=special_single"`
	MultiSpec  []*EdgeC   `gogm:"direction=incoming;relationship=special_multi"`
}

type EdgeC struct {
	// provides required node fields
	gogm.BaseNode

	Start *VertexA
	End   *VertexB
	Test  string `gogm:"name=test"`
}

func main() {
	// define your configuration
	config := gogm.Config{
		Host:                      "0.0.0.0",
		Port:                      7687,
		// deprecated in favor of protocol
	    // IsCluster:                 false,
	    Protocol:                  "neo4j", //also supports neo4j+s, neo4j+ssc, bolt, bolt+s and bolt+ssc
	    // Specify CA Public Key when using +ssc or +s
	    CAFileLocation: "my-ca-public.crt",
		Username:                  "neo4j",
		Password:                  "password",
		PoolSize:                  50,
		IndexStrategy:             gogm.VALIDATE_INDEX, //other options are ASSERT_INDEX and IGNORE_INDEX
		TargetDbs:                 nil,
		// default logger wraps the go "log" package, implement the Logger interface from gogm to use your own logger
		Logger:             gogm.GetDefaultLogger(),
		// define the log level
		LogLevel:           "DEBUG",
		// enable neo4j go driver to log
		EnableDriverLogs:   false,
		// enable gogm to log params in cypher queries. WARNING THIS IS A SECURITY RISK! Only use this when debugging
		EnableLogParams:    false,
		// enable open tracing. Ensure contexts have spans already. GoGM does not make root spans, only child spans
		OpentracingEnabled: false,
		// specify the method gogm will use to generate Load queries
		LoadStrategy: gogm.PATH_LOAD_STRATEGY // set to SCHEMA_LOAD_STRATEGY for schema-aware queries which may reduce load on the database
	}

	// register all vertices and edges
	// this is so that GoGM doesn't have to do reflect processing of each edge in real time
	// use nil or gogm.DefaultPrimaryKeyStrategy if you only want graph ids
	// we are using the default key strategy since our vertices are using BaseNode
	_gogm, err := gogm.New(&config, gogm.DefaultPrimaryKeyStrategy, &VertexA{}, &VertexB{}, &EdgeC{})
	if err != nil {
		panic(err)
	}

	//param is readonly, we're going to make stuff so we're going to do read write
	sess, err := _gogm.NewSessionV2(gogm.SessionConfig{AccessMode: gogm.AccessModeWrite})
	if err != nil {
		panic(err)
	}

	//close the session
	defer sess.Close()

	aVal := &VertexA{
		TestField: "woo neo4j",
	}

	bVal := &VertexB{
		TestTime: time.Now().UTC(),
	}

	//set bi directional pointer
	bVal.Single = aVal
	aVal.SingleA = bVal

	err = sess.SaveDepth(context.Background(), aVal, 2)
	if err != nil {
		panic(err)
	}

	//load the object we just made (save will set the uuid)
	var readin VertexA
	err = sess.Load(context.Background(), &readin, aVal.UUID)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v", readin)
}


Migrating from V1 to V2

Initialization

Initialization in gogm v1

config := gogm.Config{
    IndexStrategy: gogm.VALIDATE_INDEX, //other options are ASSERT_INDEX and IGNORE_INDEX
    PoolSize:      50,
    Port:          7687,
    IsCluster:     false, //tells it whether or not to use `bolt+routing`
    Host:          "0.0.0.0",
    Password:      "password",
    Username:      "neo4j",
}

err := gogm.Init(&config, &VertexA{}, &VertexB{}, &EdgeC{})
if err != nil {
    panic(err)
}

Equivalent in GoGM v2

// define your configuration
config := gogm.Config{
    IndexStrategy: gogm.VALIDATE_INDEX, //other options are ASSERT_INDEX and IGNORE_INDEX
    PoolSize:      50,
    Port:          7687,
    IsCluster:     false, //tells it whether or not to use `bolt+routing`
    Host:          "0.0.0.0",
    Password:      "password",
    Username:      "neo4j",
}

	// register all vertices and edges
	// this is so that GoGM doesn't have to do reflect processing of each edge in real time
	// use nil or gogm.DefaultPrimaryKeyStrategy if you only want graph ids
	_gogm, err := gogm.New(&config, gogm.UUIDPrimaryKeyStrategy, &VertexA{}, &VertexB{}, &EdgeC{})
	if err != nil {
		panic(err)
	}
	
	gogm.SetGlobalGoGM(_gogm)
Note that we call gogm.SetGloablGogm so that we can still access it from a package level
Create a session

Creating a session in GoGM v1

sess, err := gogm.NewSession(false)
Note this still works in v2, its using the global gogm to create the session. Also note this is making an instance of the deprecated ISession

Equivalent in GoGM v2

// this would also work with a local instance of gogm (localGogm.NewSessionV2)
sess, err := gogm.G().NewSessionV2(gogm.SessionConfig{AccessMode: gogm.AccessModeWrite})
Summary
  • Minimal change requires creating a global gogm, everything else should still work with ISession (gogm v1 session object)
  • ISession is now deprecated but still supported
  • SessionV2 is the new standard
GoGM CLI

CLI Installation

go install github.com/mindstand/gogm/cmd/gogmcli@latest

CLI Usage

NAME:
   gogmcli - used for neo4j operations from gogm schema

USAGE:
   gogmcli [global options] command [command options] [arguments...]

VERSION:
   2.1.1

COMMANDS:
   generate, g, gen  to generate link and unlink functions for nodes
   help, h           Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --debug, -d    execute in debug mode (default: false)
   --help, -h     show help (default: false)
   --version, -v  print the version (default: false)

Inspiration

Inspiration came from the Java OGM implementation by Neo4j.

Road Map

  • Schema Migration
  • Errors overhaul using go 1.13 error wrapping

How you can help

  • Report Bugs
  • Fix bugs
  • Contribute (refer to contribute.md)

Documentation

Index

Constants

View Source
const AccessModeRead = neo4j.AccessModeRead
View Source
const AccessModeWrite = neo4j.AccessModeWrite

Variables

View Source
var (
	// ErrNotFound is returned when gogm is unable to find data
	ErrNotFound = errors.New("gogm: data not found")

	// ErrInternal is returned for general internal gogm errors
	ErrInternal = errors.New("gogm: internal error")

	// ErrValidation is returned when there is a validation error
	ErrValidation = errors.New("gogm: struct validation error")

	// ErrInvalidParams is returned when params to a function are invalid
	ErrInvalidParams = errors.New("gogm: invalid params")

	// ErrConfiguration is returned for configuration errors
	ErrConfiguration = errors.New("gogm: configuration was malformed")

	// ErrTransaction is returned for errors related to gogm transactions
	ErrTransaction = errors.New("gogm: transaction error")

	// ErrConnection is returned for connection related errors
	ErrConnection = errors.New("gogm: connection error")
)
View Source
var (
	UUIDPrimaryKeyStrategy = &PrimaryKeyStrategy{
		StrategyName: "UUID",
		DBName:       "uuid",
		FieldName:    "UUID",
		Type:         reflect.TypeOf(""),
		GenIDFunc: func() (id interface{}) {
			return uuid.New().String()
		},
		noop: false,
	}
	DefaultPrimaryKeyStrategy = &PrimaryKeyStrategy{
		StrategyName: "default",
		DBName:       "id",
		FieldName:    "Id",
		Type:         reflect.TypeOf(int64Ptr(0)),
		GenIDFunc: func() (id interface{}) {
			return ""
		},
		noop: true,
	}
)

Functions

func PathLoadStrategyEdgeConstraint

func PathLoadStrategyEdgeConstraint(startVariable, startLabel, endLabel, endTargetField string, minJumps, maxJumps, depth int, additionalConstraints dsl.ConditionOperator) (dsl.Cypher, error)

PathLoadStrategyEdgeConstraint is similar to load many, but requires that it is related to another node via some edge

func PathLoadStrategyMany

func PathLoadStrategyMany(variable, label string, depth int, additionalConstraints dsl.ConditionOperator) (dsl.Cypher, error)

PathLoadStrategyMany loads many using path strategy

func PathLoadStrategyOne

func PathLoadStrategyOne(variable, label, fieldOn, paramName string, isGraphId bool, depth int, additionalConstraints dsl.ConditionOperator) (dsl.Cypher, error)

PathLoadStrategyOne loads one object using path strategy

func SchemaLoadStrategyMany

func SchemaLoadStrategyMany(gogm *Gogm, variable, label string, depth int, additionalConstraints dsl.ConditionOperator) (dsl.Cypher, error)

SchemaLoadStrategyMany loads many using schema strategy

func SchemaLoadStrategyOne

func SchemaLoadStrategyOne(gogm *Gogm, variable, label, fieldOn, paramName string, isGraphId bool, depth int, additionalConstraints dsl.ConditionOperator) (dsl.Cypher, error)

SchemaLoadStrategyOne loads one object using schema strategy

func SetGlobalGogm

func SetGlobalGogm(gogm *Gogm)

SetGlobalGogm sets the global instance of gogm

Types

type BaseNode

type BaseNode struct {
	// Id is the GraphId that neo4j uses internally
	Id *int64 `json:"-" gogm:"pk=default"`

	// LoadMap represents the state of how a node was loaded for neo4j.
	// This is used to determine if relationships are removed on save
	// field -- relations
	LoadMap map[string]*RelationConfig `json:"-" gogm:"-"`
}

BaseNode contains fields that ALL GoGM nodes are required to have

type BaseUUIDNode

type BaseUUIDNode struct {
	BaseNode
	// UUID is the unique identifier GoGM uses as a primary key
	UUID string `gogm:"pk=UUID"`
}

type Config

type Config struct {
	// Host is the neo4j host
	Host string `yaml:"host" json:"host" mapstructure:"host"`
	// Port is the neo4j port
	Port int `yaml:"port" json:"port" mapstructure:"port"`

	// deprecated in favor of Protocol
	// IsCluster specifies whether GoGM is connecting to a casual cluster or not, will determine whether to use bolt or neo4j protocols
	IsCluster bool `yaml:"is_cluster" json:"is_cluster" mapstructure:"is_cluster"`

	// Protocol specifies which protocol gogm will connect to neo4j with
	// The options are neo4j, neo4j+s, neo4j+ssc, bolt, bolt+s and bolt+ssc
	Protocol string `json:"protocol" yaml:"protocol" mapstructure:"protocol"`

	// Username is the GoGM username
	Username string `yaml:"username" json:"username" mapstructure:"username"`

	// Password is the GoGM password
	Password string `yaml:"password" json:"password" mapstructure:"password"`

	// PoolSize is the size of the connection pool for GoGM
	PoolSize int `yaml:"pool_size" json:"pool_size" mapstructure:"pool_size"`

	// DefaultTransactionTimeout defines the default time a transaction will wait before timing out
	DefaultTransactionTimeout time.Duration `json:"default_transaction_timeout" yaml:"default_transaction_timeout" mapstructure:"default_transaction_timeout"`

	// Realm defines the realm passed into neo4j
	Realm string `yaml:"realm" json:"realm" mapstructure:"realm"`

	// deprecated: in favor of TLSConfig
	//these security configurations will be ignored if the protocol does not contain +s
	UseSystemCertPool bool `yaml:"use_system_cert_pool" mapstructure:"use_system_cert_pool"`

	// deprecated: in favor of TLSConfig
	// CAFileLocation defines the location of the CA file for authenticating with tls
	CAFileLocation string `yaml:"ca_file_location" mapstructure:"ca_file_location"`

	// TLSConfig defines the configuration for connecting to a neo4j cluster over tls
	TLSConfig *tls.Config `yaml:"tls_config" mapstructure:"tls_config"`

	// Index Strategy defines the index strategy for GoGM
	// Options for index strategy are:
	// IGNORE_INDEX - which does no index/constraint operations
	// VALIDATE_INDEX - which validates whether the indexes/constraints exist
	// ASSERT_INDEX - which deletes existing indexes/constraints for the given nodes then creates them
	IndexStrategy IndexStrategy `yaml:"index_strategy" json:"index_strategy" mapstructure:"index_strategy"`

	// TargetDbs tells gogm which databases to expect and is also what index operations use to know which dbs to execute against
	TargetDbs []string `yaml:"target_dbs" json:"target_dbs" mapstructure:"target_dbs"`

	// Logger specifies log interfaces that gogm will use to log
	Logger Logger `yaml:"-" json:"-" mapstructure:"-"`

	// LogLevel defines the log level that the logger will use
	// if logger is not nil log level will be ignored
	LogLevel string `json:"log_level" yaml:"log_level" mapstructure:"log_level"`

	// EnableDriverLogs tells the gogm whether to log logs coming out of the neo4j go driver
	EnableDriverLogs bool `json:"enable_driver_logs" yaml:"enable_driver_logs" mapstructure:"enable_driver_logs"`

	// EnableLogParams tells gogm whether to log params going into queries when on debug/trace log level
	// WARNING THIS IS A SECURITY RISK -- ONLY ENABLE THIS FOR DEBUG
	EnableLogParams bool `json:"enable_log_properties" yaml:"enable_log_properties" mapstructure:"enable_log_properties"`

	// OpentracingEnabled tells gogm whether to use open tracing
	OpentracingEnabled bool `json:"opentracing_enabled" yaml:"opentracing_enabled" mapstructure:"opentracing_enabled"`

	// LoadStrategy tells gogm how to generate load queries
	// The options are:
	// PATH_LOAD_STRATEGY - this generates queries based on path `match p=...`. The queries are less verbose than schema but generally slower
	// SCHEMA_LOAD_STRATEGY - this generates queries based on the gogm schema. The queries are a lot more verbose but will generally execute faster
	LoadStrategy LoadStrategy `json:"load_strategy" yaml:"load_strategy" mapstructure:"load_strategy"`
}

Config defines parameters for creating a GoGM object

func (*Config) ConnectionString

func (c *Config) ConnectionString() string

ConnectionString builds the neo4j connection string

type Edge

type Edge interface {
	// GetStartNode gets start node of edge
	GetStartNode() interface{}
	// GetStartNodeType gets reflect type of start node
	GetStartNodeType() reflect.Type
	// SetStartNode sets start node of edge
	SetStartNode(v interface{}) error

	// GetEndNode gets end node of edge
	GetEndNode() interface{}
	// GetEndNodeType gets reflect type of end node
	GetEndNodeType() reflect.Type
	// SetEndNode sets end node of edge
	SetEndNode(v interface{}) error
}

Edge specifies required functions for special edge nodes

type GenerateNewIDFunc

type GenerateNewIDFunc func() interface{}

type Gogm

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

Gogm defines an instance of the GoGM OGM with a configuration and mapped types

func G

func G() *Gogm

G returns the global instance of gogm

func New

func New(config *Config, pkStrategy *PrimaryKeyStrategy, mapTypes ...interface{}) (*Gogm, error)

New returns an instance of gogm mapTypes requires pointers of the types to map and will error out if pointers are not provided

func NewContext

func NewContext(ctx context.Context, config *Config, pkStrategy *PrimaryKeyStrategy, mapTypes ...interface{}) (*Gogm, error)

NewContext returns an instance of gogm but also takes in a context since NewContext creates a driver instance and reaches out to the database

func (*Gogm) Close

func (g *Gogm) Close() error

Close implements io.Closer and closes the underlying driver

func (*Gogm) Copy

func (g *Gogm) Copy() *Gogm

Copy creates a copy instance of gogm todo verify if its copying the members or just referencing their pointers if it is each member will need copy functionality

func (*Gogm) NewSession

func (g *Gogm) NewSession(conf SessionConfig) (ISession, error)

deprecated: use NewSessionV2 instead. NewSession returns an instance of the deprecated ISession

func (*Gogm) NewSessionV2

func (g *Gogm) NewSessionV2(conf SessionConfig) (SessionV2, error)

NewSessionV2 returns an instance of SessionV2 with the provided session config

type ISession

type ISession interface {
	//transaction functions
	ITransaction

	//load single object
	Load(respObj interface{}, id string) error

	//load object with depth
	LoadDepth(respObj interface{}, id string, depth int) error

	//load with depth and filter
	LoadDepthFilter(respObj interface{}, id string, depth int, filter dsl.ConditionOperator, params map[string]interface{}) error

	//load with depth, filter and pagination
	LoadDepthFilterPagination(respObj interface{}, id string, depth int, filter dsl.ConditionOperator, params map[string]interface{}, pagination *Pagination) error

	//load slice of something
	LoadAll(respObj interface{}) error

	//load all of depth
	LoadAllDepth(respObj interface{}, depth int) error

	//load all of type with depth and filter
	LoadAllDepthFilter(respObj interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}) error

	//load all with depth, filter and pagination
	LoadAllDepthFilterPagination(respObj interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}, pagination *Pagination) error

	// load all edge query
	// Deprecated: No equivalent function in SessionV2
	LoadAllEdgeConstraint(respObj interface{}, endNodeType, endNodeField string, edgeConstraint interface{}, minJumps, maxJumps, depth int, filter dsl.ConditionOperator) error

	//save object
	Save(saveObj interface{}) error

	//save object with depth
	SaveDepth(saveObj interface{}, depth int) error

	//delete
	Delete(deleteObj interface{}) error

	//delete uuid
	DeleteUUID(uuid string) error

	//specific query, responds to slice and single objects
	Query(query string, properties map[string]interface{}, respObj interface{}) error

	//similar to query, but returns raw rows/cols
	QueryRaw(query string, properties map[string]interface{}) ([][]interface{}, error)

	//delete everything, this will literally delete everything
	PurgeDatabase() error

	// closes session
	Close() error
}

ISession: V1 session object for ogm interactions Deprecated: use SessionV2 instead

type ITransaction

type ITransaction interface {
	// Begin begins transaction
	Begin() error
	// Rollback rolls back transaction
	Rollback() error
	// RollbackWithError wraps original error into rollback error if there is one
	RollbackWithError(err error) error
	// Commit commits transaction
	Commit() error
}

ITransaction specifies functions for Neo4j ACID transactions Deprecated: Use TransactionV2 instead

type IndexStrategy

type IndexStrategy int

IndexStrategy defines the different index approaches

const (
	// ASSERT_INDEX ensures that all indices are set and sets them if they are not there
	ASSERT_INDEX IndexStrategy = 0
	// VALIDATE_INDEX ensures that all indices are set
	VALIDATE_INDEX IndexStrategy = 1
	// IGNORE_INDEX skips the index step of setup
	IGNORE_INDEX IndexStrategy = 2
)

type InvalidDecoratorConfigError

type InvalidDecoratorConfigError struct {
	Field string
	Issue string
}

InvalidDecoratorConfigError defines an error for a malformed struct tag

func NewInvalidDecoratorConfigError

func NewInvalidDecoratorConfigError(issue, field string) *InvalidDecoratorConfigError

NewInvalidDecoratorConfigError creates an InvalidDecoratorConfigError structure

func (*InvalidDecoratorConfigError) Error

Error() implements builtin Error() interface

type InvalidStructConfigError

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

InvalidStructConfigError defines an error for a malformed gogm structure

func NewInvalidStructConfigError

func NewInvalidStructConfigError(issue string) *InvalidStructConfigError

NewInvalidStructConfigError creates an InvalidStructConfigError structure

func (*InvalidStructConfigError) Error

func (i *InvalidStructConfigError) Error() string

Error() implements builtin Error() interface

type LoadStrategy

type LoadStrategy int

Specifies query based load strategy

const (
	// PathLoadStrategy uses cypher path
	PATH_LOAD_STRATEGY LoadStrategy = iota
	// SchemaLoadStrategy generates queries specifically from generated schema
	SCHEMA_LOAD_STRATEGY
)

type Logger

type Logger interface {
	Debug(s string)
	Debugf(s string, vals ...interface{})

	Info(s string)
	Infof(s string, vals ...interface{})

	Warn(s string)
	Warnf(s string, vals ...interface{})

	Error(s string)
	Errorf(s string, vals ...interface{})

	Fatal(s string)
	Fatalf(s string, vals ...interface{})
}

func GetDefaultLogger

func GetDefaultLogger() Logger

type Pagination

type Pagination struct {
	// PageNumber specifies which page number to load
	PageNumber int
	// LimitPerPage limits how many records per page
	LimitPerPage int
	// OrderByVarName specifies variable to order by
	OrderByVarName string
	// OrderByField specifies field to order by on
	OrderByField string
	// OrderByDesc specifies whether orderby is desc or asc
	OrderByDesc bool
}

Pagination is used to control the pagination behavior of `LoadAllDepthFilterPagination“

func (*Pagination) Paginate

func (p *Pagination) Paginate(query dsl.Cypher) error

type PrimaryKeyStrategy

type PrimaryKeyStrategy struct {
	// StrategyName is the name of strategy to map field
	StrategyName string
	// DBName for field in the database
	DBName    string
	FieldName string
	// Type of uuid
	Type reflect.Type
	// GenIDFunc function to generate new id
	GenIDFunc GenerateNewIDFunc
	// contains filtered or unexported fields
}

type RelationConfig

type RelationConfig struct {
	// stores graph ids
	Ids []int64 `json:"-" gomg:"-"`
	// specifies relationship type
	RelationType RelationType `json:"-"  gomg:"-"`
}

RelationConfig specifies how relationships are loaded

type RelationType

type RelationType int

Specifies Type of testRelationship

const (
	// Side of relationship can only point to 0 or 1 other nodes
	Single RelationType = 0

	// Side of relationship can point to 0+ other nodes
	Multi RelationType = 1
)

type Session deprecated

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

Deprecated: Session will be removed in a later release in favor of SessionV2

func NewSession

func NewSession(readonly bool) (*Session, error)

uses global gogm Deprecated: Gogm.NewSession instead

func NewSessionWithConfig deprecated

func NewSessionWithConfig(conf SessionConfig) (*Session, error)

Deprecated: Gogm.NewSessionWithConfig instead

func (*Session) Begin

func (s *Session) Begin() error

func (*Session) Close

func (s *Session) Close() error

func (*Session) Commit

func (s *Session) Commit() error

func (*Session) Delete

func (s *Session) Delete(deleteObj interface{}) error

func (*Session) DeleteUUID

func (s *Session) DeleteUUID(uuid string) error

func (*Session) Load

func (s *Session) Load(respObj interface{}, id string) error

func (*Session) LoadAll

func (s *Session) LoadAll(respObj interface{}) error

func (*Session) LoadAllDepth

func (s *Session) LoadAllDepth(respObj interface{}, depth int) error

func (*Session) LoadAllDepthFilter

func (s *Session) LoadAllDepthFilter(respObj interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}) error

func (*Session) LoadAllDepthFilterPagination

func (s *Session) LoadAllDepthFilterPagination(respObj interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}, pagination *Pagination) error

func (*Session) LoadAllEdgeConstraint

func (s *Session) LoadAllEdgeConstraint(respObj interface{}, endNodeType, endNodeField string, edgeConstraint interface{}, minJumps, maxJumps, depth int, filter dsl.ConditionOperator) error

func (*Session) LoadDepth

func (s *Session) LoadDepth(respObj interface{}, id string, depth int) error

func (*Session) LoadDepthFilter

func (s *Session) LoadDepthFilter(respObj interface{}, id string, depth int, filter dsl.ConditionOperator, params map[string]interface{}) error

func (*Session) LoadDepthFilterPagination

func (s *Session) LoadDepthFilterPagination(respObj interface{}, id string, depth int, filter dsl.ConditionOperator, params map[string]interface{}, pagination *Pagination) error

func (*Session) PurgeDatabase

func (s *Session) PurgeDatabase() error

func (*Session) Query

func (s *Session) Query(query string, properties map[string]interface{}, respObj interface{}) error

func (*Session) QueryRaw

func (s *Session) QueryRaw(query string, properties map[string]interface{}) ([][]interface{}, error)

func (*Session) Rollback

func (s *Session) Rollback() error

func (*Session) RollbackWithError

func (s *Session) RollbackWithError(originalError error) error

func (*Session) Save

func (s *Session) Save(saveObj interface{}) error

func (*Session) SaveDepth

func (s *Session) SaveDepth(saveObj interface{}, depth int) error

type SessionConfig

type SessionConfig neo4j.SessionConfig

type SessionV2

type SessionV2 interface {
	//transaction functions
	TransactionV2

	// Begin begins transaction
	Begin(ctx context.Context) error

	// ManagedTransaction runs tx work managed for retry
	ManagedTransaction(ctx context.Context, work TransactionWork) error

	// closes session
	Close() error
}

session version 2 is experimental to start trying breaking changes

type SessionV2Impl

type SessionV2Impl struct {
	DefaultDepth int
	// contains filtered or unexported fields
}

func (*SessionV2Impl) Begin

func (s *SessionV2Impl) Begin(ctx context.Context) error

func (*SessionV2Impl) Close

func (s *SessionV2Impl) Close() error

func (*SessionV2Impl) Commit

func (s *SessionV2Impl) Commit(ctx context.Context) error

func (*SessionV2Impl) Delete

func (s *SessionV2Impl) Delete(ctx context.Context, deleteObj interface{}) error

func (*SessionV2Impl) DeleteUUID

func (s *SessionV2Impl) DeleteUUID(ctx context.Context, uuid string) error

func (*SessionV2Impl) Load

func (s *SessionV2Impl) Load(ctx context.Context, respObj, id interface{}) error

func (*SessionV2Impl) LoadAll

func (s *SessionV2Impl) LoadAll(ctx context.Context, respObj interface{}) error

func (*SessionV2Impl) LoadAllDepth

func (s *SessionV2Impl) LoadAllDepth(ctx context.Context, respObj interface{}, depth int) error

func (*SessionV2Impl) LoadAllDepthFilter

func (s *SessionV2Impl) LoadAllDepthFilter(ctx context.Context, respObj interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}) error

func (*SessionV2Impl) LoadAllDepthFilterPagination

func (s *SessionV2Impl) LoadAllDepthFilterPagination(ctx context.Context, respObj interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}, pagination *Pagination) error

func (*SessionV2Impl) LoadDepth

func (s *SessionV2Impl) LoadDepth(ctx context.Context, respObj, id interface{}, depth int) error

func (*SessionV2Impl) LoadDepthFilter

func (s *SessionV2Impl) LoadDepthFilter(ctx context.Context, respObj, id interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}) error

func (*SessionV2Impl) LoadDepthFilterPagination

func (s *SessionV2Impl) LoadDepthFilterPagination(ctx context.Context, respObj, id interface{}, depth int, filter dsl.ConditionOperator, params map[string]interface{}, pagination *Pagination) error

func (*SessionV2Impl) ManagedTransaction

func (s *SessionV2Impl) ManagedTransaction(ctx context.Context, work TransactionWork) error

func (*SessionV2Impl) Query

func (s *SessionV2Impl) Query(ctx context.Context, query string, properties map[string]interface{}, respObj interface{}) error

func (*SessionV2Impl) QueryRaw

func (s *SessionV2Impl) QueryRaw(ctx context.Context, query string, properties map[string]interface{}) ([][]interface{}, neo4j.ResultSummary, error)

func (*SessionV2Impl) Rollback

func (s *SessionV2Impl) Rollback(ctx context.Context) error

func (*SessionV2Impl) RollbackWithError

func (s *SessionV2Impl) RollbackWithError(ctx context.Context, originalError error) error

func (*SessionV2Impl) Save

func (s *SessionV2Impl) Save(ctx context.Context, saveObj interface{}) error

func (*SessionV2Impl) SaveDepth

func (s *SessionV2Impl) SaveDepth(ctx context.Context, saveObj interface{}, depth int) error

type TransactionV2

type TransactionV2 interface {
	// Rollback rolls back transaction
	Rollback(ctx context.Context) error
	// RollbackWithError wraps original error into rollback error if there is one
	RollbackWithError(ctx context.Context, err error) error
	// Commit commits transaction
	Commit(ctx context.Context) error
	// contains filtered or unexported methods
}

TransactionV2 specifies functions for Neo4j ACID transactions

type TransactionWork

type TransactionWork func(tx TransactionV2) error

Directories

Path Synopsis
cmd
gogmcli/gen
gen provides code to generate link and unlink functions for gogm structs
gen provides code to generate link and unlink functions for gogm structs
Code generated by GoGM 2.1.1.
Code generated by GoGM 2.1.1.

Jump to

Keyboard shortcuts

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