sparql

package
v1.10.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 35 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sparql is an in-process RDF quad store with a SPARQL 1.1 query and update engine.

Index

Constants

View Source
const (
	DescribeForwardOneStep   = "ForwardOneStep"
	DescribeSymmetricOneStep = "SymmetricOneStep"
	DescribeCBD              = "CBD"
	DescribeSCBD             = "SCBD"
)

Documented DESCRIBE modes and limits (sparql-query-hints-for-describe.html).

View Source
const (
	NSXSD         = "http://www.w3.org/2001/XMLSchema#"
	NSRDF         = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
	NSRDFS        = "http://www.w3.org/2000/01/rdf-schema#"
	NSOWL         = "http://www.w3.org/2002/07/owl#"
	XSDString     = NSXSD + "string"
	XSDInteger    = NSXSD + "integer"
	XSDDecimal    = NSXSD + "decimal"
	XSDDouble     = NSXSD + "double"
	XSDFloat      = NSXSD + "float"
	XSDBoolean    = NSXSD + "boolean"
	XSDDateTime   = NSXSD + "dateTime"
	RDFType       = NSRDF + "type"
	RDFFirst      = NSRDF + "first"
	RDFRest       = NSRDF + "rest"
	RDFNil        = NSRDF + "nil"
	RDFSubject    = NSRDF + "subject"
	RDFPredicate  = NSRDF + "predicate"
	RDFObject     = NSRDF + "object"
	RDFLangString = NSRDF + "langString"

	// DefaultGraph is the named graph Neptune uses when no graph is given.
	DefaultGraph = "http://aws.amazon.com/neptune/vocab/v01/DefaultNamedGraph"
	// DefaultBase is the base IRI Neptune applies when a request carries none.
	DefaultBase = "http://aws.amazon.com/neptune/default/"
)

Well-known IRIs.

View Source
const BlobThreshold = 1024

BlobThreshold is the term size from which a dictionary entry counts as a blob.

View Source
const HintNS = "http://aws.amazon.com/neptune/vocab/v01/QueryHints#"

HintNS is the Neptune query-hint vocabulary namespace.

Variables

This section is empty.

Functions

func ParseRDFLenient

func ParseRDFLenient(f Format, data []byte, opts ParseOptions, skip bool) ([]Quad, []*ParseError)

ParseRDFLenient parses a document. With skip set, line-based formats resume after a bad line; other formats stop at their first error.

func SerializeQuads

func SerializeQuads(f Format, qs []Quad) ([]byte, error)

SerializeQuads renders quads in the given format. Triple-only formats ignore graph names.

func SerializeTriples

func SerializeTriples(f Format, ts []Triple) ([]byte, error)

SerializeTriples renders triples (no graph names).

func SortedGraphNames

func SortedGraphNames(gs []Term) []string

SortedGraphNames renders graph IRIs for listings.

func WriteResult

func WriteResult(r *Result, f ResultFormat) ([]byte, error)

WriteResult serialises a SELECT or ASK result.

Types

type Binding

type Binding map[string]Term

Binding maps variable names to terms.

type DocFetcher

type DocFetcher func(ctx context.Context, src string) (Document, error)

DocFetcher retrieves a LOAD source together with its Content-Type.

type Document

type Document struct {
	ContentType string
	Data        []byte
}

Document is a fetched LOAD source with the Content-Type the server reported.

type Expr

type Expr any

Expr is a SPARQL expression node.

type Fetcher

type Fetcher func(ctx context.Context, src string) ([]byte, error)

Fetcher retrieves the document behind a LOAD source.

type Format

type Format uint8

Format is an RDF serialization.

const (
	FormatNTriples Format = iota
	FormatNQuads
	FormatTurtle
	FormatTriG
	FormatRDFXML
	FormatJSONLD
	FormatTriX
	FormatRDF4JBinary
)

RDF formats.

func FormatForContentType

func FormatForContentType(ct string) (Format, bool)

FormatForContentType maps the media types Neptune documents for SPARQL UPDATE LOAD to a format.

func FormatForSource

func FormatForSource(src string) Format

FormatForSource guesses an RDF format from a LOAD source name.

type Hints

type Hints struct {
	QueryID      string
	DescribeMode string
	TimeoutMs    int64
	IterLimit    int
	StmtLimit    int
	HasTimeout   bool
	// contains filtered or unexported fields
}

Hints are the Neptune query hints found in a request.

type Kind

type Kind uint8

Kind classifies an RDF term.

const (
	KindNone Kind = iota
	KindIRI
	KindBlank
	KindLiteral
)

Term kinds; KindNone is the zero value and means unbound.

type NumericDataError

type NumericDataError struct{ Msg string }

NumericDataError is an integer literal beyond the 64-bit range Neptune stores.

func (*NumericDataError) Error

func (e *NumericDataError) Error() string

type ParameterError

type ParameterError struct {
	Err error
	Msg string
}

