Movatterモバイル変換


[0]ホーム

URL:


W3C

SHACL 1.2 SPARQL Extensions

W3C First Public Working Draft

More details about this document
This version:
https://www.w3.org/TR/2025/WD-shacl12-sparql-20250318/
Latest published version:
https://www.w3.org/TR/shacl12-sparql/
Latest editor's draft:
https://w3c.github.io/data-shapes/shacl12-sparql/
History:
https://www.w3.org/standards/history/shacl12-sparql/
Commit history
Test suite:
https://w3c.github.io/data-shapes/data-shapes-test-suite/
Latest Recommendation:
https://www.w3.org/TR/2017/REC-shacl-20170720/#part2
Editors:
Holger Knublauch (TopQuadrant, Inc.)
Ashley Sommer (CSIRO)
Former editor:
Dimitris Kontokostas
Feedback:
GitHub w3c/data-shapes (pull requests,new issue,open issues)
public-shacl@w3.org with subject line[shacl-sparql] (archives)

Copyright © 2025World Wide Web Consortium.W3C®liability,trademark andpermissive document license rules apply.


Abstract

This document defines SPARQL-related extensions of the SHACL Shapes Constraint Language.SHACL is a language for validating RDF graphs against a set of conditions.These conditions are provided as shapes and other constructs expressed in the form of an RDF graph.While the Core part of SHACL defines the basic syntax of shapes and the most common constraint componentssupported by SHACL, the SPARQL-related extensions cover features that extend the expressiveness of Coreby means of SPARQL.In particular, this document defines how constraints and constraint components can be defined using SPARQL.

TODO: More will be added on Node Expressions/targets once that part is ready.Other features from SHACL-AF such as user-defined functions may get added.

Status of This Document

This section describes the status of this document at the time of its publication. A list of currentW3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.

This document was published by theData Shapes Working Group as a First Public Working Draft using theRecommendation track.

Publication as a First Public Working Draft does not imply endorsement byW3C and its Members.

This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under theW3C Patent Policy.W3C maintains apublic list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes containsEssential Claim(s) must disclose the information in accordance withsection 6 of theW3C Patent Policy.

This document is governed by the03 November 2023W3C Process Document.

1.Introduction

This document specifies the SPARQL-related features of the SHACL (Shapes Constraint Language).

1.1Terminology

Throughout this document, the following terminology is used.

The SHACL SPARQL Extensions defined in this document are sometimes called SHACL-SPARQL.

Terminology that is linked to portions of RDF 1.2 Concepts and Abstract Syntax is used in SHACL-SPARQL as defined there.Terminology that is linked to portions of SPARQL 1.2 Query Language is used in SHACL-SPARQL as defined there. Terminology that is linked to portions of SHACL 1.2 Core is used in SHACL-SPARQL as defined there. A single linkage is sufficient to provide a definition for all occurences of a particular term in this document.

Definitions are complete within this document, i.e., if there is no rule tomake some situation true in this document then the situation is false.

Basic RDF Terminology
This document uses the termsRDF graph,RDF triple,IRI,literal,blank node,node of an RDF graph,datatype,RDF term, andsubject,predicate, andobject of RDF triplesas defined in RDF 1.2 Concepts and Abstract Syntax [rdf12-concepts].
Basic SHACL Terminology
This document uses the termsfocus node,value,value node,constraint,constraint component,parameter,mandatory parameter,optional parameter,shape,node shape,property shape,SHACL property path,SPARQL property path,shapes graph,target,validator,node expression,node expression function,function name,key parameter,output nodes,conform,failure,SHACL instance,SHACL subclass,SHACL type,as defined in the SHACL 1.2 Core specification [shacl12-core].
Binding, Solution
Abinding is a pair (variable,RDF term), consistent with the term's use in [sparql12-query]. Asolution is a set of bindings, informally often understood as one row in the body of the result table of a SPARQL query. Variables are not required to be bound in a solution.

1.2Document Conventions

The syntax of SHACL is RDF.The examples in this document use Turtle [rdf12-turtle].Other RDF serializations such as RDF/XML may be used in practice.The reader should be familiar with basic RDF concepts [rdf12-concepts] such as triples and with SPARQL [sparql12-query].

Within this document, the following namespace prefix bindings are used:

PrefixNamespace
rdf:http://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfs:http://www.w3.org/2000/01/rdf-schema#
sh:http://www.w3.org/ns/shacl#
xsd:http://www.w3.org/2001/XMLSchema#
ex:http://example.com/ns#

Note that the URI of the graph defining the SHACL vocabulary itself is equivalent tothe namespace above, i.e. it includes the#.References to the SHACL vocabulary, e.g. viaowl:imports should include the#.

Throughout the document, color-coded boxes containing RDF graphs in Turtle will appear.These fragments of Turtle documents use the prefix bindings given above.

# This box represents an input shapes graph# Triples that can be omitted are marked as grey e.g.<s> <p> <o> .
# This box represents an input data graph.# When highlighting is used in the examples:# Elements highlighted in blue arefocus nodesex:Bob a ex:Person .# Elements highlighted in red are focus nodes that fail validationex:Alice a ex:Person .
# This box represents an output results graph

SHACL Definitions appear in blue boxes:

SPARQL or TEXTUAL DEFINITIONS
# This box contains SPARQL or textual definitions.

Grey boxes such as this include syntax rules that apply to theshapes graph.

