Documentation
¶
Overview ¶
Author: Codex, NOR-180 terminal outcome context propagation,29October2026.
Package cypher implements APOC graph algorithms for Neo4j compatibility.
Package cypher implements APOC community detection algorithms.
Package cypher implements APOC data import/export procedures.
Package cypher - AST builder for structured query representation.
Package cypher - Query result caching for performance optimization.
Author: Codex implementation lane, 2026-10-26 (NOR-148).
Author: Codex implementation lane, 2026-10-26 (NOR-148).
Package cypher provides composite database command execution.
Package cypher provides Neo4j-compatible Cypher query execution for NornicDB.
This package implements a Cypher query parser and executor that supports the core Neo4j Cypher query language features. It enables NornicDB to be compatible with existing Neo4j applications and tools.
Supported Cypher Features:
- MATCH: Pattern matching with node and relationship patterns
- CREATE: Creating nodes and relationships
- MERGE: Upsert operations with ON CREATE/ON MATCH clauses
- DELETE/DETACH DELETE: Removing nodes and relationships
- SET: Updating node and relationship properties
- REMOVE: Removing properties and labels
- RETURN: Returning query results
- WHERE: Filtering with conditions
- WITH: Passing results between query parts
- OPTIONAL MATCH: Left outer joins
- CALL: Procedure calls
- UNWIND: List expansion
Example Usage:
// Create executor with storage backend
storage := storage.NewMemoryEngine()
executor := cypher.NewStorageExecutor(storage)
// Execute Cypher queries
result, err := executor.Execute(ctx, "CREATE (n:Person {name: 'Alice', age: 30})", nil)
if err != nil {
log.Fatal(err)
}
// Query with parameters
params := map[string]interface{}{
"name": "Alice",
"minAge": 25,
}
result, err = executor.Execute(ctx,
"MATCH (n:Person {name: $name}) WHERE n.age >= $minAge RETURN n", params)
// Complex query with relationships
result, err = executor.Execute(ctx, `
MATCH (a:Person)-[r:KNOWS]->(b:Person)
WHERE a.age > 25
RETURN a.name, r.since, b.name
ORDER BY a.age DESC
LIMIT 10
`, nil)
// Process results
for _, row := range result.Rows {
// process row (e.g. emit "Row: %v" via the configured logger)
}
Neo4j Compatibility:
The executor aims for high compatibility with Neo4j Cypher:
- Same syntax and semantics for core operations
- Parameter substitution with $param syntax
- Neo4j-style error messages and codes
- Compatible result format for drivers
- Support for Neo4j built-in functions
Query Processing Pipeline:
1. **Parsing**: Query is parsed into an AST (Abstract Syntax Tree) 2. **Validation**: Syntax and semantic validation 3. **Parameter Substitution**: Replace $param with actual values 4. **Execution Planning**: Determine optimal execution strategy 5. **Execution**: Execute against storage backend 6. **Result Formatting**: Format results for Neo4j compatibility
Performance Considerations:
- Pattern matching is optimized for common cases
- Indexes are used automatically when available
- Query planning chooses efficient execution paths
- Bulk operations are optimized for large datasets
Limitations:
Current limitations compared to full Neo4j:
- No user-defined procedures (CALL is limited to built-ins)
- No complex path expressions
- No graph algorithms (shortest path, etc.)
- No schema constraints (handled by storage layer)
- No transactions (single-query atomicity only)
ELI12 (Explain Like I'm 12):
Think of Cypher like asking questions about a social network:
**MATCH**: "Find all people named Alice" - like searching through a phone book for everyone with a specific name.
**CREATE**: "Add a new person named Bob" - like writing a new entry in the phone book.
**Relationships**: "Find who Alice knows" - like following the lines between people on a friendship map.
**WHERE**: "Find people older than 25" - like adding a filter to only show certain results.
**RETURN**: "Show me their names and ages" - like deciding which information to display from your search.
The Cypher executor is like a smart assistant that understands these questions and knows how to find the answers in your data! Author: Codex, NOR-180 terminal WAL outcome changes, 2026-10-26.
Author: Codex, NOR-180 terminal WAL outcome propagation, 2026-10-26.
Package cypher implements EXPLAIN and PROFILE query execution modes.
EXPLAIN shows the query execution plan without executing the query. PROFILE executes the query and shows the plan with runtime statistics.
ELI12 (Explain Like I'm 12) ¶
Imagine you're planning a trip. EXPLAIN is like looking at the map and saying "I'll take this road, then that highway" without actually driving. PROFILE is like actually driving the route and noting "that road took 10 minutes, the highway took 20 minutes, I passed 50 cars."
Neo4j Compatibility ¶
This implementation matches Neo4j's execution modes: - EXPLAIN: Returns plan without execution - PROFILE: Returns plan with actual execution statistics
Author: Codex implementation lane, 2026-10-26 (NOR-148). Author of change relevance: #1683 review-correction lane (DeepSeek), 2026-11-02 (NOR-148).
Author of retained field representation: #1683 implementation lane (Codex), 2026-11-01. Lucene-classic fulltext query parser used by db.index.fulltext.queryNodes / db.index.fulltext.queryRelationships.
The Neo4j fulltext procedures accept the Lucene classic query grammar (see org.neo4j.kernel.api.impl.fulltext.FulltextIndexReader — a MultiFieldQueryParser with setAllowLeadingWildcard(true)). Prior to this parser NornicDB tokenized the query string with strings.Fields and had no notion of parenthesized groups, field-scoped clauses, or escape sequences. That meant any composite query — most notably the Graphiti shape `group_id:"<g>" AND (<terms>)` — silently discarded the parenthesized default-field clause, making the lexical arm of hybrid search term-blind. This file replaces that ad-hoc tokenizer with a proper recursive-descent parser plus a per-document evaluator that intersects/unions clause matches as the boolean operators dictate.
Grammar (Lucene classic subset that the reference parser accepts):
Query := OrExpr
OrExpr := AndExpr ( ("OR"|"||") AndExpr )*
AndExpr := NotExpr ( ("AND"|"&&") NotExpr )*
NotExpr := "NOT" NotExpr | Clause
Clause := ("+"|"-")? ( FieldExpr | Group | Atom ) ("^" number)?
Group := "(" OrExpr ")"
FieldExpr := TERM ":" ( Group | Range | Atom )
Range := ("["|"{") RangeTerm "TO" RangeTerm ("]"|"}")
Atom := QUOTED ("~" digits?)? // proximity when after phrase
| TERM ("*"|"?")* // wildcards
| TERM "~" digits? // fuzzy
| REGEX
Escape rule: `\X` in a term or phrase decodes to a literal X for any character X (matches Lucene's QueryParserBase.discardEscapeChar).
Cypher function implementations for NornicDB.
This file holds the public expression-evaluation entrypoints. The heavy implementation is split across `functions_eval_part*.go`.
Author: L6 / #1665 lane (Codex gpt-6.1-sol). Numeric toString selection delegates to the shared text owner.
Package cypher provides index hint support for Neo4j-compatible query optimization.
Index hints allow users to specify which indexes should be used during query execution, overriding the query planner's automatic index selection.
Supported Hint Types ¶
- USING INDEX variable:Label(property) - Force use of a specific property index
- USING SCAN variable:Label - Force a label scan instead of index lookup
- USING JOIN ON variable - Force specific join strategy (planned)
Neo4j Compatibility ¶
This implementation follows Neo4j's index hint syntax:
MATCH (n:Person) USING INDEX n:Person(name) WHERE n.name = 'Alice' RETURN n
Multiple hints can be specified:
MATCH (a:Person)-[:KNOWS]->(b:Person) USING INDEX a:Person(name) USING INDEX b:Person(email) WHERE a.name = 'Alice' AND b.email = 'bob@example.com' RETURN a, b
ELI12 (Explain Like I'm 12) ¶
Imagine you have a huge phone book (database). Normally, the database decides the fastest way to find someone - maybe by their name index, or by scanning. Index hints are like saying "I KNOW the name index is best - use that one!" It's like telling a librarian exactly which catalog to use.
Kalman filter Cypher functions for NornicDB.
These functions expose the Kalman filter implementations as database-callable functions, enabling users to apply signal filtering and prediction directly in their Cypher queries. Perfect for real-time time series analysis.
Overview ¶
Kalman filters are optimal state estimators that combine noisy measurements with predictions to produce smooth, accurate estimates. They're widely used in aerospace, robotics, finance, and signal processing.
Available Filters ¶
Three filter types are available, each suited for different use cases:
- kalman.* - Basic scalar filter for noise smoothing
- kalman.velocity.* - 2-state filter tracking position AND velocity (trends)
- kalman.adaptive.* - Auto-switching filter that picks the best mode
State Management ¶
Users store the filter state as a JSON string in a node property. The state is passed to each function call and an updated state is returned. This allows the database to remain stateless while users maintain their own filter state.
Real-World Example: News Sentiment → Stock Prediction ¶
An LLM watches the Associated Press news feed in real-time, scoring each headline's market sentiment (-1.0 to +1.0). The Kalman filter smooths these noisy signals to predict stock movements:
// Step 1: Create a stock tracker with Kalman filtering
CREATE (s:Stock {
symbol: "AAPL",
kalmanState: kalman.velocity.init() // Track trends
})
// Step 2: LLM processes AP news headline and scores sentiment
// (This happens in your application code, score passed as parameter)
// headline: "Apple announces record iPhone sales in China"
// $sentimentScore = 0.72 (positive)
// Step 3: Process the sentiment score through Kalman filter
MATCH (s:Stock {symbol: "AAPL"})
WITH s, kalman.velocity.process($sentimentScore, s.kalmanState) AS result
SET s.kalmanState = result.state,
s.sentiment = result.value,
s.momentum = result.velocity,
s.lastUpdate = timestamp()
RETURN result.value AS smoothedSentiment,
result.velocity AS sentimentTrend
// Step 4: Predict sentiment 5 time-steps ahead
MATCH (s:Stock {symbol: "AAPL"})
RETURN s.symbol,
s.sentiment AS currentSentiment,
s.momentum AS trend,
kalman.velocity.predict(s.kalmanState, 5) AS predictedSentiment,
CASE
WHEN s.momentum > 0.1 THEN "BULLISH"
WHEN s.momentum < -0.1 THEN "BEARISH"
ELSE "NEUTRAL"
END AS signal
// Step 5: Find stocks with strongest momentum
MATCH (s:Stock)
WHERE s.kalmanState IS NOT NULL
RETURN s.symbol, s.sentiment, s.momentum
ORDER BY abs(s.momentum) DESC
LIMIT 10
Why Kalman Filtering Works for This ¶
Individual news headlines are noisy - one bad headline doesn't mean the stock will crash. The Kalman filter:
- Smooths out noise from individual headlines
- Tracks the TREND (velocity) of sentiment over time
- Predicts where sentiment is heading
- Adapts to changing conditions automatically
ELI12 (Explain Like I'm 12) ¶
Imagine you're trying to guess tomorrow's weather by asking 10 friends. Some say "sunny", some say "rainy" - it's confusing! The Kalman filter is like having a really smart friend who:
- Remembers what everyone said yesterday
- Notices if opinions are trending toward "sunny" or "rainy"
- Doesn't freak out when one person gives a weird answer
- Uses all this to make a better prediction than any single friend
For stocks: news headlines are like those friends - some are right, some are wrong, some are noise. Kalman helps you see the real trend!
Other Use Cases ¶
- IoT sensor smoothing (temperature, pressure, GPS)
- User behavior prediction (session length, click rates)
- Memory decay tracking (see NornicDB's knowledge-layer scoring system)
- Query latency monitoring
- Any noisy time series data!
Package cypher — RISK-1 corrected op_type classifier (Plan 04-03-02).
Closed-enum classifier {read, write, schema, admin, fabric, parse_error} for the MET-09 op_type label on the Cypher metric catalog (pkg/observability/catalog_cypher.go AllowedCypherOpTypes).
RISK-1 correction (RESEARCH RISK-1): the original CONTEXT D-04 wording named a `plan.Root.Op` chokepoint that does NOT exist on the normal-path executor — `*ExecutionPlan` is built ONLY on EXPLAIN/PROFILE; normal Execute uses QueryAnalyzer.Analyze() (*QueryInfo, error). This file's classifier reads the actual normal-path classifier surface (*QueryInfo flags and its statement-effect owner's answer), NOT the non-existent plan field.
Three observation sites use this classifier (see executor.go):
- Admin dispatch (Site 1) — emits op_type="admin" BEFORE Analyze() is called for SHOW DATABASES, CREATE/DROP DATABASE, ALTER DATABASE etc. Caller passes isAdmin=true.
- Parse error (Site 2) — emits op_type="parse_error" at validateSyntax() err path. Caller bypasses this function entirely (or passes nil info) and emits parse_error directly. The defensive nil-info branch below surfaces parse_error as a safety net.
- Normal path (Site 3) — after analyzer.Analyze() returns *QueryInfo, before execute. Caller passes (info, isFabric, false) and the function returns one of read|write|schema|fabric.
AGENTS.md §4 functional pattern: pure function, no side effects, no observability imports. Pkg/cypher remains a leaf consumer of pkg/observability; the OBSERVATION call lives in executor.go at the chokepoints — this is the CLASSIFIER.
Package cypher provides optimized query executors for specific patterns.
These executors implement specialized algorithms that are significantly faster than generic traversal for certain query patterns. Each executor is designed for a specific pattern detected by DetectQueryPattern(ctx).
Performance characteristics:
- MutualRelationship: O(E) instead of O(N * D²)
- IncomingCountAgg: O(E) instead of O(N * separate_calls)
- EdgePropertyAgg: O(E) single-pass accumulation
- LargeResultSet: Batch node lookups, pre-allocation
Package cypher provides parallel query execution support for NornicDB.
Parallel execution significantly improves query performance on large datasets by distributing work across multiple CPU cores. This is especially beneficial for:
- Filtering large node sets (WHERE clauses)
- Aggregation operations (COUNT, SUM, AVG, COLLECT)
- Relationship traversal
- UNION queries (parallel branch execution)
Neo4j Compatibility ¶
Neo4j Enterprise uses parallel execution for query processing. This implementation brings similar capabilities to NornicDB, enabling comparable performance for analytical workloads.
Configuration ¶
Parallel execution can be configured via ParallelConfig:
config := cypher.ParallelConfig{
Enabled: true,
MaxWorkers: 8, // Use 8 cores max
MinBatchSize: 500, // Parallelize when >500 items
}
ELI12 (Explain Like I'm 12) ¶
Imagine you have 1000 books to check for a specific word. Instead of checking one by one, you get 4 friends to help. Each friend takes 250 books and checks them at the same time. That's parallel execution - doing work simultaneously!
Package cypher provides Cypher query parsing and execution for NornicDB.
Package cypher: D-04b deterministic plan-tree hash for slow-query log + Phase 6 span attribution.
PlanHash returns a 16-character lowercase hex digest of the bound execution plan computed via FNV-1a 64-bit (stdlib hash/fnv). The canonical form walks PlanOperator.OperatorType, .Description, .Identifiers, .Arguments, and .Children; argument values are restricted to a stable known type set (string|int64|float64|bool) — see W4 below — so the hash is deterministic across map iteration order, Go versions, and process restarts.
Why fixed 16-char hex?
- 64-bit FNV-1a is non-cryptographic but stable across stdlib versions.
- 16 hex chars is enough collision resistance for plan-class fingerprinting (~4e9 plans before 50% collision probability via the birthday bound).
- Phase 6 (TRC-04) will reuse this exact function for the nornicdb.cypher.plan span attribute; operators correlate slow-query log records with traces via plan_hash equality.
W4 canonical-form pin (Pitfall 8): Arguments map values are restricted to string|int64|float64|bool. Other types contribute a single 0x00 nil byte to the canonical form — see the type switch default branch comment marked "TODO: PlanHash arg type expansion". Phase 2 ships these four types because they are what the executor actually emits; future expansion (e.g., time.Duration) requires an explicit canonical-form change AND a new TestPlanHash_Stability golden value to flag the schema bump.
Package cypher - Query analysis and AST capture.
Package cypher provides query pattern detection for optimization routing.
This file identifies query patterns that can be executed more efficiently than the generic traversal algorithm. Pattern detection happens BEFORE execution, allowing the executor to route to specialized implementations.
Supported patterns:
- Mutual Relationship: (a)-[:TYPE]->(b)-[:TYPE]->(a) - cycle back to start
- Incoming Count Aggregation: MATCH (x)<-[:TYPE]-(y) RETURN x, count(y)
- Edge Property Aggregation: RETURN avg(r.prop), count(r) GROUP BY node
- Large Result Set: Any traversal with LIMIT > 100
Package cypher: D-04 query literal redactor for slow-query log emission (LOG-08).
RedactLiterals walks the Cypher token stream, replacing STRING_LITERAL, CHAR_LITERAL (NornicDB's grammar accepts single-quoted strings as an alternate spelling of STRING_LITERAL — see CHAR_LITERAL in CypherLexer.g4), INTEGER, FLOAT, and DIGIT (hex, octal) tokens with the constant RedactedPlaceholder. Identifiers, keywords, and parameter REFERENCES ($name) are preserved verbatim because parameter VALUES bind separately at execution time and never appear as inline literals in the query text.
The redactor is invoked at every log emission site that includes raw query text — currently the slow-query log (D-04c) — so PII stored in literal values (names, emails, passwords) cannot leak through unauthenticated /metrics or operator log surfaces. Phase 6 (TRC-04) calls this same helper before attaching query text to the nornicdb.cypher.plan span.
On parse/lex failure the redactor returns RedactedPlaceholder (fail-closed per RESEARCH Pattern 5 line 660) — better to lose query readability than leak partial literal content from a half-tokenized input.
Package cypher - Pre-compiled regex patterns for performance.
This file contains all regex patterns used in hot paths, pre-compiled at package init time. Moving regex compilation from function calls to package initialization provides 5-10x performance improvements for operations that use these patterns repeatedly.
Performance Impact:
- Schema DDL operations: 5-10x faster (9 patterns)
- Duration parsing: 3-5x faster (2 patterns)
Schema command parsing and execution for Cypher.
This file implements Neo4j schema management commands:
- CREATE CONSTRAINT
- CREATE INDEX
- CREATE RANGE INDEX
- CREATE FULLTEXT INDEX
- CREATE VECTOR INDEX
Schema OPTIONS payload ownership.
Every CREATE INDEX and CREATE CONSTRAINT form ends with the same optional tail: OPTIONS and exactly one payload, either a map literal or a parameter reference. Neo4j reads OPTIONS $options exactly as it reads OPTIONS {...}, and there it applies the map's configuration, so this file owns that payload end to end: schemaOptionsTail admits its syntax, schemaOptionMap binds the map value it designates when the statement runs, and schemaVectorOptions reads the vector configuration a bound map carries.
Syntax and binding are separate on purpose. Admission is structural and runs wherever the statement is parsed; binding reads expressions and parameters, so it runs only at the execution boundary, after the whole statement's syntax is verified. EXPLAIN validates syntax and compiles metadata without binding, so no option expression is evaluated and no parameter is read.
Author: Codex, NOR-180 terminal outcome retention, 29 October 2026; the invocation's committed work by Claude, 30 October 2026.
Package cypher - Optimized string-based pattern matching for hot paths.
This file provides fast string-based alternatives to regex patterns for operations that are called on every query. These functions are 5-10x faster than their regex equivalents.
Performance comparison (benchmark on M1 Mac):
- extractLimitSkip vs regex FindStringSubmatch: ~6x faster
- extractParameter vs regex FindAllStringSubmatch: ~5x faster
Author: L6 / #1665 lane (Codex gpt-6.1-sol). Numeric text delegates to convert; temporal formatting retains its own contract.
Author: Codex, NOR-180 terminal WAL outcome changes, 2026-10-26. Package cypher - Transaction support for Cypher queries.
Implements BEGIN/COMMIT/ROLLBACK for Neo4j-compatible transaction control.
Author: Codex, NOR-180 terminal outcome context propagation,29October2026.
Author: Codex, NOR-180 implementation lane, 2026-10-26.
Package cypher provides Cypher query execution for NornicDB.
Index ¶
- Constants
- Variables
- func AccessDatabases(manager GraphDatabaseResolver, database string) ([]string, error)
- func ApplyIndexHint(ctx context.Context, store storage.Engine, schema *storage.SchemaManager, ...) ([]*storage.Node, error)
- func AuthorizeQuery(ctx context.Context, query string) error
- func AuthorizeReadOnlyQuery(ctx context.Context, query string) error
- func CachedDatabaseExecutor[T any](mu *sync.RWMutex, cache *map[string]T, name string, valid func(T) bool, ...) (T, error)
- func CheckStatementAccess(ctx context.Context, query string, stage SourceStage) error
- func ClearUserProcedures()
- func ConfigureTransactionMemory(global int64, defaults TransactionMemoryLimits)
- func ContainsKeyword(ctx context.Context, s, keyword string) (bool, error)
- func ExtractLimit(ctx context.Context, query string) (int, bool, error)
- func ExtractLimitString(ctx context.Context, query string) (string, error)
- func ExtractParameters(query string) []string
- func ExtractSkip(ctx context.Context, query string) (int, bool, error)
- func ExtractSkipString(ctx context.Context, query string) (string, error)
- func FindKeywordIndex(ctx context.Context, s, keyword string) (int, error)
- func FormatCypherDuration(months, days, seconds, nanos int64) string
- func GetAuthTokenFromContext(ctx context.Context) string
- func GetAuthenticatedPrincipalFromContext(ctx context.Context) string
- func GetCachedRegex(pattern string) (*regexp.Regexp, error)
- func GetUseDatabaseFromContext(ctx context.Context) string
- func GraphAccessTarget(manager GraphDatabaseResolver, graph string, canAccess func(string) bool) (database string, remote, allowed bool)
- func IsRetrySafeMergeCommitQuery(ctx context.Context, info *QueryInfo) bool
- func MergeUniqueConflictIsRetrySafe(ctx context.Context, statements []CommitStatement, err error) bool
- func MissingPermission(requirements PermissionRequirements, allows func(permission string) bool, ...) string
- func Neo4jPlanMap(plan *ExecutionPlan, profile bool) map[string]any
- func ParseAggregationProperty(expr string) (variable, property string)
- func ParseKnowledgePolicyDDL(ctx context.Context, stmt string, stage SourceStage) (command interface{}, owned bool, retErr error)
- func PlanHash(plan *ExecutionPlan) string
- func QueryDiagnosticParameters(ctx context.Context, query string, params map[string]any) map[string]any
- func RedactLiterals(query string) string
- func RegisterUserProcedure(spec ProcedureSpec, handler ProcedureHandler) error
- func ReplaceParameters(query string, replacer func(paramName string) string) string
- func ResolveNamedZoneLocalTime(local time.Time, location *time.Location, preferLater bool) time.Time
- func ResolvedStatementQueryType(metadata map[string]interface{}) (string, bool)
- func SetDatabaseTransactionMemoryLimits(database string, limits DatabaseTransactionMemoryLimits)
- func SetParallelConfig(config ParallelConfig)
- func SplitByCreate(ctx context.Context, s string) ([]string, error)
- func SplitByKeyword(ctx context.Context, s, keyword string) ([]string, error)
- func SplitByMatch(ctx context.Context, s string) ([]string, error)
- func StatementDatabase(database, query string) string
- func StatementShapeHash(redactedQuery string) string
- func StripComments(query string) string
- func TransactionDatabaseError(ctx context.Context, databases TransactionDatabases, ...) error
- func TransactionMemoryPoolUsage(database string) (global, databaseUsed int64)
- func UnsupportedTypePlaceholder(value interface{}) (map[string]interface{}, bool)
- func ValidateIndexHints(schema *storage.SchemaManager, hints []IndexHint) error
- func ValidateStatementText(query string) error
- func WithAuthToken(ctx context.Context, authToken string) context.Context
- func WithAuthenticatedPrincipal(ctx context.Context, principal string) context.Context
- func WithAuthenticationDisabled(ctx context.Context) context.Context
- func WithClientStatement(ctx context.Context) context.Context
- func WithClientTransactionTimeout(ctx context.Context) context.Context
- func WithDatabasePermissionResolver(ctx context.Context, database string, resolver DatabasePermissionResolver) context.Context
- func WithPermissionChecker(ctx context.Context, checker PermissionChecker) context.Context
- func WithProcedureGrantChecker(ctx context.Context, allowsBoosted func(procedure string) bool) context.Context
- func WithReadOnlyStatements(ctx context.Context) context.Context
- func WithRequestIdentity(ctx context.Context, identity *RequestIdentity) context.Context
- func WithResultStream(ctx context.Context, stream *ResultStream) context.Context
- func WithStatementAdmitted(ctx context.Context, executor *StorageExecutor, admitted func()) context.Context
- func WithTemporalViewport(ctx context.Context, viewport TemporalViewport) context.Context
- func WithTransactionControl(ctx context.Context) context.Context
- func WithTransactionMetadata(ctx context.Context, metadata map[string]any) context.Context
- type AST
- type ASTBinaryExpr
- type ASTBuilder
- type ASTCall
- type ASTCaseExpr
- type ASTCaseWhen
- type ASTClause
- type ASTClauseType
- type ASTCreate
- type ASTDelete
- type ASTExprType
- type ASTExpression
- type ASTFunctionCall
- type ASTMatch
- type ASTMerge
- type ASTNode
- type ASTOrderBy
- type ASTOrderItem
- type ASTPattern
- type ASTPropertyAccess
- type ASTRelationship
- type ASTRemove
- type ASTRemoveItem
- type ASTReturn
- type ASTReturnItem
- type ASTSet
- type ASTSetItem
- type ASTUnaryExpr
- type ASTUnwind
- type ASTWhere
- type ASTWith
- type AdministrationOutcome
- type AggregateResult
- type AggregationResult
- type AlterDecayProfileBindingCmd
- type AlterDecayProfileCmd
- type AlterPromotionPolicyCmd
- type AlterPromotionPolicyDefinitionCmd
- type AlterPromotionProfileCmd
- type AuthenticatedUser
- type Clause
- type ClauseType
- type ClientConnection
- type CommitStatement
- type Comparison
- type ConnectionListing
- type CreateClause
- type CreateDecayProfileBindingCmd
- type CreateDecayProfileBundleCmd
- type CreatePromotionPolicyCmd
- type CreatePromotionProfileCmd
- type CypherDate
- func (v *CypherDate) MarshalMsgpack() ([]byte, error)
- func (CypherDate) PropertyValueKind() string
- func (v CypherDate) RemoteParameterValue() interface{}
- func (v CypherDate) StoragePropertyValue() (any, bool)
- func (v CypherDate) String() string
- func (v CypherDate) TemporalTime() time.Time
- func (v *CypherDate) UnmarshalMsgpack(data []byte) error
- type CypherDateTime
- type CypherDuration
- func (d *CypherDuration) MarshalMsgpack() ([]byte, error)
- func (*CypherDuration) PropertyValueKind() string
- func (d CypherDuration) RemoteParameterValue() interface{}
- func (v *CypherDuration) StoragePropertyValue() (any, bool)
- func (d *CypherDuration) String() string
- func (d *CypherDuration) ToTimeDuration() time.Duration
- func (d *CypherDuration) TotalDays() float64
- func (d *CypherDuration) TotalSeconds() float64
- func (d *CypherDuration) UnmarshalMsgpack(data []byte) error
- type CypherLocalDateTime
- func (v *CypherLocalDateTime) MarshalMsgpack() ([]byte, error)
- func (CypherLocalDateTime) PropertyValueKind() string
- func (v CypherLocalDateTime) RemoteParameterValue() interface{}
- func (v CypherLocalDateTime) StoragePropertyValue() (any, bool)
- func (v CypherLocalDateTime) String() string
- func (v CypherLocalDateTime) TemporalTime() time.Time
- func (v *CypherLocalDateTime) UnmarshalMsgpack(data []byte) error
- type CypherLocalTime
- func (v *CypherLocalTime) MarshalMsgpack() ([]byte, error)
- func (CypherLocalTime) PropertyValueKind() string
- func (v CypherLocalTime) RemoteParameterValue() interface{}
- func (v CypherLocalTime) StoragePropertyValue() (any, bool)
- func (v CypherLocalTime) String() string
- func (v CypherLocalTime) TemporalTime() time.Time
- func (v *CypherLocalTime) UnmarshalMsgpack(data []byte) error
- type CypherPoint
- func (p CypherPoint) CRSHref() string
- func (p CypherPoint) CRSName() string
- func (p CypherPoint) Coordinates() []float64
- func (p CypherPoint) Is3D() bool
- func (CypherPoint) PropertyValueKind() string
- func (p CypherPoint) RemoteParameterValue() interface{}
- func (v CypherPoint) StoragePropertyValue() (any, bool)
- func (p CypherPoint) String() string
- type CypherTime
- func (v *CypherTime) MarshalMsgpack() ([]byte, error)
- func (CypherTime) PropertyValueKind() string
- func (v CypherTime) RemoteParameterValue() interface{}
- func (v CypherTime) StoragePropertyValue() (any, bool)
- func (v CypherTime) String() string
- func (v CypherTime) TemporalTime() time.Time
- func (v *CypherTime) UnmarshalMsgpack(data []byte) error
- type CypherUUID
- type CypherVector
- func (v CypherVector) CypherSize() int64
- func (v CypherVector) Dimension() int
- func (v CypherVector) Equal(other CypherVector) bool
- func (CypherVector) PropertyValueKind() string
- func (v CypherVector) RemoteParameterValue() interface{}
- func (v CypherVector) StoragePropertyValue() (any, bool)
- func (v CypherVector) String() string
- type DatabaseExecutorCache
- type DatabaseIdentityProvider
- type DatabaseInfoInterface
- type DatabaseManagerInterface
- type DatabaseOptionsManager
- type DatabasePermissionResolver
- type DatabaseScopedExecutorOptions
- type DatabaseStorageResolver
- type DatabaseTransactionMemoryLimits
- type DeleteClause
- type DropDecayProfileCmd
- type DropPromotionPolicyCmd
- type DropPromotionProfileCmd
- type EdgeDirection
- type EdgeFilterFunc
- type EdgePattern
- type EmbeddingChunk
- type ExecuteResult
- type ExecutionMode
- type ExecutionPlan
- type Executor
- type Expression
- type FastRPConfig
- type FilterFunc
- type FulltextQuery
- type FunctionCall
- type GraphDatabaseResolver
- type GraphProjection
- type HotPathTrace
- type IndexHint
- type IndexHintContext
- type IndexHintType
- type InferenceManager
- type KalmanAdaptiveProcessResult
- type KalmanAdaptiveState
- type KalmanProcessResult
- type KalmanState
- type KalmanVelocityProcessResult
- type KalmanVelocityState
- type Literal
- type MapFunc
- type MatchClause
- type MemoryEdge
- type MemoryNode
- type NodeCount
- type NodeMutatedCallback
- type NodePattern
- type OrderItem
- type ParallelConfig
- type Parameter
- type Parser
- type PathContext
- type PathResult
- type Pattern
- type PatternInfo
- type PermissionChecker
- type PermissionDeniedError
- type PermissionRequirements
- type PlanOperator
- type PluginFunctionHandler
- type PluginFunctionInfo
- type PrincipalAccess
- type ProcedureColumn
- type ProcedureCypherInput
- type ProcedureHandler
- type ProcedureMetadataRenderer
- type ProcedureMode
- type ProcedureNodeImages
- type ProcedureParam
- type ProcedureRegistry
- func (r *ProcedureRegistry) ClearUser()
- func (r *ProcedureRegistry) Get(name string) (registeredProcedure, bool)
- func (r *ProcedureRegistry) List() []ProcedureSpec
- func (r *ProcedureRegistry) ListBuiltIns() []ProcedureSpec
- func (r *ProcedureRegistry) RegisterBuiltIn(spec ProcedureSpec, handler ProcedureHandler) error
- func (r *ProcedureRegistry) RegisterUser(spec ProcedureSpec, handler ProcedureHandler) error
- type ProcedureResultCache
- type ProcedureSpec
- type ProjectedRelationship
- type PropertyAccess
- type Query
- type QueryAnalyzer
- type QueryCache
- type QueryCachePolicy
- type QueryEmbedder
- type QueryEmbedderBinding
- func (b *QueryEmbedderBinding) BeginUse(ctx context.Context) (context.Context, func(), error)
- func (b *QueryEmbedderBinding) Load() QueryEmbedder
- func (b *QueryEmbedderBinding) SetLifetime(begin func(context.Context) (context.Context, func(), error))
- func (b *QueryEmbedderBinding) Shutdown(ctx context.Context) error
- func (b *QueryEmbedderBinding) Store(embedder QueryEmbedder)
- type QueryInfo
- type QueryPattern
- type QueryPlanCache
- func (pc *QueryPlanCache) Clear()
- func (pc *QueryPlanCache) Get(cypher string) ([]Clause, QueryType, bool)
- func (pc *QueryPlanCache) Put(cypher string, clauses []Clause, queryType QueryType)
- func (pc *QueryPlanCache) SetCypherMetrics(m *observability.CypherMetrics)
- func (pc *QueryPlanCache) Stats() (hits, misses int64, size int)
- type QueryStats
- type QueryType
- type RelationshipPattern
- type RequestIdentity
- type Result
- type ResultStream
- type ResultStreamStarter
- type ReturnClause
- type ReturnItem
- type SearchResult
- type SearchServiceResolver
- type SemanticError
- type SetClause
- type SetItem
- type SettingsResolver
- type SettingsSnapshot
- type ShapeCapture
- type ShapeCaptures
- type ShapeKind
- type ShapeMatch
- type ShapeProbe
- type ShowDecayProfilesCmd
- type ShowPromotionPoliciesCmd
- type ShowPromotionProfilesCmd
- type SmartQueryCache
- func (sc *SmartQueryCache) Get(cypher string, params map[string]interface{}) (*ExecuteResult, bool)
- func (sc *SmartQueryCache) Invalidate()
- func (sc *SmartQueryCache) InvalidateLabels(labels []string)
- func (sc *SmartQueryCache) Put(cypher string, params map[string]interface{}, result *ExecuteResult, ...)
- func (sc *SmartQueryCache) PutWithLabels(cypher string, params map[string]interface{}, result *ExecuteResult, ...)
- func (sc *SmartQueryCache) SetCacheMetrics(m *observability.CacheMetrics)
- func (sc *SmartQueryCache) Stats() (hits, misses int64, size int, smartInvals, fullInvals int64)
- type SourceStage
- type StatementCaches
- type StorageExecutor
- func (e *StorageExecutor) BatchGetNodes(ctx context.Context, ids []storage.NodeID) map[storage.NodeID]*storage.Node
- func (e *StorageExecutor) CachedResultColumns(ctx context.Context, query string, incoming []string) resultmetadata.Names
- func (e *StorageExecutor) ClearQueryCaches()
- func (e *StorageExecutor) CompositeGraphs() (graphs []string, composite bool)
- func (e *StorageExecutor) CypherMetrics() *observability.CypherMetrics
- func (e *StorageExecutor) Database() string
- func (e *StorageExecutor) EntityElementIDDatabase(native, selected string) string
- func (e *StorageExecutor) Execute(ctx context.Context, cypher string, params map[string]interface{}) (result *ExecuteResult, retErr error)
- func (e *StorageExecutor) ExecuteOptimized(ctx context.Context, query string, patternInfo PatternInfo) (*ExecuteResult, bool)
- func (e *StorageExecutor) Flush() error
- func (e *StorageExecutor) FunctionStorage(database string) (storage.Engine, error)
- func (e *StorageExecutor) GetDefaultEmbeddingDimensions() int
- func (e *StorageExecutor) GetEmbedder() QueryEmbedder
- func (e *StorageExecutor) GetInferenceManager() InferenceManager
- func (e *StorageExecutor) GetLocalizationRenderer() ProcedureMetadataRenderer
- func (e *StorageExecutor) GetVectorRegistry() *vectorspace.IndexRegistry
- func (e *StorageExecutor) HasActiveTransaction() bool
- func (e *StorageExecutor) HasPendingTransactionWrites() bool
- func (e *StorageExecutor) InvalidateCommittedWriteCaches()
- func (e *StorageExecutor) InvalidateEntityCaches(entityID string, tokens []string)
- func (e *StorageExecutor) LastHotPathTrace() HotPathTrace
- func (e *StorageExecutor) Logger() *slog.Logger
- func (e *StorageExecutor) ProjectedScopeAfterClause(clause string, incoming []string, cypher25 bool) resultmetadata.Names
- func (e *StorageExecutor) QueryCachePolicy() (maxEntries int, ttl time.Duration)
- func (e *StorageExecutor) QueryEmbedderBinding() *QueryEmbedderBinding
- func (e *StorageExecutor) ResultColumns(ctx context.Context, query string, incoming resultmetadata.Scope, ...) ([]string, error)
- func (e *StorageExecutor) ResultProjection(ctx context.Context, query string, incoming []string, stage SourceStage) resultmetadata.Projection
- func (e *StorageExecutor) SetAPOCLocalFileAccessRoot(root string)
- func (e *StorageExecutor) SetAPOCRemoteURLAllowlist(hosts []string)
- func (e *StorageExecutor) SetAllowLocalAPOCExportFileAccess(enabled bool)
- func (e *StorageExecutor) SetAllowLocalAPOCFileAccess(enabled bool)
- func (e *StorageExecutor) SetAllowLocalAPOCImportFileAccess(enabled bool)
- func (e *StorageExecutor) SetAllowRemoteAPOCURLAccess(enabled bool)
- func (e *StorageExecutor) SetCacheMetrics(m *observability.CacheMetrics)
- func (e *StorageExecutor) SetCypherMetrics(m *observability.CypherMetrics, database string)
- func (e *StorageExecutor) SetDatabaseManager(dbManager DatabaseManagerInterface)
- func (e *StorageExecutor) SetDefaultEmbeddingDimensions(dims int)
- func (e *StorageExecutor) SetDeferFlush(enabled bool)
- func (e *StorageExecutor) SetEmbedder(embedder QueryEmbedder)
- func (e *StorageExecutor) SetInferenceManager(mgr InferenceManager)
- func (e *StorageExecutor) SetLocalizationRenderer(renderer ProcedureMetadataRenderer)
- func (e *StorageExecutor) SetLogger(logger *slog.Logger)
- func (e *StorageExecutor) SetNodeMutatedCallback(cb NodeMutatedCallback)
- func (e *StorageExecutor) SetSearchService(svc *search.Service)
- func (e *StorageExecutor) SetSearchServiceResolver(database string, resolve SearchServiceResolver)
- func (e *StorageExecutor) SetSettingsResolver(resolver SettingsResolver)
- func (e *StorageExecutor) SetSharedExecutor(shared bool)
- func (e *StorageExecutor) SetSlowQueryThreshold(d time.Duration)
- func (e *StorageExecutor) SetVectorRegistry(reg *vectorspace.IndexRegistry)
- func (e *StorageExecutor) ShareEmbedderFrom(parent *StorageExecutor)
- func (e *StorageExecutor) ShareInferenceManagerFrom(parent *StorageExecutor)
- func (e *StorageExecutor) ShareQueryStatisticsFrom(source *StorageExecutor)
- func (e *StorageExecutor) ShareStatementCachesFrom(source *StorageExecutor)
- func (e *StorageExecutor) SlowQueryThreshold() time.Duration
- func (e *StorageExecutor) StatementCacheSelectionValid() bool
- func (e *StorageExecutor) StatementCaches() *StatementCaches
- func (e *StorageExecutor) StatementColumns(query string) []string
- func (e *StorageExecutor) StatementFacts(query string, incoming resultmetadata.Scope, cypher25 bool, stage SourceStage) resultmetadata.Facts
- func (e *StorageExecutor) StatementFactsWith(query string, incoming resultmetadata.Scope, cypher25 bool, ...) resultmetadata.Facts
- func (e *StorageExecutor) StatementResultColumns(query string, stage SourceStage) ([]string, error)
- func (e *StorageExecutor) StatementResultColumnsContext(ctx context.Context, query string, stage SourceStage) ([]string, error)
- func (e *StorageExecutor) TransactionEnded() bool
- func (e *StorageExecutor) TransactionOutlivesSession() bool
- func (e *StorageExecutor) UseDatabaseStatementCaches(manager *multidb.DatabaseManager, name string) error
- func (e *StorageExecutor) UseStatementCaches(caches *StatementCaches)
- type TemporalViewport
- type TemporalViewportMode
- type TransactionCapableEngine
- type TransactionContext
- type TransactionDatabases
- type TransactionMemoryLimits
- type TraversalContext
- type TraversalMatch
- type TraversalSegment
- type TypedExecuteResult
- type UserListing
- type VectorCoordinateType
- type WhereClause
- type WorkerPool
Constants ¶
const ( RawSource = cyphertext.RawSource AcceptedSource = cyphertext.AcceptedSource )
const RedactedPlaceholder = "<REDACTED>"
RedactedPlaceholder is the sentinel substituted for every redacted literal. Stable string contract: operators searching slow-query logs grep for it.
const VarLengthUnboundedMaxHops = 1 << 24 // ~16.7M
VarLengthUnboundedMaxHops is the depth cap applied when a variable-length relationship pattern is written without an explicit upper bound — for example `[*]`, `[*..]`, or `[*N..]`. The previous defaults (10 and 100) were surprising in practice: BFS traversals silently returned no rows on graphs whose actual diameter exceeded the cap. This sentinel is large enough that it acts effectively unbounded for any realistic graph (BFS terminates when the frontier is exhausted) while still keeping the field a plain int so all downstream `>=` comparisons stay correct.
Variables ¶
var ErrQueryEmbedderClosed = errors.New("query embedder binding is closed")
ErrQueryEmbedderClosed reports provider use after the binding's owner stopped.
var PluginFunctionList func() []PluginFunctionInfo
PluginFunctionList lists the loaded plugins' functions for SHOW FUNCTIONS (#1168); nornicdb.Open sets it, with PluginFunctionLookup. Each entry's Name is the name a statement calls (case-sensitive), and Signature is in SHOW FUNCTIONS' form, from which the argument and return descriptions are read.
Example:
cypher.PluginFunctionList = func() []cypher.PluginFunctionInfo {
return []cypher.PluginFunctionInfo{{
Name: "acme.text.slug",
Category: "text",
Description: "Returns the text as a URL slug.",
Signature: "acme.text.slug(text :: STRING) :: STRING",
}}
}
var PluginFunctionLookup func(name string) (handler *PluginFunctionHandler, found bool)
Functions ¶
func AccessDatabases ¶
func AccessDatabases(manager GraphDatabaseResolver, database string) ([]string, error)
AccessDatabases returns the databases a principal must be allowed to use for a statement on database, the graph name it selects (a request or session database, a USE, :USE or subquery USE, a composite constituent):
- a composite constituent "composite.alias": the composite and the constituent's database (the full name when the composite has no such alias);
- any other name: the name and, when it is an alias, the database it names.
The executor checks each one (authorizeSelectedDatabase), and Bolt and HTTP check a request's or session's database with the same list, so a graph is allowed or refused the same way however a statement selects it. manager may be nil (no database manager): the name alone. When the composite's constituents can't be read, the list is the composite and the error is returned with it.
func ApplyIndexHint ¶
func ApplyIndexHint(ctx context.Context, store storage.Engine, schema *storage.SchemaManager, hint IndexHint, propertyValue interface{}) ([]*storage.Node, error)
ApplyIndexHint attempts to use the specified index for node lookup. Returns nodes matching the index lookup, or nil if index doesn't exist.
Parameters:
- ctx: The caller's context; its cancellation ends the label-scan fallback
- storage: The storage engine to query
- schema: The schema manager for index lookup
- hint: The index hint to apply
- propertyValue: The value to look up in the index
Returns:
- Matching nodes if index exists and value found
- nil, nil if index doesn't exist (fall back to scan)
- nil, error if lookup fails
func AuthorizeQuery ¶ added in v1.2.2
AuthorizeQuery enforces requirements when an entitlement checker is present. Top-level and nested execution boundaries both call it so dynamically supplied procedure statements cannot bypass transport authorization.
func AuthorizeReadOnlyQuery ¶
AuthorizeReadOnlyQuery admits a complete read-only query or script without granting execution permissions. It accepts registered READ procedures whose declared effects are fixed and nonadministrative; the caller must still pass its original context to the normal execution and authorization boundary. For example, a read-only diagnostic tool can call this before Execute.
func CachedDatabaseExecutor ¶
func CachedDatabaseExecutor[T any](mu *sync.RWMutex, cache *map[string]T, name string, valid func(T) bool, create func() (T, error)) (T, error)
CachedDatabaseExecutor returns a valid database execution view, creating and publishing one under the database cache lock only after its selection is checked again. The discarded contender is never exposed to callers.
func CheckStatementAccess ¶
func CheckStatementAccess(ctx context.Context, query string, stage SourceStage) error
CheckStatementAccess admits statement effects against the caller's requested read restriction. Dynamic statement procedures are admitted here; their resolved text re-enters this same owner before execution. EXPLAIN has no write effects. The source stage prevents client escapes from being interpreted twice.
func ClearUserProcedures ¶
func ClearUserProcedures()
ClearUserProcedures resets user-defined procedures (primarily for tests/reload paths).
func ConfigureTransactionMemory ¶
func ConfigureTransactionMemory(global int64, defaults TransactionMemoryLimits)
ConfigureTransactionMemory sets dbms.memory.transaction.total.max (global) and refreshes each database setting that inherits its process default.
func ContainsKeyword ¶
ContainsKeyword checks if a query contains a keyword (case-insensitive). Respects word boundaries.
func ExtractLimit ¶
ExtractLimit extracts the LIMIT value from a query string. Returns the value and true if found, or 0 and false if not found. This is ~6x faster than regex FindStringSubmatch.
Example:
ExtractLimit("MATCH (n) RETURN n LIMIT 10")
// Returns: 10, true
func ExtractLimitString ¶
ExtractLimitString extracts the LIMIT value as a string (for compatibility). Returns empty string if not found.
func ExtractParameters ¶
ExtractParameters finds all parameter references ($name) in a query string. Returns a slice of parameter names (without the $ prefix). This is ~5x faster than regex FindAllStringSubmatch.
Example:
ExtractParameters("MATCH (n) WHERE n.name = $name AND n.age > $minAge")
// Returns: ["name", "minAge"]
func ExtractSkip ¶
ExtractSkip extracts the SKIP value from a query string. Returns the value and true if found, or 0 and false if not found.
Example:
ExtractSkip("MATCH (n) RETURN n SKIP 5 LIMIT 10")
// Returns: 5, true
func ExtractSkipString ¶
ExtractSkipString extracts the SKIP value as a string (for compatibility). Returns empty string if not found.
func FindKeywordIndex ¶
FindKeywordIndex finds the position of a keyword in a query (case-insensitive). Returns -1 if not found. Respects word boundaries. This is faster than using regexp for simple keyword detection.
func FormatCypherDuration ¶
FormatCypherDuration renders Neo4j's independent month, day, second, and nanosecond duration groups in canonical Cypher ISO form.
func GetAuthTokenFromContext ¶
GetAuthTokenFromContext extracts forwarded Authorization token from context.
func GetAuthenticatedPrincipalFromContext ¶ added in v1.3.3
GetAuthenticatedPrincipalFromContext returns the trusted caller identity.
func GetCachedRegex ¶
GetCachedRegex returns a compiled regex for the pattern, using cache if available. This avoids re-compiling the same pattern on every =~ comparison.
func GetUseDatabaseFromContext ¶
GetUseDatabaseFromContext extracts the database name from :USE command if present in context. Returns empty string if no :USE command was found.
func GraphAccessTarget ¶
func GraphAccessTarget(manager GraphDatabaseResolver, graph string, canAccess func(string) bool) (database string, remote, allowed bool)
GraphAccessTarget resolves selection permissions and identifies remote constituents. Direct readers do not copy parent metadata again or reinterpret foreign names as local aliases.
func IsRetrySafeMergeCommitQuery ¶ added in v1.1.0
IsRetrySafeMergeCommitQuery reports whether a query's write shape is limited to a MERGE commit race that can be retried safely. MERGE may be combined with MATCH, OPTIONAL MATCH, SET, WITH, UNWIND, and RETURN, but side-effecting clauses such as CREATE, DELETE, REMOVE, FOREACH, LOAD CSV, or CALL make the statement non-retryable.
The analyzer's keyword flags are conservative (CREATE in ON CREATE SET or in a string sets HasCreate), so when one of them is set the statement's clauses decide (#961): MERGE … ON CREATE SET … is MERGE work, not CREATE. A canceled classification is not retry-safe; it never replaces the commit error.
func MergeUniqueConflictIsRetrySafe ¶
func MergeUniqueConflictIsRetrySafe(ctx context.Context, statements []CommitStatement, err error) bool
MergeUniqueConflictIsRetrySafe reports whether a commit-time UNIQUE violation err of MERGE-only work (IsRetrySafeMergeCommitQuery) can succeed when retried, so it is reported as a transient race: every value the statements' SET items (SET, ON CREATE SET, ON MATCH SET) write to a violated property must be the value a MERGE pattern of the statement keys on, which the retry then matches. A SET writing any other value clashes on every retry and is reported as the constraint violation it is (MERGE (u:U {k: 7}) SET u.k = 5 against a stored k = 5, #657). SET x = / += $map is decided by the parameter map's keys and values. Whatever can't be decided statically (a computed value, a map from a variable, a statement the clause splitter can't split) is not retry-safe, so a real duplicate is never retried.
Only writes that can reach the violated constraint's label count, and only MERGE keys on that label (#961). An ON CREATE SET item on a node its own MERGE introduces writes a node whose labels are exactly the pattern's plus the statement's static SET x:Label items, so MERGE (o:O {h: $h}) ON CREATE SET o.id = 'sha256:' + $h can't clash on V.id. Every other write may reach a node with more labels than its pattern names (a matched node), so it counts whatever its pattern says. A canceled classification returns false, retaining the caller's commit outcome.
func MissingPermission ¶
func MissingPermission(requirements PermissionRequirements, allows func(permission string) bool, allowsBoosted func(procedure string) bool) string
MissingPermission is the entitlement decision used by statement execution (AuthorizeQuery) and non-Cypher consumers: the first permission requirements need that allows denies, in Neo4j's order (schema, admin, write, read), or "" when allows grants them all. A query that needs admin only for procedures that allowsBoosted grants every one of boosted needs no admin (AdminGrantedBy).
func Neo4jPlanMap ¶
func Neo4jPlanMap(plan *ExecutionPlan, profile bool) map[string]any
Neo4jPlanMap renders the plan tree in the shape Neo4j puts in Bolt SUCCESS metadata and HTTP results: each node carries operatorType, identifiers, args (with EstimatedRows), and children; the profile form adds rows and dbHits. Bolt and HTTP both deliver this map so plans reach clients (#744).
func ParseAggregationProperty ¶
ParseAggregationProperty is a convenience function that returns just the variable and property. Returns ("", "") if not a valid aggregation with a property. This provides compatibility with the regex match[1], match[2] pattern.
func ParseKnowledgePolicyDDL ¶ added in v1.1.0
func ParseKnowledgePolicyDDL(ctx context.Context, stmt string, stage SourceStage) (command interface{}, owned bool, retErr error)
ParseKnowledgePolicyDDL attempts to parse a knowledge-layer DDL statement. Returns (command, true, nil) on success, (nil, false, nil) if the input is not a knowledge-layer DDL statement, or (nil, false, err) on parse error. The original context and explicit source stage preserve stored policy spelling.
func PlanHash ¶ added in v1.1.0
func PlanHash(plan *ExecutionPlan) string
PlanHash returns the 16-char hex FNV-1a digest of the canonical form of plan.
Nil safety: PlanHash(nil) and PlanHash(&ExecutionPlan{Root: nil}) both return "0000000000000000" — the zero placeholder operators expect when the executor emits a slow-query log without a populated plan tree (e.g., normal-mode queries that don't run EXPLAIN/PROFILE).
func QueryDiagnosticParameters ¶
func QueryDiagnosticParameters(ctx context.Context, query string, params map[string]any) map[string]any
QueryDiagnosticParameters projects query-owned credentials from parameters for display without changing execution inputs. It retains the request's source context and uses the existing pure composite preparation reader for explicit PASSWORD values. No catalog command is executed. For example, a password read from CREATE COMPOSITE DATABASE remains secret under an ordinary parameter key.
func RedactLiterals ¶ added in v1.1.0
RedactLiterals returns the input query with literal tokens replaced by RedactedPlaceholder. STRING_LITERAL, CHAR_LITERAL, INTEGER, and FLOAT tokens, and DIGIT tokens (hex and octal integers such as 0xBEEF), are always replaced. Statements the grammar rejects also have their identifiers replaced (see below). Empty queries and malformed or truncated input return RedactedPlaceholder (fail-closed).
NornicDB issue #563 defect 3: this used to return RedactedPlaceholder for any statement that failed a full cantlr.Parse. That parser rule does not cover every shape NornicDB's own executor accepts: CALL { ... UNION ... } subqueries, deep OR-chained CALL{UNION} branch fan-outs, and any statement ending in `LIMIT $limit` (a parameter literally named "limit", which the grammar's LIMIT clause rejects as a keyword collision; this is what collapsed the multi-MATCH variable-length (*m..n) traversal shape from the #563 scan, the *m..n syntax itself parses fine). Those statements execute successfully but were logged as the bare placeholder with no structure at all.
The redactor now runs in two steps.
Step 1 fails the whole statement closed (returns RedactedPlaceholder) on any of these lexer-level signals:
- the lexer's own error listener fires;
- the lexer emits an ERRCHAR token, ANTLR's catch-all for input it cannot tokenize, e.g. a stray control character or the opening quote of an unterminated string such as `MATCH (n {name: "ali`;
- brackets do not nest: every `(`, `{`, and `[` must be closed by its own type, in order. A closer with no open bracket (`) MATCH (n) (`), a closer of the wrong type (`{pw: Secret) RETURN n}`), or an opener still open at EOF (`MATCH ((((`) all fail closed. Brackets inside a string literal or comment are part of that single token and never count;
- two ID tokens appear back to back on the default channel, e.g. the unquoted value in `{name: John Secret}`.
Signal 4 also fires on a few valid statements. Keywords the lexer tokenizes never lex as ID, but some Cypher keywords (NULLS, FIRST, LAST, USE, LOAD, CSV, HEADERS, FROM, ERROR, CONTINUE, FINISH, ZONED, LOCAL, DATETIME, TRAILING) are not lexer tokens, so statements such as `ORDER BY n.x DESC NULLS LAST` and `CREATE CONSTRAINT ... IS :: ZONED DATETIME` are redacted whole. That is the safe direction.
Step 2 checks the statement against the grammar with cantlr.Validate, but only when it is at most redactGrammarCheckMaxBytes long; a longer statement is treated as one the grammar rejected, without parsing it. When the grammar accepts it, the output keeps every identifier and replaces only literals. When the grammar rejects it, the output keeps the statement's shape but replaces every identifier as well as every literal, because a bare word in text the grammar cannot place may be an unquoted value. In that mode only these stay: keywords, punctuation, whitespace, parameter names after `$`, and label or relationship-type names after `:` directly inside a `(` or `[`. Comments are replaced too. The executor accepts some statements the grammar rejects (CALL { ... UNION ... } subqueries, `LIMIT $limit`, map projections, COUNT { }), so those keep their clause structure, labels, and parameter names instead of collapsing to the bare placeholder.
Principle: when in doubt, redact. A false-closed redaction only costs log readability; a false-open one leaks the exact PII/secret content this redactor exists to protect.
Performance: this fires on the slow-query log path, i.e. exactly when the server is already under load, so its cost is bounded: one lexer pass over the statement, plus a grammar parse only for statements of at most redactGrammarCheckMaxBytes. A full parse of a large statement can allocate hundreds of megabytes of prediction state, and the log keeps only its first 500 characters. The executor's log sites go through (*StorageExecutor).redactForLog, which also reuses the executor's cached grammar verdict for the statement text, so the output is the same on both parsers.
func RegisterUserProcedure ¶
func RegisterUserProcedure(spec ProcedureSpec, handler ProcedureHandler) error
RegisterUserProcedure registers a user-defined procedure into the global registry.
func ReplaceParameters ¶
ReplaceParameters replaces all parameter references with their values. The replacer function receives the parameter name (without $) and returns the replacement string. This is ~5x faster than regex ReplaceAllStringFunc.
Example:
ReplaceParameters("WHERE n.name = $name", func(param string) string {
return fmt.Sprintf("'%s'", params[param])
})
func ResolveNamedZoneLocalTime ¶
func ResolveNamedZoneLocalTime(local time.Time, location *time.Location, preferLater bool) time.Time
ResolveNamedZoneLocalTime interprets local's UTC clock components in location, shifting gaps forward. String constructors and legacy Bolt values prefer the earlier overlap instant; map constructors set preferLater for the later one.
func ResolvedStatementQueryType ¶
ResolvedStatementQueryType is the execution owner's mode, when available. Protocol adapters share this reader; no transport reclassifies argument text.
func SetDatabaseTransactionMemoryLimits ¶
func SetDatabaseTransactionMemoryLimits(database string, limits DatabaseTransactionMemoryLimits)
SetDatabaseTransactionMemoryLimits replaces a database's override selection independently for each setting. Nil restores inheritance; a pointer to zero selects unlimited. Existing pools and running-statement ceilings are retained.
func SetParallelConfig ¶
func SetParallelConfig(config ParallelConfig)
SetParallelConfig updates the parallel execution configuration.
func SplitByCreate ¶
SplitByCreate splits by "CREATE " keyword. Convenience wrapper for hot path.
func SplitByKeyword ¶
SplitByKeyword splits a string by a keyword (case-insensitive), respecting word boundaries. This is ~8x faster than regexp.MustCompile(`(?i)\bKEYWORD\s+`).Split().
Example:
SplitByKeyword("MATCH (a) MATCH (b)", "MATCH")
// Returns: ["", "(a) ", "(b)"]
func SplitByMatch ¶
SplitByMatch splits by "MATCH " keyword. Convenience wrapper for hot path.
func StatementDatabase ¶
StatementDatabase is the one database decision for administration commands, used by the executor and the HTTP transaction boundary. It shares the command reader with USE validation; statement execution modes keep the same target.
func StatementShapeHash ¶
StatementShapeHash returns a 16-char hex FNV-1a digest of a literal-redacted Cypher statement's *shape*, for use as the slow-query log's plan_hash field when no ExecutionPlan tree is available (NornicDB issue #563 defect 2: the normal, non-EXPLAIN/PROFILE Execute() path never builds one — it always called PlanHash(nil), which collapses to the zero placeholder for every single slow query, making the field useless for grouping).
This is NOT a plan hash — it never sees the chosen execution plan, only the query text after RedactLiterals has already stripped literal values. It hashes on statement shape instead: whitespace is collapsed to single spaces and trimmed first, so two invocations of the same statement that differ only in incidental formatting (or, since literals are already redacted, only in the literal values a caller supplied) still hash identically, while two textually different statements — even ones that happen to compile to the same physical plan — hash differently. Callers that need true plan-level grouping should thread a real *ExecutionPlan through PlanHash instead; this is the best available fallback until one is cheaply available on the hot Execute() path (see the TRC-04 note on PlanHash's caller in executor.go).
Nil-safety mirrors PlanHash: an empty/whitespace-only input returns the same "0000000000000000" zero placeholder PlanHash(nil) returns, so callers cannot distinguish "no plan and no text" from "no plan tree" by field value alone — both mean "nothing to group on".
func StripComments ¶
StripComments returns query without its Cypher comments: // to the end of the line, and /* … */ (replaced by a space, keeping its line breaks), as cyphertext.CommentReplacement. // and /* inside string literals and quoted names are text. A query without comments is returned as is, without allocating. It is the comment rule the HTTP server's statement checks use (#683).
func TransactionDatabaseError ¶
func TransactionDatabaseError(ctx context.Context, databases TransactionDatabases, txDB, target, query string) error
TransactionDatabaseError is the one check that a transaction stays on one database: the error for a statement of a transaction on txDB that targets database target (with USE or :USE), or nil when target is txDB (by name or alias, through databases) or a constituent of composite txDB. The executor and the HTTP transaction boundary both use it. A transaction cannot span databases (Neo4j Operations Manual: "a transaction cannot span across multiple databases"); composite databases read several constituents through Fabric instead. A write gets Neo4j's Neo.ClientError.Statement.AccessMode "Writing to more than one database per transaction is not allowed" (verified against Neo4j 5.26). Neo4j Community has one user database, so its error for a read of a second one could not be observed; a read gets the same code with the message worded for a read.
func TransactionMemoryPoolUsage ¶
TransactionMemoryPoolUsage is the bytes the transactions of the process (global) and of database hold now.
func UnsupportedTypePlaceholder ¶
UnsupportedTypePlaceholder is what Neo4j sends a Bolt 5 client for a value the protocol has no structure for (a VECTOR or a UUID): the map {reason: 'UNKNOWN_TYPE', originalType: <type>}, originalType as VECTOR(3, INTEGER64) or UUID. ok is false for any other value.
func ValidateIndexHints ¶
func ValidateIndexHints(schema *storage.SchemaManager, hints []IndexHint) error
ValidateIndexHints checks if all specified index hints can be satisfied. Returns an error if any hint references a non-existent index.
Parameters:
- schema: The schema manager to validate against
- hints: The index hints to validate
Returns:
- nil if all hints are valid
- Error describing which hint cannot be satisfied
func ValidateStatementText ¶
ValidateStatementText admits raw transport text before any adapter can discard malformed comments. For example, CREATE (:N) /* fails before writes.
func WithAuthToken ¶
WithAuthToken stores an Authorization header token on context for execution paths that need to forward caller identity across remote constituents.
func WithAuthenticatedPrincipal ¶ added in v1.3.3
WithAuthenticatedPrincipal attaches an identity produced by successful authentication.
func WithAuthenticationDisabled ¶
WithAuthenticationDisabled marks the statements run with ctx as run by a server whose authentication is disabled. Immutable privileges can be granted and revoked only then, as in Neo4j; without the mark (any authenticated route, or an embedded caller) they can't.
func WithClientStatement ¶
WithClientStatement marks text supplied as a client statement, not protocol transaction control.
func WithClientTransactionTimeout ¶
WithClientTransactionTimeout marks ctx's BEGIN as that of a transaction whose client set its own timeout (Bolt tx_timeout): it replaces the server's transaction timeout for the transaction.
func WithDatabasePermissionResolver ¶ added in v1.3.1
func WithDatabasePermissionResolver(ctx context.Context, database string, resolver DatabasePermissionResolver) context.Context
WithDatabasePermissionResolver attaches database-scoped entitlements to an execution context. USE routing updates the selected database automatically.
func WithPermissionChecker ¶ added in v1.2.2
func WithPermissionChecker(ctx context.Context, checker PermissionChecker) context.Context
WithPermissionChecker attaches a caller's effective entitlements to an execution context. Nested dynamic statements inherit the same checker.
func WithProcedureGrantChecker ¶
func WithProcedureGrantChecker(ctx context.Context, allowsBoosted func(procedure string) bool) context.Context
WithProcedureGrantChecker attaches allowsBoosted, which reports whether the principal's roles hold EXECUTE BOOSTED PROCEDURE for a procedure: a query that needs administrator rights only for the procedure it calls is then authorized without them (AuthorizeQuery).
func WithReadOnlyStatements ¶
WithReadOnlyStatements restricts this statement and dynamically executed child statements to read-only effects. It narrows, never replaces, authorization. For example a Bolt READ transaction keeps this scope on each RUN context.
func WithRequestIdentity ¶
func WithRequestIdentity(ctx context.Context, identity *RequestIdentity) context.Context
WithRequestIdentity attaches a request's identity.
func WithResultStream ¶
func WithResultStream(ctx context.Context, stream *ResultStream) context.Context
WithResultStream returns ctx carrying stream for the next Execute.
func WithStatementAdmitted ¶
func WithStatementAdmitted(ctx context.Context, executor *StorageExecutor, admitted func()) context.Context
WithStatementAdmitted runs admitted when executor has authorized a statement on its own database (the decision Execute and nested execution take before running one, authorizeSelectedDatabase) and before that statement runs; it can run once per statement. A caller that builds an executor for a statement uses it to finish and share that executor only once the principal is admitted there. Other executors the statement reaches (a USE target, a nested statement) don't run it.
func WithTemporalViewport ¶
func WithTemporalViewport(ctx context.Context, viewport TemporalViewport) context.Context
func WithTransactionControl ¶
WithTransactionControl permits a transaction owner to issue its lifecycle command.
func WithTransactionMetadata ¶
WithTransactionMetadata carries a client's transaction metadata (Bolt's tx_metadata, on BEGIN or on RUN for an auto-commit transaction) to the transaction the executor opens for ctx: it is that transaction's metadata, as if tx.setMetaData set it first, and change events and SHOW TRANSACTIONS see it. Empty metadata leaves ctx as it is.
Types ¶
type AST ¶
type AST struct {
Clauses []ASTClause
RawQuery string
QueryType QueryType
// IsReadOnly is the statement-effect owner's answer for the text this AST
// was built from (readStatementExecutionContract.effect, proven read). It is
// not a scan of Clauses: a procedure mode, a schema change or an
// unresolved procedure decides the statement without a clause kind that
// exposes it. A published AST is immutable; QueryInfo.GetAST publishes a
// new one when the answer changes.
IsReadOnly bool
IsCompound bool
}
AST represents a complete parsed query.
type ASTBinaryExpr ¶
type ASTBinaryExpr struct {
Left ASTExpression
Operator string
Right ASTExpression
}
ASTBinaryExpr represents a binary operation.
type ASTBuilder ¶
type ASTBuilder struct{}
ASTBuilder builds Abstract Syntax Trees from Cypher queries. This is separate from QueryAnalyzer to allow lazy AST building only when needed.
Usage:
builder := NewASTBuilder()
ast, err := builder.Build("MATCH (n:Person) WHERE n.age > 21 RETURN n.name")
if err != nil {
// handle error
}
// ast.Clauses contains structured representation
func NewASTBuilder ¶
func NewASTBuilder() *ASTBuilder
NewASTBuilder creates a new AST builder. Lexical extents come from cyphertext; the builder retains its advisory pattern/clause structure.
func (*ASTBuilder) Build ¶
Build parses a Cypher query into an AST.
IsReadOnly answers the statement-effect owner (readStatementExecutionContract), so a registered WRITE procedure, a schema or catalog mutation and an unresolved procedure are writes even when no clause kind here exposes them. Text the effect owner cannot read keeps the structural result with a conservative write effect: its diagnostic belongs to admission, not to this builder. The caller cancellation is returned.
type ASTCall ¶
type ASTCall struct {
Procedure string
Arguments []ASTExpression
RawArgs string
Yield []string
}
ASTCall represents a CALL clause.
type ASTCaseExpr ¶
type ASTCaseExpr struct {
Input *ASTExpression
Whens []ASTCaseWhen
Default *ASTExpression
}
ASTCaseExpr represents a CASE expression.
type ASTCaseWhen ¶
type ASTCaseWhen struct {
Condition ASTExpression
Result ASTExpression
}
ASTCaseWhen represents a WHEN clause in CASE.
type ASTClause ¶
type ASTClause struct {
Type ASTClauseType
RawText string // Original text of the clause
StartPos int // Position in original query
EndPos int // End position in original query
// Parsed content (populated based on clause type)
Match *ASTMatch
Create *ASTCreate
Merge *ASTMerge
Delete *ASTDelete
Set *ASTSet
Remove *ASTRemove
Return *ASTReturn
With *ASTWith
Where *ASTWhere
Unwind *ASTUnwind
OrderBy *ASTOrderBy
Limit *int64
Skip *int64
Call *ASTCall
}
ASTClause represents a parsed clause with its content.
type ASTClauseType ¶
type ASTClauseType int
ASTClauseType identifies the clause type.
const ( ASTClauseMatch ASTClauseType = iota ASTClauseOptionalMatch ASTClauseCreate ASTClauseMerge ASTClauseDelete ASTClauseDetachDelete ASTClauseSet ASTClauseRemove ASTClauseReturn ASTClauseWith ASTClauseWhere ASTClauseUnwind ASTClauseOrderBy ASTClauseLimit ASTClauseSkip ASTClauseCall ASTClauseUnion ASTClauseForeach )
type ASTCreate ¶
type ASTCreate struct {
Patterns []ASTPattern
}
ASTCreate represents a CREATE clause.
type ASTExprType ¶
type ASTExprType int
ASTExprType identifies expression types.
const ( ASTExprLiteral ASTExprType = iota ASTExprVariable ASTExprProperty ASTExprFunction ASTExprBinary ASTExprUnary ASTExprList ASTExprMap ASTExprParameter ASTExprCase )
type ASTExpression ¶
type ASTExpression struct {
Type ASTExprType
RawText string
// Different expression types populate different fields
Literal interface{} // For literals
Variable string // For variable references
Property *ASTPropertyAccess
Function *ASTFunctionCall
Binary *ASTBinaryExpr
Unary *ASTUnaryExpr
List []ASTExpression
Map map[string]ASTExpression
Parameter string // For $param
Case *ASTCaseExpr
}
ASTExpression represents an expression.
type ASTFunctionCall ¶
type ASTFunctionCall struct {
Name string
Arguments []ASTExpression
Distinct bool
}
ASTFunctionCall represents a function call.
type ASTMatch ¶
type ASTMatch struct {
Patterns []ASTPattern
Optional bool
}
ASTMatch represents a MATCH clause.
type ASTMerge ¶
type ASTMerge struct {
Pattern ASTPattern
OnCreate []ASTSetItem
OnMatch []ASTSetItem
}
ASTMerge represents a MERGE clause.
type ASTNode ¶
type ASTNode struct {
Variable string
Labels []string
Properties map[string]ASTExpression
RawProps string
}
ASTNode represents a node in a pattern.
type ASTOrderItem ¶
type ASTOrderItem struct {
Expression ASTExpression
Descending bool
RawText string
}
ASTOrderItem represents a single ORDER BY item.
type ASTPattern ¶
type ASTPattern struct {
Nodes []ASTNode
Relationships []ASTRelationship
RawText string
}
ASTPattern represents a graph pattern.
type ASTPropertyAccess ¶
ASTPropertyAccess represents property access (n.name).
type ASTRelationship ¶
type ASTRelationship struct {
Variable string
Type string
Direction EdgeDirection
Properties map[string]ASTExpression
MinHops *int
MaxHops *int
}
ASTRelationship represents a relationship in a pattern.
type ASTRemove ¶
type ASTRemove struct {
Items []ASTRemoveItem
}
ASTRemove represents a REMOVE clause.
type ASTRemoveItem ¶
type ASTRemoveItem struct {
Variable string
Property string // For property removal
Labels []string // For label removal
}
ASTRemoveItem represents a property or label removal.
type ASTReturn ¶
type ASTReturn struct {
Items []ASTReturnItem
Distinct bool
}
ASTReturn represents a RETURN clause.
type ASTReturnItem ¶
type ASTReturnItem struct {
Expression ASTExpression
Alias string
RawText string
}
ASTReturnItem represents an item in RETURN.
type ASTSetItem ¶
type ASTSetItem struct {
Variable string
Property string
Value ASTExpression
RawValue string // Original value text for complex expressions
}
ASTSetItem represents a single SET assignment.
type ASTUnaryExpr ¶
type ASTUnaryExpr struct {
Operator string
Operand ASTExpression
}
ASTUnaryExpr represents a unary operation.
type ASTUnwind ¶
type ASTUnwind struct {
Expression ASTExpression
Variable string
RawExpr string
}
ASTUnwind represents an UNWIND clause.
type ASTWhere ¶
type ASTWhere struct {
Condition ASTExpression
RawText string
}
ASTWhere represents a WHERE clause.
type ASTWith ¶
type ASTWith struct {
Items []ASTReturnItem
Distinct bool
}
ASTWith represents a WITH clause.
type AdministrationOutcome ¶
type AdministrationOutcome struct{ CreatedDatabase string }
AdministrationOutcome records an actual successful catalog creation. A no-op IF NOT EXISTS and a generic result row do not report a created database.
type AggregateResult ¶
type AggregateResult struct {
Count int64
Sum float64
Values []interface{} // For COLLECT
Min interface{}
Max interface{}
HasData bool
}
AggregateResult holds partial aggregation results from a worker.
type AggregationResult ¶
type AggregationResult struct {
Function string // COUNT, SUM, AVG, MIN, MAX, COLLECT
Variable string // The variable name (e.g., "n")
Property string // The property name (e.g., "age"), empty for COUNT(n) or COUNT(*)
Distinct bool // True if DISTINCT was specified
IsStar bool // True if COUNT(*)
}
AggregationResult holds the parsed components of an aggregation expression.
func ParseAggregation ¶
func ParseAggregation(expr string) *AggregationResult
ParseAggregation parses an aggregation expression like "COUNT(n.prop)" or "SUM(DISTINCT n.age)". This replaces 8 separate regex patterns with one unified parser (~5x faster).
Returns nil if the expression is not a valid aggregation.
Example:
ParseAggregation("COUNT(n.age)") → {Function: "COUNT", Variable: "n", Property: "age"}
ParseAggregation("SUM(DISTINCT x.value)") → {Function: "SUM", Variable: "x", Property: "value", Distinct: true}
ParseAggregation("COUNT(*)") → {Function: "COUNT", IsStar: true}
type AlterDecayProfileBindingCmd ¶ added in v1.3.1
type AlterDecayProfileBindingCmd struct {
Binding knowledgepolicy.DecayProfileBinding
}
type AlterDecayProfileCmd ¶ added in v1.1.0
type AlterPromotionPolicyCmd ¶ added in v1.1.0
type AlterPromotionPolicyDefinitionCmd ¶ added in v1.3.1
type AlterPromotionPolicyDefinitionCmd struct {
Policy knowledgepolicy.PromotionPolicyDef
}
type AlterPromotionProfileCmd ¶ added in v1.1.0
type AuthenticatedUser ¶
AuthenticatedUser is the signed-in user of a request: SHOW CURRENT USER lists it, and SHOW TRANSACTIONS reports its name as the username.
type Clause ¶
type Clause interface {
// contains filtered or unexported methods
}
Clause represents a query clause.
type ClauseType ¶
type ClauseType int
ClauseType represents the type of a Cypher clause
const ( ClauseUnknown ClauseType = iota ClauseMatch ClauseCreate ClauseMerge ClauseDelete ClauseSet ClauseRemove ClauseReturn ClauseWith ClauseUnwind ClauseCall ClauseForeach ClauseLoadCSV ClauseShow ClauseDrop ClauseOptionalMatch )
type ClientConnection ¶
ClientConnection identifies the connection a statement arrived on, for SHOW TRANSACTIONS (connectionId, clientAddress, protocol).
type CommitStatement ¶
CommitStatement is one statement of a committing transaction with the parameters it ran with.
type Comparison ¶
type Comparison struct {
Left Expression
Operator string
Right Expression
}
Comparison represents a comparison expression.
type ConnectionListing ¶
type ConnectionListing struct {
ConnectionID string
ConnectTime string
Connector string
Username string
UserAgent string
ServerAddress string
ClientAddress string
}
ConnectionListing is an immutable accepted-connection snapshot for dbms.listConnections. Transports supply it through RequestIdentity.Connections instead of exposing live sessions.
type CreateClause ¶
type CreateClause struct {
Pattern Pattern
}
CreateClause represents a CREATE clause.
type CreateDecayProfileBindingCmd ¶ added in v1.1.0
type CreateDecayProfileBindingCmd struct {
Binding knowledgepolicy.DecayProfileBinding
}
type CreateDecayProfileBundleCmd ¶ added in v1.1.0
type CreateDecayProfileBundleCmd struct {
Bundle knowledgepolicy.DecayProfileBundle
}
type CreatePromotionPolicyCmd ¶ added in v1.1.0
type CreatePromotionPolicyCmd struct {
Policy knowledgepolicy.PromotionPolicyDef
IfNotExists bool
}
type CreatePromotionProfileCmd ¶ added in v1.1.0
type CreatePromotionProfileCmd struct {
Profile knowledgepolicy.PromotionProfileDef
}
type CypherDate ¶
CypherDate is a calendar date without a time or zone.
func (*CypherDate) MarshalMsgpack ¶
func (v *CypherDate) MarshalMsgpack() ([]byte, error)
func (CypherDate) PropertyValueKind ¶
func (CypherDate) PropertyValueKind() string
func (CypherDate) RemoteParameterValue ¶
func (v CypherDate) RemoteParameterValue() interface{}
RemoteParameterValue is the date as a driver Date.
func (CypherDate) StoragePropertyValue ¶
func (v CypherDate) StoragePropertyValue() (any, bool)
func (CypherDate) String ¶
func (v CypherDate) String() string
func (CypherDate) TemporalTime ¶
func (v CypherDate) TemporalTime() time.Time
func (*CypherDate) UnmarshalMsgpack ¶
func (v *CypherDate) UnmarshalMsgpack(data []byte) error
type CypherDateTime ¶
CypherDateTime is a zoned instant. ZoneID is retained for named-zone wire encoding.
func (CypherDateTime) PropertyValueKind ¶
func (CypherDateTime) PropertyValueKind() string
func (CypherDateTime) RemoteParameterValue ¶
func (v CypherDateTime) RemoteParameterValue() interface{}
RemoteParameterValue is the instant in its named zone, or at its offset in a zone named "Offset", which the driver sends as a fixed offset.
func (CypherDateTime) StoragePropertyValue ¶
func (v CypherDateTime) StoragePropertyValue() (any, bool)
func (CypherDateTime) String ¶
func (v CypherDateTime) String() string
func (CypherDateTime) TemporalTime ¶
func (v CypherDateTime) TemporalTime() time.Time
type CypherDuration ¶
type CypherDuration struct {
Years int64 // Calendar years
Months int64 // Calendar months
Days int64 // Calendar days
Hours int64 // Clock hours
Minutes int64 // Clock minutes
Seconds int64 // Clock seconds
Nanos int64 // Sub-second precision (nanoseconds)
}
CypherDuration represents a Neo4j-compatible duration type.
This type stores time intervals with separate components for calendar units (years, months, days) and clock units (hours, minutes, seconds).
Calendar units are stored separately because they have variable lengths:
- A year can be 365 or 366 days
- A month can be 28-31 days
Clock units have fixed lengths and are stored precisely.
Fields ¶
- Years: Number of years (calendar unit)
- Months: Number of months (calendar unit)
- Days: Number of days (calendar unit)
- Hours: Number of hours (clock unit)
- Minutes: Number of minutes (clock unit)
- Seconds: Number of seconds (clock unit)
- Nanos: Nanoseconds for sub-second precision
Example ¶
dur := &CypherDuration{
Years: 1, Months: 6, Days: 15,
Hours: 2, Minutes: 30, Seconds: 45,
}
_ = dur.String() // serializes as P1Y6M15DT2H30M45S
ELI12 ¶
Think of CypherDuration like a time capsule with two compartments:
Calendar compartment: "How many birthdays/months/days to skip?" (Years, Months, Days - these depend on the calendar)
Clock compartment: "How much to move the clock hands?" (Hours, Minutes, Seconds - these are always the same length)
We keep them separate because months aren't all the same length! February has 28-29 days, while January has 31.
func (*CypherDuration) MarshalMsgpack ¶
func (d *CypherDuration) MarshalMsgpack() ([]byte, error)
MarshalMsgpack encodes all duration components for msgpack extension storage.
func (*CypherDuration) PropertyValueKind ¶
func (*CypherDuration) PropertyValueKind() string
PropertyValueKind identifies durations as durable typed properties.
func (CypherDuration) RemoteParameterValue ¶
func (d CypherDuration) RemoteParameterValue() interface{}
RemoteParameterValue is the duration as a driver Duration: months, days, and seconds with their nanoseconds.
func (*CypherDuration) StoragePropertyValue ¶
func (v *CypherDuration) StoragePropertyValue() (any, bool)
func (*CypherDuration) String ¶
func (d *CypherDuration) String() string
String returns the duration in ISO 8601 format.
The format is: P[n]Y[n]M[n]DT[n]H[n]M[n]S
Only non-zero components are included. If no components are present, returns "PT0S" (zero duration).
Example ¶
dur := &CypherDuration{Days: 5, Hours: 2}
_ = dur.String() // serializes as "P5DT2H"
zeroDur := &CypherDuration{}
_ = zeroDur.String() // serializes as "PT0S"
func (*CypherDuration) ToTimeDuration ¶
func (d *CypherDuration) ToTimeDuration() time.Duration
ToTimeDuration converts to Go's time.Duration.
Note: This only converts the clock components (hours, minutes, seconds, nanos). Calendar components (years, months, days) are converted to their approximate durations which may not be accurate for actual date arithmetic.
For precise date calculations, use AddDurationToDate instead.
Example ¶
dur := &CypherDuration{Hours: 2, Minutes: 30}
goDur := dur.ToTimeDuration()
_ = goDur // formats as 2h30m0s
func (*CypherDuration) TotalDays ¶
func (d *CypherDuration) TotalDays() float64
TotalDays returns the approximate total number of days.
Note: This is an approximation because it assumes:
- 1 year = 365.25 days (average accounting for leap years)
- 1 month = 30.4375 days (365.25 / 12)
For precise date calculations, use the individual components with AddDurationToDate instead.
Example ¶
dur := &CypherDuration{Years: 1}
_ = dur.TotalDays() // returns ~365.25
func (*CypherDuration) TotalSeconds ¶
func (d *CypherDuration) TotalSeconds() float64
TotalSeconds returns the approximate total number of seconds.
Note: This is an approximation for the calendar components. See TotalDays for the assumptions used.
Example ¶
dur := &CypherDuration{Hours: 2, Minutes: 30}
_ = dur.TotalSeconds() // returns 9000
func (*CypherDuration) UnmarshalMsgpack ¶
func (d *CypherDuration) UnmarshalMsgpack(data []byte) error
UnmarshalMsgpack decodes all duration components from extension storage.
type CypherLocalDateTime ¶
CypherLocalDateTime is a calendar date and wall-clock time without a zone.
func (*CypherLocalDateTime) MarshalMsgpack ¶
func (v *CypherLocalDateTime) MarshalMsgpack() ([]byte, error)
func (CypherLocalDateTime) PropertyValueKind ¶
func (CypherLocalDateTime) PropertyValueKind() string
func (CypherLocalDateTime) RemoteParameterValue ¶
func (v CypherLocalDateTime) RemoteParameterValue() interface{}
RemoteParameterValue is the date and time of day as a driver LocalDateTime.
func (CypherLocalDateTime) StoragePropertyValue ¶
func (v CypherLocalDateTime) StoragePropertyValue() (any, bool)
func (CypherLocalDateTime) String ¶
func (v CypherLocalDateTime) String() string
func (CypherLocalDateTime) TemporalTime ¶
func (v CypherLocalDateTime) TemporalTime() time.Time
func (*CypherLocalDateTime) UnmarshalMsgpack ¶
func (v *CypherLocalDateTime) UnmarshalMsgpack(data []byte) error
type CypherLocalTime ¶
CypherLocalTime is a wall-clock time without a zone.
func (*CypherLocalTime) MarshalMsgpack ¶
func (v *CypherLocalTime) MarshalMsgpack() ([]byte, error)
func (CypherLocalTime) PropertyValueKind ¶
func (CypherLocalTime) PropertyValueKind() string
func (CypherLocalTime) RemoteParameterValue ¶
func (v CypherLocalTime) RemoteParameterValue() interface{}
RemoteParameterValue is the time of day as a driver LocalTime.
func (CypherLocalTime) StoragePropertyValue ¶
func (v CypherLocalTime) StoragePropertyValue() (any, bool)
func (CypherLocalTime) String ¶
func (v CypherLocalTime) String() string
func (CypherLocalTime) TemporalTime ¶
func (v CypherLocalTime) TemporalTime() time.Time
func (*CypherLocalTime) UnmarshalMsgpack ¶
func (v *CypherLocalTime) UnmarshalMsgpack(data []byte) error
type CypherPoint ¶
CypherPoint is a Cypher POINT value: a coordinate reference system, identified by its SRID, and two or three coordinates. For geographic points X is the longitude, Y the latitude and Z the height, as in Neo4j. Points are stored as properties (msgpack extension 47), sent over Bolt as Point2D / Point3D structures and over HTTP as GeoJSON-like maps (#817).
func NewCypherPoint ¶
func NewCypherPoint(srid int, coordinates ...float64) (CypherPoint, bool)
NewCypherPoint builds a point from an SRID and its coordinates, as Bolt's Point2D / Point3D structures carry it. ok is false for an unknown SRID or a coordinate count that does not match its coordinate reference system.
func (CypherPoint) CRSHref ¶
func (p CypherPoint) CRSHref() string
CRSHref is the spatialreference.org link Neo4j's HTTP results carry.
func (CypherPoint) CRSName ¶
func (p CypherPoint) CRSName() string
CRSName is the coordinate reference system's name (cartesian, wgs-84-3d…).
func (CypherPoint) Coordinates ¶
func (p CypherPoint) Coordinates() []float64
Coordinates are the point's coordinates in order (x, y[, z]).
func (CypherPoint) Is3D ¶
func (p CypherPoint) Is3D() bool
Is3D reports whether the point has a third coordinate.
func (CypherPoint) PropertyValueKind ¶
func (CypherPoint) PropertyValueKind() string
PropertyValueKind identifies points as durable typed properties.
func (CypherPoint) RemoteParameterValue ¶
func (p CypherPoint) RemoteParameterValue() interface{}
RemoteParameterValue is the point as a driver Point2D, or Point3D in a three-dimensional reference system.
func (CypherPoint) StoragePropertyValue ¶
func (v CypherPoint) StoragePropertyValue() (any, bool)
func (CypherPoint) String ¶
func (p CypherPoint) String() string
String is the point's own text, as Neo4j shows the value: point({srid:7203, x:1.0, y:2.0}).
type CypherTime ¶
CypherTime is a wall-clock time with a fixed offset.
func (*CypherTime) MarshalMsgpack ¶
func (v *CypherTime) MarshalMsgpack() ([]byte, error)
func (CypherTime) PropertyValueKind ¶
func (CypherTime) PropertyValueKind() string
func (CypherTime) RemoteParameterValue ¶
func (v CypherTime) RemoteParameterValue() interface{}
RemoteParameterValue is the time of day and offset as a driver Time.
func (CypherTime) StoragePropertyValue ¶
func (v CypherTime) StoragePropertyValue() (any, bool)
func (CypherTime) String ¶
func (v CypherTime) String() string
func (CypherTime) TemporalTime ¶
func (v CypherTime) TemporalTime() time.Time
func (*CypherTime) UnmarshalMsgpack ¶
func (v *CypherTime) UnmarshalMsgpack(data []byte) error
type CypherUUID ¶
type CypherUUID struct {
// contains filtered or unexported fields
}
CypherUUID is a Cypher 25 UUID value (#907): 128 bits, written as 8-4-4-4-12 lower-case hex digits. As in Neo4j:
- uuid() is a random version 7 UUID (time-ordered), uuid(msb, lsb) the UUID of two 64-bit halves and uuid(text) the UUID text names (in any case, with its four dashes);
- two UUIDs are equal when their bits are; a UUID is never equal to its text, and UUIDs have no < or > but sort by their bits as unsigned;
- toString writes the text, uuid.mostSignificantBits and uuid.leastSignificantBits read the halves as signed integers.
func (CypherUUID) LeastSignificantBits ¶
func (u CypherUUID) LeastSignificantBits() int64
LeastSignificantBits is the last 64 bits as a signed integer.
func (CypherUUID) MostSignificantBits ¶
func (u CypherUUID) MostSignificantBits() int64
MostSignificantBits is the first 64 bits as a signed integer.
func (CypherUUID) PropertyValueKind ¶
func (CypherUUID) PropertyValueKind() string
func (CypherUUID) RemoteParameterValue ¶
func (u CypherUUID) RemoteParameterValue() interface{}
RemoteParameterValue is the UUID as its text.
func (CypherUUID) StoragePropertyValue ¶
func (v CypherUUID) StoragePropertyValue() (any, bool)
func (CypherUUID) String ¶
func (u CypherUUID) String() string
String is the UUID's text: 550e8400-e29b-41d4-a716-446655440000.
type CypherVector ¶
type CypherVector struct {
Type VectorCoordinateType
Ints []int64
Floats []float64
}
CypherVector is a Cypher 25 VECTOR value (#907): a fixed number of coordinates of one numeric type. As in Neo4j:
- the coordinate types are INTEGER64 (INTEGER, INT, INT64), INTEGER32 (INT32), INTEGER16 (INT16), INTEGER8 (INT8), FLOAT64 (FLOAT) and FLOAT32;
- an integer vector truncates float coordinates toward zero, and a coordinate outside the type's range is an ArithmeticError; a float32 vector rounds to float32, and a coordinate that isn't finite is an error;
- two vectors are equal only with the same type and coordinates, a vector is never equal to a list, and vectors have no < or >;
- a vector is not a list: indexing and iterating it are type errors, toIntegerList / toFloatList / size read it.
Ints holds an integer vector's coordinates and Floats a float vector's.
func (CypherVector) CypherSize ¶
func (v CypherVector) CypherSize() int64
CypherSize is size(vector): the dimension (cypherfn.Sized).
func (CypherVector) Dimension ¶
func (v CypherVector) Dimension() int
Dimension is the number of coordinates.
func (CypherVector) Equal ¶
func (v CypherVector) Equal(other CypherVector) bool
Equal reports whether v and other have the same type and coordinates.
func (CypherVector) PropertyValueKind ¶
func (CypherVector) PropertyValueKind() string
func (CypherVector) RemoteParameterValue ¶
func (v CypherVector) RemoteParameterValue() interface{}
RemoteParameterValue is the vector's coordinates as a list.
func (CypherVector) StoragePropertyValue ¶
func (v CypherVector) StoragePropertyValue() (any, bool)
func (CypherVector) String ¶
func (v CypherVector) String() string
String is the vector as toString writes it: vector([1, 2], 2, INTEGER64).
type DatabaseExecutorCache ¶
type DatabaseExecutorCache[T any] struct { // contains filtered or unexported fields }
DatabaseExecutorCache binds one protocol's cache lifetime to the common publication algorithm. A protocol supplies only its view creation and a validity predicate; no second cache algorithm is needed.
func NewDatabaseExecutorCache ¶
func NewDatabaseExecutorCache[T any](mu *sync.RWMutex, entries *map[string]T, valid func(T) bool, create func(string) (T, error), before func()) *DatabaseExecutorCache[T]
NewDatabaseExecutorCache binds an existing protocol cache to the common get-or-create owner while preserving its invalidation lock.
func (*DatabaseExecutorCache[T]) Clear ¶
func (c *DatabaseExecutorCache[T]) Clear()
Clear invalidates all cached views.
func (*DatabaseExecutorCache[T]) Delete ¶
func (c *DatabaseExecutorCache[T]) Delete(name string)
Delete invalidates one database after its catalog entry changes.
func (*DatabaseExecutorCache[T]) EvictInvalid ¶
func (c *DatabaseExecutorCache[T]) EvictInvalid()
EvictInvalid removes views whose catalog selections have been retired.
func (*DatabaseExecutorCache[T]) Get ¶
func (c *DatabaseExecutorCache[T]) Get(name string) (T, error)
Get returns the current valid database view, building one if needed.
type DatabaseIdentityProvider ¶
type DatabaseIdentityProvider interface {
DatabaseIdentity(name string) (string, time.Time)
ServerIdentity() (string, time.Time)
}
DatabaseIdentityProvider optionally supplies persisted administrative identities. DatabaseIdentity returns a database UUID and its actual creation time; ServerIdentity returns the installation UUID and its creation time. Unknown identities use an empty string and unknown times use time.Time{}. SHOW DATABASES and dbms.info use this provider without requiring custom DatabaseManagerInterface implementations to support identity metadata.
type DatabaseInfoInterface ¶
type DatabaseInfoInterface = catalogadapter.DatabaseInfoInterface
DatabaseInfoInterface provides database metadata without importing multidb.
type DatabaseManagerInterface ¶
type DatabaseManagerInterface interface {
CreateDatabase(ctx context.Context, request multidb.DatabaseCreateRequest) error
// DropDatabase is the single DROP-state owner: it reports a truly absent
// name as multidb.ErrDatabaseNotFound and finishes a pending drop.
DropDatabase(ctx context.Context, name string) error
ListDatabases() []DatabaseInfoInterface
Exists(name string) bool
CreateAlias(ctx context.Context, alias, databaseName string) error
DropAlias(ctx context.Context, alias string) error
ListAliases(databaseName string) map[string]string
ResolveDatabase(nameOrAlias string) (string, error)
SetDatabaseLimits(ctx context.Context, databaseName string, limits interface{}) error
GetDatabaseLimits(databaseName string) (interface{}, error)
// Composite database methods
CreateCompositeDatabase(ctx context.Context, name string, constituents []interface{}) error
DropCompositeDatabase(ctx context.Context, name string) error
AddConstituent(ctx context.Context, compositeName string, constituent interface{}) error
RemoveConstituent(ctx context.Context, compositeName string, alias string) error
GetCompositeConstituents(compositeName string) ([]interface{}, error)
ListCompositeDatabases() []DatabaseInfoInterface
IsCompositeDatabase(name string) bool
// GetStorageForUse returns the storage engine for a database, supporting
// composite databases. authToken is forwarded for remote constituents.
GetStorageForUse(name string, authToken string) (interface{}, error)
}
DatabaseManagerInterface is the query layer's database-management contract. Atomic standard creation carries the shared typed catalog request. Catalog mutations receive the operation context through every adapter. Read-only resolution/storage APIs retain their existing signatures.
type DatabaseOptionsManager ¶
type DatabaseOptionsManager interface {
DatabaseOptions(name string) (map[string]string, error)
SetDatabaseOption(ctx context.Context, name, key, value string) error
}
DatabaseOptionsManager is the optional DatabaseManagerInterface extension for ALTER DATABASE … SET / REMOVE OPTION and SHOW DATABASES' options column (#937). CREATE initial options belong to DatabaseCreateRequest.
type DatabasePermissionResolver ¶ added in v1.3.1
DatabasePermissionResolver answers whether the caller holds an entitlement for the database where a statement is executing. "access" checks selection of a containing composite or alias; data permissions apply to its target.
type DatabaseScopedExecutorOptions ¶
type DatabaseScopedExecutorOptions struct {
Name string
Storage DatabaseStorageResolver
AuthToken string
UseAuthenticatedStorage bool
QueryCachePolicy bool
QueryCacheMaxEntries int
QueryCacheTTL time.Duration
StatementCacheManager *multidb.DatabaseManager
FallbackStatementCaches *StatementCaches
LocalizationRenderer ProcedureMetadataRenderer
BaseExecutor *StorageExecutor
Configure func(*StorageExecutor, storage.Engine)
}
DatabaseScopedExecutorOptions identifies the common executor lifetime and database selection shared by HTTP and Bolt. Protocol-specific configuration remains with the caller and runs before the executor is published.
type DatabaseStorageResolver ¶
DatabaseStorageResolver resolves the storage view selected by a protocol.
type DatabaseTransactionMemoryLimits ¶
DatabaseTransactionMemoryLimits selects a database's own settings. A nil field inherits the current process default for that setting; a pointer to zero explicitly selects unlimited. Changes apply to new statements only. SetDatabaseTransactionMemoryLimits reads these values without retaining the pointers, so later caller edits cannot alter the installed configuration.
Examples:
SetDatabaseTransactionMemoryLimits("analytics", DatabaseTransactionMemoryLimits{TransactionMax: new(int64(1 << 30))})
SetDatabaseTransactionMemoryLimits("analytics", DatabaseTransactionMemoryLimits{}) // inherit both defaults
SetDatabaseTransactionMemoryLimits("analytics", DatabaseTransactionMemoryLimits{TransactionMax: new(int64(0))}) // explicitly unlimited
type DeleteClause ¶
DeleteClause represents a DELETE clause.
type DropDecayProfileCmd ¶ added in v1.1.0
type DropPromotionPolicyCmd ¶ added in v1.1.0
type DropPromotionProfileCmd ¶ added in v1.1.0
type EdgeDirection ¶
type EdgeDirection int
EdgeDirection represents edge direction.
const ( EdgeBoth EdgeDirection = iota EdgeOutgoing EdgeIncoming )
type EdgeFilterFunc ¶
EdgeFilterFunc tests whether an edge matches filter criteria.
type EdgePattern ¶
type EdgePattern struct {
Variable string
Type string
Direction EdgeDirection
Properties map[string]any
MinHops *int
MaxHops *int
}
EdgePattern represents an edge in a pattern.
type EmbeddingChunk ¶
type EmbeddingChunk struct {
ID string `cypher:"id" json:"id"`
ParentID string `cypher:"parent_id" json:"parent_id"`
Index int `cypher:"chunk_index" json:"chunk_index"`
Text string `cypher:"text" json:"text"`
Embedding []float32 `cypher:"embedding" json:"embedding"`
}
EmbeddingChunk represents a chunk with embedding data.
type ExecuteResult ¶
type ExecuteResult struct {
// Administration carries the command owner's successful outcome. Transports
// consume this identity rather than re-reading source or inspecting rows.
Administration *AdministrationOutcome `json:"-"`
Columns []string
Rows [][]interface{}
Stats *QueryStats
Metadata map[string]interface{} // Additional result metadata (e.g., execution plan)
// MapKeyOrders retains evaluated map traversal order for transaction HTTP metadata.
MapKeyOrders map[uintptr][]string `json:"-"`
}
ExecuteResult holds execution results in Neo4j-compatible format.
type ExecutionMode ¶
type ExecutionMode string
ExecutionMode represents how a query should be executed
const ( ModeNormal ExecutionMode = "normal" ModeExplain ExecutionMode = "EXPLAIN" ModeProfile ExecutionMode = "PROFILE" )
type ExecutionPlan ¶
type ExecutionPlan struct {
// Root operator of the plan
Root *PlanOperator `json:"root"`
// Query being explained/profiled
Query string `json:"query"`
// Execution mode (EXPLAIN or PROFILE)
Mode ExecutionMode `json:"mode"`
// Total statistics (only for PROFILE)
TotalDBHits int64 `json:"totalDbHits,omitempty"`
TotalTime time.Duration `json:"totalTime,omitempty"`
TotalRows int64 `json:"totalRows,omitempty"`
// Unobserved identifies execution boundaries without captured measurements.
// Such boundaries must never be populated with planner estimates.
Unobserved []string `json:"unobserved,omitempty"`
// TotalDBHitsObserved is false when an actual callback's accesses cannot
// be fully measured, even if some of its nested readers were observed.
TotalDBHitsObserved bool `json:"totalDbHitsObserved,omitempty"`
}
ExecutionPlan represents the complete query execution plan
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor executes Cypher queries.
type Expression ¶
type Expression interface {
// contains filtered or unexported methods
}
Expression represents a Cypher expression.
type FastRPConfig ¶
type FastRPConfig struct {
EmbeddingDimension int
IterationWeights []float64
NormalizationStrength float64
NodeSelfInfluence float64
PropertyRatio float64
FeatureProperties []string
RelationshipWeightProperty string
RandomSeed int64
NodeLabels []string // nil: every projected label
RelationshipTypes []string // nil: every projected type
// Configuration is the configuration as gds.fastRP.stats reports it.
Configuration map[string]interface{}
}
FastRPConfig holds configuration for FastRP, as GDS's gds.fastRP reads it (#1191).
type FilterFunc ¶
FilterFunc is a function that tests whether a node matches filter criteria.
type FulltextQuery ¶ added in v1.1.11
type FulltextQuery struct {
// contains filtered or unexported fields
}
FulltextQuery is a parsed Lucene-classic query, ready for per-document evaluation.
func ParseFulltextQuery ¶ added in v1.1.11
func ParseFulltextQuery(input string) (*FulltextQuery, error)
ParseFulltextQuery parses input, returning a Neo4j-style parse error for structurally malformed queries. It never panics; the tokenizer accepts any input and the parser rejects only unbalanced groups or dangling operators.
func (*FulltextQuery) IsEmpty ¶ added in v1.1.11
func (q *FulltextQuery) IsEmpty() bool
IsEmpty reports whether the query has no evaluable content (empty input).
func (*FulltextQuery) Match ¶ added in v1.1.11
func (q *FulltextQuery) Match(ctx *ftEvalCtx, doc *ftDoc) (bool, float64)
Match returns (matched, score) for a single doc. Callers build the doc once per candidate and pass shared bookkeeping via ctx.
func (*FulltextQuery) PrimaryTerms ¶ added in v1.1.11
func (q *FulltextQuery) PrimaryTerms() []string
PrimaryTerms exposes the list of lower-cased scoring terms so callers can build docFreq maps before evaluating each doc.
type FunctionCall ¶
type FunctionCall struct {
Name string
Args []Expression
}
FunctionCall represents a function call.
type GraphDatabaseResolver ¶
type GraphDatabaseResolver interface {
IsCompositeDatabase(string) bool
ResolveDatabase(string) (string, error)
}
GraphDatabaseResolver is the catalog view needed to resolve graph selections. It accepts native typed constituent snapshots or the legacy generic adapter.
type GraphProjection ¶
type GraphProjection struct {
Name string
NodeIDs []string
NodeLabels map[string][]string // node -> the projected labels it carries
Labels []string // the projected labels ("__ALL__" for '*')
NodeProperties projectedNodePropertyValueMap // node -> typed value (int64, float64, []int64 or []float64)
// NodePropertyTypes is each projected property key's GDS type:
// Integer, Float, List of Integer or List of Float.
NodePropertyTypes map[string]string
NodePropertyKeys map[string][]string // projected label -> its property keys
Relationships []ProjectedRelationship
Types []string // the projected relationship types ("__ALL__" for '*')
RelationshipPropertyKeys map[string][]string // projected type -> its property keys
NodeProjection map[string]interface{}
RelationshipProjection map[string]interface{}
NodeCount int
RelationshipCount int
CreatedAt time.Time
Database string
Configuration map[string]interface{} // as gds.graph.list reports it
// contains filtered or unexported fields
}
GraphProjection is a gds.graph.project graph (#1190): its nodes, in node ID order, and its relationships, oriented as projected. An UNDIRECTED relationship is held in both directions, as GDS holds and counts it. NodeProperties preserves each projected numeric type; direct Go consumers must handle int64, float64, []int64 and []float64 values rather than assume float64. For example, age, ok := projection.NodeProperties["alice"]["age"].(int64).
type HotPathTrace ¶
type HotPathTrace struct {
OuterIndexTopK bool
FabricBatchedApplyRows bool
SimpleMatchLimitFastPath bool
CosineVectorIndexFastPath bool
CompoundQueryFastPath bool
TraversalStartSeedTopK bool
TraversalEndSeedTopK bool
UnwindSimpleMergeBatch bool
UnwindMergeChainBatch bool
UnwindRelationshipMergeBatch bool
UnwindFixedChainLinkBatch bool
UnwindMultiMatchCreateBatch bool
CallTailProjectionFastPath bool
CallTailPipelineUsed bool
MergeSchemaLookupUsed bool
MergeScanFallbackUsed bool
}
HotPathTrace records which key query hot paths were used for the most recent Execute call.
type IndexHint ¶
type IndexHint struct {
Type IndexHintType
Variable string // The variable name (e.g., "n" in "n:Person")
Label string // The label (e.g., "Person")
Property string // The property for index hints (e.g., "name")
Properties []string // Multiple properties for composite hints
}
IndexHint represents a parsed index hint from a Cypher query.
Example:
USING INDEX n:Person(name)
→ IndexHint{Type: HintIndex, Variable: "n", Label: "Person", Property: "name"}
func ParseIndexHints ¶
ParseIndexHints extracts all index hints from a Cypher query.
Parameters:
- query: The full Cypher query string
Returns:
- Slice of parsed IndexHint structs
- The query with hints removed (for further processing)
Example:
query := "MATCH (n:Person) USING INDEX n:Person(name) WHERE n.name = 'Alice' RETURN n"
hints, cleanQuery := ParseIndexHints(query)
// hints = [{Type: HintIndex, Variable: "n", Label: "Person", Property: "name"}]
// cleanQuery = "MATCH (n:Person) WHERE n.name = 'Alice' RETURN n"
type IndexHintContext ¶
type IndexHintContext struct {
Hints []IndexHint
HintsByVar map[string][]IndexHint // Variable -> hints for that variable
}
IndexHintContext holds index hints for a query execution.
func NewIndexHintContext ¶
func NewIndexHintContext(hints []IndexHint) *IndexHintContext
NewIndexHintContext creates a new context from parsed hints.
func (*IndexHintContext) GetHintsForVariable ¶
func (ctx *IndexHintContext) GetHintsForVariable(variable string) []IndexHint
GetHintsForVariable returns all hints for a specific variable.
func (*IndexHintContext) HasIndexHint ¶
func (ctx *IndexHintContext) HasIndexHint(variable, label, property string) bool
HasIndexHint checks if there's an index hint for a variable/label/property combination.
func (*IndexHintContext) ShouldForceScan ¶
func (ctx *IndexHintContext) ShouldForceScan(variable, label string) bool
ShouldForceScan checks if a label scan should be forced for a variable.
type IndexHintType ¶
type IndexHintType int
IndexHintType represents the type of index hint.
const ( // HintIndex forces use of a specific property index. HintIndex IndexHintType = iota // HintScan forces a label scan instead of index lookup. HintScan // HintJoin forces a specific join strategy. HintJoin )
type InferenceManager ¶
type InferenceManager interface {
Generate(ctx context.Context, prompt string, params heimdall.GenerateParams) (string, error)
Chat(ctx context.Context, req heimdall.ChatRequest) (*heimdall.ChatResponse, error)
}
InferenceManager is the minimal LLM contract used by Cypher db.infer. It mirrors Heimdall manager methods to keep adapters thin.
type KalmanAdaptiveProcessResult ¶
type KalmanAdaptiveProcessResult struct {
Value float64 `json:"value"`
Mode string `json:"mode"`
State string `json:"state"`
}
KalmanAdaptiveProcessResult is the result of kalman.adaptive.process()
type KalmanAdaptiveState ¶
type KalmanAdaptiveState struct {
// Underlying basic filter state
Basic KalmanState `json:"basic"`
// Underlying velocity filter state
Velocity KalmanVelocityState `json:"velocity"`
// Current mode: "basic" or "velocity"
Mode string `json:"mode"`
// Observations since last switch
SinceSwitch int `json:"ss"`
// Trend detection threshold
TrendThreshold float64 `json:"tt"`
// Stability threshold
StabilityThreshold float64 `json:"st"`
// Switch hysteresis count
Hysteresis int `json:"hy"`
// Total observations
Observations int `json:"n"`
// Last filtered value
LastFiltered float64 `json:"lf"`
// Trend score (running velocity estimate)
TrendScore float64 `json:"ts"`
}
KalmanAdaptiveState represents the serializable state of an adaptive filter.
type KalmanProcessResult ¶
KalmanProcessResult is the result of kalman.process()
type KalmanState ¶
type KalmanState struct {
// Current state estimate
X float64 `json:"x"`
// Previous state (for velocity calculation)
LastX float64 `json:"lx"`
// Estimate covariance (uncertainty)
P float64 `json:"p"`
// Kalman gain
K float64 `json:"k"`
// Setpoint error factor
E float64 `json:"e"`
// Process noise (scaled)
Q float64 `json:"q"`
// Measurement noise
R float64 `json:"r"`
// Variance scale for adaptive R
VarianceScale float64 `json:"vs"`
// Number of observations processed
Observations int `json:"n"`
}
KalmanState represents the serializable state of a basic Kalman filter. This is stored as JSON in a node property and passed to kalman.* functions.
type KalmanVelocityProcessResult ¶
type KalmanVelocityProcessResult struct {
Value float64 `json:"value"`
Velocity float64 `json:"velocity"`
State string `json:"state"`
}
KalmanVelocityProcessResult is the result of kalman.velocity.process()
type KalmanVelocityState ¶
type KalmanVelocityState struct {
// Position estimate
Pos float64 `json:"pos"`
// Velocity estimate
Vel float64 `json:"vel"`
// 2x2 Covariance matrix [p00, p01, p10, p11]
P [4]float64 `json:"p"`
// Position process noise
QPos float64 `json:"qp"`
// Velocity process noise
QVel float64 `json:"qv"`
// Measurement noise
R float64 `json:"r"`
// Time step
Dt float64 `json:"dt"`
// Number of observations
Observations int `json:"n"`
}
KalmanVelocityState represents the serializable state of a 2-state Kalman filter. Tracks both position and velocity for trend prediction.
type MatchClause ¶
type MatchClause struct {
Pattern Pattern
Optional bool
Where *WhereClause
}
MatchClause represents a MATCH clause.
type MemoryEdge ¶
type MemoryEdge struct {
ID string `cypher:"id" json:"id"`
Source string `cypher:"source" json:"source"`
Target string `cypher:"target" json:"target"`
Type string `cypher:"type" json:"type"`
Weight float64 `cypher:"weight" json:"weight"`
Decay float64 `cypher:"decay" json:"decay"`
CreatedAt time.Time `cypher:"created_at" json:"created_at"`
LastUpdated time.Time `cypher:"last_updated" json:"last_updated"`
}
MemoryEdge represents an edge between memory nodes with decay.
type MemoryNode ¶
type MemoryNode struct {
ID string `cypher:"id" json:"id"`
Title string `cypher:"title" json:"title"`
Content string `cypher:"content" json:"content"`
Type string `cypher:"type" json:"type"`
Tags []string `cypher:"tags" json:"tags"`
Weight float64 `cypher:"weight" json:"weight"`
Decay float64 `cypher:"decay" json:"decay"`
CreatedAt time.Time `cypher:"created_at" json:"created_at"`
UpdatedAt time.Time `cypher:"updated_at" json:"updated_at"`
LastAccess time.Time `cypher:"last_access" json:"last_access"`
AccessCount int64 `cypher:"access_count" json:"access_count"`
}
MemoryNode represents a memory/knowledge node with decay support.
type NodeCount ¶
type NodeCount struct {
Label string `cypher:"label" json:"label"`
Count int64 `cypher:"count" json:"count"`
}
NodeCount represents a count aggregation result.
type NodeMutatedCallback ¶
type NodeMutatedCallback func(nodeID string)
StorageExecutor executes Cypher queries against a storage backend.
The StorageExecutor provides the main interface for executing Cypher queries in NornicDB. It handles query parsing, validation, parameter substitution, and execution against the underlying storage engine.
Key features:
- Neo4j-compatible Cypher syntax support
- Parameter substitution with $param syntax
- Query validation and error reporting
- Optimized execution planning
- Thread-safe concurrent execution
Example:
storage := storage.NewMemoryEngine()
executor := cypher.NewStorageExecutor(storage)
// Simple node creation
result, _ := executor.Execute(ctx, "CREATE (n:Person {name: 'Alice'})", nil)
// Parameterized query
params := map[string]interface{}{"name": "Bob", "age": 30}
result, _ = executor.Execute(ctx,
"CREATE (n:Person {name: $name, age: $age})", params)
// Complex pattern matching
result, _ = executor.Execute(ctx, `
MATCH (a:Person)-[:KNOWS]->(b:Person)
WHERE a.age > 25
RETURN a.name, b.name
`, nil)
Thread Safety:
The executor is thread-safe and can handle concurrent queries.
NodeMutatedCallback is called when a node is created or mutated via Cypher (CREATE, MERGE, SET, REMOVE, or procedures that update nodes). This allows external systems (like the embed queue) to be notified so embeddings can be (re)generated.
type NodePattern ¶
NodePattern represents a node in a pattern.
type OrderItem ¶
type OrderItem struct {
Expression Expression
Descending bool
}
OrderItem represents an ORDER BY item.
type ParallelConfig ¶
type ParallelConfig struct {
// Enabled enables/disables parallel execution globally
Enabled bool
// MaxWorkers is the maximum number of goroutines to use
// Default: runtime.NumCPU()
MaxWorkers int
// MinBatchSize is the minimum number of items before parallelizing
// Below this threshold, sequential execution is used (overhead not worth it)
// Default: 1000
MinBatchSize int
}
ParallelConfig controls parallel execution behavior.
func DefaultParallelConfig ¶
func DefaultParallelConfig() ParallelConfig
DefaultParallelConfig returns the default parallel execution configuration.
func GetParallelConfig ¶
func GetParallelConfig() ParallelConfig
GetParallelConfig returns the current parallel execution configuration.
type Parameter ¶
type Parameter struct {
Name string
}
Parameter represents a query parameter ($name).
type Parser ¶
type Parser struct{}
Parser parses Cypher queries into AST.
The execution path's workhorse is a scannerless recursive descent parser over the raw query text (no lexer, no parse tree): clause boundaries and operator precedence are found by scanning for top-level keywords and operators while skipping quoted text, comments and brackets, and each construct recurses into its split fragments (keyword_scan.go, operators.go, row_expression.go).
type PathContext ¶
type PathContext struct {
// contains filtered or unexported fields
}
PathContext holds node/relationship mappings for expression evaluation
type PathResult ¶
type PathResult struct {
Nodes []*storage.Node
Relationships []*storage.Edge
Length int
SegmentLengths []int
}
PathResult represents a path through the graph
type Pattern ¶
type Pattern struct {
Nodes []NodePattern
Edges []EdgePattern
}
Pattern represents a graph pattern.
type PatternInfo ¶
type PatternInfo struct {
Pattern QueryPattern
RelType string // Relationship type for the pattern (e.g., "FOLLOWS")
StartVar string // Start node variable (e.g., "a")
EndVar string // End node variable (e.g., "b")
RelVar string // Relationship variable (e.g., "r")
AggFunctions []string // Aggregation functions used (e.g., ["count", "avg"])
AggProperty string // Property being aggregated (e.g., "rating")
Limit int // LIMIT value if present
GroupByVars []string // Variables in implicit GROUP BY
}
PatternInfo contains details about a detected pattern
func DetectQueryPattern ¶
func DetectQueryPattern(ctx context.Context, query string) (info PatternInfo, err error)
DetectQueryPattern analyzes a Cypher query and returns pattern info
func (PatternInfo) IsOptimizable ¶
func (p PatternInfo) IsOptimizable() bool
IsOptimizable returns true if the pattern can be optimized
func (PatternInfo) NeedsRelationshipTypeScan ¶
func (p PatternInfo) NeedsRelationshipTypeScan() bool
NeedsRelationshipTypeScan returns true if the optimization needs all edges of a type
type PermissionChecker ¶ added in v1.2.2
PermissionChecker answers whether the caller holds an entitlement.
type PermissionDeniedError ¶ added in v1.2.2
type PermissionDeniedError struct {
// Permission identifies the missing grant, or "read-only" when the
// selected constituent forbids mutation regardless of caller grants.
Permission string
}
PermissionDeniedError identifies the entitlement needed for a query.
func (*PermissionDeniedError) BoltErrorCode ¶
func (e *PermissionDeniedError) BoltErrorCode() string
BoltErrorCode is the Neo4j status of a permission failure, on Bolt and HTTP alike (nornicerrors.Neo4jStatus).
func (*PermissionDeniedError) Error ¶ added in v1.2.2
func (e *PermissionDeniedError) Error() string
func (*PermissionDeniedError) StatusMessage ¶
func (e *PermissionDeniedError) StatusMessage() string
StatusMessage is the message clients see for a permission failure: the missing permission only, whatever statement or procedure it was found in.
type PermissionRequirements ¶ added in v1.2.2
type PermissionRequirements struct {
Read bool
Write bool
Schema bool
Admin bool
// BoostedProcedures name the procedures the query calls when they alone
// make the query need administrator rights: a role holding EXECUTE
// BOOSTED PROCEDURE for every one of them may run the query without
// them.
BoostedProcedures []string
}
PermissionRequirements describes the entitlements required to execute a query. Procedure requirements come from the registered procedure contract, while query requirements preserve the established top-level Cypher classification.
func QueryPermissionRequirements ¶ added in v1.2.2
func QueryPermissionRequirements(ctx context.Context, query string, stage SourceStage) PermissionRequirements
QueryPermissionRequirements returns the permissions required by a query and a registered procedure invoked by that query, when present.
func (PermissionRequirements) AdminGrantedBy ¶
func (r PermissionRequirements) AdminGrantedBy(allowsBoosted func(procedure string) bool) bool
AdminGrantedBy reports whether a role's procedure grants satisfy the query's administrator requirement: it needs admin only for the procedures it calls, and allowsBoosted grants every one of them boosted.
type PlanOperator ¶
type PlanOperator struct {
// Operator type (e.g., "NodeByLabelScan", "Filter", "Expand")
OperatorType string `json:"operatorType"`
// Human-readable description
Description string `json:"description"`
// Operator-specific arguments
Arguments map[string]interface{} `json:"arguments,omitempty"`
// Variables introduced by this operator
Identifiers []string `json:"identifiers,omitempty"`
// Child operators (execution flows bottom-up)
Children []*PlanOperator `json:"children,omitempty"`
// Cost estimation (for EXPLAIN and PROFILE)
EstimatedRows int64 `json:"estimatedRows"`
// Actual statistics (only for PROFILE)
ActualRows int64 `json:"rows,omitempty"`
DBHits int64 `json:"dbHits,omitempty"`
Time time.Duration `json:"time,omitempty"`
// Observed flags distinguish a measured zero from an unavailable counter.
RowsObserved bool `json:"rowsObserved,omitempty"`
DBHitsObserved bool `json:"dbHitsObserved,omitempty"`
}
PlanOperator represents a single operator in the execution plan
type PluginFunctionHandler ¶
PluginFunctionLookup is a callback to look up functions from loaded plugins. Set by pkg/nornicdb during database initialization. Returns the function handler and true if found, nil and false otherwise. PluginFunctionHandler is an admitted callable. Raw Go functions must pass registry.Compile before lookup publication. Author: Codex NOR-184 lane.
type PluginFunctionInfo ¶
PluginFunctionInfo describes a loaded plugin's function for SHOW FUNCTIONS.
type PrincipalAccess ¶
type PrincipalAccess struct {
// GraphAccess resolves a graph name (a database, alias or composite
// constituent) to the database its data is in, and reports whether the
// principal may use it; nil allows every graph.
GraphAccess func(graph string) (database string, allowed bool)
// DatabaseAccess is the principal's read and write on a database; nil
// leaves read and write to Entitlement.
DatabaseAccess func(database string) auth.ResolvedAccess
// Entitlement reports a global entitlement (schema, admin, and read and
// write when DatabaseAccess is nil); nil holds every one.
Entitlement func(permission string) bool
}
PrincipalAccess is the one permission resolver for a principal, which HTTP and Bolt both build from their stores: whether the principal holds a permission on a graph.
func (PrincipalAccess) Allows ¶
func (p PrincipalAccess) Allows(graph, permission string) bool
Allows reports whether the principal holds permission on graph: it may use the graph, read and write come from its access to the database the graph's data is in, and the other permissions from its global entitlements.
type ProcedureColumn ¶
ProcedureColumn defines one YIELD column in canonical metadata. Description and IsDeprecated describe that column in SHOW PROCEDURES.
type ProcedureCypherInput ¶
type ProcedureCypherInput struct {
Argument int
Field string
ParametersArgument int
StoredText string
// MaxArguments bounds an overload interpreting text; zero is unrestricted.
MaxArguments int
}
ProcedureCypherInput declares text interpreted by a handler. Field selects a canonical retrieval request property; otherwise Argument is statement text. ParametersArgument is one-based (zero means the caller's existing bindings). StoredText describes a custom procedure's registered body.
type ProcedureHandler ¶
type ProcedureHandler func(ctx context.Context, exec *StorageExecutor, cypher string, args []interface{}) (*ExecuteResult, error)
ProcedureHandler executes a registered procedure.
type ProcedureMetadataRenderer ¶ added in v1.3.1
type ProcedureMetadataRenderer interface {
Render(context.Context, localization.RenderRequest) (string, language.Tag, error)
}
ProcedureMetadataRenderer renders localized procedure metadata for a request context.
type ProcedureMode ¶
type ProcedureMode string
ProcedureMode represents Neo4j-compatible procedure execution mode.
const ( ProcedureModeRead ProcedureMode = "READ" ProcedureModeWrite ProcedureMode = "WRITE" ProcedureModeSchema ProcedureMode = "SCHEMA" ProcedureModeAdmin ProcedureMode = "ADMIN" ProcedureModeDBMS ProcedureMode = "DBMS" )
type ProcedureNodeImages ¶
type ProcedureNodeImages uint8
ProcedureNodeImages declares which image a procedure call supplies for the node objects in its arguments. It describes what the handler reads; it is not a runtime switch, because the statement that calls the procedure owns how a node image is materialized.
const ( // FullNodeImages is the native full node contract, and the zero value: a // node argument carries its complete image, embedding vector payloads // included. Every registration keeps this image unless it declares // otherwise, so an existing RegisterUser, RegisterBuiltIn or plugin // registration needs no change. FullNodeImages ProcedureNodeImages = iota // MetadataNodeImages declares that the handler reads a node argument's // identity, labels, Cypher properties and embedding metadata, but never the embedding // vector payloads a node object holds outside those properties // (storage.Node.ChunkEmbeddings and storage.Node.NamedEmbeddings). For // example, a procedure that walks the graph from a node it is given // declares the metadata image; one that reads or returns those vectors // keeps FullNodeImages. MetadataNodeImages )
type ProcedureParam ¶
type ProcedureParam struct {
Name string
Type string
Optional bool
Description string
Default string
IsDeprecated bool
}
ProcedureParam defines one procedure argument in canonical metadata. Description and IsDeprecated are exposed by SHOW PROCEDURES. Default is its display representation, not an argument value; an empty Default omits the metadata entry. Optional does not change the procedure's declared arity.
For example, an optional map argument can use:
ProcedureParam{Name: "options", Type: "MAP", Optional: true,
Default: "DefaultParameterValue{value={}, type=MAP}"}
type ProcedureRegistry ¶
type ProcedureRegistry struct {
// contains filtered or unexported fields
}
ProcedureRegistry resolves each built-in or user procedure by its exact registered name, including namespace and letter case, as Neo4j does. For example, "tenant.Report" and "tenant.report" are distinct registrations; CALL tenant.REPORT() cannot select either.
func NewProcedureRegistry ¶
func NewProcedureRegistry() *ProcedureRegistry
func (*ProcedureRegistry) ClearUser ¶
func (r *ProcedureRegistry) ClearUser()
func (*ProcedureRegistry) Get ¶
func (r *ProcedureRegistry) Get(name string) (registeredProcedure, bool)
func (*ProcedureRegistry) List ¶
func (r *ProcedureRegistry) List() []ProcedureSpec
func (*ProcedureRegistry) ListBuiltIns ¶
func (r *ProcedureRegistry) ListBuiltIns() []ProcedureSpec
func (*ProcedureRegistry) RegisterBuiltIn ¶
func (r *ProcedureRegistry) RegisterBuiltIn(spec ProcedureSpec, handler ProcedureHandler) error
RegisterBuiltIn registers a built-in procedure through the public API. The handler's read-observation policy is opaque: the public entry point carries no source review, so it never opts a handler in, not even for the name of a reviewed built-in it replaces. A reviewed package-private registration opts in through registerBuiltIn.
func (*ProcedureRegistry) RegisterUser ¶
func (r *ProcedureRegistry) RegisterUser(spec ProcedureSpec, handler ProcedureHandler) error
RegisterUser registers a user-defined or plugin procedure through the public API. The handler's read-observation policy is opaque, whatever name the registration takes, including the name of a reviewed built-in.
type ProcedureResultCache ¶
type ProcedureResultCache struct {
Deterministic bool
RetrievalRequest bool
Continuation bool
CypherInputs []ProcedureCypherInput
}
ProcedureResultCache describes execution, not an independent cache decision. The query determinism owner combines these declarations with the caller's actual arguments and classifies every executable text with the same rules. Unknown handlers (including plugins) remain non-cacheable by default.
type ProcedureSpec ¶
type ProcedureSpec struct {
Name string
Signature string
Description string
DescriptionMessage localization.Message
Mode ProcedureMode
WorksOnSystem bool
Admin bool
IsDeprecated bool
DeprecatedBy string
Params []ProcedureParam
Returns []ProcedureColumn
// ResultSchemas declares a closed set of headers for a value-dependent procedure.
// Returns still describes every legal YIELD field; no runtime observation extends it.
ResultSchemas func() [][]string `json:"-"`
MinArgs int
MaxArgs int
// ResultCache declares execution dependencies; an undeclared handler is
// opaque to the determinism owner and cannot supply cached results.
ResultCache ProcedureResultCache
// ExecutesStatements requests a native statement rollback owner. Its
// handler resolves arguments normally; actual inner writes promote a
// Fabric participant at the shared execution boundary.
ExecutesStatements bool
// ExecutesReadOnlyStatements declares nested executable text whose owner
// enforces read-only admission. It preserves full argument images without
// requesting a write rollback owner for an otherwise fixed READ procedure.
ExecutesReadOnlyStatements bool
// OwnsTransactions owns autocommit batch boundaries. Native explicit
// transactions retain shipped folding; Fabric-managed scopes reject it
// before invocation because their rollback cannot undo committed batches.
OwnsTransactions bool
// NodeImages declares the image a call supplies for the node objects in
// its arguments. The zero value, FullNodeImages, is the native full
// contract, so no existing registration changes. Declare
// MetadataNodeImages only for a handler that reads a node argument's
// identity, labels, Cypher properties and embedding metadata, but never the embedding vector
// payloads a node object holds outside those properties
// (storage.Node.ChunkEmbeddings and storage.Node.NamedEmbeddings).
NodeImages ProcedureNodeImages
}
ProcedureSpec is the canonical contract for built-in and user-defined procedures. Admin, IsDeprecated and DeprecatedBy describe the procedure in SHOW PROCEDURES; they do not replace handler authorization or change execution behavior. An empty DeprecatedBy is exposed as null. For example, a deprecated procedure can set IsDeprecated: true and DeprecatedBy: "custom.replacement".
func ListRegisteredProcedures ¶
func ListRegisteredProcedures() []ProcedureSpec
ListRegisteredProcedures returns built-in and user-registered procedures.
func RegisteredProceduresForCalls ¶
func RegisteredProceduresForCalls(ctx context.Context, query string, stage SourceStage) []ProcedureSpec
RegisteredProceduresForCalls returns the registered procedures named by every grammar-owned CALL clause, including nested subqueries. Strings and comments do not add calls; quoted name parts use the same registry identity as execution. For example, RegisteredProceduresForCalls(ctx, "CALL db.labels()", RawSource) resolves the declaration listed by SHOW PROCEDURES without exposing its handler.
type ProjectedRelationship ¶
type ProjectedRelationship struct {
ID string // the stored relationship's id
Source string
Target string
Type string // the projected type's name
Properties map[string]float64 // the projected properties that have a value
}
ProjectedRelationship is one relationship of a projection, from Source to Target as projected.
type PropertyAccess ¶
PropertyAccess represents property access (e.g., n.name).
type QueryAnalyzer ¶
type QueryAnalyzer struct {
// contains filtered or unexported fields
}
QueryAnalyzer extracts query metadata with caching.
func NewQueryAnalyzer ¶
func NewQueryAnalyzer(maxSize int) *QueryAnalyzer
NewQueryAnalyzer creates a new query analyzer with cache.
func (*QueryAnalyzer) Analyze ¶
Analyze extracts query information, using cache when available. Every returned analysis carries the statement-effect owner's answer; a procedure registry change refreshes the cached answer instead of re-reading it on every hit, and a cancellation while computing one is returned.
func (*QueryAnalyzer) CacheSize ¶
func (a *QueryAnalyzer) CacheSize() int
CacheSize returns current cache size.
func (*QueryAnalyzer) ClearCache ¶
func (a *QueryAnalyzer) ClearCache()
ClearCache clears the analysis cache.
type QueryCache ¶
type QueryCache struct {
// contains filtered or unexported fields
}
QueryCache provides LRU (Least Recently Used) caching for Cypher query results with automatic TTL (Time To Live) expiration.
The cache improves performance by storing results of expensive read-only queries and returning them instantly on subsequent identical requests. It automatically handles cache invalidation when write operations occur.
Features:
- LRU eviction when cache is full (keeps most recently used)
- TTL-based expiration for time-sensitive data
- Thread-safe concurrent access
- Automatic invalidation on writes (CREATE, DELETE, SET, etc.)
- Hit/miss statistics for monitoring
Example 1 - Basic Caching:
cache := NewQueryCache(1000) // Store up to 1000 query results
// First query - cache miss, executes and stores
result1, found := cache.Get("MATCH (n) RETURN count(n)", nil)
// found == false, executes query
cache.Put("MATCH (n) RETURN count(n)", nil, result1, 5*time.Minute)
// Second query - cache hit, instant return
result2, found := cache.Get("MATCH (n) RETURN count(n)", nil)
// found == true, returns cached result (10-100x faster!)
Example 2 - With Parameters:
params := map[string]interface{}{"name": "Alice", "minAge": 25}
cypher := "MATCH (n:Person {name: $name}) WHERE n.age >= $minAge RETURN n"
// Parameters are part of cache key
result, found := cache.Get(cypher, params)
if !found {
result = executeQuery(cypher, params)
cache.Put(cypher, params, result, 1*time.Minute)
}
Example 3 - Cache Invalidation:
// Read queries use cache
cache.Get("MATCH (n:User) RETURN n.name", nil)
// Write query invalidates entire cache
executor.Execute(ctx, "CREATE (n:User {name: 'Bob'})", nil)
cache.Invalidate() // All cached results cleared
// Next query will be cache miss
cache.Get("MATCH (n:User) RETURN n.name", nil) // Re-executes
ELI12 (Explain Like I'm 12):
Imagine you're doing math homework and your friend asks "What's 127 × 384?" You grab your calculator and spend 30 seconds calculating: 48,768.
Five minutes later, they ask the SAME question again. Instead of using your calculator again, you just look at your paper where you wrote the answer: 48,768. That's caching! You remembered the answer from before.
But what if you're told "new homework sheet" (a write operation)? You erase your paper because those old answers might not be right anymore. That's cache invalidation.
The QueryCache does this for database queries - it remembers answers to questions it's seen before, so it can reply instantly without doing all the work again!
Performance Impact:
- Cache hits are 10-100x faster than executing queries
- Reduces database load for read-heavy workloads
- Memory usage: ~1KB per cached query result
Thread Safety:
All methods are thread-safe and can be called from multiple goroutines.
func NewQueryCache ¶
func NewQueryCache(maxSize int) *QueryCache
NewQueryCache creates a new query cache with the specified maximum size.
The cache uses LRU (Least Recently Used) eviction - when full, it removes the oldest unused entries to make room for new ones.
Parameters:
- maxSize: Maximum number of query results to cache (recommended: 100-10000)
Returns:
- *QueryCache ready for use
Example:
// Small cache for testing cache := NewQueryCache(100) // Production cache for high-traffic application cache := NewQueryCache(10000) // Memory-constrained environment cache := NewQueryCache(50)
Memory Usage:
- Approximately maxSize * 1KB for typical queries
- 1000 entries ≈ 1MB memory
- 10000 entries ≈ 10MB memory
func (*QueryCache) Get ¶
func (qc *QueryCache) Get(cypher string, params map[string]interface{}) (*ExecuteResult, bool)
Get retrieves a cached query result if it exists and hasn't expired.
The method checks both existence and TTL expiration. If found and valid, it moves the entry to the front of the LRU list (marking it as recently used) and increments the hit counter. Otherwise, it increments the miss counter.
Parameters:
- cypher: The Cypher query string
- params: Query parameters (can be nil). Different params = different cache entry.
Returns:
- *ExecuteResult: The cached result if found and valid
- bool: true if cache hit, false if cache miss
Example 1 - Simple Usage:
result, found := cache.Get("MATCH (n) RETURN n.name", nil)
if found {
// cache hit — return the cached result
return result
}
// cache miss — execute the query and Put() the result into the cache
Example 2 - With Parameters:
params := map[string]interface{}{"id": "user-123"}
result, found := cache.Get("MATCH (n:User {id: $id}) RETURN n", params)
Example 3 - Pattern for Query Execution:
func (e *Executor) ExecuteWithCache(cypher string, params map[string]interface{}) (*ExecuteResult, error) {
// Try cache first
if result, found := e.cache.Get(cypher, params); found {
return result, nil
}
// Cache miss - execute query
result, err := e.executeQuery(cypher, params)
if err != nil {
return nil, err
}
// Store in cache for next time
e.cache.Put(cypher, params, result, 5*time.Minute)
return result, nil
}
Thread Safety:
Safe to call concurrently from multiple goroutines.
func (*QueryCache) Invalidate ¶
func (qc *QueryCache) Invalidate()
Invalidate clears all cached query results.
This method is called after write operations (CREATE, DELETE, SET, REMOVE, MERGE) to ensure cached results don't become stale. It removes all entries from the cache.
Future Enhancement: Smart invalidation that only removes entries affected by specific labels or patterns, rather than clearing the entire cache.
Example 1 - After Write Operations:
// Execute write query
_, err := executor.Execute(ctx, "CREATE (n:User {name: 'Bob'})", nil)
if err == nil {
cache.Invalidate() // Clear cache so old counts/results are refreshed
}
Example 2 - Manual Cache Reset:
// Clear cache after bulk import importUsers(dataFile) cache.Invalidate() // Force all queries to re-execute with new data
Example 3 - Integration Pattern:
func (e *Executor) Execute(ctx context.Context, cypher string) (*ExecuteResult, error) {
// Check if query modifies data
if isWriteQuery(cypher) {
defer e.cache.Invalidate() // Clear cache after write
}
// Try cache for read queries
if isReadQuery(cypher) {
if result, found := e.cache.Get(cypher, nil); found {
return result, nil
}
}
return e.executeQuery(ctx, cypher)
}
ELI12:
Imagine you have a notebook with answers to questions about your toy collection. You write "I have 10 cars" in the notebook. Later, you get 3 new cars as gifts. Now your notebook is WRONG - it still says 10! So you erase the ENTIRE notebook and start fresh. Next time someone asks, you'll count again and get the right answer: 13 cars.
That's what Invalidate does - it erases all the old answers because something changed, and the old answers might be wrong now.
Thread Safety:
Safe to call concurrently from multiple goroutines.
func (*QueryCache) Put ¶
func (qc *QueryCache) Put(cypher string, params map[string]interface{}, result *ExecuteResult, ttl time.Duration)
Put stores a query result in the cache with the specified TTL (Time To Live).
If the cache is at capacity, the least recently used entry is evicted first (LRU eviction policy). The new entry is added to the front of the LRU list.
Parameters:
- cypher: The Cypher query string
- params: Query parameters (can be nil)
- result: The query result to cache
- ttl: How long the result stays valid (e.g., 5*time.Minute)
Example 1 - Basic Caching:
result, err := executor.Execute(ctx, "MATCH (n:User) RETURN count(n)", nil)
if err == nil {
cache.Put("MATCH (n:User) RETURN count(n)", nil, result, 5*time.Minute)
}
Example 2 - Different TTLs for Different Queries:
// Fast-changing data - short TTL
cache.Put("MATCH (n:ActiveSession) RETURN n", nil, result, 30*time.Second)
// Stable data - longer TTL
cache.Put("MATCH (n:Country) RETURN n.name", nil, result, 1*time.Hour)
// Very stable reference data
cache.Put("MATCH (n:Constant) RETURN n", nil, result, 24*time.Hour)
Example 3 - Pattern After Query Execution:
result, err := executeQuery(cypher, params)
if err != nil {
return nil, err
}
// Cache successful results
if isReadOnlyQuery(cypher) {
cache.Put(cypher, params, result, 5*time.Minute)
}
return result, nil
ELI12:
When you learn a new fact, you write it in your notebook with a date. Later, if someone asks you that fact, you check your notebook first instead of looking it up again. The TTL is like saying "this fact is only good for 1 hour" - after that, you need to check the source again.
Thread Safety:
Safe to call concurrently from multiple goroutines.
func (*QueryCache) Stats ¶
func (qc *QueryCache) Stats() (hits, misses int64, size int)
Stats returns cache performance statistics for monitoring.
Returns:
- hits: Number of successful cache retrievals
- misses: Number of cache misses (not found or expired)
- size: Current number of cached entries
Example 1 - Monitoring Cache Performance:
hits, misses, size := cache.Stats() hitRate := float64(hits) / float64(hits+misses) * 100 // emit hit-rate metric e.g. "Cache hit rate: 87.50% (450/1000 entries)"
Example 2 - Prometheus Metrics:
func collectMetrics() {
hits, misses, size := cache.Stats()
prometheus.CacheHits.Set(float64(hits))
prometheus.CacheMisses.Set(float64(misses))
prometheus.CacheSize.Set(float64(size))
}
Example 3 - Auto-Tuning Cache Size:
hits, misses, size := cache.Stats()
hitRate := float64(hits) / float64(hits+misses)
if hitRate < 0.5 && size == maxSize {
// Low hit rate and cache is full — emit a structured warning so
// operators can react (e.g. via the package logger).
}
ELI12:
Imagine you're playing a video game and trying to remember enemy patterns. - Hits: Times you remembered correctly and didn't get hit - Misses: Times you forgot and had to learn again - Size: How many patterns you have memorized right now
If your hit rate is 80%, that means 8 out of 10 times you remembered!
Thread Safety:
Safe to call concurrently from multiple goroutines.
type QueryCachePolicy ¶
QueryCachePolicy configures an executor's database-scoped result cache. Zero MaxEntries disables caching; non-positive TTL uses the process default. For example, NewStorageExecutor(store, QueryCachePolicy{MaxEntries: 100, TTL: time.Minute}).
type QueryEmbedder ¶
type QueryEmbedder interface {
Embed(ctx context.Context, text string) ([]float32, error)
ChunkText(text string, maxTokens, overlap int) ([]string, error)
}
QueryEmbedder generates embeddings for search queries. This is a minimal interface to avoid import cycles with embed package.
type QueryEmbedderBinding ¶
type QueryEmbedderBinding struct {
// contains filtered or unexported fields
}
QueryEmbedderBinding publishes one query provider to every protocol and scope. The zero value has no provider. A load takes one atomic snapshot; publication replaces both the provider's embedding cache and its result-cache generation. It retains no registry of services, executors, caches, or previous providers.
func (*QueryEmbedderBinding) BeginUse ¶
BeginUse admits one provider-using operation and returns its cancellation context and release function. A host-bound binding admits through its host; a standalone binding enrolls the use in its own owner, which Shutdown joins. Callers must release before returning, including on errors.
func (*QueryEmbedderBinding) Load ¶
func (b *QueryEmbedderBinding) Load() QueryEmbedder
Load returns the current provider, or nil while it is unavailable.
func (*QueryEmbedderBinding) SetLifetime ¶
func (b *QueryEmbedderBinding) SetLifetime(begin func(context.Context) (context.Context, func(), error))
SetLifetime binds provider users to their database owner. Configure it during construction, before exposing the binding or sharing it with scoped executors.
func (*QueryEmbedderBinding) Shutdown ¶
func (b *QueryEmbedderBinding) Shutdown(ctx context.Context) error
Shutdown stops a standalone binding: it refuses new provider use and joins every admitted one, so its caller may then dispose the provider it stored. A host-bound binding's users are joined by the host's own stop.
func (*QueryEmbedderBinding) Store ¶
func (b *QueryEmbedderBinding) Store(embedder QueryEmbedder)
Store publishes a provider, including nil to make it unavailable. Old queries may finish using their captured snapshot, but their cached results cannot be served to a query that captured a different publication.
type QueryInfo ¶
type QueryInfo struct {
// Query type flags - set during analysis
HasMatch bool
HasOptionalMatch bool
HasCreate bool
HasMerge bool
HasDelete bool
HasDetachDelete bool
HasSet bool
HasRemove bool
HasReturn bool
HasWith bool
HasUnwind bool
HasCall bool
HasExplain bool
HasProfile bool
HasShow bool
HasSchema bool
HasUnion bool
HasForeach bool
HasLoadCSV bool
HasShortestPath bool
HasOrderBy bool
HasLimit bool
HasSkip bool
HasAggregation bool // COUNT, SUM, AVG, etc. (cached with conservative TTL)
// First clause type for routing
FirstClause ClauseType
// Derived properties
IsSchemaQuery bool
IsCompoundQuery bool
// Labels mentioned (for cache invalidation)
Labels []string
// Relationship types mentioned
RelationshipTypes []string
// The parsed AST clauses (if full parsing done)
Clauses []Clause
// Original query (normalized)
NormalizedQuery string
// contains filtered or unexported fields
}
QueryInfo contains analyzed metadata extracted during query parsing. This is populated once and cached to avoid repeated string parsing.
func (*QueryInfo) GetAST ¶
GetAST returns the structured AST for the query. The AST is lazily built on first call and cached for subsequent calls. This is useful for LLM features that need structured query representation.
The statement-effect owner is refreshed first so the AST and Writes carry one answer, and a cached analysis keeps the answer it already resolved instead of resolving the effect again. When a registry change turns the statement from a read into a write, GetAST publishes a new AST for the current answer and leaves the AST a caller may still hold untouched. An unchanged warm AST is returned as the same pointer without another allocation.
func (*QueryInfo) ReadOnly ¶
ReadOnly reports a statement that changes nothing and returns rows, so the read-only optimizations (result caching, streaming, vector-free node reads) may serve it.
func (*QueryInfo) Writes ¶
Writes reports the statement-effect owner's answer: the statement changes state through the grammar's updating clauses, a registered WRITE procedure, ordinary schema DDL or a catalog/administration mutation. An analysis whose effect was never read counts as a write, so no optimization treats unknown text as a read.
type QueryPattern ¶
type QueryPattern int
QueryPattern identifies optimizable query structures
const ( // PatternGeneric is the default - use standard execution PatternGeneric QueryPattern = iota // PatternMutualRelationship detects (a)-[:T]->(b)-[:T]->(a) cycles // Optimized via single-pass edge set intersection PatternMutualRelationship // PatternIncomingCountAgg detects MATCH (x)<-[:T]-(y) RETURN x, count(y) // Optimized via single-pass edge counting PatternIncomingCountAgg // PatternOutgoingCountAgg detects MATCH (x)-[:T]->(y) RETURN x, count(y) // Optimized via single-pass edge counting PatternOutgoingCountAgg // PatternEdgePropertyAgg detects avg/sum/count on edge properties // Optimized via single-pass accumulation PatternEdgePropertyAgg // PatternLargeResultSet detects queries returning many rows (LIMIT > 100) // Optimized via batch node lookups and pre-allocation PatternLargeResultSet )
func (QueryPattern) String ¶
func (p QueryPattern) String() string
String returns a human-readable pattern name
type QueryPlanCache ¶
type QueryPlanCache struct {
// contains filtered or unexported fields
}
QueryPlanCache caches parsed query ASTs to skip repeated parsing. Parsing can take 10-20% of query execution time for simple queries.
The cache uses a normalized query string (whitespace collapsed, case normalized) as the key, so "MATCH (n) RETURN n" and "match (n) return n" share the cache.
Example:
planCache := NewQueryPlanCache(500)
// First execution parses and caches
plan, found := planCache.Get("MATCH (n:User) RETURN n")
if !found {
var err error
plan, err = parser.Parse(ctx, "MATCH (n:User) RETURN n")
if err != nil { return err }
planCache.Put("MATCH (n:User) RETURN n", plan)
}
// Second execution uses cached plan (skip parsing!)
plan, found = planCache.Get("MATCH (n:User) RETURN n")
// found == true
func NewQueryPlanCache ¶
func NewQueryPlanCache(maxSize int) *QueryPlanCache
NewQueryPlanCache creates a new query plan cache.
func (*QueryPlanCache) Get ¶
func (pc *QueryPlanCache) Get(cypher string) ([]Clause, QueryType, bool)
Get retrieves a cached query plan.
func (*QueryPlanCache) Put ¶
func (pc *QueryPlanCache) Put(cypher string, clauses []Clause, queryType QueryType)
Put stores a parsed query plan.
func (*QueryPlanCache) SetCypherMetrics ¶ added in v1.1.0
func (pc *QueryPlanCache) SetCypherMetrics(m *observability.CypherMetrics)
SetCypherMetrics installs the Plan 04-03 CypherMetrics bag for planner- specific observation per CONTEXT D-12a. Nil-safe (nil bag → no observation).
func (*QueryPlanCache) Stats ¶
func (pc *QueryPlanCache) Stats() (hits, misses int64, size int)
Stats returns plan cache statistics.
type QueryStats ¶
type QueryStats struct {
NodesCreated int `json:"nodes_created"`
NodesDeleted int `json:"nodes_deleted"`
RelationshipsCreated int `json:"relationships_created"`
RelationshipsDeleted int `json:"relationships_deleted"`
PropertiesSet int `json:"properties_set"`
LabelsAdded int `json:"labels_added"`
LabelsRemoved int `json:"labels_removed"`
// Schema counters: a schema command reports the indexes and constraints
// it created or dropped (countSchemaChanges).
IndexesAdded int `json:"indexes_added"`
IndexesRemoved int `json:"indexes_removed"`
ConstraintsAdded int `json:"constraints_added"`
ConstraintsRemoved int `json:"constraints_removed"`
// contains filtered or unexported fields
}
QueryStats holds query execution statistics.
type RelationshipPattern ¶
type RelationshipPattern struct {
Variable string // r in [r:TYPE]
Types []string // TYPE in [r:TYPE|OTHER]
Direction string // "outgoing" (-[r]->), "incoming" (<-[r]-), "both" (-[r]-)
MinHops int // min in [*min..max]
MaxHops int // max in [*min..max]
VariableLength bool // whether the pattern explicitly uses `*`
Properties map[string]interface{}
}
RelationshipPattern represents a parsed relationship pattern
type RequestIdentity ¶
type RequestIdentity struct {
Connection ClientConnection
// User is nil when no one signed in.
User *AuthenticatedUser
// Users lists the user store; nil without one, and SHOW USERS then
// lists the signed-in user only.
Users func() []UserListing
// Connections snapshots the transport's accepted connections; nil for embedded callers.
Connections func() []ConnectionListing
}
RequestIdentity is what the executor knows about where a statement comes from: the connection (SHOW TRANSACTIONS' connectionId, clientAddress and protocol), the signed-in user (SHOW CURRENT USER, SHOW TRANSACTIONS' username) and the user store SHOW USERS lists. A server builds it once per Bolt session or HTTP request and attaches it with WithRequestIdentity, so a statement carries one context value for all three.
type ResultStream ¶
type ResultStream struct {
// contains filtered or unexported fields
}
ResultStream lets a caller consume the rows of an auto-commit read as the statement produces them, instead of after the whole result is built (#939). The caller puts it in the context it passes to Execute (WithResultStream) and calls Finish when Execute returns. Execute and Next run on different goroutines: the caller either runs Execute on its own goroutine, or starts consuming on another one when the stream starts (NewResultStream's onStart).
A statement the stream applies to buffers its first rows. If it ends within the threshold, nothing changes: Execute returns every row in its result, and Started never closes. Once the statement has produced more rows than the threshold, Started closes: Columns names the result's columns, Next hands out rows, and the statement only produces the rows Next asks for, plus at most one batch ahead (Next). Execute then returns once the statement has finished, with the statement's counters and error and without the streamed rows. An error the statement meets after its first threshold rows (making the next row included) starts the stream too and is the error Execute returns, so a caller reports it where the client reaches it, as Neo4j does.
The statement stops when the context passed to Execute is cancelled; a caller that stops reading cancels it and waits for Done.
Execute uses the stream only for a top-level auto-commit read that ends in a plain RETURN (no ORDER BY, DISTINCT, SKIP, LIMIT or aggregation) over rows the pipeline produces one at a time. Every other statement runs as before and returns its whole result.
func NewResultStream ¶
func NewResultStream(threshold int, onStart ResultStreamStarter) *ResultStream
NewResultStream returns a stream whose statement starts streaming after threshold rows (at least 1). onStart, when set, is told when it does: a caller running the statement on its own goroutine uses it to start consuming the rows on another.
func (*ResultStream) Columns ¶
func (s *ResultStream) Columns() []string
Columns returns the result's columns once Started is closed.
func (*ResultStream) Finish ¶
func (s *ResultStream) Finish()
Finish tells the stream that Execute returned. The caller that runs Execute calls it exactly once, after Execute returns.
func (*ResultStream) Next ¶
func (s *ResultStream) Next(n int) ([][]interface{}, bool)
Next returns up to n rows (every remaining row when n <= 0) once Started is closed, producing them as needed, and whether the result is exhausted: the statement finished and every row was returned. Once it reports exhaustion, the caller reads Execute's return values. Next is not safe for concurrent use.
The first Next that needs the statement to produce rows sets the batch size to its n. The statement then makes one batch ahead of the rows asked for, so producing a batch overlaps sending the previous one; rows a batch holds beyond n are kept for the next Next.
func (*ResultStream) Started ¶
func (s *ResultStream) Started() <-chan struct{}
Started is closed once the statement streams: Columns and Next apply.
type ResultStreamStarter ¶
type ResultStreamStarter interface {
// ResultStreamStarted is called on the statement's goroutine when it
// starts streaming, after Started is closed.
ResultStreamStarted()
}
ResultStreamStarter is told when a statement starts streaming.
type ReturnClause ¶
type ReturnClause struct {
Distinct bool
Items []ReturnItem
OrderBy []OrderItem
Skip *int
Limit *int
}
ReturnClause represents a RETURN clause.
type ReturnItem ¶
type ReturnItem struct {
Expression Expression
Alias string
}
ReturnItem represents an item in a RETURN clause.
type SearchResult ¶
type SearchResult struct {
ID string `cypher:"id" json:"id"`
Score float64 `cypher:"score" json:"score"`
Title string `cypher:"title" json:"title"`
Content string `cypher:"content" json:"content"`
Similarity float64 `cypher:"similarity" json:"similarity"`
}
SearchResult represents a search result with score.
type SearchServiceResolver ¶
SearchServiceResolver returns a database's current search service, or nil when it has none.
type SemanticError ¶
type SemanticError struct {
Code string
Detail string
Message string
// contains filtered or unexported fields
}
SemanticError describes a Cypher validation failure that must retain its Neo4j-compatible Bolt classification and conformance detail.
func (*SemanticError) BoltErrorCode ¶
func (e *SemanticError) BoltErrorCode() string
BoltErrorCode returns the Neo4j-compatible Bolt error code.
func (*SemanticError) BoltErrorDetail ¶
func (e *SemanticError) BoltErrorDetail() string
BoltErrorDetail returns the openCypher conformance error detail.
func (*SemanticError) Error ¶
func (e *SemanticError) Error() string
Error formats the error so non-Bolt callers retain the Neo4j status code.
type SetItem ¶
type SetItem struct {
Variable string
Property string
Value Expression
}
SetItem represents a SET operation.
type SettingsResolver ¶ added in v1.3.1
type SettingsResolver func() SettingsSnapshot
SettingsResolver returns the current database-scoped settings snapshot.
type SettingsSnapshot ¶ added in v1.3.1
SettingsSnapshot contains configured and active values for SHOW SETTINGS.
type ShapeCapture ¶
type ShapeCaptures ¶
type ShapeCaptures struct {
Ordered []ShapeCapture
ByName map[string]any
}
func NewShapeCaptures ¶
func NewShapeCaptures() ShapeCaptures
func (*ShapeCaptures) Add ¶
func (c *ShapeCaptures) Add(name string, value any)
func (ShapeCaptures) Any ¶
func (c ShapeCaptures) Any(name string) any
func (ShapeCaptures) Int ¶
func (c ShapeCaptures) Int(name string) int
func (ShapeCaptures) String ¶
func (c ShapeCaptures) String(name string) string
type ShapeMatch ¶
type ShapeMatch struct {
Kind ShapeKind
Captures ShapeCaptures
Probe ShapeProbe
}
type ShapeProbe ¶
type ShowDecayProfilesCmd ¶ added in v1.1.0
type ShowDecayProfilesCmd struct{}
type ShowPromotionPoliciesCmd ¶ added in v1.1.0
type ShowPromotionPoliciesCmd struct{}
type ShowPromotionProfilesCmd ¶ added in v1.1.0
type ShowPromotionProfilesCmd struct{}
type SmartQueryCache ¶
type SmartQueryCache struct {
// contains filtered or unexported fields
}
SmartQueryCache extends QueryCache with label-aware invalidation. Instead of clearing the entire cache on any write, it tracks which labels each cached query depends on and only invalidates affected entries.
Performance:
- Writes to :User only invalidate queries touching :User
- Queries on :Product remain cached when :User is modified
- Reduces cache misses by 50-80% in multi-label workloads
Example:
cache := NewSmartQueryCache(1000)
// Cache query for User nodes
cache.PutWithLabels("MATCH (n:User) RETURN n", nil, result, 5*time.Minute, []string{"User"})
// This invalidates only User-related queries
cache.InvalidateLabels([]string{"User"})
// Product queries remain cached!
result, found := cache.Get("MATCH (n:Product) RETURN n", nil)
func NewSmartQueryCache ¶
func NewSmartQueryCache(maxSize int) *SmartQueryCache
NewSmartQueryCache creates a cache with label-aware invalidation.
func (*SmartQueryCache) Get ¶
func (sc *SmartQueryCache) Get(cypher string, params map[string]interface{}) (*ExecuteResult, bool)
Get retrieves a cached result (same as QueryCache).
func (*SmartQueryCache) Invalidate ¶
func (sc *SmartQueryCache) Invalidate()
Invalidate clears the entire cache (fallback for complex operations).
func (*SmartQueryCache) InvalidateLabels ¶
func (sc *SmartQueryCache) InvalidateLabels(labels []string)
InvalidateLabels removes only cache entries that depend on the given labels. This is much more efficient than full invalidation for multi-label workloads. Also invalidates queries with NO labels (like "MATCH (n) RETURN count(n)") since they match all nodes and are affected by any label change.
func (*SmartQueryCache) Put ¶
func (sc *SmartQueryCache) Put(cypher string, params map[string]interface{}, result *ExecuteResult, ttl time.Duration)
Put stores a result, auto-extracting labels from the query.
func (*SmartQueryCache) PutWithLabels ¶
func (sc *SmartQueryCache) PutWithLabels(cypher string, params map[string]interface{}, result *ExecuteResult, ttl time.Duration, labels []string)
PutWithLabels stores a result with associated labels for smart invalidation.
func (*SmartQueryCache) SetCacheMetrics ¶ added in v1.1.0
func (sc *SmartQueryCache) SetCacheMetrics(m *observability.CacheMetrics)
SetCacheMetrics installs the Plan 04-03 D-12a cross-cutting cache bag for query-result observation. Nil-safe (nil bag → no observation). Per CONTEXT D-12 the closed `cache` enum binds to "query_result" here.
type SourceStage ¶
type SourceStage = cyphertext.SourceStage
SourceStage distinguishes client source from already projected compiler text. It aliases the canonical source owner; callers must select their ingress.
type StatementCaches ¶
type StatementCaches struct {
// contains filtered or unexported fields
}
StatementCaches owns bounded statement-text caches for one database. Selection generations on entries have a shorter lifetime than this canonical owner.
func DatabaseStatementCaches ¶
func DatabaseStatementCaches(manager *multidb.DatabaseManager, name string) (*StatementCaches, error)
func NewStatementCaches ¶
func NewStatementCaches() *StatementCaches
func (*StatementCaches) Dispose ¶
func (c *StatementCaches) Dispose()
Dispose retires the canonical database owner. Removed aliases and routed targets instead invalidate their selection tokens and dependent entries.
func (*StatementCaches) Disposed ¶
func (c *StatementCaches) Disposed() bool
func (*StatementCaches) InvalidateScopes ¶
func (c *StatementCaches) InvalidateScopes()
InvalidateScopes purges only entries depending on removed catalog selections. Scope retirement precedes this sweep, and writers recheck tokens while locked.
type StorageExecutor ¶
type StorageExecutor struct {
// contains filtered or unexported fields
}
func NewDatabaseScopedExecutor ¶
func NewDatabaseScopedExecutor(options DatabaseScopedExecutorOptions) (*StorageExecutor, error)
NewDatabaseScopedExecutor builds the one database-scoped execution view used by protocol adapters. It binds canonical statement caches before publication.
func NewStorageExecutor ¶
func NewStorageExecutor(store storage.Engine, cachePolicy ...QueryCachePolicy) *StorageExecutor
NewStorageExecutor creates a new Cypher executor with the given storage backend.
The executor is initialized with a parser and connected to the storage engine. An optional QueryCachePolicy overrides its environment-derived cache capacity and lifetime; when several policies are supplied, the last one takes precedence. It's ready to execute Cypher queries immediately after creation.
Parameters:
- store: Storage engine to execute queries against (required)
Returns:
- StorageExecutor ready for query execution
Example:
// Create storage and executor storage := storage.NewMemoryEngine() executor := cypher.NewStorageExecutor(storage) // Executor is ready for queries result, err := executor.Execute(ctx, "MATCH (n) RETURN count(n)", nil)
func (*StorageExecutor) BatchGetNodes ¶
func (e *StorageExecutor) BatchGetNodes(ctx context.Context, ids []storage.NodeID) map[storage.NodeID]*storage.Node
BatchGetNodes retrieves multiple nodes in a single operation Used for large result set optimization
func (*StorageExecutor) CachedResultColumns ¶
func (e *StorageExecutor) CachedResultColumns(ctx context.Context, query string, incoming []string) resultmetadata.Names
CachedResultColumns is a legacy cache-only hint for the Fabric consumers being replaced by planned Facts. It never compiles or guesses a cold header.
func (*StorageExecutor) ClearQueryCaches ¶ added in v1.1.0
func (e *StorageExecutor) ClearQueryCaches()
ClearQueryCaches clears executor-local caches that can retain stale read results.
func (*StorageExecutor) CompositeGraphs ¶
func (e *StorageExecutor) CompositeGraphs() (graphs []string, composite bool)
CompositeGraphs lists the graphs of the composite database this executor runs on, as qualified names (composite.alias, sorted), for graph.names(); composite is false for any other database. The executor is the function contexts' GraphCatalog (cypherfn.Context.Graphs).
func (*StorageExecutor) CypherMetrics ¶ added in v1.1.0
func (e *StorageExecutor) CypherMetrics() *observability.CypherMetrics
CypherMetrics returns the injected metrics bag (or nil if unset). Exposed so cloned executors can re-inject when constructed via newTxScopedExecutor outside the cloneWithStorage pathway.
func (*StorageExecutor) Database ¶ added in v1.1.0
func (e *StorageExecutor) Database() string
Database returns the configured database label value used for tenant-tagged Cypher metric observations (D-08).
func (*StorageExecutor) EntityElementIDDatabase ¶
func (e *StorageExecutor) EntityElementIDDatabase(native, selected string) string
EntityElementIDDatabase preserves source identity on composite values while retaining an ordinary statement's explicit execution-database presentation.
func (*StorageExecutor) Execute ¶
func (e *StorageExecutor) Execute(ctx context.Context, cypher string, params map[string]interface{}) (result *ExecuteResult, retErr error)
Execute parses and executes a Cypher query with optional parameters.
This is the main entry point for Cypher query execution. The method handles the complete query lifecycle: parsing, validation, parameter substitution, execution planning, and result formatting.
Parameters:
- ctx: Context for cancellation and timeouts
- cypher: Cypher query string
- params: Optional parameters for $param substitution
Returns:
- ExecuteResult with columns and rows
- Error if query parsing or execution fails
Example:
// Simple query without parameters
result, err := executor.Execute(ctx, "MATCH (n:Person) RETURN n.name", nil)
if err != nil {
log.Fatal(err)
}
// Parameterized query
params := map[string]interface{}{
"name": "Alice",
"minAge": 25,
}
result, err = executor.Execute(ctx, `
MATCH (n:Person {name: $name})
WHERE n.age >= $minAge
RETURN n.name, n.age
`, params)
// Process results
// emit "Columns: %v" via the configured logger
for _, row := range result.Rows {
// process row (e.g. emit "Row: %v" via the configured logger)
}
Supported Query Types:
Core Clauses:
- MATCH: Pattern matching and traversal
- OPTIONAL MATCH: Left outer joins (returns nulls for no matches)
- CREATE: Node and relationship creation
- MERGE: Upsert operations with ON CREATE SET / ON MATCH SET
- DELETE / DETACH DELETE: Node and relationship deletion
- SET: Property updates
- REMOVE: Property and label removal
Projection & Chaining:
- RETURN: Result projection with expressions, aliases, aggregations
- WITH: Query chaining and intermediate aggregation
- UNWIND: List expansion into rows
Filtering & Ordering:
- WHERE: Filtering conditions (=, <>, <, >, <=, >=, IS NULL, IS NOT NULL, IN, CONTAINS, STARTS WITH, ENDS WITH, AND, OR, NOT)
- ORDER BY: Result sorting (ASC/DESC)
- SKIP / LIMIT: Pagination
Aggregation Functions:
- COUNT, SUM, AVG, MIN, MAX, COLLECT
Procedures & Functions:
- CALL: Procedure invocation (db.labels, db.propertyKeys, db.index.vector.*, etc.)
- CALL {}: Subquery execution with UNION support
Advanced:
- UNION / UNION ALL: Query composition
- FOREACH: Iterative updates
- LOAD CSV: Data import
- EXPLAIN / PROFILE: Query analysis
- SHOW: Schema introspection
Path Functions:
- shortestPath / allShortestPaths
Error Handling:
Returns detailed error messages for syntax errors, type mismatches, and execution failures with Neo4j-compatible error codes.
func (*StorageExecutor) ExecuteOptimized ¶
func (e *StorageExecutor) ExecuteOptimized(ctx context.Context, query string, patternInfo PatternInfo) (*ExecuteResult, bool)
ExecuteOptimized attempts to execute a query using an optimized path. Returns (result, true) if optimization was applied, (nil, false) otherwise.
func (*StorageExecutor) Flush ¶
func (e *StorageExecutor) Flush() error
Flush persists all pending writes to storage. This implements FlushableExecutor for Bolt-level deferred commits. Writes are committed synchronously by their transactions; there is no buffered write cache to flush.
func (*StorageExecutor) FunctionStorage ¶
func (e *StorageExecutor) FunctionStorage(database string) (storage.Engine, error)
func (*StorageExecutor) GetDefaultEmbeddingDimensions ¶
func (e *StorageExecutor) GetDefaultEmbeddingDimensions() int
GetDefaultEmbeddingDimensions returns the configured default embedding dimensions. Returns 1024 as fallback if not configured.
func (*StorageExecutor) GetEmbedder ¶
func (e *StorageExecutor) GetEmbedder() QueryEmbedder
GetEmbedder returns the current query embedder, or nil during startup. Scoped executors should use ShareEmbedderFrom to observe later readiness.
func (*StorageExecutor) GetInferenceManager ¶
func (e *StorageExecutor) GetInferenceManager() InferenceManager
GetInferenceManager returns the configured inference manager.
func (*StorageExecutor) GetLocalizationRenderer ¶ added in v1.3.1
func (e *StorageExecutor) GetLocalizationRenderer() ProcedureMetadataRenderer
GetLocalizationRenderer returns the renderer inherited by scoped executors.
func (*StorageExecutor) GetVectorRegistry ¶
func (e *StorageExecutor) GetVectorRegistry() *vectorspace.IndexRegistry
GetVectorRegistry exposes the current registry (for tests and adapters).
func (*StorageExecutor) HasActiveTransaction ¶
func (e *StorageExecutor) HasActiveTransaction() bool
HasActiveTransaction reports whether this executor still owns an explicit transaction.
func (*StorageExecutor) HasPendingTransactionWrites ¶ added in v1.2.2
func (e *StorageExecutor) HasPendingTransactionWrites() bool
HasPendingTransactionWrites reports whether the active explicit transaction has staged graph mutations. Unknown transaction implementations return true so cache coherence fails safe.
func (*StorageExecutor) InvalidateCommittedWriteCaches ¶ added in v1.2.2
func (e *StorageExecutor) InvalidateCommittedWriteCaches()
InvalidateCommittedWriteCaches evicts cached graph state after a write was committed by another executor sharing the same storage engine. Transaction- scoped Bolt executors use this to keep the long-lived read executor coherent without discarding its immutable analysis and plan caches.
func (*StorageExecutor) InvalidateEntityCaches ¶ added in v1.1.0
func (e *StorageExecutor) InvalidateEntityCaches(entityID string, tokens []string)
InvalidateEntityCaches evicts targeted cache entries affected by a specific entity state change.
func (*StorageExecutor) LastHotPathTrace ¶
func (e *StorageExecutor) LastHotPathTrace() HotPathTrace
LastHotPathTrace returns a snapshot of the latest per-query hot path trace.
func (*StorageExecutor) Logger ¶ added in v1.1.0
func (e *StorageExecutor) Logger() *slog.Logger
Logger returns the bound *slog.Logger. Exposed so transient executors (e.g., per-transaction sessions cloned from a base) can inherit the configured logger without re-threading from main.
func (*StorageExecutor) ProjectedScopeAfterClause ¶
func (e *StorageExecutor) ProjectedScopeAfterClause(clause string, incoming []string, cypher25 bool) resultmetadata.Names
ProjectedScopeAfterClause owns which variables are visible after a clause. Visit requires a policy for both known names (fresh, sorted) and unknown facts. USE selects a graph without binding a variable. CALL bodies contribute only their projected outputs; registry outputs include implicit CALL and YIELD *. This read-only API consumes the bound projection program without starting a semantic/type walk or depending on header consumers.
func (*StorageExecutor) QueryCachePolicy ¶ added in v1.3.1
func (e *StorageExecutor) QueryCachePolicy() (maxEntries int, ttl time.Duration)
QueryCachePolicy returns the database-scoped query-result cache capacity and lifetime.
func (*StorageExecutor) QueryEmbedderBinding ¶
func (e *StorageExecutor) QueryEmbedderBinding() *QueryEmbedderBinding
QueryEmbedderBinding exposes this executor's publication owner for protocol adapters. Capture it at construction, rather than copying a loaded provider.
func (*StorageExecutor) ResultColumns ¶
func (e *StorageExecutor) ResultColumns(ctx context.Context, query string, incoming resultmetadata.Scope, cypher25 bool, stage SourceStage) ([]string, error)
ResultColumns is the strict ordered-header view of the execution program. Unknown facts are an error, never an empty successful header.
func (*StorageExecutor) ResultProjection ¶
func (e *StorageExecutor) ResultProjection(ctx context.Context, query string, incoming []string, stage SourceStage) resultmetadata.Projection
ResultProjection is the execution descriptor from the owner program. It never expands a compound wildcard from the statement's entry scope.
func (*StorageExecutor) SetAPOCLocalFileAccessRoot ¶ added in v1.2.0
func (e *StorageExecutor) SetAPOCLocalFileAccessRoot(root string)
SetAPOCLocalFileAccessRoot sets the local import root used for APOC file URLs.
func (*StorageExecutor) SetAPOCRemoteURLAllowlist ¶ added in v1.2.1
func (e *StorageExecutor) SetAPOCRemoteURLAllowlist(hosts []string)
SetAPOCRemoteURLAllowlist restricts APOC HTTP(S) fetches to approved hosts.
func (*StorageExecutor) SetAllowLocalAPOCExportFileAccess ¶ added in v1.2.0
func (e *StorageExecutor) SetAllowLocalAPOCExportFileAccess(enabled bool)
SetAllowLocalAPOCExportFileAccess enables or disables local-file APOC exports.
func (*StorageExecutor) SetAllowLocalAPOCFileAccess ¶ added in v1.2.0
func (e *StorageExecutor) SetAllowLocalAPOCFileAccess(enabled bool)
SetAllowLocalAPOCFileAccess enables or disables local APOC file reads/writes.
func (*StorageExecutor) SetAllowLocalAPOCImportFileAccess ¶ added in v1.2.0
func (e *StorageExecutor) SetAllowLocalAPOCImportFileAccess(enabled bool)
SetAllowLocalAPOCImportFileAccess enables or disables local-file APOC loads/imports.
func (*StorageExecutor) SetAllowRemoteAPOCURLAccess ¶ added in v1.2.1
func (e *StorageExecutor) SetAllowRemoteAPOCURLAccess(enabled bool)
SetAllowRemoteAPOCURLAccess enables or disables APOC HTTP(S) fetches.
func (*StorageExecutor) SetCacheMetrics ¶ added in v1.1.0
func (e *StorageExecutor) SetCacheMetrics(m *observability.CacheMetrics)
SetCacheMetrics installs the Plan 04-01 cross-cutting CacheMetrics bag for D-12a query-result cache observation. Routes the bag into the owned SmartQueryCache so cache_hits_total{cache="query_result"} + cache_misses_total + cache_evictions_total emit on every Get/Put/Evict.
Nil-safe; mirrors SetCypherMetrics shape.
func (*StorageExecutor) SetCypherMetrics ¶ added in v1.1.0
func (e *StorageExecutor) SetCypherMetrics(m *observability.CypherMetrics, database string)
SetCypherMetrics installs the Plan 04-03 CypherMetrics typed bag (MET-08) and the database label value passed on tenant-tagged families when D-08 tenantLabelsEnabled=true. Mirrors the SetLogger / SetSlowQueryThreshold non-breaking pattern (D-01 non-breaking ctor).
Also propagates the bag into the executor's owned planCache so the planner_cache_{hits,misses,size} families fire from QueryPlanCache.Get/Put without callers having to reach into private fields.
Nil-safe: passing m=nil leaves observation as a no-op so tests and alternate constructors that don't wire metrics don't have to. The three observation chokepoints in Execute() guard on m == nil.
Cloned executors inherit metrics + database via cloneWithStorage so the bag flows through per-query / per-tx scoped clones.
func (*StorageExecutor) SetDatabaseManager ¶
func (e *StorageExecutor) SetDatabaseManager(dbManager DatabaseManagerInterface)
SetDatabaseManager sets the database manager for system commands. When set, enables CREATE DATABASE, DROP DATABASE, and SHOW DATABASES commands.
Example:
executor := cypher.NewStorageExecutor(storage) executor.SetDatabaseManager(dbManager) // Now CREATE DATABASE, DROP DATABASE, SHOW DATABASES work
func (*StorageExecutor) SetDefaultEmbeddingDimensions ¶
func (e *StorageExecutor) SetDefaultEmbeddingDimensions(dims int)
SetDefaultEmbeddingDimensions sets the default dimensions for vector indexes. This is used when CREATE VECTOR INDEX doesn't specify dimensions in OPTIONS.
func (*StorageExecutor) SetDeferFlush ¶
func (e *StorageExecutor) SetDeferFlush(enabled bool)
SetDeferFlush enables/disables deferred flush mode. When enabled, writes are not auto-flushed - the Bolt layer calls Flush().
func (*StorageExecutor) SetEmbedder ¶
func (e *StorageExecutor) SetEmbedder(embedder QueryEmbedder)
SetEmbedder sets the query embedder for server-side embedding. When set, db.index.vector.queryNodes can accept string queries which are automatically embedded before search.
Example:
executor := cypher.NewStorageExecutor(storage)
executor.SetEmbedder(embedder)
// Now vector search accepts both:
// CALL db.index.vector.queryNodes('idx', 10, [0.1, 0.2, ...]) // Vector
// CALL db.index.vector.queryNodes('idx', 10, 'search query') // String (auto-embedded)
func (*StorageExecutor) SetInferenceManager ¶
func (e *StorageExecutor) SetInferenceManager(mgr InferenceManager)
SetInferenceManager sets the inference manager used by db.infer.
func (*StorageExecutor) SetLocalizationRenderer ¶ added in v1.3.1
func (e *StorageExecutor) SetLocalizationRenderer(renderer ProcedureMetadataRenderer)
SetLocalizationRenderer sets the immutable renderer used for procedure metadata.
func (*StorageExecutor) SetLogger ¶ added in v1.1.0
func (e *StorageExecutor) SetLogger(logger *slog.Logger)
SetLogger installs the structured slog.Logger used for slow-query and operational records. D-01 non-breaking: NewStorageExecutor's signature is unchanged; callers (cmd/nornicdb/main.go) call SetLogger after construction so the *slog.Logger from observability.NewLogger flows through.
Discard-fallback: passing nil installs a slog.Logger backed by io.Discard so subsequent log emissions cannot panic. The "component" attribute is pre-bound here (not per-call) to honor the RESEARCH "Per-call .With() allocation" anti-pattern.
func (*StorageExecutor) SetNodeMutatedCallback ¶
func (e *StorageExecutor) SetNodeMutatedCallback(cb NodeMutatedCallback)
SetNodeMutatedCallback sets a callback that is invoked when nodes are created or mutated (CREATE, MERGE, SET, REMOVE, or procedures that update nodes). This allows the embed queue to be notified so embeddings can be (re)generated.
Example:
executor := cypher.NewStorageExecutor(storage)
executor.SetNodeMutatedCallback(func(nodeID string) {
embedQueue.Enqueue(nodeID)
})
func (*StorageExecutor) SetSearchService ¶
func (e *StorageExecutor) SetSearchService(svc *search.Service)
SetSearchService sets the unified search service used by Cypher procedures. When set, db.index.vector.queryNodes will delegate to search.Service.
func (*StorageExecutor) SetSearchServiceResolver ¶
func (e *StorageExecutor) SetSearchServiceResolver(database string, resolve SearchServiceResolver)
SetSearchServiceResolver has the executor resolve database's search service on each use instead of keeping one (SetSearchService). Executors it is cloned into for another database (USE, composite constituents) resolve that database's service.
func (*StorageExecutor) SetSettingsResolver ¶ added in v1.3.1
func (e *StorageExecutor) SetSettingsResolver(resolver SettingsResolver)
SetSettingsResolver configures database-scoped values for SHOW SETTINGS.
func (*StorageExecutor) SetSharedExecutor ¶
func (e *StorageExecutor) SetSharedExecutor(shared bool)
SetSharedExecutor marks an executor as the cached, per-database executor that every auto-commit client of its database runs on. A shared executor rejects bare BEGIN/COMMIT/ROLLBACK statements: a statement must never leave the cached executor inside a transaction. Protocol transaction owners (Bolt/HTTP sessions) use their own per-session executors and are never marked shared. See the sharedExecutor field.
func (*StorageExecutor) SetSlowQueryThreshold ¶ added in v1.1.0
func (e *StorageExecutor) SetSlowQueryThreshold(d time.Duration)
SetSlowQueryThreshold configures the D-04c slow-query emission gate. Zero or negative durations disable slow-query logging entirely. Threaded from cfg.Logging.SlowQueryThreshold at the bootstrap site.
func (*StorageExecutor) SetVectorRegistry ¶
func (e *StorageExecutor) SetVectorRegistry(reg *vectorspace.IndexRegistry)
SetVectorRegistry allows wiring a shared index registry (e.g., per database). Defaults to an internal registry when not set.
func (*StorageExecutor) ShareEmbedderFrom ¶
func (e *StorageExecutor) ShareEmbedderFrom(parent *StorageExecutor)
ShareEmbedderFrom binds a scoped executor to its parent's current and future query embedder. Call it during construction, before serving requests.
func (*StorageExecutor) ShareInferenceManagerFrom ¶
func (e *StorageExecutor) ShareInferenceManagerFrom(parent *StorageExecutor)
ShareInferenceManagerFrom connects this scope to its parent's current and future model publication. Configure before exposing the scoped executor.
func (*StorageExecutor) ShareQueryStatisticsFrom ¶
func (e *StorageExecutor) ShareQueryStatisticsFrom(source *StorageExecutor)
ShareQueryStatisticsFrom shares a database's collector with a fresh executor. Configure this before executing queries; transaction state remains independent. For example, a protocol transaction executor can share its cached database executor's collector while keeping a separate storage transaction.
transactionExecutor := NewStorageExecutor(databaseStorage) transactionExecutor.ShareQueryStatisticsFrom(databaseExecutor)
func (*StorageExecutor) ShareStatementCachesFrom ¶
func (e *StorageExecutor) ShareStatementCachesFrom(source *StorageExecutor)
ShareStatementCachesFrom gives a fresh executor the source executor's caches that depend only on the statement text: the syntax verdicts and the upper-cased text. Configure it before executing queries. Protocol transactions (Bolt and HTTP explicit transactions) build a new executor per transaction; without the shared verdicts every statement in such a transaction was validated again from scratch, which under NORNICDB_PARSER=antlr is a full grammar parse of the statement.
transactionExecutor := NewStorageExecutor(databaseStorage) transactionExecutor.ShareStatementCachesFrom(databaseExecutor)
func (*StorageExecutor) SlowQueryThreshold ¶ added in v1.1.0
func (e *StorageExecutor) SlowQueryThreshold() time.Duration
SlowQueryThreshold returns the configured slow-query emission gate. Exposed so cloned executors inherit the threshold from their base.
func (*StorageExecutor) StatementCacheSelectionValid ¶
func (e *StorageExecutor) StatementCacheSelectionValid() bool
StatementCacheSelectionValid lets protocol caches reject removed selections without retiring a surviving canonical owner or mutating a shared executor.
func (*StorageExecutor) StatementCaches ¶
func (e *StorageExecutor) StatementCaches() *StatementCaches
func (*StorageExecutor) StatementColumns ¶
func (e *StorageExecutor) StatementColumns(query string) []string
StatementColumns is the legacy names-only public view. A nil result denotes unresolved or invalid facts and must never be treated as a successful header. Execution and rewriting consumers use ResultColumns or StatementFacts.
func (*StorageExecutor) StatementFacts ¶
func (e *StorageExecutor) StatementFacts(query string, incoming resultmetadata.Scope, cypher25 bool, stage SourceStage) resultmetadata.Facts
StatementFacts exposes the one cached execution projection program. Scope, imports, classification and ordered columns are established together. The owner's answer is complete or a terminal error; it never declines execution.
func (*StorageExecutor) StatementFactsWith ¶
func (e *StorageExecutor) StatementFactsWith(query string, incoming resultmetadata.Scope, cypher25 bool, schema resultmetadata.ParticipantSchema, stage SourceStage) resultmetadata.Facts
StatementFactsWith completes participant-owned signatures during compilation. Signature answers are not cached under query text: a participant may change its procedure registry independently of this executor's registry generation.
func (*StorageExecutor) StatementResultColumns ¶
func (e *StorageExecutor) StatementResultColumns(query string, stage SourceStage) ([]string, error)
StatementResultColumns is the strict public header view with this executor's incoming record scope. Rewriters and transaction adapters preserve its error.
func (*StorageExecutor) StatementResultColumnsContext ¶
func (e *StorageExecutor) StatementResultColumnsContext(ctx context.Context, query string, stage SourceStage) ([]string, error)
StatementResultColumnsContext is the public execution view, using the same participant-signature resolver as Fabric planning before any effects.
func (*StorageExecutor) TransactionEnded ¶
func (e *StorageExecutor) TransactionEnded() bool
TransactionEnded reports whether this executor's explicit transaction can do no more work: none is active, or its end owner ended it (TERMINATE TRANSACTIONS, the server's transaction timeout). Its client's statements see the termination's status until it ends the transaction (one of the other transaction type sees ForbiddenDueToTransactionType first). A transport session holding the handle retires only once this holds (pkg/txsession).
func (*StorageExecutor) TransactionOutlivesSession ¶
func (e *StorageExecutor) TransactionOutlivesSession() bool
TransactionOutlivesSession reports whether this executor's explicit transaction stays open when the transport session holding it expires unrenewed (pkg/txsession). An open client transaction does: its end owner decides its end (NOR-284). A Fabric coordinator's participant doesn't: its coordinator renews the session while its composite transaction lives, so the session's expiry is the lapse of the coordinator's lease, and the session ends the part, as it ends a transaction that has ended.
func (*StorageExecutor) UseDatabaseStatementCaches ¶
func (e *StorageExecutor) UseDatabaseStatementCaches(manager *multidb.DatabaseManager, name string) error
UseDatabaseStatementCaches binds both the canonical owner and selected alias or constituent generation before publishing a fresh protocol executor.
func (*StorageExecutor) UseStatementCaches ¶
func (e *StorageExecutor) UseStatementCaches(caches *StatementCaches)
UseStatementCaches configures a fresh executor before its first execution.
type TemporalViewport ¶
type TemporalViewport struct {
Mode TemporalViewportMode
AsOf time.Time
}
func AsOfTemporalViewport ¶
func AsOfTemporalViewport(asOf time.Time) TemporalViewport
func CurrentTemporalViewport ¶
func CurrentTemporalViewport() TemporalViewport
func TemporalViewportFromContext ¶
func TemporalViewportFromContext(ctx context.Context) (TemporalViewport, bool)
func (TemporalViewport) Enabled ¶
func (v TemporalViewport) Enabled() bool
type TemporalViewportMode ¶
type TemporalViewportMode int
const ( TemporalViewportLive TemporalViewportMode = iota TemporalViewportAsOf )
type TransactionCapableEngine ¶
type TransactionCapableEngine interface {
BeginTransaction(context.Context, storage.BeginRequest) (*storage.BadgerTransaction, error)
}
TransactionCapableEngine is an engine that supports ACID transactions. Used for type assertion to wrap implicit writes in rollback-capable transactions. BeginTransaction uses ctx for admission and snapshot capture. The returned handle has its own lifetime; subsequent operations supply their own contexts.
type TransactionContext ¶
type TransactionContext struct {
// contains filtered or unexported fields
}
TransactionContext holds the active transaction for a Cypher session.
type TransactionDatabases ¶
type TransactionDatabases interface {
ResolveDatabase(name string) (string, error)
IsCompositeDatabase(name string) bool
}
TransactionDatabases resolves database names for TransactionDatabaseError: aliases, and whether a name is a composite database.
type TransactionMemoryLimits ¶
type TransactionMemoryLimits struct {
// TransactionMax is db.memory.transaction.max.
TransactionMax int64
// DatabaseTotalMax is db.memory.transaction.total.max.
DatabaseTotalMax int64
}
TransactionMemoryLimits are byte limits, 0 for unlimited.
type TraversalContext ¶
type TraversalContext struct {
// contains filtered or unexported fields
}
TraversalContext holds state during graph traversal
type TraversalMatch ¶
type TraversalMatch struct {
StartNode nodePatternInfo
EndNode nodePatternInfo
Relationship RelationshipPattern
// For chained patterns like (a)-[:R1]->(b)-[:R2]->(c), we store intermediate segments
IntermediateNodes []nodePatternInfo
Segments []TraversalSegment // All segments in the chain
IsChained bool // True if this is a multi-segment pattern
PathVariable string // Variable name for path assignment (e.g., "path" in "path = (a)-[r]-(b)")
TraversalLimit int // Early traversal cap for LIMIT-only shapes (0 = disabled)
// UnusedPropertyVariables lists pattern node variables whose properties no
// later clause (RETURN, WHERE) reads, so the traversal may load a named
// labelled endpoint by ID + labels alone. nil means "not analysed": every
// variable is treated as property-read (the safe fallback). Computed by
// the planner in executeMatchWithRelationshipsWithPathSeeded.
UnusedPropertyVariables map[string]bool
// IntermediateNode marks a chained segment whose end node is an
// intermediate binding of the chain rather than the pattern's final
// endpoint. Its properties may be read by a later segment (a zero-length
// variable relationship binds the next segment's start to it), so the
// traversal must not load it labels-only or exist-only.
IntermediateNode bool
// contains filtered or unexported fields
}
TraversalMatch represents a parsed traversal pattern
type TraversalSegment ¶
type TraversalSegment struct {
FromNode nodePatternInfo
ToNode nodePatternInfo
Relationship RelationshipPattern
}
TraversalSegment represents one segment in a chained pattern
type TypedExecuteResult ¶
type TypedExecuteResult[T any] struct { Columns []string Rows []T Stats *QueryStats }
TypedExecuteResult wraps query results with typed row access.
func TypedExecute ¶
func TypedExecute[T any](ctx context.Context, exec *StorageExecutor, cypher string, params map[string]interface{}) (*TypedExecuteResult[T], error)
TypedExecute executes a Cypher query and decodes results into typed structs. This is a top-level function (not a method) to avoid polluting the executor interface.
Usage:
result, err := TypedExecute[MemoryNode](ctx, executor, "MATCH (n:Memory) RETURN n", nil)
for _, node := range result.Rows {
// print or process node.Title, node.Content
}
func (*TypedExecuteResult[T]) Count ¶
func (r *TypedExecuteResult[T]) Count() int
Count returns the number of rows.
func (*TypedExecuteResult[T]) First ¶
func (r *TypedExecuteResult[T]) First() (T, bool)
First returns the first row or zero value if empty.
func (*TypedExecuteResult[T]) IsEmpty ¶
func (r *TypedExecuteResult[T]) IsEmpty() bool
IsEmpty returns true if no rows were returned.
type UserListing ¶
UserListing is one SHOW USERS row.
func UserListingsFromAuth ¶
func UserListingsFromAuth(users []*auth.User) []UserListing
UserListingsFromAuth converts the auth store's users for SHOW USERS; a disabled user is suspended.
type VectorCoordinateType ¶
type VectorCoordinateType uint8
VectorCoordinateType is a vector's coordinate type.
const ( VectorInteger64 VectorCoordinateType = iota VectorInteger32 VectorInteger16 VectorInteger8 VectorFloat64 VectorFloat32 )
func (VectorCoordinateType) IsFloat ¶
func (t VectorCoordinateType) IsFloat() bool
IsFloat reports whether the coordinates are floats.
func (VectorCoordinateType) String ¶
func (t VectorCoordinateType) String() string
String is the coordinate type's canonical name (INTEGER64, FLOAT32, …).
type WhereClause ¶
type WhereClause struct {
Expression Expression
}
WhereClause represents a WHERE clause.
type WorkerPool ¶
type WorkerPool struct {
// contains filtered or unexported fields
}
WorkerPool manages a pool of worker goroutines for parallel execution.
func NewWorkerPool ¶
func NewWorkerPool(numWorkers int) *WorkerPool
NewWorkerPool creates a new worker pool with the specified number of workers.
func (*WorkerPool) Stop ¶
func (p *WorkerPool) Stop()
Stop stops the worker pool and waits for all jobs to complete.
func (*WorkerPool) Submit ¶
func (p *WorkerPool) Submit(job func())
Submit submits a job to the worker pool.
func (*WorkerPool) Wait ¶
func (p *WorkerPool) Wait()
Wait waits for all submitted jobs to complete.
Source Files
¶
- admin_error_redaction.go
- administration_transaction.go
- aggregation_projection_scope.go
- algorithm_graph_reader.go
- apoc_algorithms.go
- apoc_collections.go
- apoc_community.go
- apoc_custom.go
- apoc_load_export.go
- apoc_map_functions.go
- apoc_map_null_contract.go
- apoc_native_functions.go
- apoc_native_temporal.go
- apoc_util_hash.go
- arithmetic_values.go
- arrow_validation.go
- ast_builder.go
- authorization.go
- binding_where_compile.go
- bounded_cache.go
- cache.go
- cache_key.go
- cache_policy.go
- call.go
- call_apoc_dynamic.go
- call_apoc_helpers.go
- call_apoc_path.go
- call_apoc_periodic.go
- call_cdc.go
- call_compat.go
- call_fulltext.go
- call_imports.go
- call_index_mgmt.go
- call_query_statistics.go
- call_rag.go
- call_rag_graph.go
- call_rag_relationships.go
- call_schema_visualization.go
- call_scope_reader.go
- call_shared_utils.go
- call_temporal.go
- call_txlog.go
- call_vector.go
- case_closure_balance.go
- case_evaluation.go
- case_expression.go
- catalog_visibility.go
- clauses.go
- coll_functions.go
- comparison.go
- comparison_chain.go
- composite_command_preparation.go
- composite_commands.go
- constant_functions.go
- constituent_display_view.go
- constraint_requirement.go
- count_store.go
- create.go
- create_pipeline_helpers.go
- create_pipeline_template.go
- create_semantic_validation.go
- cypher25_expression_rewrite.go
- cypher25_value_text.go
- database_drop.go
- database_executor_cache.go
- database_options.go
- database_scoped_executor.go
- deleted_entity_projection.go
- duration.go
- dynamic_statement_admission.go
- dynamic_tokens.go
- execution_dependencies.go
- execution_determinism.go
- execution_input_values.go
- executor.go
- executor_entry.go
- executor_fabric.go
- executor_hotpath_trace.go
- executor_internal.go
- executor_match_limit_fastpath.go
- executor_match_vector_cosine_fastpath.go
- executor_mutations.go
- executor_mutations_delete_guard.go
- executor_mutations_where_eval.go
- executor_query_routing.go
- executor_show.go
- executor_spans.go
- executor_subqueries.go
- executor_use.go
- explain.go
- expression_failure.go
- expression_fragment.go
- expression_provenance.go
- expression_stats.go
- expression_subquery_scope.go
- expression_validation.go
- fabric_participants.go
- fabric_value_codec.go
- fastrp.go
- fulltext_documents.go
- fulltext_literal_candidates.go
- fulltext_query.go
- function_aliases.go
- function_arity.go
- function_catalog.go
- function_context.go
- function_match.go
- function_semantic_validation.go
- function_syntax.go
- functions.go
- functions_cypher25.go
- functions_eval_functions.go
- functions_eval_math.go
- functions_eval_operators.go
- functions_eval_props_literals.go
- functions_helpers.go
- functions_neo5.go
- functions_parse.go
- functions_text_locate.go
- gds_functions.go
- gds_numeric_input.go
- gds_projection.go
- gds_projection_identity.go
- gds_property_values.go
- graph_entity_identity.go
- graph_identity_scope.go
- graph_token_reads.go
- group_by_rewrite.go
- helpers.go
- identifier_unquote.go
- index_creation.go
- index_hints.go
- inference_binding.go
- inline_buffer.go
- json_values.go
- kalman_functions.go
- keyword_scan.go
- knowledgepolicy_ddl.go
- knowledgepolicy_execute.go
- knowledgepolicy_functions.go
- knowledgepolicy_procedures.go
- label_chain.go
- label_expression.go
- label_expression_rewrite.go
- linkprediction.go
- list_literal.go
- literal_normalization.go
- live_text_index.go
- localized_errors.go
- log_events.go
- logical_operators.go
- map_literal_validation.go
- map_pattern_context.go
- match.go
- match_aggregation.go
- match_index_order_bounds.go
- match_index_order_groups.go
- match_index_seek.go
- match_multi.go
- match_rows.go
- match_semantic_validation.go
- match_with.go
- match_with_chain.go
- match_with_rel.go
- merge.go
- merge_actions.go
- merge_context.go
- merge_node_writes.go
- merge_relationship_pattern.go
- merge_semantic_validation.go
- minted_create.go
- mutation_times.go
- native_completion_metadata.go
- native_node_vectors.go
- native_statement_coordinator.go
- node_helpers.go
- node_id_results.go
- node_index_candidate_plan.go
- normalization_predicate.go
- numeric_expression_admission.go
- numeric_literal_rewrite.go
- numeric_literal_validation.go
- op_type.go
- operators.go
- optimistic_metadata.go
- optimized_executors.go
- optional_match_traversal.go
- optional_match_traversal_agg.go
- optional_match_traversal_compile.go
- optional_match_traversal_general.go
- parallel.go
- parameters.go
- parser.go
- path_selector.go
- path_selector_match.go
- path_selector_search.go
- path_selector_search_pair.go
- path_selector_search_run.go
- path_selector_search_walk.go
- pattern_bound_node_values.go
- pattern_comprehension_classification.go
- pattern_expression.go
- pattern_parser.go
- pattern_property_reader.go
- pattern_row.go
- percentile_semantics.go
- periodic_transaction_owner.go
- pipeline_aggregate_stream.go
- pipeline_body_clauses.go
- pipeline_call_chain_plan.go
- pipeline_call_operator.go
- pipeline_clause_effects.go
- pipeline_clause_plan.go
- pipeline_dispatch.go
- pipeline_executor.go
- pipeline_imports.go
- pipeline_match_product.go
- pipeline_mutation.go
- pipeline_pattern_template.go
- pipeline_physical_reads.go
- pipeline_procedure_call.go
- pipeline_projection.go
- pipeline_row_stream.go
- pipeline_shared_clauses.go
- pipeline_traversal_match.go
- pipeline_traversal_source.go
- pipeline_value_helpers.go
- pipeline_write_stretch.go
- plan_hash.go
- plugin_typed_invocation.go
- point_values.go
- predicate_helpers.go
- procedure_arguments.go
- procedure_call_parsing.go
- procedure_catalog_identity.go
- procedure_ddl.go
- procedure_privileges.go
- procedure_registry.go
- procedure_registry_builtin.go
- procedure_result_columns.go
- procedure_result_headers.go
- procedure_statement_stats.go
- procedure_validation.go
- profile_access.go
- profile_plan.go
- profile_runtime.go
- projection_item_source.go
- property_access_semantic_validation.go
- property_storage_ownership.go
- quantified_path_pattern.go
- quantifier_fold.go
- quantifier_semantic_validation.go
- query_body_structure.go
- query_embed_chunk.go
- query_embedder.go
- query_info.go
- query_patterns.go
- query_property_visibility.go
- query_stats.go
- query_structure_rewrite.go
- quoted_variables.go
- range_semantics.go
- read_only_query.go
- redaction.go
- reduce_form.go
- regex_match.go
- regex_patterns.go
- rel_existence_pattern.go
- relationship_brackets.go
- relationship_declaration.go
- relationship_edges.go
- relationship_endpoint_projection.go
- relationship_graph_values.go
- relationship_merge_identity.go
- relationship_merge_identity_cache.go
- relationship_mutation_validation.go
- relationship_quantifier_rewrite.go
- relationship_variable_repeat.go
- remote_parameter_values.go
- remote_path_values.go
- remote_statement_policy.go
- remove_clause.go
- repeatable_elements.go
- resolved_statement_mode.go
- result_columns.go
- result_columns_bound.go
- result_columns_command.go
- result_columns_compile.go
- result_columns_execution.go
- result_columns_inputs.go
- result_columns_locals.go
- result_columns_membership.go
- result_columns_normalization.go
- result_columns_observers.go
- result_columns_program.go
- result_columns_projection.go
- result_columns_projection_scope.go
- result_columns_scope.go
- result_columns_syntax.go
- result_restoration.go
- result_stream.go
- result_value_path.go
- retained_predicate.go
- retrieval_request.go
- return_order_semantic_validation.go
- reveal.go
- rewrite_free_cache.go
- row_collection_expression.go
- row_conversion_validation.go
- row_entity_refresh.go
- row_expression.go
- row_extension_expression.go
- row_function_expression.go
- row_graph_function_validation.go
- row_list_loops.go
- row_map_projection.go
- row_math_expression.go
- row_operation_values.go
- row_predicate_plan.go
- row_predicate_program.go
- row_property_chain.go
- row_subscript_validation.go
- row_value_program.go
- runtime_type_errors.go
- runtime_value.go
- schema.go
- schema_constraint_preparation.go
- schema_constraint_requirement.go
- schema_contracts.go
- schema_index_admission.go
- schema_lookup_index.go
- schema_options.go
- schema_property_types.go
- schema_transaction.go
- schema_type_properties.go
- schema_typed_property_index.go
- search_refresh_scope.go
- semantic_errors.go
- semantic_validation.go
- set_helpers.go
- set_merge_strict.go
- set_semantic_validation.go
- set_write_count.go
- shape_matcher.go
- shell_commands.go
- shortest_path.go
- shortest_path_match.go
- show_admin.go
- show_constraint_kinds.go
- show_result_declaration.go
- show_schema_values.go
- size_semantics.go
- skip_limit_semantic_validation.go
- source_normalization.go
- source_stage.go
- stable_sort.go
- standalone_order_rewrite.go
- statement_access.go
- statement_admission.go
- statement_caches.go
- statement_execution_context.go
- statement_execution_contract.go
- statement_framing.go
- statement_node_images.go
- statement_property_views.go
- statement_relationship_reads.go
- statement_text_admission.go
- static_comprehension_types.go
- static_function_argument_types.go
- static_function_literal_arguments.go
- static_operand.go
- static_operator_types.go
- static_type_scope.go
- storage_membership.go
- string_literal.go
- string_patterns.go
- subquery_import_grouping.go
- subquery_value_expression.go
- subscript_evaluation.go
- syntax_unicode_validation.go
- system_procedure_scope.go
- temporal_accessors.go
- temporal_arithmetic.go
- temporal_between.go
- temporal_fields.go
- temporal_format.go
- temporal_history_query.go
- temporal_parse.go
- temporal_pattern.go
- temporal_pattern_parse.go
- temporal_truncation.go
- temporal_values.go
- temporal_viewport.go
- temporal_zone.go
- temporal_zone_names.go
- three_valued_membership.go
- transaction.go
- transaction_admission.go
- transaction_batch.go
- transaction_commit.go
- transaction_count_store_read.go
- transaction_end.go
- transaction_memory.go
- transaction_memory_estimate.go
- transaction_metadata.go
- transaction_script.go
- transaction_storage_wrapper.go
- transaction_storage_wrapper_edge_stream.go
- transaction_storage_wrapper_locks.go
- transaction_storage_wrapper_reads.go
- transaction_storage_wrapper_stored_reads.go
- transaction_wal.go
- transaction_write_state.go
- transactional_batch_expression.go
- transactional_call_batch_size.go
- traversal.go
- traversal_cancel_state.go
- traversal_endpoint_analysis.go
- traversal_execution.go
- traversal_relationship_id_seed.go
- traversal_relationship_property_seed.go
- traversal_scan_plan.go
- traversal_seed_cost.go
- type_conversion.go
- type_predicate.go
- typed_expression_bindings.go
- typed_results.go
- types.go
- unwind_multi_match_create.go
- unwind_relationship_merge_batch.go
- unwind_routing.go
- uuid_v5.go
- uuid_values.go
- validator_strictness.go
- value_bindings.go
- value_contract.go
- value_equality.go
- value_equivalence.go
- value_equivalence_index.go
- value_ordering.go
- value_type_names.go
- vector_call_rewrite.go
- vector_functions.go
- vector_index_publication.go
- vector_query_embed_cache.go
- vector_registry.go
- vector_similarity_functions.go
- vector_values.go
- visibility_procedures.go
- where_by_variable.go
- write_endpoints.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package antlr provides ANTLR-based Cypher parsing for NornicDB.
|
Package antlr provides ANTLR-based Cypher parsing for NornicDB. |
|
internal
|
|
|
text
Package text implements Cypher string operations in Unicode code points.
|
Package text implements Cypher string operations in Unicode code points. |
|
Package resultmetadata carries read-only names across query metadata consumers.
|
Package resultmetadata carries read-only names across query metadata consumers. |
|
Package testutil provides shared test utilities for the NornicDB Cypher package.
|
Package testutil provides shared test utilities for the NornicDB Cypher package. |