ParameterError is an invalid input value, such as a LOAD source that cannot be read or parsed.

func (*ParameterError) Error

func (e *ParameterError) Error() string

func (*ParameterError) Unwrap

func (e *ParameterError) Unwrap() error

type ParseError

type ParseError struct {
	Msg    string
	Record int
}

ParseError is a syntax error at a record (statement or line) of an RDF document.

func (*ParseError) Error

func (e *ParseError) Error() string

type ParseOptions

type ParseOptions struct {
	// Base resolves relative IRIs (Neptune's loader default is http://aws.amazon.com/neptune/default).
	Base string
	// Graph receives triples that name no graph; DefaultGraph when unset.
	Graph Term
	// KeepBlankLabels keeps blank-node labels verbatim instead of scoping them to this document.
	KeepBlankLabels bool
}

ParseOptions tunes RDF parsing.

type Quad

type Quad struct {
	Triple
	G Term
}

Quad is a triple in a named graph.

func ParseRDF

func ParseRDF(f Format, data []byte, opts ParseOptions) ([]Quad, error)

ParseRDF parses a whole document; on error it returns the quads read before it together with a *ParseError.

type Query

type Query struct {
	Where    *group
	Values   *valuesData
	Prefixes map[string]string

	Base      string
	Proj      []projItem
	Template  []triplePat
	Describe  []node
	From      []Term
	FromNamed []Term
	GroupBy   []projItem
	Having    []Expr
	Order     []orderCond
	Hints     Hints
	Limit     int
	Offset    int
	Form      queryForm
	Distinct  bool
	Star      bool
	// contains filtered or unexported fields
}

Query is a parsed SPARQL query.

func ParseQuery

func ParseQuery(src string) (*Query, error)

ParseQuery parses a SPARQL 1.1 query.

func (*Query) Explain

func (q *Query) Explain() string

Explain renders the query's algebra as an indented tree.

func (*Query) IsAsk

func (q *Query) IsAsk() bool

IsAsk reports whether the query is an ASK.

func (*Query) IsSelect

func (q *Query) IsSelect() bool

IsSelect reports whether the query is a SELECT.

func (*Query) ProjectedVars

func (q *Query) ProjectedVars() []string

ProjectedVars lists the variables a SELECT produces.

func (*Query) SetDataset

func (q *Query) SetDataset(from, named []Term)

SetDataset overrides the query's FROM / FROM NAMED clauses (SPARQL protocol default-graph-uri / named-graph-uri).

func (*Query) SetService

func (q *Query) SetService(f ServiceFunc)

SetService supplies the federation transport for SERVICE clauses.

type Result

type Result struct {
	Vars    []string
	Rows    []Binding
	Triples []Triple
	Kind    ResultKind
	Bool    bool
}

Result is the outcome of a query.

func ParseSelectJSON

func ParseSelectJSON(data []byte) (*Result, error)

ParseSelectJSON decodes a SPARQL 1.1 Query Results JSON document (SELECT or ASK).

type ResultFormat

type ResultFormat uint8

ResultFormat is a query-result serialization.

const (
	ResultJSON ResultFormat = iota
	ResultXML
	ResultCSV
	ResultTSV
	ResultBoolean
	ResultBinary
)

Query-result formats.

type ResultKind

type ResultKind uint8

ResultKind says which payload of a Result is populated.

const (
	ResultSelect ResultKind = iota
	ResultAsk
	ResultGraph
)

Result kinds.

type ServiceFunc

type ServiceFunc func(ctx context.Context, endpoint, query string) (*Result, error)

ServiceFunc runs a SELECT query against the remote SPARQL endpoint of a SERVICE clause.

type Storage

type Storage struct {
	Entries   int
	Terms     int
	TermBytes int
	Blobs     int
	BlobBytes int
}

Storage counts the store's quads and dictionary terms.

type Store

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

Store is a concurrency-safe in-memory RDF quad store.

func NewStore

func NewStore() *Store

NewStore returns an empty store.

func (*Store) Add

func (s *Store) Add(qs []Quad) int

Add inserts quads, returning how many were new.

func (*Store) Apply

func (s *Store) Apply(ctx context.Context, u *Update, opts UpdateOptions) (UpdateResult, error)

Apply runs a parsed update under the write lock; a failing operation rolls the whole request back.

func (*Store) ApplyGraphWrite

func (s *Store) ApplyGraphWrite(g Term, qs []Quad, replace bool)

ApplyGraphWrite implements Graph Store PUT (replace) and POST (merge) into g. Quads that name other graphs are written there too, and every triple also lands in g, as Neptune documents.

func (*Store) Clear

func (s *Store) Clear()

Clear removes every quad.

func (*Store) ClearGraph

func (s *Store) ClearGraph(g Term) int

ClearGraph removes every triple in g and reports how many were removed.

func (*Store) Export

func (s *Store) Export() []byte

Export serialises the store as N-Quads for persistence.

func (*Store) GraphQuads