SPARQL variables using the$ marker represent externalbindings that arepre-bound or, in the case of$PATH,substituted in the SPARQL query before execution (as explained in3.3Validation with SPARQL-based Constraint Components).

true denotes the RDF term"true"^^xsd:boolean.false denotes the RDF term"false"^^xsd:boolean.

1.3Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key wordsMAY,MUST, andSHOULD in this document are to be interpreted as described inBCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

This document defines theSHACL-SPARQL language that extends SHACL Core.This specification describes conformance criteria for:

This document includes syntactic rules that shapes and other nodes need to fulfill in theshapes graph.These rules are typically of the formA shape must have... orThe values of X are literals orAll objects of triples with predicate P must be IRIs.The complete list of these rules can be found in theappendix.Nodes that violate any of these rules are calledill-formed.Nodes that violate none of these rules are calledwell-formed.Ashapes graph is ill-formed if it contains at least one ill-formed node.

2.SPARQL-based Constraints

SHACL-SPARQL supports aconstraint component that can be used to express restrictions based on a SPARQL SELECT query.

Constraint Component IRI:sh:SPARQLConstraintComponent

Parameters:
PropertySummary
sh:sparqlASPARQL-based constraint declaring the SPARQL query to evaluate.

Thesyntax rules andvalidation process for SPARQL-based constraints are defined in the rest of this section.

2.1An Example SPARQL-based Constraint

This section is non-normative.

The following example illustrates the syntax of aSPARQL-based constraint.

