Documentation
¶
Overview ¶
Package cypher provides Cypher query parsing and execution for gograph.
Package cypher provides Cypher query parsing and execution capabilities for gograph.
Package cypher provides Cypher query parsing and execution for gograph. It implements a Cypher-compatible query language for graph database operations.
The package supports:
- CREATE: Create nodes and relationships
- MATCH: Query and pattern matching
- SET: Update properties
- DELETE: Remove nodes and relationships
- REMOVE: Remove labels and properties
- RETURN: Return query results
Basic Usage:
executor := cypher.NewExecutor(store)
result, err := executor.Execute(ctx, "CREATE (n:Person {name: 'Alice'})", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created %d nodes\n", result.AffectedNodes)
Index ¶
- func Parse(input string) (*ast.Query, error)
- type Attribute
- type Executor
- func (e *Executor) Execute(ctx context.Context, query string, params map[string]interface{}) (Result, error)
- func (e *Executor) ExecuteAST(ctx context.Context, query *ast.Query, params map[string]interface{}) (Result, error)
- func (e *Executor) ExecuteWithTx(t *tx.Transaction, query *ast.Query, params map[string]interface{}) (Result, error)
- type Logger
- type Meter
- type Observability
- type ObservabilityOption
- type Parser
- type Result
- type Span
- type SpanOption
- type StatementRouter
- type Tracer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Parse ¶ added in v0.2.0
Parse is a convenience function that parses a Cypher query string. It creates a new parser and parses the query in one call.
Parameters:
- input: The Cypher query string to parse
Returns the parsed Query AST, or an error if parsing fails.
Example:
query, err := cypher.Parse("MATCH (n:Person) RETURN n.name")
if err != nil {
log.Fatal(err)
}
Types ¶
type Executor ¶
type Executor struct {
// Store is the underlying storage database.
Store *storage.DB
// Index provides efficient lookups for nodes and relationships.
Index *graph.Index
// contains filtered or unexported fields
}
Executor executes Cypher queries against the graph database. It coordinates parsing, planning, and execution of queries.
The executor delegates statement execution to specialized handlers via the StatementRouter, maintaining clean separation of concerns.
Example:
executor := cypher.NewExecutor(store)
result, err := executor.Execute(ctx, "MATCH (n:Person) RETURN n.name", nil)
if err != nil {
log.Fatal(err)
}
for _, row := range result.Rows {
fmt.Println(row["n.name"])
}
func NewExecutor ¶
NewExecutor creates a new query executor for the given storage.
Parameters:
- store: The storage database to execute queries against
Returns a new Executor instance ready to execute queries.
Example:
store, _ := storage.Open("/path/to/db")
executor := cypher.NewExecutor(store)
func (*Executor) Execute ¶
func (e *Executor) Execute(ctx context.Context, query string, params map[string]interface{}) (Result, error)
Execute parses and executes a Cypher query string.
Parameters:
- ctx: Context for cancellation and timeouts
- query: The Cypher query string to execute
- params: Optional query parameters (e.g., {"name": "Alice"})
Returns the query result or an error if execution fails.
Example:
// Execute a CREATE query
result, err := executor.Execute(ctx, "CREATE (n:Person {name: 'Alice'})", nil)
// Execute with parameters
result, err := executor.Execute(ctx,
"CREATE (n:Person {name: $name})",
map[string]interface{}{"name": "Alice"},
)
func (*Executor) ExecuteAST ¶ added in v0.2.0
func (e *Executor) ExecuteAST(ctx context.Context, query *ast.Query, params map[string]interface{}) (Result, error)
ExecuteAST executes a parsed AST query.
Parameters:
- ctx: Context for cancellation and timeouts
- query: The parsed AST query
- params: Optional query parameters
Returns the query result or an error if execution fails.
Example:
p := parser.New("MATCH (n:Person) RETURN n.name")
ast, _ := p.Parse()
result, err := executor.ExecuteAST(ctx, ast, nil)
func (*Executor) ExecuteWithTx ¶
func (e *Executor) ExecuteWithTx(t *tx.Transaction, query *ast.Query, params map[string]interface{}) (Result, error)
ExecuteWithTx executes a parsed query within an existing transaction.
Parameters:
- t: The transaction to execute within
- query: The parsed AST query
- params: Optional query parameters
Returns the query result or an error if execution fails.
Example:
tx, _ := manager.Begin(false)
result, err := executor.ExecuteWithTx(tx, ast, params)
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
type Logger ¶
type Logger interface {
// Debug logs a debug message with optional key-value pairs.
Debug(msg string, args ...any)
// Info logs an informational message with optional key-value pairs.
Info(msg string, args ...any)
// Warn logs a warning message with optional key-value pairs.
Warn(msg string, args ...any)
// Error logs an error message with optional key-value pairs.
Error(msg string, args ...any)
}
Logger defines the interface for logging operations. Implementations can use different logging backends (slog, zap, logrus, etc.).
type Meter ¶
type Meter interface {
// RecordHistogram records a histogram observation.
RecordHistogram(ctx context.Context, name string, value float64, attrs ...Attribute)
// RecordCounter increments a counter.
RecordCounter(ctx context.Context, name string, value float64, attrs ...Attribute)
}
Meter defines the interface for recording metrics. Implementations can use different metrics backends (Prometheus, StatsD, etc.).
type Observability ¶
type Observability struct {
// Logger is used for logging operations.
Logger Logger
// Tracer is used for distributed tracing.
Tracer Tracer
// Meter is used for recording metrics.
Meter Meter
}
Observability contains the logging, tracing, and metering interfaces used throughout the Cypher execution pipeline.
It provides a unified interface for observability concerns, allowing users to plug in their own implementations or use the defaults.
Example:
// Use default observability (uses slog for logging)
obs := cypher.NewObservability()
// Use custom logger
obs := cypher.NewObservability(cypher.WithLogger(myLogger))
// Use custom tracer and meter
obs := cypher.NewObservability(
cypher.WithTracer(myTracer),
cypher.WithMeter(myMeter),
)
func NewObservability ¶
func NewObservability(opts ...ObservabilityOption) *Observability
NewObservability creates a new Observability instance with default implementations. By default, it uses slog for logging and no-op implementations for tracing and metrics.
Parameters:
- opts: Optional configuration options
Returns a new Observability instance.
Example:
// Default observability
obs := cypher.NewObservability()
// With custom options
obs := cypher.NewObservability(
cypher.WithLogger(myLogger),
cypher.WithTracer(myTracer),
)
type ObservabilityOption ¶
type ObservabilityOption func(*Observability)
ObservabilityOption configures optional parameters for observability.
func WithLogger ¶
func WithLogger(l Logger) ObservabilityOption
WithLogger sets the Logger implementation.
Parameters:
- l: The Logger implementation to use
Returns an ObservabilityOption that can be passed to NewObservability.
Example:
obs := cypher.NewObservability(cypher.WithLogger(myLogger))
func WithMeter ¶
func WithMeter(m Meter) ObservabilityOption
WithMeter sets the Meter implementation.
Parameters:
- m: The Meter implementation to use
Returns an ObservabilityOption that can be passed to NewObservability.
Example:
obs := cypher.NewObservability(cypher.WithMeter(myMeter))
func WithTracer ¶
func WithTracer(t Tracer) ObservabilityOption
WithTracer sets the Tracer implementation.
Parameters:
- t: The Tracer implementation to use
Returns an ObservabilityOption that can be passed to NewObservability.
Example:
obs := cypher.NewObservability(cypher.WithTracer(myTracer))
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
func NewParser ¶
NewParser creates a new Parser for the given Cypher query string.
Parameters:
- input: The Cypher query string to parse
Returns a new Parser instance.
Example:
p := cypher.NewParser("MATCH (n:Person) RETURN n.name")
query, err := p.Parse()
type Result ¶
type Result struct {
// AffectedNodes is the number of nodes created, modified, or deleted.
AffectedNodes int
// AffectedRels is the number of relationships created or deleted.
AffectedRels int
// NodesCreated is the number of nodes created during the query.
NodesCreated int
// RelsCreated is the number of relationships created during the query.
RelsCreated int
// Rows contains matched data rows for MATCH queries.
// Each row is a map of column names to values.
Rows []map[string]interface{}
// Columns contains the names of columns returned in Rows.
Columns []string
}
Result contains the count of affected graph elements after executing a data-modifying Cypher query (CREATE, SET, DELETE, REMOVE).
It also contains the result data for MATCH queries, including the matched rows and column names.
Example:
result, err := executor.Execute(ctx, "CREATE (n:Person)", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Nodes created: %d\n", result.AffectedNodes)
fmt.Printf("Relationships created: %d\n", result.AffectedRels)
// For MATCH queries
result, err := executor.Execute(ctx, "MATCH (n:Person) RETURN n.name", nil)
for _, row := range result.Rows {
fmt.Println(row["n.name"])
}
func (*Result) AddAffected ¶
AddAffected increments the count of affected nodes and relationships.
Parameters:
- nodes: The number of nodes to add to the affected count
- rels: The number of relationships to add to the affected count
Example:
result := &cypher.Result{}
result.AddAffected(2, 1) // 2 nodes and 1 relationship affected
fmt.Printf("Total affected: %d nodes, %d relationships\n",
result.AffectedNodes, result.AffectedRels)
type Span ¶
type Span interface {
// End completes the span.
End()
// AddEvent adds an event to the span.
AddEvent(name string, attrs ...Attribute)
// SetAttributes sets attributes on the span.
SetAttributes(attrs ...Attribute)
}
Span represents a tracing span for observing execution.
type StatementRouter ¶ added in v0.2.3
type StatementRouter struct {
// contains filtered or unexported fields
}
StatementRouter routes AST statements to their respective execution handlers. It encapsulates the statement dispatch logic, keeping the Executor focused on high-level coordination.
type Tracer ¶
type Tracer interface {
// StartSpan starts a new span with the given name and options.
StartSpan(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)
// RecordError records an error on the current span.
RecordError(ctx context.Context, err error, attrs ...Attribute)
}
Tracer defines the interface for distributed tracing. Implementations can use different tracing backends (OpenTelemetry, Jaeger, etc.).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ast defines the Abstract Syntax Tree (AST) nodes for Cypher queries.
|
Package ast defines the Abstract Syntax Tree (AST) nodes for Cypher queries. |
|
Package context provides parsing context management for the Cypher query parser.
|
Package context provides parsing context management for the Cypher query parser. |
|
Package creators provides functionality for creating nodes and relationships in the graph database.
|
Package creators provides functionality for creating nodes and relationships in the graph database. |
|
Package lexer provides lexical analysis for Cypher query strings.
|
Package lexer provides lexical analysis for Cypher query strings. |
|
Package matchers provides pattern matching functionality for Cypher queries.
|
Package matchers provides pattern matching functionality for Cypher queries. |
|
Package modifiers provides functionality for modifying nodes and relationships in the graph database.
|
Package modifiers provides functionality for modifying nodes and relationships in the graph database. |
|
Package utils provides utility functions for the Cypher query engine.
|
Package utils provides utility functions for the Cypher query engine. |
|
Package visitor provides AST visitor implementations for validating and inspecting Cypher query syntax trees.
|
Package visitor provides AST visitor implementations for validating and inspecting Cypher query syntax trees. |