func (s *Store) GraphQuads(g Term) []Quad

GraphQuads returns a sorted copy of the triples in graph g.

func (*Store) Graphs

func (s *Store) Graphs() []Term

Graphs lists the graph names that currently hold triples, sorted.

func (*Store) Import

func (s *Store) Import(data []byte) error

Import replaces the store's contents with N-Quads data produced by Export.

func (*Store) Len

func (s *Store) Len() int

Len returns the number of quads.

func (*Store) Query

func (s *Store) Query(ctx context.Context, src string) (*Result, error)

Query parses and runs a SPARQL query against the store.

func (*Store) RebuildIndexes

func (s *Store) RebuildIndexes()

RebuildIndexes recreates the subject, predicate, object and graph indexes from the quads.

func (*Store) ReplaceGraph

func (s *Store) ReplaceGraph(g Term, qs []Quad)

ReplaceGraph atomically swaps the contents of g for qs (all forced into g).

func (*Store) Run

func (s *Store) Run(ctx context.Context, q *Query) (*Result, error)

Run evaluates a parsed query under a read lock.

func (*Store) Stats

func (s *Store) Stats() (int, int, int)

Stats summarises the store for the DFE statistics endpoints: distinct predicate sets per subject (signatures), subjects (instances) and distinct predicates.

func (*Store) Storage

func (s *Store) Storage() Storage

Storage reports the quad count and the distinct terms a Neptune dictionary would hold.

func (*Store) Stream

func (s *Store) Stream() *streamlog.Log

Stream returns the store's Neptune Streams commit log.

func (*Store) Summary

func (s *Store) Summary() Summary

Summary lists the store's classes, predicate counts and subject structures for the graph summary endpoint.

func (*Store) Update

func (s *Store) Update(ctx context.Context, src string, opts UpdateOptions) (UpdateResult, error)

Update parses and applies a SPARQL update request atomically.

func (*Store) Wipe

func (s *Store) Wipe()

Wipe empties the store and its stream log, as the fast reset does.

type SubjectStructure

type SubjectStructure struct {
	Predicates []string `json:"predicates"`
	Count      int      `json:"count"`
}

SubjectStructure is a distinct predicate set and how many subjects have it.

type Summary

type Summary struct {
	Classes             []string           `json:"classes"`
	Predicates          []map[string]int   `json:"predicates"`
	SubjectStructures   []SubjectStructure `json:"subjectStructures"`
	NumDistinctSubjects int                `json:"numDistinctSubjects"`
	NumDistinctPreds    int                `json:"numDistinctPredicates"`
	NumQuads            int                `json:"numQuads"`
	NumClasses          int                `json:"numClasses"`
}

Summary is the Neptune graph summary payload for an RDF graph.

type SyntaxError

type SyntaxError struct{ Msg string }

SyntaxError reports malformed query, update or RDF input.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Term

type Term struct {
	Value    string
	Datatype string
	Lang     string
	Kind     Kind
}

Term is an RDF term. A plain literal has an empty Datatype; a language-tagged one has Lang set.

func Blank

func Blank(s string) Term

Blank returns a blank-node term.

func IRI

func IRI(s string) Term

IRI returns an IRI term.

func LangLiteral

func LangLiteral(s, lang string) Term

LangLiteral returns a language-tagged literal.

func Literal

func Literal(s string) Term

Literal returns a plain (xsd:string) literal.

func Typed

func Typed(s, dt string) Term

Typed returns a datatyped literal; xsd:string collapses to a plain literal.

func (Term) Bound

func (t Term) Bound() bool

Bound reports whether the term is set.

func (Term) DT

func (t Term) DT() string

DT returns the effective datatype IRI of a literal.

func (Term) IsIRI

func (t Term) IsIRI() bool

IsIRI reports whether t is an IRI.

func (Term) String

func (t Term) String() string

String renders the term in N-Triples syntax.

type Triple

type Triple struct{ S, P, O Term }

Triple is a subject-predicate-object statement.

type Update

type Update struct {
	Hints Hints
	// contains filtered or unexported fields
}

Update is a parsed SPARQL update request.

func ParseUpdate

func ParseUpdate(src string) (*Update, error)

ParseUpdate parses a SPARQL 1.1 Update request.

func (*Update) Access

func (u *Update) Access() (bool, bool)

Access reports whether the request writes and/or deletes data, for IAM action selection.

func (*Update) SetUsing

func (u *Update) SetUsing(using, named []Term)

SetUsing applies the protocol's using-graph-uri / using-named-graph-uri to update operations lacking USING.

type UpdateOptions

type UpdateOptions struct {
	Fetch    Fetcher
	FetchDoc DocFetcher
	Service  ServiceFunc
}

UpdateOptions carries the update's external dependencies; FetchDoc wins over Fetch.

type UpdateResult

type UpdateResult struct{ Inserted, Deleted int }

UpdateResult counts the triples an update changed.

Jump to

Keyboard shortcuts

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