Example 1: A SPARQL-based constraint
ex:LanguageExampleShapea sh:NodeShape ;sh:targetClass ex:Country ;sh:sparql [a sh:SPARQLConstraint ; # This triple is optionalsh:message "Values are literals with German language tag." ;sh:prefixes ex: ;sh:select """SELECT $this (ex:germanLabel AS ?path) ?valueWHERE {$this ex:germanLabel ?value .FILTER (!isLiteral(?value) || !langMatches(lang(?value), "de"))}""" ;] .

The target of the shape above includes allSHACL instances ofex:Country.For those nodes (represented by the variablethis), the SPARQL query walks through the values ofex:germanLabeland verifies that they are literals with a German language code.

ex:ValidCountry a ex:Country ;ex:germanLabel "Spanien"@de .ex:InvalidCountry a ex:Country ;ex:germanLabel "Spain"@en .
[a sh:ValidationReport ;sh:conforms false ;sh:result [a sh:ValidationResult ;sh:resultSeverity sh:Violation ;sh:focusNode ex:InvalidCountry ;sh:resultPath ex:germanLabel ;sh:value "Spain"@en ;sh:sourceConstraintComponent sh:SPARQLConstraintComponent ;sh:sourceShape ex:LanguageExampleShape ;# ...]] .

The SPARQL query returns result setsolutions for all bindings of the variablevalue that violate the constraint.There is a validation result for eachsolution in that result set, applying themapping rules explained later.In this example, each validation result will have thebinding for the variablethis as thesh:focusNode,ex:germanLabel assh:resultPath and the violating value assh:value.

The following example illustrates a similar scenario as above, but with aproperty shape.

Example 2
ex:LanguageExamplePropertyShapea sh:PropertyShape ;sh:targetClass ex:Country ;sh:path ex:germanLabel ;sh:sparql [a sh:SPARQLConstraint ; # This triple is optionalsh:message "Values are literals with German language tag." ;sh:prefixes ex: ;sh:select """SELECT $this ?valueWHERE {$this $PATH ?value .FILTER (!isLiteral(?value) || !langMatches(lang(?value), "de"))}""" ;] .

2.2Syntax of SPARQL-based Constraints

Shapes may have values for the propertysh:sparql, and these values are eitherIRIs orblank nodes.These values are calledSPARQL-based constraints.

SPARQL-based constraints have exactly onevalue for the propertysh:select.The value ofsh:select is aliteral of datatypexsd:string.The classsh:SPARQLConstraint is defined in the SHACL vocabulary and may be used as thetype of these constraints (although no type is required).Using theprefix handling rules, the value ofsh:select is a valid SPARQL 1.2 SELECT query.The SPARQL query derived from the value ofsh:selectprojects the variablethis in the SELECT clause.

The following two properties are similar to their use inshapes:

SPARQL-based constraints may have values for the propertysh:message and these are eitherxsd:string literals or literals with a language tag.SPARQL-based constraints may have at most one value for the propertysh:deactivatedand this value is eithertrue orfalse.

SELECT queries used in the context ofproperty shapes use a special variable namedPATH as a placeholder for the path used by the shape.

The only legal use of the variablePATH in the SPARQL queries ofSPARQL-based constraintsandSELECT-based validators is in thepredicate position of atriple pattern.A query that uses the variablePATH in any other position isill-formed.

2.2.1Prefix Declarations for SPARQL Queries

Ashapes graph may include declarations of namespace prefixes so that these prefixes can be used to abbreviate the SPARQL queries derived from the same shapes graph.The syntax of such prefix declarations is illustrated by the following example.

Example 3
ex:a owl:Ontology ;owl:imports sh: ;sh:declare [sh:prefix "ex" ;sh:namespace "http://example.com/ns#"^^xsd:anyURI ;] ;sh:declare [sh:prefix "schema" ;sh:namespace "http://schema.org/"^^xsd:anyURI ;] .

Thevalues of the propertysh:declare areIRIs orblank nodes,and these values are calledprefix declarations.The SHACL vocabulary includes the classsh:PrefixDeclaration as type for suchprefix declarationsalthough nordf:type triple is required for them.Prefix declarations have exactly one value for the propertysh:prefix.The values ofsh:prefix areliterals of datatypexsd:string.Prefix declarations have exactly one value for the propertysh:namespace.The values ofsh:namespace areliterals of datatypexsd:anyURI.Such a pair of values specifies a single mapping of a prefix to a namespace.

The recommendedsubject for values ofsh:declare is the IRI of the named graph containing the shapes that use the prefixes.These IRIs are often declared as an instance ofowl:Ontology, but this is not required.

Prefix declarations can be used bySPARQL-based constraints,thevalidators ofSPARQL-based constraint components,and by similar features defined by SHACL extensions.These nodes can use the propertysh:prefixes to specify a set of prefix mappings.An example use of thesh:prefixes property can be found in theexample above.

The values ofsh:prefixes are eitherIRIs orblank nodes.A SHACL processor collects a set of prefix mappings as the union of allindividual prefix mappings that arevalues of theSPARQL property pathsh:prefixes/owl:imports*/sh:declareof theSPARQL-based constraint orvalidator.If such a collection of prefix declarations contains multiple different namespaces for the samevalue ofsh:prefix,then theshapes graph isill-formed.(Note that SHACL processorsMAY ignore prefix declarations that are never reached).

A SHACL processor transforms the values ofsh:select (and similar properties such assh:ask)into SPARQL by prependingPREFIX declarationsfor all prefix mappings.Each value ofsh:prefix is turned into thePNAME_NS, while each value ofsh:namespace is turnedinto theIRIREF in thePREFIX declaration.For the example shapes graph above, a SHACL-SPARQL processor would produce lines such asPREFIX ex: <http://example.com/ns#>.The SHACL-SPARQL processorMUST produce afailure if the resulting query string cannot be parsed into a valid SPARQL 1.2 query.

In the rest of this document, thesh:prefixes statements may have been omitted for brevity.

2.3Validation with SPARQL-based Constraints

This section explains thevalidator ofsh:SPARQLConstraintComponent.Note that this validator only explains one possible implementation strategy, andSHACL processors may choose alternative approaches as long as the outcome is equivalent.

TEXTUAL DEFINITION
There are no validation results if theSPARQL-based constraint hastrueas avalue for the propertysh:deactivated.Otherwise, execute the SPARQL query specified by theSPARQL-based constraint$sparqlpre-binding the variablesthis and, if supported,shapesGraph andcurrentShape as described in2.3.1Pre-bound Variables in SPARQL Constraints ($this, $shapesGraph, $currentShape). If theshape is aproperty shape, then prior to executionsubstitute the variablePATH where it appears in thepredicateposition of atriple patternwith a valid SPARQL surface syntax string of theSHACL property pathspecified viash:path at theproperty shape.There is one validation result for eachsolution that does not havetrue as thebinding for the variablefailure.These validation resultsMUST have the property values explained in2.3.2Mapping of Solution Bindings to Result Properties.AfailureMUST be produced if and only if one of thesolutions hastrue as thebinding forfailure.

2.3.1Pre-bound Variables in SPARQL Constraints ($this, $shapesGraph, $currentShape)

When the SPARQL queries ofSPARQL-based constraints and thevalidatorsofSPARQL-based constraint components areprocessed,the SHACL-SPARQL processorpre-binds values for the variables in the following table.

VariableInterpretation
thisThefocus node.
shapesGraph (Optional)Can be used to query the shapes graph as inGRAPH $shapesGraph { ... }.If the shapes graph is a named graph in the same dataset as the data graph then it is theIRI of the shapes graph in the dataset.Not all SHACL-SPARQL processors need to support this variable.Processors that do not support the variableshapesGraphMUST report afailure if they encounter a query that references this variable.Use ofGRAPH $shapesGraph { ... } should be handled with extreme caution.It may result in constraints that are not interoperable across different SHACL-SPARQL processors and that may not run on remote RDF datasets.
currentShape (Optional)The currentshape. Typically used in conjunction with the variableshapesGraph.The same support policies as forshapesGraph apply for this variable.

2.3.2Mapping of Solution Bindings to Result Properties

The propertyvalues of the validation result nodes are derived by the following rules, through a combination of result solutions and the values of the constraint itself.The rules are meant to be executed from top to bottom, so that the first bound value will be used.

PropertyProduction Rules
sh:focusNode
  1. The binding for the variablethis
sh:resultPath
  1. The binding for the variablepath, if that is aIRI
  2. For results produced by aproperty shape, aSHACL property path that is equivalent to thevalue ofsh:path of the shape
sh:value
  1. The binding for the variablevalue
  2. Thevalue node
sh:resultMessage
  1. The binding for the variablemessage
  2. For SPARQL-based constraints: The values ofsh:message of theSPARQL-based constraint.For SPARQL-based constraint components: The values ofsh:message of thevalidator of theSPARQL-based constraint component.
  3. For SPARQL-based constraint components: The values ofsh:message of theSPARQL-based constraint component.
These message literals may include the names of any SELECT result variables via{?varName} or{$varName}.If the constraint is based on aSPARQL-based constraint component, then the component'sparameter names can also be used.These{?varName} and{$varName} blocksSHOULD be replaced with suitable string representations of the values of said variables.
sh:sourceConstraint
  1. TheSPARQL-based constraint, i.e. the value ofsh:sparql

3.SPARQL-based Constraint Components

SPARQL-based constraints provide a lot of flexibilitybut may be hard to understand for some people or lead to repetition.This section introducesSPARQL-based constraint components as a way to abstract the complexity of SPARQLand to declare high-level reusable components similar to theCore constraint components.Such constraint components can be declared using the SHACL RDF vocabulary and thus shared and reused.

3.1An Example SPARQL-based Constraint Component

This section is non-normative.

The following example demonstrates how SPARQL can be used to specify new constraint components using the SHACL-SPARQL language.The example implementssh:pattern andsh:flags using aSPARQL ASK query to validate that eachvalue node matches a given regular expression.Note that this is only an example implementation and should not be considered normative.

Example 4: Constraint component based on SPARQL
sh:PatternConstraintComponenta sh:ConstraintComponent ;sh:parameter [sh:path sh:pattern ;] ;sh:parameter [sh:path sh:flags ;sh:optional true ;] ;sh:validator shimpl:hasPattern .shimpl:hasPatterna sh:SPARQLAskValidator ;sh:message "Value does not match pattern {$pattern}" ;sh:ask """ASK { FILTER (!isBlank($value) && IF(bound($flags), regex(str($value), $pattern, $flags), regex(str($value), $pattern)))}""" .

Constraint components provide instructions to validation engines on how to identify and validateconstraints within ashape.In general, if ashapeS has avalue for a propertyp, and there is aconstraint componentC that specifiesp as a parameter, andS has values for allmandatory parameters ofC,then the set of these parameter values (including theoptional parameters) declare aconstraint and the validation engine uses a suitablevalidator fromCto perform the validation of this constraint.In the example above,sh:PatternConstraintComponent declares the mandatory parametersh:pattern,the optional parametersh:flags,and avalidator that can be used to perform validation against eithernode shapes orproperty shapes.

3.2Syntax of SPARQL-based Constraint Components

ASPARQL-based constraint component is anIRI that hasSHACL typesh:ConstraintComponent in theshapes graph.

The mechanism to declare newconstraint components in this document is limited to those based on SPARQL.However, then general syntax of declaring parameters and validators has been designed to also work for other extension languages such as JavaScript.

3.2.1Parameter Declarations (sh:parameter)

Theparameters of aconstraint component are declared via the propertysh:parameter.The values ofsh:parameter are calledparameter declarations.The classsh:Parameter may be used astype ofparameter declarations but no such triple is required.Eachparameter declaration has exactly one value for the propertysh:path.Atparameter declarations, thevalue ofsh:path is anIRI.

Thelocal name of anIRI is defined as the longestNCNAMEat the end of theIRI, not immediately preceded by the first colon in theIRI.Theparameter name of aparameter declaration is defined as thelocal name of thevalue ofsh:path.To ensure that a correct mapping from parameters into SPARQL variables is possible, the following syntax rules apply:

Everyparameter name is a validSPARQL VARNAME.Parameter names must not be one of the following:this,shapesGraph,currentShape,path,PATH,value.A constraint component where two or moreparameter declarations use the sameparameter names isill-formed.

The values ofsh:optional must be literals with datatypexsd:boolean.Aparameter declaration can have at most one value for the propertysh:optional.If set totrue then the parameter declaration declares anoptional parameter.Everyconstraint component has at least one non-optional parameter.

The classsh:Parameter is defined as aSHACL subclass ofsh:PropertyShape,and all properties that are applicable to property shapes may also be used for parameters.This includes descriptive properties such assh:name andsh:descriptionbut also constraint parameters such assh:class.Shapes that do notconform with the constraints declared for the parameters areill-formed.Some implementationsMAY use these constraint parameters to prevent the execution of constraint components with invalid parameter values.

3.2.2Label Templates (sh:labelTemplate)

The propertysh:labelTemplate can be used at anyconstraint component to suggest howconstraints could be rendered to humans.The values ofsh:labelTemplate are strings (possibly with language tag) andare calledlabel templates.

The remainder of this section is informative.

Label templates can include the names of the parameters that are declared for the constraint component using the syntaxes{?varName} or{$varName},wherevarName is the name of theparameter name.At display time, these{?varName} and{$varName} blocksSHOULD be replaced with the actual parameter values.There may be multiple label templates for the same subject, but they should not have the same language tags.

3.2.3Validators

For every supported shape type (i.e.,property shape ornode shape)the constraint component declares a suitablevalidator.For a given constraint, a validator is selected from the constraint component using the following rules, in order:

  1. Fornode shapes, use one of the values ofsh:nodeValidator, if present.
  2. Forproperty shapes, use one of the values ofsh:propertyValidator, if present.
  3. Otherwise, use one of the values ofsh:validator.

If no suitable validator can be found, a SHACL-SPARQL processor ignores the constraint.

SHACL-SPARQL includes two types of validators, based onSPARQL SELECT (forsh:nodeValidator andsh:propertyValidator)orSPARQL ASK queries (forsh:validator).

3.2.3.1SELECT-based Validators

Validators withSHACL typesh:SPARQLSelectValidator are calledSELECT-based validators.The values ofsh:nodeValidator must beSELECT-based validators.The values ofsh:propertyValidator must beSELECT-based validators.SELECT-based validators have exactly onevalue for the propertysh:select.The value ofsh:select is a valid SPARQL SELECT query using the aforementionedprefix handling rules.The SPARQL query derived from the value ofsh:selectprojects the variablethis in its SELECT clause.

The remainder of this section is informative.

The following example illustrates the declaration of a constraint component based on a SPARQL SELECT query.It is a generalized variation of the example from2.1An Example SPARQL-based Constraint.That SPARQL query included two constants: the specific propertyex:germanLabel and the language tagde.Constraint components make it possible to generalize such scenarios, so that constants getpre-bound withparameters.This allows the query logic to be reused in multiple places, without having to write any new SPARQL.

Example 5: Constraint component based on SPARQL
ex:LanguageConstraintComponentUsingSELECTa sh:ConstraintComponent ;rdfs:label "Language constraint component" ;sh:parameter [sh:path ex:lang ;sh:datatype xsd:string ;sh:minLength 2 ;sh:name "language" ;sh:description "The language tag, e.g. \"de\"." ;] ;sh:labelTemplate "Values are literals with language \"{$lang}\"" ;sh:propertyValidator [a sh:SPARQLSelectValidator ;sh:message "Values are literals with language \"{?lang}\"" ;sh:select """SELECT DISTINCT $this ?valueWHERE {$this $PATH ?value .FILTER (!isLiteral(?value) || !langMatches(lang(?value), $lang))}"""] .

Once a constraint component has been declared (in ashapes graph), its parameters can be used as illustrated in the following example.

Example 6: Shape declaration using ex:LanguageConstraintComponent
ex:LanguageExampleShapea sh:NodeShape ;sh:targetClass ex:Country ;sh:property [sh:path ex:germanLabel ;ex:lang "de" ;] ;sh:property [sh:path ex:englishLabel ;ex:lang "en" ;] .

The example shape above specifies the condition that all values ofex:germanLabel carry the language tagdewhile all values ofex:englishLabel haveen as their language.These details are specified via two property shapes that have values for theex:lang parameter required by the constraint component.

3.2.3.2ASK-based Validators

Many constraint components are of the form in which allvalue nodes are tested individually against some boolean condition.Writing SELECT queries for these becomes burdensome, especially if a constraint component can beused for bothproperty shapes andnode shapes.SHACL-SPARQL provides an alternative, more compact syntax for validators based on ASK queries.

Validators withSHACL typesh:SPARQLAskValidator are calledASK-based validators.The values ofsh:validator must beASK-based validators.ASK-based validators have exactly one value for the propertysh:ask.The value ofsh:ask must be a literal with datatypexsd:string.The value ofsh:ask must be a valid SPARQL ASK query using the aforementionedprefix handling rules.

The remainder of this section is informative.

The ASK queries returntrue if and only if a givenvalue node(represented by the pre-bound variablevalue) conforms to the constraint.

The following example declares a constraint component using an ASK query.

Example 7: Constraint component based on SPARQL
ex:LanguageConstraintComponentUsingASKa sh:ConstraintComponent ;rdfs:label "Language constraint component" ;sh:parameter [sh:path ex:lang ;sh:datatype xsd:string ;sh:minLength 2 ;sh:name "language" ;sh:description "The language tag, e.g. \"de\"." ;] ;sh:labelTemplate "Values are literals with language \"{$lang}\"" ;sh:validator ex:hasLang .ex:hasLanga sh:SPARQLAskValidator ;sh:message "Values are literals with language \"{$lang}\"" ;sh:ask """ASK {FILTER (isLiteral($value) && langMatches(lang($value), $lang))}""" .

Note that the validation condition implemented by an ASK query is "in the inverse direction" from its SELECT counterpart:ASK queries returntrue for value nodes that conform to the constraint, while SELECT queries return those value nodes that do not conform.

3.3Validation with SPARQL-based Constraint Components

This section defines thevalidator ofSPARQL-based constraint components.Note that this validator only explains one possible implementation strategy, andSHACL processors may choose alternative approaches as long as the outcome is equivalent.

As the first step, avalidatorMUST be selected based on the rules outlinedin3.2.3Validators.Then the following rules apply, producing a set ofsolutions of SPARQL queries:

The SPARQL query executions aboveMUSTpre-bind the variablesthis and, if supported,shapesGraph andcurrentShapeas described in2.3.1Pre-bound Variables in SPARQL Constraints ($this, $shapesGraph, $currentShape).In addition, eachvalue of aparameter of theconstraint component in theconstraintMUST bepre-bound as a variable that has theparameter name as its name.

The production rules for the validation results are identical to those forSPARQL-based constraints,using thesolutionsQS as produced above.

4.SPARQL-based Node Expressions

This section introducesnode expression functions based on SPARQL.

4.1Select Expressions

Anode expression that has avalue forsh:select is called aselect expression with thefunction namesh:SelectExpression.

A node in an RDF graph is awell-formedselect expression if it is ablank nodethat is thesubject of exactly onetriple withsh:select aspredicate and aliteral asobjectwithdatatypexsd:string.Using theprefix handling rules, the value ofsh:select is a valid SPARQL 1.2 SELECT query.The SPARQL query derived from the value ofsh:selectprojects exactly one variable in the SELECT clause.

EVALUATION OF SELECT EXPRESSIONS

Theoutput nodes of aselect expression are the listresultNodes consisting of exactly the bindings of the (only)variable that is projected from the SELECT clause.If present in thescope, the value of the scope variablefocusNodeMUST bepre-bound as the value of the SPARQL variablethis.

eval(expr, activeGraph, scope) -> resultNodes

The remainder of this section is informative.

Example 8: A dynamically computed property using a node expression based on a SPARQL query

Here is an example use of aselect expression, computing the values of a property shape for the property "full name" as the concatenation of theex:firstName, a space, and theex:lastName.

ex:Person-fullNamea sh:PropertyShape ;sh:name "full name" ;sh:path ex:fullName ;sh:values[sh:prefixes <http://example.org/ns> ;sh:select """SELECT ?fullNameWHERE {$this ex:firstName ?firstName .$this ex:lastName ?lastName .BIND (CONCAT(?firstName, " ", ?lastName) AS ?fullName) .}"""] ;sh:datatype xsd:string .<http://example.org/ns>a owl:Ontology ;sh:declare [sh:prefix "ex" ;sh:namespace "http://example.org/ns#"^^xsd:anyURI ;] .

This example also illustrates the use ofsh:prefixes to insert PREFIX declarations into the beginning of the query before parsing.Note that the query is executed with the currentfocus nodepre-bound to the variablethis.

Example 9: Dynamically computed target nodes using a node expression based on a SPARQL query

Here is an example use of aselect expression, computing the target nodes of a shape to consist of all instances ofex:Person where theex:age is less than18.

ex:ChildShapea sh:NodeShape ;rdfs:label "Child shape" ;rdfs:comment "This shape applies to all persons under 18 years of age." ;sh:targetNode[sh:select """PREFIX ex: <http://example.org/ns#>SELECT ?personWHERE {?person a/rdfs:subClassOf* ex:Person .?person ex:age ?age .FILTER (?age < 18) .}"""] .

From the following data graph, onlyex:Benjamin is a target node.

ex:Benjamina ex:Person ;ex:age 17 .ex:Klausa ex:Person ;ex:age 48 .ex:Bernda ex:Person .

Appendix

A.Pre-binding of Variables in SPARQL Queries

Some features of SHACL-SPARQL rely on the concept ofpre-binding of variables as defined in this section.

The definition of pre-binding used by SHACL requires the following restrictions on SPARQL queries.SHACL-SPARQL processorsMUST report afailure when it is operating on ashapes graphthat contains SHACL-SPARQL queries (viash:select andsh:ask) that violate any of these restrictions.Note that the termpotentially pre-bound variables includes the variablesthis,shapesGraph,currentShape,value (for ASK queries),and any variables that represent theparameters of theconstraint component that uses the query.

DEFINITION:Values Insertion

For solution mappingμ, defineTable(μ) to be the multiset formed fromμ.

   Table(μ) = { μ }
   Card[μ] = 1

Define theValues Insertion functionReplace(X, μ) toreplace each occurenceY of aBasic Graph Pattern,Property Path Expression,Graph(Var, pattern)inX withjoin(Y, Table(μ)).

DEFINITION:Pre-binding of variables

The evaluation of theSPARQL QueryQ = (E, DS, QF) withpre-bound variablesμis defined as the evaluation of SPARQL queryQ' = (Replace(E, μ), DS, QF).

B.Summary of SHACL Syntax Rules

This section enumerates all normative syntax rules of SHACL.This section is automatically generated from other parts of this spec and hyperlinks are provided backinto the prose if the context of the rule in unclear. Nodes that violate these rules in ashapes graph areill-formed.

Syntax Rule IdSyntax Rule Text
sparql-nodeKindShapes may have values for the propertysh:sparql, and these values are eitherIRIs orblank nodes.
SPARQLConstraint-select-countSPARQL-based constraints have exactly onevalue for the propertysh:select
SPARQLConstraint-select-datatypeThe value ofsh:select is aliteral of datatypexsd:string.
select-query-validUsing theprefix handling rules, the value ofsh:select is a valid SPARQL 1.2 SELECT query.
select-query-thisThe SPARQL query derived from the value ofsh:selectprojects the variablethis in the SELECT clause.
SPARQLConstraint-message-datatypeSPARQL-based constraints may have values for the propertysh:message and these are eitherxsd:string literals or literals with a language tag.
SPARQLConstraint-deactivated-maxCountSPARQL-based constraints may have at most one value for the propertysh:deactivated
PATH-positionThe only legal use of the variablePATH in the SPARQL queries ofSPARQL-based constraintsandSELECT-based validators is in thepredicate position of atriple pattern.
declare-nodeKindThevalues of the propertysh:declare areIRIs orblank nodes
prefix-countPrefix declarations have exactly one value for the propertysh:prefix
prefix-datatypeThe values ofsh:prefix areliterals of datatypexsd:string.
namespace-countPrefix declarations have exactly one value for the propertysh:namespace.
namespace-datatypeThe values ofsh:namespace areliterals of datatypexsd:anyURI.
prefixes-nodeKindThe values ofsh:prefixes are eitherIRIs orblank nodes.
prefixes-duplicatesA SHACL processor collects a set of prefix mappings as the union of allindividual prefix mappings that arevalues of theSPARQL property pathsh:prefixes/owl:imports*/sh:declareof theSPARQL-based constraint orvalidator.If such a collection of prefix declarations contains multiple different namespaces for the samevalue ofsh:prefix,then theshapes graph isill-formed.
ConstraintComponentASPARQL-based constraint component is anIRI that hasSHACL typesh:ConstraintComponent in theshapes graph.
Parameter-predicate-countEachparameter declaration has exactly one value for the propertysh:path
ParameterAtparameter declarations, thevalue ofsh:path is anIRI.
parameter-name-VARNAMEEveryparameter name is a validSPARQL VARNAME.
parameter-name-not-inParameter names must not be one of the following:this,shapesGraph,currentShape,path,PATH,value.
parameter-name-uniqueA constraint component where two or moreparameter declarations use the sameparameter names isill-formed.
optional-datatypeThe values ofsh:optional must be literals with datatypexsd:boolean.
optional-maxCountAparameter declaration can have at most one value for the propertysh:optional.
ConstraintComponent-parameterEveryconstraint component has at least one non-optional parameter.
Parameter-conformanceShapes that do notconform with the constraints declared for the parameters areill-formed.
labelTemplate-datatypeThe values ofsh:labelTemplate are strings (possibly with language tag)
nodeValidator-classThe values ofsh:nodeValidator must beSELECT-based validators.
propertyValidator-classThe values ofsh:propertyValidator must beSELECT-based validators.
SPARQLSelectValidator-select-countSELECT-based validators have exactly onevalue for the propertysh:select.
validator-classThe values ofsh:validator must beASK-based validators.
ask-countASK-based validators have exactly one value for the propertysh:ask
ask-datatypeThe value ofsh:ask must be a literal with datatypexsd:string.
ask-sparqlThe value ofsh:ask must be a valid SPARQL ASK query using the aforementionedprefix handling rules.
SelectExpression-syntaxA node in an RDF graph is awell-formedselect expression if it is ablank nodethat is thesubject of exactly onetriple withsh:select aspredicate and aliteral asobjectwithdatatypexsd:string.
SelectExpression-query-validUsing theprefix handling rules, the value ofsh:select is a valid SPARQL 1.2 SELECT query.
SelectExpression-query-output-nodesThe SPARQL query derived from the value ofsh:selectprojects exactly one variable in the SELECT clause.
pre-binding-limitations

The definition of pre-binding used by SHACL requires the following restrictions on SPARQL queries.SHACL-SPARQL processorsMUST report afailure when it is operating on ashapes graphthat contains SHACL-SPARQL queries (viash:select andsh:ask) that violate any of these restrictions.Note that the termpotentially pre-bound variables includes the variablesthis,shapesGraph,currentShape,value (for ASK queries),and any variables that represent theparameters of theconstraint component that uses the query.

  • SPARQL queries must not contain aMINUS clause
  • SPARQL queries must not contain a federated query (SERVICE)
  • SPARQL queries must not contain aVALUES clause
  • SPARQL queries must not use the syntax form ​​AS ?var for any potentially pre-bound variable
  • Subqueries must return all potentially pre-bound variables, exceptshapesGraph andcurrentShape which are optional as already mentioned in2.3.1Pre-bound Variables in SPARQL Constraints ($this, $shapesGraph, $currentShape)

C.Potential SPARQL Definitions of SHACL Core Constraint Validators

This section is non-normative.

This appendix uses parts of SPARQL 1.2 in non-normative alternative definitions of the semantics ofconstraint components andtargetsfrom [shacl12-core].While these may help some implementers, SPARQL is not required for the implementation of the SHACL Core language.

SPARQL variables using the$ marker represent externalbindings that arepre-bound or, in the case of$PATH,substituted in the SPARQL query before execution (as explained in3.3Validation with SPARQL-based Constraint Components).TODO: Assuming SHACL Core 1.2 allows node expressions as constraint parameters, explain that they are evaluated prior to substitution.

C.1sh:targetClass

The following query expresses a potential definition ofclass targets in SPARQL.The variabletargetClass will bepre-bound to the given value ofsh:targetClass.Allbindings of the variablethis from thesolutions become focus nodes.

POTENTIAL DEFINITION IN SPARQL
SELECT DISTINCT ?this    # ?this is the focus nodeWHERE {?this rdf:type/rdfs:subClassOf* $targetClass .}

C.2sh:targetSubjectsOf

The following query expresses a potential definition ofsubjects-of targets in SPARQL.The variabletargetSubjectsOf will bepre-bound to the given value ofsh:targetSubjectsOf.Allbindings of the variablethis from thesolutions become focus nodes.

POTENTIAL DEFINITION IN SPARQL
SELECT DISTINCT ?this    # ?this is the focus nodeWHERE {?this $targetSubjectsOf ?any .}

C.3sh:targetObjectsOf

The following query expresses a potential definition ofobjects-of targets in SPARQL.The variabletargetObjectsOf will bepre-bound to the given value ofsh:targetObjectsOf.Allbindings of the variablethis from thesolutions become focus nodes.

POTENTIAL DEFINITION IN SPARQL
SELECT DISTINCT ?this    # ?this is the focus nodeWHERE {?any $targetObjectsOf ?this .}

C.4sh:class

The following query expresses a potential SPARQL-based validator forsh:class.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {$value rdf:type/rdfs:subClassOf* $class .}

C.5sh:nodeKind

The following query expresses a potential SPARQL-based validator forsh:nodeKind.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {FILTER ((isIRI($value) && $nodeKind IN ( sh:IRI, sh:BlankNodeOrIRI, sh:IRIOrLiteral ) ) ||(isLiteral($value) && $nodeKind IN ( sh:Literal, sh:BlankNodeOrLiteral, sh:IRIOrLiteral ) ) ||(isBlank($value)   && $nodeKind IN ( sh:BlankNode, sh:BlankNodeOrIRI, sh:BlankNodeOrLiteral ) )) .}

C.6sh:minExclusive (etc)

The following query expresses a potential SPARQL-based validator forsh:minExclusive.The SPARQL expression produces an error if the value node cannot be compared to the specified range,for example when someone compares a string with an integer.If the comparison cannot be performed, then there is a validation result.This is different from, say, a plain SPARQL query, in which such errors would silently not lead to any results.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {FILTER ($minExclusive < $value)}

Similar definitions are possible for:

C.7sh:minLength

The following query expresses a potential SPARQL-based validator forsh:minLength.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {FILTER (STRLEN(str($value)) >= $minLength) .}

C.8sh:maxLength

The following query expresses a potential SPARQL-based validator forsh:maxLength.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {FILTER (STRLEN(str($value)) <= $maxLength) .}

C.9sh:pattern

The following query expresses a potential SPARQL-based validator forsh:pattern.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {FILTER (!isBlank($value) && IF(bound($flags), regex(str($value), $pattern, $flags), regex(str($value), $pattern)))}

C.10sh:disjoint

The following query expresses a potential SPARQL-based validator forsh:disjoint.

POTENTIAL DEFINITION IN SPARQL (Must return no results for the given $PATH)
SELECT DISTINCT $this ?valueWHERE {$this $PATH ?value .$this $disjoint ?value .}

C.11sh:lessThan

The following query expresses a potential SPARQL-based validator forsh:lessThan.

POTENTIAL DEFINITION IN SPARQL (Must return no results for the given $PATH)
SELECT $this ?valueWHERE {$this $PATH ?value .$this $lessThan ?otherValue .BIND (?value < ?otherValue AS ?result) .FILTER (!bound(?result) || !(?result)) .}

C.12sh:lessThanOrEquals

The following query expresses a potential SPARQL-based validator forsh:lessThanOrEquals.

POTENTIAL DEFINITION IN SPARQL (Must return no results for the given $PATH)
SELECT $this ?valueWHERE {$this $PATH ?value .$this $lessThanOrEquals ?otherValue .BIND (?value <= ?otherValue AS ?result) .FILTER (!bound(?result) || !(?result)) .}

C.13sh:in

The following query expresses a potential SPARQL-based validator forsh:in.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {GRAPH $shapesGraph {$in (rdf:rest*)/rdf:first $value .}}

D.Security and Privacy Considerations

This section is non-normative.

Like most RDF-based technologies, SHACL processors may operate on graphs that are combinedfrom various sources. Some applications may have an open "linked data" architecture and dynamicallyassemble RDF triples from sources that are outside of an organization's network of trust.Since RDF allows anyone to add statements about any resource, triples may modify the originallyintended semantics of shape definitions or nodes in a data graph and thus lead to misleading results.Protection against this (and the following) scenario can be achieved by only using trustedand verified RDF sources and eliminating the possibility that graphs are dynamically added viaowl:imports andsh:shapesGraph.

SHACL-SPARQL includes all thesecurity issues of SPARQL.

E.Acknowledgements

This section is non-normative.

The original 1.0 version of SHACL was produced by the RDF Data Shapes Working Group.See itsSHACL 1.0 Acknowledgements section.

F.Revision History

This section is non-normative.

The detailed list of changes and their diffs can be found in the Git repository.

G.Changes between SHACL 1.0 SPARQL and SHACL 1.2 SPARQL Extensions

This section is non-normative.

H.References

H.1Normative references

[css]
CSS Snapshot 2023. Chris Lilley; Elika Etemad; Tab Atkins Jr.; Florian Rivoal. W3C. 7 December 2023. W3C Working Group Note. URL:https://www.w3.org/TR/css-2023/
[rdf12-concepts]
RDF 1.2 Concepts and Abstract Syntax. Olaf Hartig; Pierre-Antoine Champin; Gregg Kellogg; Andy Seaborne. W3C. 25 February 2025. W3C Working Draft. URL:https://www.w3.org/TR/rdf12-concepts/
[rdf12-turtle]
RDF 1.2 Turtle. Gregg Kellogg; Dominik Tomaszuk. W3C. 20 February 2025. W3C Working Draft. URL:https://www.w3.org/TR/rdf12-turtle/
[REC-xml-names]
Namespaces in XML 1.0 (Third Edition). Tim Bray; Dave Hollander; Andrew Layman; Richard Tobin; Henry Thompson et al. W3C. 8 December 2009. W3C Recommendation. URL:https://www.w3.org/TR/xml-names/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc2119
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc8174
[shacl12-core]
SHACL 1.2 Core. W3C. W3C Editor's Draft. URL:https://w3c.github.io/data-shapes/shacl12-core/
[sparql12-query]
SPARQL 1.2 Query Language. Olaf Hartig; Andy Seaborne; Ruben Taelman; Gregory Williams; Thomas Pellissier Tanon. W3C. 28 February 2025. W3C Working Draft. URL:https://www.w3.org/TR/sparql12-query/
[vc-data-model]
Verifiable Credentials Data Model v1.1. Manu Sporny; Grant Noble; Dave Longley; Daniel Burnett; Brent Zundel; Kyle Den Hartog. W3C. 3 March 2022. W3C Recommendation. URL:https://www.w3.org/TR/vc-data-model/


[8]ページ先頭

©2009-2025 Movatter.jp