From 54f02c4c9dc9ee9827d0cc555f96fc6190728267 Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Fri, 28 Apr 2023 11:38:53 +0200 Subject: [PATCH 1/7] shapes: drop v2 folder --- shapes/{v2 => }/gather_map.ttl | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename shapes/{v2 => }/gather_map.ttl (100%) diff --git a/shapes/v2/gather_map.ttl b/shapes/gather_map.ttl similarity index 100% rename from shapes/v2/gather_map.ttl rename to shapes/gather_map.ttl From 68aae9422d0fd8ddd07ced7e0ee9ecadb2e6bf1f Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Fri, 28 Apr 2023 11:48:17 +0200 Subject: [PATCH 2/7] shapes: adjust shapes following Core avoid duplication and add CI/CD --- .github/workflows/shapes.yml | 29 +++ .gitignore | 3 +- shapes/cc.ttl | 95 ++++++++ shapes/external_shapes.ttl | 20 ++ shapes/gather_map.ttl | 235 ++++++-------------- shapes/generate_shape.py | 79 +++++++ shapes/mapping_validator.py | 40 ++++ shapes/requirements.txt | 3 + shapes/shacl.ttl | 406 +++++++++++++++++++++++++++++++++++ shapes/tests.py | 76 +++++++ 10 files changed, 821 insertions(+), 165 deletions(-) create mode 100644 .github/workflows/shapes.yml create mode 100644 shapes/cc.ttl create mode 100644 shapes/external_shapes.ttl create mode 100755 shapes/generate_shape.py create mode 100644 shapes/mapping_validator.py create mode 100644 shapes/requirements.txt create mode 100644 shapes/shacl.ttl create mode 100755 shapes/tests.py diff --git a/.github/workflows/shapes.yml b/.github/workflows/shapes.yml new file mode 100644 index 0000000..33563f5 --- /dev/null +++ b/.github/workflows/shapes.yml @@ -0,0 +1,29 @@ +# This workflow will install Python dependencies, run tests and lint with a single version of Python +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: Test case validation with SHACL shapes + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.9 + uses: actions/setup-python@v2 + with: + python-version: 3.9 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + cd shapes + pip install -r requirements.txt + - name: Run tests + run: | + cd shapes + python3 tests.py diff --git a/.gitignore b/.gitignore index 496ee2c..6a4dae1 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.DS_Store \ No newline at end of file +.DS_Store +__pycache__ diff --git a/shapes/cc.ttl b/shapes/cc.ttl new file mode 100644 index 0000000..31db232 --- /dev/null +++ b/shapes/cc.ttl @@ -0,0 +1,95 @@ +@prefix brick: . +@prefix csvw: . +@prefix dc: . +@prefix dcam: . +@prefix dcat: . +@prefix dcmitype: . +@prefix dcterms: . +@prefix doap: . +@prefix foaf: . +@prefix geo: . +@prefix odrl: . +@prefix org: . +@prefix owl: . +@prefix prof: . +@prefix prov: . +@prefix qb: . +@prefix rdf: . +@prefix rdfs: . +@prefix rml: . +@prefix schema: . +@prefix sh: . +@prefix skos: . +@prefix sosa: . +@prefix ssn: . +@prefix time: . +@prefix vann: . +@prefix void: . +@prefix wgs: . +@prefix xml: . +@prefix xsd: . + + a sh:NodeShape ; + sh:and ( [ sh:description """ + rml:strategy specifies the collection strategy to use: rml:append + or rml:catessianProduct. rml:append is the default strategy. + """ ; + sh:in ( rml:append rml:cartessian ) ; + sh:maxCount 1 ; + sh:message """ + Zero or one rml:strategy is required. + """ ; + sh:minCount 0 ; + sh:name "strategy" ; + sh:nodeKind sh:IRI ; + sh:path rml:strategy ] [ sh:description """ + rml:gatherAs specifies how to gather the collection e.g. a rdf:Alt, + rdf:List, rdf:Bag, or rdf:Seq. + """ ; + sh:in ( rdf:Alt rdf:List rdf:Bag rdf:Seq ) ; + sh:maxCount 1 ; + sh:message """ + One rml:gatherAs is required. + """ ; + sh:minCount 1 ; + sh:name "gatherAs" ; + sh:nodeKind sh:IRI ; + sh:path rml:gatherAs ] [ sh:datatype xsd:boolean ; + sh:description """ + Defines the behavior when the collection is empty. True will generate + a rdf:nil for a RDF collection or a resource with no members for an RDF + container. False will not generate any collection or container. + Default is false. + """ ; + sh:maxCount 1 ; + sh:message """ + Zero or one rml:allowEmptyListAndContainer is required with datatype + xsd:boolean. + """ ; + sh:minCount 0 ; + sh:name "allowEmptyListAndContainer" ; + sh:nodeKind sh:Literal ; + sh:path rml:allowEmptyListAndContainer ] [ sh:description """ + RML Term Maps to gather in the collection or container. + """ ; + sh:message """ + one or more rml:gather properties are needed, each pointing to a + RML Term Map. + """ ; + sh:minCount 1 ; + sh:name "gather" ; + sh:nodeKind sh:BlankNodeOrIRI ; + sh:path rml:gather ] ) ; + sh:description """ + Represents a Gather Map. + """ ; + sh:message """ + Gather Map requires one rml:strategy, one rml:gatherAs, and a list of + Term Map with rml:gather. + """ ; + sh:name "GatherMap" . + + a sh:NodeShape . + + a sh:NodeShape . + diff --git a/shapes/external_shapes.ttl b/shapes/external_shapes.ttl new file mode 100644 index 0000000..98f45a2 --- /dev/null +++ b/shapes/external_shapes.ttl @@ -0,0 +1,20 @@ +############################################################################### +# RML FNML external resources shapes # +# Copyright Dylan Van Assche, IDLab - UGent - imec (2023) # +############################################################################### +@prefix sh: . +@prefix schema: . +@prefix rdf: . +@prefix rml: . +@prefix xsd: . + +# Shapes are defined in the corresponding repositories of each specification +# Provide their IRI as stub to allow validation in CC. + +schema:RMLTermMapShape + a sh:NodeShape; +. + +schema:RMLLogicalTargetPropertiesShape + a sh:NodeShape; +. diff --git a/shapes/gather_map.ttl b/shapes/gather_map.ttl index 884a1ae..b1744d2 100644 --- a/shapes/gather_map.ttl +++ b/shapes/gather_map.ttl @@ -5,178 +5,85 @@ @prefix sh: . @prefix schema: . @prefix rdf: . -@prefix rml: . -@prefix rmlcc: . +@prefix rml: . @prefix xsd: . schema:RMLGatherMapShape a sh:NodeShape ; - sh:ignoredProperties (rdf:type) ; - sh:name "rmlcc:GatherMap" ; + sh:name "GatherMap" ; sh:description """ Represents a Gather Map. """ ; sh:message """ - rmlcc:GatherMap requires one rml:strategy, one rml:gatherAs, and a list of - rml:TermMap with rml:gather. + Gather Map requires one rml:strategy, one rml:gatherAs, and a list of + Term Map with rml:gather. """ ; - # Exactly one rml:template, one rml:constant or one rml:reference is - # required. - sh:property [ - sh:path [sh:alternativePath (rml:template - rml:constant - rml:reference)] ; - sh:name "rml:template/rml:constant/rml:reference" ; - sh:description """ - Exactly one rml:template, one rml:constant or one rml:reference is - required for a named collection. When none of them are given, - the collection is unnamed. - """ ; - sh:message """ - Exactly one rml:template, one rml:constant or one rml:reference is - required for a named collection. When none of them are given, - the collection is unnamed. - """ ; - sh:minCount 0 ; - sh:maxCount 1 ; - ] ; - - # rml:template - sh:property [ - sh:path rml:template ; - sh:name "rml:template" ; - sh:description """ - A template (format string) to specify how to generate a value for a - subject, predicate, or object, using one or more columns from a logical - table row or iterator. - """ ; - sh:message """ - rml:template must be a string. - """ ; - sh:nodeKind sh:Literal ; - sh:datatype xsd:string ; - ] ; - - # rml:constant - sh:property [ - sh:path rml:constant ; - sh:name "rml:constant" ; - sh:description """ - A property for indicating whether a term map is a constant-valued term - map. - """ ; - sh:message """ - rml:constant must be an IRI. - """ ; - sh:nodeKind sh:IRI ; - ] ; - - # rml:reference - sh:property [ - sh:path rml:reference ; - sh:name "rml:reference" ; - sh:description """ - A reference rml:reference is used to refer to a column in case of - databases, a record in case of CSV or TSV data source, an element in - case of XML data source, an object in case of a JSON data source, etc. - - A reference must be a valid identifier, considering the reference - formulation (rml:referenceFormulation) specified. The reference can be - an absolute path, or a path relative to the iterator specified at the - logical source. - """ ; - sh:message """ - rml:reference must be a string. - """ ; - sh:nodeKind sh:Literal ; - sh:datatype xsd:string ; - ] ; - - # rml:termType - sh:property [ - sh:path rml:termType ; - sh:name "rml:termType" ; - sh:description """ - An IRI indicating whether subject or object generated using the value - from column name specified for rml:column should be an IRI reference, - blank node, or a literal. - """ ; - sh:message """ - rml:termType must be either rml:IRI or rml:BlankNode for an rml:SubjectMap. - May only be provided once. - """ ; - sh:maxCount 1 ; - sh:in (rml:IRI rml:BlankNode) ; - sh:nodeKind sh:IRI ; - ] ; - - # rmlcc:strategy - sh:property [ - sh:path rmlcc:strategy ; - sh:name "rmlcc:strategy" ; - sh:description """ - rmlcc:strategy specifies the collection strategy to use: rmlcc:append - or rmlcc:catessianProduct. rmlcc:append is the default strategy. - """ ; - sh:message """ - Zero or one rmlcc:strategy is required. - """ ; - sh:in (rmlcc:append rmlcc:cartessian) ; - sh:nodeKind sh:IRI; - sh:minCount 0 ; - sh:maxCount 1 ; - ] ; - - # rmlcc:gatherAs - sh:property [ - sh:path rmlcc:gatherAs ; - sh:name "rmlcc:gatherAs" ; - sh:description """ - rmlcc:gatherAs specifies how to gather the collection e.g. a rdf:Alt, - rdf:List, rdf:Bag, or rdf:Seq. - """ ; - sh:message """ - One rmlcc:gatherAs is required. - """ ; - sh:in (rdf:Alt rdf:List rdf:Bag rdf:Seq) ; - sh:nodeKind sh:IRI; - sh:minCount 1 ; - sh:maxCount 1 ; - ] ; - - # rmlcc:allowEmptyListAndContainer - sh:property [ - sh:path rmlcc:allowEmptyListAndContainer ; - sh:name "rmlcc:allowEmptyListAndContainer" ; - sh:description """ - Defines the behavior when the collection is empty. True will generate - a rdf:nil for a RDF collection or a resource with no members for an RDF - container. False will not generate any collection or container. - Default is false. - """ ; - sh:message """ - Zero or one rmlcc:allowEmptyListAndContainer is required with datatype - xsd:boolean. - """ ; - sh:minCount 0 ; - sh:maxCount 1 ; - sh:nodeKind sh:Literal ; - sh:datatype xsd:boolean ; - ] ; - - # rmlcc:gather - sh:property [ - sh:path rmlcc:gather ; - sh:name "rmlcc:gather" ; - sh:description """ - RML Term Maps to gather in the collection or container. - """ ; - sh:message """ - one or more rmlcc:gather properties are needed, each pointing to a - RML Term Map. - """ ; - sh:nodeKind sh:BlankNodeOrIRI ; - sh:minCount 1 ; - ] ; + sh:and ( + # Inherited shapes + schema:RMLTermMapShape + schema:RMLLogicalTargetPropertiesShape + # Gather Map specific shapes + [ + sh:path rml:strategy ; + sh:name "strategy" ; + sh:description """ + rml:strategy specifies the collection strategy to use: rml:append + or rml:catessianProduct. rml:append is the default strategy. + """ ; + sh:message """ + Zero or one rml:strategy is required. + """ ; + sh:in (rml:append rml:cartessian) ; + sh:nodeKind sh:IRI; + sh:minCount 0 ; + sh:maxCount 1 ; + ] + [ + sh:path rml:gatherAs ; + sh:name "gatherAs" ; + sh:description """ + rml:gatherAs specifies how to gather the collection e.g. a rdf:Alt, + rdf:List, rdf:Bag, or rdf:Seq. + """ ; + sh:message """ + One rml:gatherAs is required. + """ ; + sh:in (rdf:Alt rdf:List rdf:Bag rdf:Seq) ; + sh:nodeKind sh:IRI; + sh:minCount 1 ; + sh:maxCount 1 ; + ] + [ + sh:path rml:allowEmptyListAndContainer ; + sh:name "allowEmptyListAndContainer" ; + sh:description """ + Defines the behavior when the collection is empty. True will generate + a rdf:nil for a RDF collection or a resource with no members for an RDF + container. False will not generate any collection or container. + Default is false. + """ ; + sh:message """ + Zero or one rml:allowEmptyListAndContainer is required with datatype + xsd:boolean. + """ ; + sh:minCount 0 ; + sh:maxCount 1 ; + sh:nodeKind sh:Literal ; + sh:datatype xsd:boolean ; + ] + [ + sh:path rml:gather ; + sh:name "gather" ; + sh:description """ + RML Term Maps to gather in the collection or container. + """ ; + sh:message """ + one or more rml:gather properties are needed, each pointing to a + RML Term Map. + """ ; + sh:nodeKind sh:BlankNodeOrIRI ; + sh:minCount 1 ; + ] + ) ; . diff --git a/shapes/generate_shape.py b/shapes/generate_shape.py new file mode 100755 index 0000000..5d4db63 --- /dev/null +++ b/shapes/generate_shape.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python + +import argparse +import sys +from os import path +from glob import glob +from rdflib import Graph, Namespace +from rdflib.plugins.serializers.turtle import TurtleSerializer +from rdflib import plugin + +SUBSHAPE_FORMAT = 'turtle' +SUBSHAPE_GLOB_PATTERN = '*.ttl' +SHACL = Namespace('http://www.w3.org/ns/shacl#') +RML = Namespace('http://w3id.org/rml/') + + +class TurtleWithPrefixes(TurtleSerializer): + """ + A turtle serializer that always emits prefixes + Workaround for https://github.com/RDFLib/rdflib/issues/1048 + """ + roundtrip_prefixes = True # Undocumented, forces to write all prefixes + + +class ShapeGenerator: + """ + Generates a complete SHACL shape of all the SHACL subshapes. + Useful for using the shapes in the shacl.org Playground. + """ + def __init__(self, glob_pattern: str, rdf_format: str, + destination: str) -> None: + self._glob_pattern: str = glob_pattern + self._rdf_format: str = rdf_format + self._destination: str = destination + self._shape = Graph() + self._shape.bind('sh', SHACL) + self._shape.bind('rml', RML) + # Register TurtleWithPrefixes serializer as 'tortoise' format + plugin.register('tortoise', + plugin.Serializer, + 'generate_shape', + 'TurtleWithPrefixes') + + def generate(self) -> None: + """ + Generate a full shape from the sub shapes. + """ + print('Reading subshapes:') + for sub_shape in glob(self._glob_pattern): + if 'cc' in sub_shape or 'shacl' in sub_shape: + continue + print(f"\t{sub_shape}") + g = Graph() + g.bind('sh', SHACL) + g.bind('rml', RML) + self._shape += g.parse(sub_shape, format=self._rdf_format) + + print(f'Writing shape to {self._destination}') + self._shape.serialize(destination=self._destination, format='tortoise') + + +if __name__ == '__main__': + p = argparse.ArgumentParser(description='Generate a complete SHACL shape ' + 'from the subshapes.') + p.add_argument('destination', type=str, help='Location to write the ' + 'complete SHACL shape as Turtle.') + # Arguments parsing + args = p.parse_args() + if not path.exists(args.destination): + print(f'{args.destination} file path does not exist!') + sys.exit(1) + + if path.isdir(args.destination): + args.destination = path.join(args.destination, 'cc.ttl') + + # Generate shape + generator = ShapeGenerator(SUBSHAPE_GLOB_PATTERN, SUBSHAPE_FORMAT, + args.destination) + generator.generate() diff --git a/shapes/mapping_validator.py b/shapes/mapping_validator.py new file mode 100644 index 0000000..f239f59 --- /dev/null +++ b/shapes/mapping_validator.py @@ -0,0 +1,40 @@ +from logging import debug, info, critical +from pyshacl import validate +from rdflib import Graph +from shutil import get_terminal_size + + +class MappingValidator: + def __init__(self, shape: str) -> None: + g = Graph() + g.parse(shape, format='turtle') + self._shape = g + + def validate(self, rules: Graph, print_report: bool = True) -> None: + valid: bool + report_graph: Graph + report_text: str + valid, report_graph, report_text = validate(rules, + shacl_graph=self._shape) + debug(f'RML rules valid: {valid}') + debug(f'SHACL validation report: {report_text}') + + # If mapping rules are invalid, print SHACL report and raise exception + if not valid and print_report: + self._print_report(report_text) + msg = 'RML mapping rules are invalid, a detailed explanation' \ + ' is available in the report' + critical(msg) + raise ValueError(msg) + + def _print_report(self, report_text: str) -> None: + tty_columns: int + tty_columns, _ = get_terminal_size() + info('-' * tty_columns) + title: str = 'RML rules validation report' + white_space: int = int((tty_columns - len(title)) / 2) + title = ' ' * white_space + title + ' ' * white_space + info(title) + info('-' * tty_columns) + info(report_text) + info('-' * tty_columns) \ No newline at end of file diff --git a/shapes/requirements.txt b/shapes/requirements.txt new file mode 100644 index 0000000..e9fdd84 --- /dev/null +++ b/shapes/requirements.txt @@ -0,0 +1,3 @@ +parameterized +rdflib +pyshacl \ No newline at end of file diff --git a/shapes/shacl.ttl b/shapes/shacl.ttl new file mode 100644 index 0000000..e37856a --- /dev/null +++ b/shapes/shacl.ttl @@ -0,0 +1,406 @@ +@prefix rdf: . +@prefix rdfs: . +@prefix sh: . +@prefix xsd: . + +@prefix shsh: . + +shsh: + rdfs:label "SHACL for SHACL"@en ; + rdfs:comment "This shapes graph can be used to validate SHACL shapes graphs against a subset of the SHACL syntax rules."@en ; + sh:declare [ + sh:prefix "shsh" ; + sh:namespace "http://www.w3.org/ns/shacl-shacl#" ; + ] . + + +shsh:ListShape + a sh:NodeShape ; + rdfs:label "List shape"@en ; + rdfs:comment "A shape describing well-formed RDF lists. Currently does not check for non-recursion. This could be expressed using SHACL-SPARQL."@en ; + rdfs:seeAlso ; + sh:property [ + sh:path [ sh:zeroOrMorePath rdf:rest ] ; + rdfs:comment "Each list member (including this node) must be have the shape shsh:ListNodeShape."@en ; + sh:hasValue rdf:nil ; + sh:node shsh:ListNodeShape ; + ] . + +shsh:ListNodeShape + a sh:NodeShape ; + rdfs:label "List node shape"@en ; + rdfs:comment "Defines constraints on what it means for a node to be a node within a well-formed RDF list. Note that this does not check whether the rdf:rest items are also well-formed lists as this would lead to unsupported recursion."@en ; + sh:or ( [ + sh:hasValue rdf:nil ; + sh:property [ + sh:path rdf:first ; + sh:maxCount 0 ; + ] ; + sh:property [ + sh:path rdf:rest ; + sh:maxCount 0 ; + ] ; + ] + [ + sh:not [ sh:hasValue rdf:nil ] ; + sh:property [ + sh:path rdf:first ; + sh:maxCount 1 ; + sh:minCount 1 ; + ] ; + sh:property [ + sh:path rdf:rest ; + sh:maxCount 1 ; + sh:minCount 1 ; + ] ; + ] ) . + +shsh:ShapeShape + a sh:NodeShape ; + rdfs:label "Shape shape"@en ; + rdfs:comment "A shape that can be used to validate syntax rules for other shapes."@en ; + + # See https://www.w3.org/TR/shacl/#shapes for what counts as a shape + sh:targetClass sh:NodeShape ; + sh:targetClass sh:PropertyShape ; + sh:targetSubjectsOf sh:targetClass, sh:targetNode, sh:targetObjectsOf, sh:targetSubjectsOf ; + sh:targetSubjectsOf sh:and, sh:class, sh:closed, sh:datatype, sh:disjoint, sh:equals, sh:flags, sh:hasValue, + sh:ignoredProperties, sh:in, sh:languageIn, sh:lessThan, sh:lessThanOrEquals, sh:maxCount, sh:maxExclusive, + sh:maxInclusive, sh:maxLength, sh:minCount, sh:minExclusive, sh:minInclusive, sh:minLength, sh:node, sh:nodeKind, + sh:not, sh:or, sh:pattern, sh:property, sh:qualifiedMaxCount, sh:qualifiedMinCount, sh:qualifiedValueShape, + sh:qualifiedValueShape, sh:qualifiedValueShapesDisjoint, sh:qualifiedValueShapesDisjoint, sh:uniqueLang, sh:xone ; + + sh:targetObjectsOf sh:node ; # node-node + sh:targetObjectsOf sh:not ; # not-node + sh:targetObjectsOf sh:property ; # property-node + sh:targetObjectsOf sh:qualifiedValueShape ; # qualifiedValueShape-node + + # Shapes are either node shapes or property shapes + sh:xone ( shsh:NodeShapeShape shsh:PropertyShapeShape ) ; + + sh:property [ + sh:path sh:targetNode ; + sh:nodeKind sh:IRIOrLiteral ; # targetNode-nodeKind + ] ; + sh:property [ + sh:path sh:targetClass ; + sh:nodeKind sh:IRI ; # targetClass-nodeKind + ] ; + sh:property [ + sh:path sh:targetSubjectsOf ; + sh:nodeKind sh:IRI ; # targetSubjectsOf-nodeKind + ] ; + sh:property [ + sh:path sh:targetObjectsOf ; + sh:nodeKind sh:IRI ; # targetObjectsOf-nodeKind + ] ; + sh:or ( [ sh:not [ + sh:class rdfs:Class ; + sh:or ( [ sh:class sh:NodeShape ] [ sh:class sh:PropertyShape ] ) + ] ] + [ sh:nodeKind sh:IRI ] + ) ; # implicit-targetClass-nodeKind + + sh:property [ + sh:path sh:severity ; + sh:maxCount 1 ; # severity-maxCount + sh:nodeKind sh:IRI ; # severity-nodeKind + ] ; + sh:property [ + sh:path sh:message ; + sh:or ( [ sh:datatype xsd:string ] [ sh:datatype rdf:langString ] ) ; # message-datatype + ] ; + sh:property [ + sh:path sh:deactivated ; + sh:maxCount 1 ; # deactivated-maxCount + sh:in ( true false ) ; # deactivated-datatype + ] ; + + sh:property [ + sh:path sh:and ; + sh:node shsh:ListShape ; # and-node + ] ; + sh:property [ + sh:path sh:class ; + sh:nodeKind sh:IRI ; # class-nodeKind + ] ; + sh:property [ + sh:path sh:closed ; + sh:datatype xsd:boolean ; # closed-datatype + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path sh:ignoredProperties ; + sh:node shsh:ListShape ; # ignoredProperties-node + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path ( sh:ignoredProperties [ sh:zeroOrMorePath rdf:rest ] rdf:first ) ; + sh:nodeKind sh:IRI ; # ignoredProperties-members-nodeKind + ] ; + sh:property [ + sh:path sh:datatype ; + sh:nodeKind sh:IRI ; # datatype-nodeKind + sh:maxCount 1 ; # datatype-maxCount + ] ; + sh:property [ + sh:path sh:disjoint ; + sh:nodeKind sh:IRI ; # disjoint-nodeKind + ] ; + sh:property [ + sh:path sh:equals ; + sh:nodeKind sh:IRI ; # equals-nodeKind + ] ; + sh:property [ + sh:path sh:in ; + sh:maxCount 1 ; # in-maxCount + sh:node shsh:ListShape ; # in-node + ] ; + sh:property [ + sh:path sh:languageIn ; + sh:maxCount 1 ; # languageIn-maxCount + sh:node shsh:ListShape ; # languageIn-node + ] ; + sh:property [ + sh:path ( sh:languageIn [ sh:zeroOrMorePath rdf:rest ] rdf:first ) ; + sh:datatype xsd:string ; # languageIn-members-datatype + ] ; + sh:property [ + sh:path sh:lessThan ; + sh:nodeKind sh:IRI ; # lessThan-nodeKind + ] ; + sh:property [ + sh:path sh:lessThanOrEquals ; + sh:nodeKind sh:IRI ; # lessThanOrEquals-nodeKind + ] ; + sh:property [ + sh:path sh:maxCount ; + sh:datatype xsd:integer ; # maxCount-datatype + sh:maxCount 1 ; # maxCount-maxCount + ] ; + sh:property [ + sh:path sh:maxExclusive ; + sh:maxCount 1 ; # maxExclusive-maxCount + sh:nodeKind sh:Literal ; # maxExclusive-nodeKind + ] ; + sh:property [ + sh:path sh:maxInclusive ; + sh:maxCount 1 ; # maxInclusive-maxCount + sh:nodeKind sh:Literal ; # maxInclusive-nodeKind + ] ; + sh:property [ + sh:path sh:maxLength ; + sh:datatype xsd:integer ; # maxLength-datatype + sh:maxCount 1 ; # maxLength-maxCount + ] ; + sh:property [ + sh:path sh:minCount ; + sh:datatype xsd:integer ; # minCount-datatype + sh:maxCount 1 ; # minCount-maxCount + ] ; + sh:property [ + sh:path sh:minExclusive ; + sh:maxCount 1 ; # minExclusive-maxCount + sh:nodeKind sh:Literal ; # minExclusive-nodeKind + ] ; + sh:property [ + sh:path sh:minInclusive ; + sh:maxCount 1 ; # minInclusive-maxCount + sh:nodeKind sh:Literal ; # minInclusive-nodeKind + ] ; + sh:property [ + sh:path sh:minLength ; + sh:datatype xsd:integer ; # minLength-datatype + sh:maxCount 1 ; # minLength-maxCount + ] ; + sh:property [ + sh:path sh:nodeKind ; + sh:in ( sh:BlankNode sh:IRI sh:Literal sh:BlankNodeOrIRI sh:BlankNodeOrLiteral sh:IRIOrLiteral ) ; # nodeKind-in + sh:maxCount 1 ; # nodeKind-maxCount + ] ; + sh:property [ + sh:path sh:or ; + sh:node shsh:ListShape ; # or-node + ] ; + sh:property [ + sh:path sh:pattern ; + sh:datatype xsd:string ; # pattern-datatype + sh:maxCount 1 ; # multiple-parameters + # Not implemented: syntax rule pattern-regex + ] ; + sh:property [ + sh:path sh:flags ; + sh:datatype xsd:string ; # flags-datatype + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path sh:qualifiedMaxCount ; + sh:datatype xsd:integer ; # qualifiedMaxCount-datatype + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path sh:qualifiedMinCount ; + sh:datatype xsd:integer ; # qualifiedMinCount-datatype + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path sh:qualifiedValueShape ; + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path sh:qualifiedValueShapesDisjoint ; + sh:datatype xsd:boolean ; # qualifiedValueShapesDisjoint-datatype + sh:maxCount 1 ; # multiple-parameters + ] ; + sh:property [ + sh:path sh:uniqueLang ; + sh:datatype xsd:boolean ; # uniqueLang-datatype + sh:maxCount 1 ; # uniqueLang-maxCount + ] ; + sh:property [ + sh:path sh:xone ; + sh:node shsh:ListShape ; # xone-node + ] . + +shsh:NodeShapeShape + a sh:NodeShape ; + sh:targetObjectsOf sh:node ; # node-node + sh:property [ + sh:path sh:path ; + sh:maxCount 0 ; # NodeShape-path-maxCount + ] ; + sh:property [ + sh:path sh:lessThan ; + sh:maxCount 0 ; # lessThan-scope + ] ; + sh:property [ + sh:path sh:lessThanOrEquals ; + sh:maxCount 0 ; # lessThanOrEquals-scope + ] ; + sh:property [ + sh:path sh:maxCount ; + sh:maxCount 0 ; # maxCount-scope + ] ; + sh:property [ + sh:path sh:minCount ; + sh:maxCount 0 ; # minCount-scope + ] ; + sh:property [ + sh:path sh:qualifiedValueShape ; + sh:maxCount 0 ; # qualifiedValueShape-scope + ] ; + sh:property [ + sh:path sh:uniqueLang ; + sh:maxCount 0 ; # uniqueLang-scope + ] . + +shsh:PropertyShapeShape + a sh:NodeShape ; + sh:targetObjectsOf sh:property ; # property-node + sh:property [ + sh:path sh:path ; + sh:maxCount 1 ; # path-maxCount + sh:minCount 1 ; # PropertyShape-path-minCount + sh:node shsh:PathShape ; # path-node + ] . + +# Values of sh:and, sh:or and sh:xone must be lists of shapes +shsh:ShapesListShape + a sh:NodeShape ; + sh:targetObjectsOf sh:and ; # and-members-node + sh:targetObjectsOf sh:or ; # or-members-node + sh:targetObjectsOf sh:xone ; # xone-members-node + sh:property [ + sh:path ( [ sh:zeroOrMorePath rdf:rest ] rdf:first ) ; + sh:node shsh:ShapeShape ; + ] . + + +# A path of blank node path syntax, used to simulate recursion +_:PathPath + sh:alternativePath ( + ( [ sh:zeroOrMorePath rdf:rest ] rdf:first ) + ( sh:alternativePath [ sh:zeroOrMorePath rdf:rest ] rdf:first ) + sh:inversePath + sh:zeroOrMorePath + sh:oneOrMorePath + sh:zeroOrOnePath + ) . + +shsh:PathShape + a sh:NodeShape ; + rdfs:label "Path shape"@en ; + rdfs:comment "A shape that can be used to validate the syntax rules of well-formed SHACL paths."@en ; + rdfs:seeAlso ; + sh:property [ + sh:path [ sh:zeroOrMorePath _:PathPath ] ; + sh:node shsh:PathNodeShape ; + ] . + +shsh:PathNodeShape + sh:xone ( # path-metarule + [ sh:nodeKind sh:IRI ] # 2.3.1.1: Predicate path + [ sh:nodeKind sh:BlankNode ; # 2.3.1.2: Sequence path + sh:node shsh:PathListWithAtLeast2Members ; + ] + [ sh:nodeKind sh:BlankNode ; # 2.3.1.3: Alternative path + sh:closed true ; + sh:property [ + sh:path sh:alternativePath ; + sh:node shsh:PathListWithAtLeast2Members ; + sh:minCount 1 ; + sh:maxCount 1 ; + ] + ] + [ sh:nodeKind sh:BlankNode ; # 2.3.1.4: Inverse path + sh:closed true ; + sh:property [ + sh:path sh:inversePath ; + sh:minCount 1 ; + sh:maxCount 1 ; + ] + ] + [ sh:nodeKind sh:BlankNode ; # 2.3.1.5: Zero-or-more path + sh:closed true ; + sh:property [ + sh:path sh:zeroOrMorePath ; + sh:minCount 1 ; + sh:maxCount 1 ; + ] + ] + [ sh:nodeKind sh:BlankNode ; # 2.3.1.6: One-or-more path + sh:closed true ; + sh:property [ + sh:path sh:oneOrMorePath ; + sh:minCount 1 ; + sh:maxCount 1 ; + ] + ] + [ sh:nodeKind sh:BlankNode ; # 2.3.1.7: Zero-or-one path + sh:closed true ; + sh:property [ + sh:path sh:zeroOrOnePath ; + sh:minCount 1 ; + sh:maxCount 1 ; + ] + ] + ) . + +shsh:PathListWithAtLeast2Members + a sh:NodeShape ; + sh:node shsh:ListShape ; + sh:property [ + sh:path [ sh:oneOrMorePath rdf:rest ] ; + sh:minCount 2 ; # 1 other list node plus rdf:nil + ] . + +shsh:ShapesGraphShape + a sh:NodeShape ; + sh:targetObjectsOf sh:shapesGraph ; + sh:nodeKind sh:IRI . # shapesGraph-nodeKind + +shsh:EntailmentShape + a sh:NodeShape ; + sh:targetObjectsOf sh:entailment ; + sh:nodeKind sh:IRI . # entailment-nodeKind + diff --git a/shapes/tests.py b/shapes/tests.py new file mode 100755 index 0000000..91dfdde --- /dev/null +++ b/shapes/tests.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# (c) Dylan Van Assche (2020 - 2023) +# IDLab - Ghent University - imec +# MIT license +# + +import os +import argparse +import unittest +import logging +from parameterized import parameterized +from glob import glob +from rdflib import Graph + +from mapping_validator import MappingValidator + +TEST_CASES_DIR = os.path.join(os.path.abspath('../test-cases'), + '*/mapping.ttl') +CC_SHAPE_FILE = os.path.abspath('cc.ttl') +SHACL_SHAPE_FILE = os.path.abspath('shacl.ttl') + + +class MappingValidatorTests(unittest.TestCase): + def _validate_rules(self, path: str) -> None: + rules = Graph().parse(path, format='turtle') + mapping_validator = MappingValidator(CC_SHAPE_FILE) + mapping_validator.validate(rules) + + def _validate_shapes(self, path: str) -> None: + rules = Graph().parse(path, format='turtle') + mapping_validator = MappingValidator(SHACL_SHAPE_FILE) + mapping_validator.validate(rules) + + def test_non_existing_mapping_rules(self) -> None: + with self.assertRaises(FileNotFoundError): + p = os.path.abspath('does_not_exist.ttl') + self._validate_rules(p) + + @parameterized.expand([(p,) for p in sorted(glob(TEST_CASES_DIR))], + skip_on_empty=True) + def test_validation_rules(self, path: str) -> None: + """ + Test if our SHACL shapes are able to validate our validation mapping + rules test cases. + """ + print(f'Testing validation with: {path}') + self._validate_rules(path) + + def test_validation_shapes(self) -> None: + """ + Test if our SHACL shapes are valid according to the W3C Recommdendation + of SHACL. Validation with the official SHACL shapes for SHACL. + + See https://www.w3.org/TR/shacl/#shacl-shacl + """ + path = './cc.ttl' + print(f'Testing shape with: {path}') + self._validate_shapes(path) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Execute tests for SHACL ' + 'shapes on RML mapping rules.') + parser.add_argument('--verbose', '-v', action='count', default=1, + help='Set verbosity level of messages. Example: -vvv') + args = parser.parse_args() + + args.verbose = 70 - (10 * args.verbose) if args.verbose > 0 else 0 + logging.basicConfig(level=args.verbose, + format='%(asctime)s %(levelname)s: %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + + print(TEST_CASES_DIR) + unittest.main(failfast=True) + From 24bc41f8114d4f8a6b8e0ea00ef1f182438346ec Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Fri, 28 Apr 2023 11:56:21 +0200 Subject: [PATCH 3/7] shapes: Strategy was moved to Core --- shapes/cc.ttl | 4 +++- shapes/external_shapes.ttl | 4 ++++ shapes/gather_map.ttl | 4 ++-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/shapes/cc.ttl b/shapes/cc.ttl index 31db232..6a0de6c 100644 --- a/shapes/cc.ttl +++ b/shapes/cc.ttl @@ -34,13 +34,13 @@ rml:strategy specifies the collection strategy to use: rml:append or rml:catessianProduct. rml:append is the default strategy. """ ; - sh:in ( rml:append rml:cartessian ) ; sh:maxCount 1 ; sh:message """ Zero or one rml:strategy is required. """ ; sh:minCount 0 ; sh:name "strategy" ; + sh:node ; sh:nodeKind sh:IRI ; sh:path rml:strategy ] [ sh:description """ rml:gatherAs specifies how to gather the collection e.g. a rdf:Alt, @@ -91,5 +91,7 @@ a sh:NodeShape . + a sh:NodeShape . + a sh:NodeShape . diff --git a/shapes/external_shapes.ttl b/shapes/external_shapes.ttl index 98f45a2..86affde 100644 --- a/shapes/external_shapes.ttl +++ b/shapes/external_shapes.ttl @@ -18,3 +18,7 @@ schema:RMLTermMapShape schema:RMLLogicalTargetPropertiesShape a sh:NodeShape; . + +schema:RMLStrategyAppendShape + a sh:NodeShape; +. diff --git a/shapes/gather_map.ttl b/shapes/gather_map.ttl index b1744d2..5093920 100644 --- a/shapes/gather_map.ttl +++ b/shapes/gather_map.ttl @@ -34,8 +34,8 @@ schema:RMLGatherMapShape sh:message """ Zero or one rml:strategy is required. """ ; - sh:in (rml:append rml:cartessian) ; - sh:nodeKind sh:IRI; + sh:node schema:RMLStrategyAppendShape ; + sh:nodeKind sh:IRI ; sh:minCount 0 ; sh:maxCount 1 ; ] From 1fcb43b15e6eb774df5e09bd2b9d57113d574227 Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Wed, 3 May 2023 11:45:59 +0200 Subject: [PATCH 4/7] shapes: use dedicated IRI http://schema.org/ is not a good IRI for shapes --- shapes/cc.ttl | 14 +++++++------- shapes/external_shapes.ttl | 8 ++++---- shapes/gather_map.ttl | 10 +++++----- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/shapes/cc.ttl b/shapes/cc.ttl index 6a0de6c..b4ec400 100644 --- a/shapes/cc.ttl +++ b/shapes/cc.ttl @@ -17,7 +17,7 @@ @prefix rdf: . @prefix rdfs: . @prefix rml: . -@prefix schema: . +@prefix : . @prefix sh: . @prefix skos: . @prefix sosa: . @@ -29,8 +29,8 @@ @prefix xml: . @prefix xsd: . - a sh:NodeShape ; - sh:and ( [ sh:description """ + a sh:NodeShape ; + sh:and ( [ sh:description """ rml:strategy specifies the collection strategy to use: rml:append or rml:catessianProduct. rml:append is the default strategy. """ ; @@ -40,7 +40,7 @@ """ ; sh:minCount 0 ; sh:name "strategy" ; - sh:node ; + sh:node ; sh:nodeKind sh:IRI ; sh:path rml:strategy ] [ sh:description """ rml:gatherAs specifies how to gather the collection e.g. a rdf:Alt, @@ -89,9 +89,9 @@ """ ; sh:name "GatherMap" . - a sh:NodeShape . + a sh:NodeShape . - a sh:NodeShape . + a sh:NodeShape . - a sh:NodeShape . + a sh:NodeShape . diff --git a/shapes/external_shapes.ttl b/shapes/external_shapes.ttl index 86affde..79e8304 100644 --- a/shapes/external_shapes.ttl +++ b/shapes/external_shapes.ttl @@ -3,7 +3,7 @@ # Copyright Dylan Van Assche, IDLab - UGent - imec (2023) # ############################################################################### @prefix sh: . -@prefix schema: . +@prefix : . @prefix rdf: . @prefix rml: . @prefix xsd: . @@ -11,14 +11,14 @@ # Shapes are defined in the corresponding repositories of each specification # Provide their IRI as stub to allow validation in CC. -schema:RMLTermMapShape +:RMLTermMapShape a sh:NodeShape; . -schema:RMLLogicalTargetPropertiesShape +:RMLLogicalTargetPropertiesShape a sh:NodeShape; . -schema:RMLStrategyAppendShape +:RMLStrategyAppendShape a sh:NodeShape; . diff --git a/shapes/gather_map.ttl b/shapes/gather_map.ttl index 5093920..a0f960a 100644 --- a/shapes/gather_map.ttl +++ b/shapes/gather_map.ttl @@ -3,12 +3,12 @@ # Copyright Dylan Van Assche, IDLab - UGent - imec (2023) # ############################################################################### @prefix sh: . -@prefix schema: . +@prefix : . @prefix rdf: . @prefix rml: . @prefix xsd: . -schema:RMLGatherMapShape +:RMLGatherMapShape a sh:NodeShape ; sh:name "GatherMap" ; sh:description """ @@ -21,8 +21,8 @@ schema:RMLGatherMapShape sh:and ( # Inherited shapes - schema:RMLTermMapShape - schema:RMLLogicalTargetPropertiesShape + :RMLTermMapShape + :RMLLogicalTargetPropertiesShape # Gather Map specific shapes [ sh:path rml:strategy ; @@ -34,7 +34,7 @@ schema:RMLGatherMapShape sh:message """ Zero or one rml:strategy is required. """ ; - sh:node schema:RMLStrategyAppendShape ; + sh:node :RMLStrategyAppendShape ; sh:nodeKind sh:IRI ; sh:minCount 0 ; sh:maxCount 1 ; From 73cc2843f42821a5f86ab2e5b33f99142e0c0010 Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Mon, 8 May 2023 15:36:57 +0200 Subject: [PATCH 5/7] LICENSE: add CC-BY-4.0 license --- LICENSE | 397 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 14 +- 2 files changed, 410 insertions(+), 1 deletion(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8050a3b --- /dev/null +++ b/LICENSE @@ -0,0 +1,397 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + + diff --git a/README.md b/README.md index 9a05cd1..99ca5e5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# Collections and Containers in RML specification +# RML-CC + +Collections and Containers in RML specification ## Specification @@ -19,3 +21,13 @@ It is accessible using URL https://w3id.org/rml/cc/spec. - Run `node publish.js` to get the `index.html` + archived version in the [`docs`](docs) folder URL https://w3id.org/rml/cc/spec must redirect to the `/spec/docs`(docs) folder. + +## License + +RML-CC (c) by W3C Community Group on Knowledge Graph Construction + +RML-CC is licensed under a +Creative Commons Attribution-ShareAlike 4.0 International License. + +You should have received a copy of the license along with this +work. If not, see . From 9d8519295eb55ad7d811507305dd82c464717334 Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Tue, 9 May 2023 11:28:32 +0200 Subject: [PATCH 6/7] README: add W3ID links --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 99ca5e5..01bc113 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,11 @@ # RML-CC -Collections and Containers in RML specification +Collections and Containers in RML specification, SHACL shapes, ontology, and test-cases. + +- Specification: http://w3id.org/rml/cc/spec +- Ontology: http://w3id.org/rml/cc/ +- SHACL shapes: http://w3id.org/rml/cc/shapes +- Test-cases: [test-cases](./test-cases) ## Specification From 9253c25666f9337e006d2d3bf276887b5266202c Mon Sep 17 00:00:00 2001 From: Dylan Van Assche Date: Tue, 9 May 2023 13:35:45 +0200 Subject: [PATCH 7/7] spec: add conformance section Clean up status as well --- spec/dev.html | 3 +- spec/docs/20230509/index.html | 1155 +++++++++++++++++++++++++++++++++ spec/docs/index.html | 122 ++-- spec/rendered.html | 114 ++-- spec/section/status.md | 5 - 5 files changed, 1293 insertions(+), 106 deletions(-) create mode 100644 spec/docs/20230509/index.html delete mode 100644 spec/section/status.md diff --git a/spec/dev.html b/spec/dev.html index bd20a9a..eb0f3b2 100644 --- a/spec/dev.html +++ b/spec/dev.html @@ -190,7 +190,8 @@
-
+
+
diff --git a/spec/docs/20230509/index.html b/spec/docs/20230509/index.html new file mode 100644 index 0000000..9d5dcb8 --- /dev/null +++ b/spec/docs/20230509/index.html @@ -0,0 +1,1155 @@ + + + + + + +RML-CC: Collections and Containers in RML + + + + + + + + + + + + + + + + +
+ +

RML-CC: Collections and Containers in RML

+

+ Draft Community Group Report + +

+
+ +
Latest published version:
+ none +
+
Latest editor's draft:
https://w3id.org/rml/cc/spec
+ + + + +
Editors:
+ Christophe Debruyne (Montefiore Institute, University of Liège) +
+ Franck Michel (Université Côte d'Azur, CNRS, Inria) +
+ + + +
+ + +
+
+

Abstract

This document describes the [RML] vocabulary and approach to generating RDF containers and collections [RDF11-Concepts].

+
+ +

Status of This Document

+ This specification was published by the + Knowledge Graph Construction Community Group. It is not a W3C Standard nor is it + on the W3C Standards Track. + + Please note that under the + W3C Community Contributor License Agreement (CLA) + there is a limited opt-out and other conditions apply. + + Learn more about + W3C Community and Business Groups. +

+

1. Conformance

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 words MAY, MUST, and SHOULD in this document + are to be interpreted as described in + BCP 14 + [RFC2119] [RFC8174] + when, and only when, they appear in all capitals, as shown here. +

+ +

2. Overview

This section is non-normative.

+

The RDF Mapping Language (RML) [RML] is a language for expressing mappings between heterogeneous data and RDF. In RML, rules can be expressed to iterate over a data source and refer to specific data within an iteration. Using these iterators and references, RML rules define how to express data in the data source in RDF. RML is based on and extends R2RML [R2RML]. R2RML is defined to express customized mappings only from relational databases to RDF datasets.

+

This document describes RML-CC: +an extension of RML that enables the generation of RDF collections and containers with RML.

+

2.1 Conformance

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 words MUST and SHOULD in this document are to be interpreted as +described in BCP 14 [RFC2119] [RFC8174] when, +and only when, they appear in all capitals, as shown here.

+

2.2 Document conventions

We assume readers have basic familiarity with RDF and RML.

+

In this document, examples assume +the following namespace prefix bindings unless otherwise stated:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
PrefixNamespace
rml:http://w3id.org/rml/
rr:http://www.w3.org/ns/r2rml#
xsd:http://www.w3.org/2001/XMLSchema#
ex:http://example.org/
:http://example.org/
+

The examples are contained in color-coded boxes. We use the Turtle syntax [Turtle] to write RDF.

+
# This box contains an example input
+ +
# This box contains an example mapping
+ +
# This box contains the example output
+ +

3. Definitions

3.1 Iterations

In the course of this document, term "iteration" is used to refer to the iterations that stem from the logical source when processing the input documents. +An iteration results from the input data (documents, records returned by a query to a database etc.) on which the logical source may apply an optional rml:iterator.

+

In the running example, the data source consists of a single document, the iterator then extracts each of the three sub-documents within the array, thus the logical source yields three iterations.

+

3.2 Multi-valued term map

A multi-valued term map is a term map that, during a single iteration, may yield multiple RDF terms or multiple collections or containers in the case of a gather map.

+

3.3 Named collection or container

A named collection or container is a collection or container whose head node is assigned either an IRI or a blank node identifier.

+

3.4 Well-formed vs. ill-formed collections and containers

There is an important difference between valid RDF and well-formed containers and collections. The following RDF is valid, though the collection is ill-formed since the first cons-pair has two rdf:first and two rdf:rest properties:

+
ex:illformedList 
+  rdf:first 1 ; rdf:rest (2, 3) ;
+  rdf:first 4 ; rdf:rest (5, 6) .
+ +

Similarly, an ill-formed container would have multiple times the same rdf:_n property, e.g.:

+
ex:illformedContainer rdf:_1 1 ; rdf:_2 2 ; rdf:_3 3 ; rdf:_1 4 .
+ +

An RML collection and container validator (RMLCCV) is a system that checks for the well-formedness of collections and containers. The RMLCCV MUST report on any ill-formed collections and containers that are raised in the RDF generation process. An RML processor may include an RMLCCV, but this is not required.

+
+ +

4. Presentation and Example (Informative)

This section gives a brief overview of the RML mapping language. +It also provides simple examples of the generation of RDF collections and containers from JSON documents.

+

Herebelow we present the three main constructs for generating collections and containers. Other predicates, and their use in examples, will be explained further down this document.

+

An rml:GatherMap is a term map that generates a collection (rdf:List) or container (rdf:Bag, rdf:Seq, rdf:Alt). +A gather map has a list of term maps that inform the RML processor which RDF terms have to be generated as members of the list or container. +The rml:gather predicate is used to link an instance of rml:GatherMap with a list of term maps. The generation of a collection or container depends on the rml:gatherAs predicate, which may take any of the following values: rdf:List, rdf:Bag, rdf:Seq, and rdf:Alt.

+

The figure below illustrates the GatherMap and its relationships with other entities of the RML model.

+
+ Graphical overview of RML's vocabulary to generate RDF collections and containers. +
Figure 1 Graphical overview of RML's vocabulary to generate RDF collections and containers.
+
+ + +

4.1 Running example

In this section, the data source consists of a JSON file, data.json, containing the following JSON array:

+
[ 
+  { "id": "a",  "values": [ "1" , "2" , "3" ] },
+  { "id": "b",  "values": [ "4" , "5" , "6" ] },
+  { "id": "c",  "values": [ "7" , "8" , "9" ] } 
+]
+ +

The associated RML mapping starts as follows:

+
@prefix rml: .
+@prefix rr:  .
+@prefix ql:  .
+@prefix ex:  .
+@base        .
+
+<#TM> a rr:TriplesMap;
+  rml:logicalSource [
+    rml:source "data.json" ;
+    rml:referenceFormulation ql:JSONPath ;
+    rml:iterator "$.*" ;
+  ];
+
+  rr:subjectMap [
+    rr:template "{id}" ;
+  ] ;
+.
+
+ +

Note that the rml:iterator in the logical source will yield three iterations, each one providing one of the three sub-documents of the JSON array:

+
{ "id": "a",  "values": [ "1" , "2" , "3" ] }
+{ "id": "b",  "values": [ "4" , "5" , "6" ] }
+{ "id": "c",  "values": [ "7" , "8" , "9" ] }
+ + +

4.2 A simple example

Given the JSON document and the RML mapping completed with the following predicate object map:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

In this example, each iteration yields a new (unique) blank node that is the head of the collection being produced. +The following output will be produced:

+
:a ex:with ("1" "2" "3") .
+:b ex:with ("4" "5" "6") .
+:c ex:with ("7" "8" "9") .
+ + +

4.3 Collections and containers identified with an IRI or blank node ID

+

In the previous example, the gather map does not contain any rr:template, rr:constant or rml:reference property. +By contrast, the example below identifies the collection with a rr:template property. The IRI generated by the template will be assigned to the head node of the collection. We refer to this as a named collection.

+

The following mapping:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rr:template "list/{id}" ;
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

will yield the following output:

+
:a ex:with :list/a . :list/a rdf:first "1" ; rdf:rest ("2" "3") .
+:b ex:with :list/b . :list/b rdf:first "4" ; rdf:rest ("5" "6") .
+:c ex:with :list/c . :list/c rdf:first "7" ; rdf:rest ("8" "9") .
+ +

This is similar to the previous example, yet in this case the head node of each produced collection is assigned an IRI :list/a, :list/b and :list/c.

+
+ +

5. Vocabulary definition

This section introduces the classes, properties, and constants of the RML Containers and Collections specification.

+

5.1 Classes

+

5.1.1 rml:GatherMap

Gather maps are term maps that use rml:gather and rml:gatherAs to generate collections and containers from a list of term maps.

+
    +
  • A rml:GatherMap MUST have exactly one rml:gather property.
  • +
  • A rml:GatherMap MUST have exactly one rml:gatherAs property.
  • +
  • A rml:GatherMap MAY have zero or exactly one rml:strategy property.
  • +
+

5.2 Properties

+

5.2.1 rml:gather

+

The rml:gather informs the RML processor where the terms of a collection or container come from. This property relates a gather map with a non-empty list of term maps. +That list of term maps may contain other gather maps thus generating nested containers and/or collections.

+
    +
  • The domain of rml:gather is rml:GatherMap.
  • +
  • The range of rml:gather is a non-empty list (rdf:List) of rr:TermMap instances. In particular, this list may include instances of rml:GatherMap thus allowing for nested gather maps.
  • +
+

5.2.2 rml:strategy

+

Declaring an rml:strategy in a gather map informs the processor about how to create collections and containers when faced with multi-valued term maps. +This specification defines rml:append and rml:cartesianProduct as instances of rml:Strategy.

+

In the rml:append strategy, the sets of RDF terms generated by each term map of the gather map are simply appended to the collection (respectively container) being constructed. Thus, only one collection (respectively container) is generated.

+

Conversely, in the rml:cartesianProduct strategy, the gather map generates collections (respectively containers) each containing one RDF term generated by each term map of the gather map. In other words, it carries out a cartesian product between the terms generated by each term map, thus constructing as many collections (respectively containers) as the product of the number of RDF terms from each term map.

+

A gather map does not need to specify a strategy, the default strategy is rml:append.

+

5.2.3 rml:gatherAs

+

The property rml:gatherAs relates a gather map with the desired result type: a type of container or collections.

+
    +
  • The domain of rml:gatherAs is rml:GatherMap.
  • +
  • The range of rml:gatherAs is one of the following: rdf:Seq, rdf:Bag, rdf:Alt, rdf:List.
  • +
+

5.2.4 rml:allowEmptyListAndContainer

+

This predicate is to be used alongside rml:gather and rml:gatherAs. It specifies the behavior of a gather map in case the rml:gather does not yield any element.

+

The range of rml:allowEmptyListAndContainer is xsd:boolean. +When true, the gather map will generate rdf:nil for an RDF collection, or a resource with no members for an RDF container. +When false, the gather map will not generate a collection or container.

+
    +
  • The domain of rml:allowEmptyListAndContainer is rml:GatherMap.
  • +
  • The range of rml:allowEmptyListAndContainer is xsd:boolean.
  • +
+

Property rml:allowEmptyListAndContainer is optional, it takes the value false by default.

+

5.3 Constants

+

5.3.1 rml:append

+

rml:append is an instance of class rml:Strategy. +Used as the object of property rml:strategy, it informs the processor that the sets of RDF terms generated by each term map of the gather map are to be appended within the collection or container. The order is that in which the term maps are declared in the gather map. Example:

+

For the input document:

+
{ 
+  "a": [ "1" , "2" , "3" ],
+  "b": [ "4" , "5" ] 
+}
+ +

The following term map:

+
rr:objectMap [
+    rml:gather ( [ rml:reference "a.*" ] [ rml:reference "b.*" ]) ;
+    rml:gatherAs rdf:List ;
+    rml:strategy rml:append;   # this is the default strategy
+] ;
+ +

would generate a list by appending the terms produced by the two term maps in the gather map:

+
("1" "2" "3" "4" "5" )
+ + +

5.3.2 rml:cartesianProduct

+

rml:cartesianProduct is an instance of class rml:Strategy. +Used as the object of property rml:strategy, it informs the processor that the RDF terms generated by each term map of the gather map are to be grouped (in the constructed collection or container) by doing a cartesian product of these terms. +Therefore, this constructs as many collections or containers as the product of the number of terms from each term map. Example:

+

For the input document:

+
{ 
+  "a": [ "1" , "2" , "3" ],
+  "b": [ "4" , "5" ] 
+}
+ +

The following term map:

+
rr:objectMap [
+    rml:gather ( [ rml:reference "a.*" ] [ rml:reference "b.*" ]) ;
+    rml:gatherAs rdf:List ;
+    rml:strategy rml:cartesianProduct;
+] ;
+ +

would generate 3*2 = 6 lists by grouping the terms produced by the two term maps in the gather map:

+
("1" "4") ("1" "5") 
+("2" "4") ("2" "5")
+("3" "4") ("3" "5")
+ +

6. Considerations

6.1 The use of rr:column

+

In RML, rr:column is considered a subproperty of rml:reference. One can still avail of rr:column when creating mappings for relational databases. The use of rr:column is valid but one is encouraged to favor rml:reference.

+

6.2 Using a rml:GatherMap in various types of term map

+

Although most examples demonstrate the use of a gather map in the context of an object map, a gather map is a regular term map. +As such, it can be used in other types of term maps such as a subject or predicate map.

+

Term maps generate RDF terms (IRI, blank node, literal) to be used as the terms of RDF triples. +If such a term map generates a collection or container by means of a gather map, the term retained to form an RDF triple is the head node of the collection or container. +In the case of an RDF list, this is the node that is the subject of the first rdf:first predicate.

+

The examples section demonstrates how a gather map can be used within a subject map.

+

6.3 Named collection or container: assigning an IRI or blank node identifier to a collection and container

+

If a gather map does not contain any rr:template, rr:constant or rml:reference property, then the head node of each generated collection or container is a new blank node.

+

Conversely, if a gather map contains either a rr:template, rr:constant or rml:reference property, then the gather map yields named collections or containers whose head node is identified as instructed by the rr:template, rr:constant or rml:reference property.

+

The following mapping:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rr:template "seq/{id}" ;
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:Seq ;
+  ] ;
+] ;
+ +

will yield the following output:

+
:a ex:with :seq/a . :seq/a rdf:_1 "1" ; rdf:_2 "2" , rdf:_3 "3" .
+:b ex:with :seq/b . :seq/b rdf:_1 "4" ; rdf:_2 "5" , rdf:_3 "6" .
+:c ex:with :seq/c . :seq/c rdf:_1 "7" ; rdf:_2 "8" , rdf:_3 "9"  .
+ + +

6.4 Generating well-formed named collections or containers

+

When generating a named collection or container, it may happen that the same IRI or blank node identifier be generated several times, either across multiple iterations or because the gather map is multi-valued as exemplified with the rml:cartesianProduct strategy.

+

In this situation, to avoid generating ill-formed collections or containers, the processor MUST concatenate (i.e. append) the new collection or container to the previous one. +In other words, when a gather map creates a named collection or container, the processor must first check whether a named collection or container with the same head node IRI or blank node identifier already exists, and if so, it must append the terms to the existing one.

+

Below we exemplify two such situations.

+

6.4.1 Named collections or containers generated across multiple iterations

Here we reuse the running example yet with a slight variation: there are two JSON objects with the value "a" for "id".

+
[ 
+  { "id": "a",  "values": [ "1" , "2" , "3" ] },
+  { "id": "b",  "values": [ "4" , "5" , "6" ] },
+  { "id": "a",  "values": [ "7" , "8" , "9" ] } 
+]
+ +

Let's consider the following mapping:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

The gather map has no rr:template, rr:constant nor rml:reference property. The expected output consists of three lists, two related to :a and one to :b:

+
:a ex:with ("1" "2" "3"), ("7" "8" "9")  .
+:b ex:with ("4" "5" "6") .
+ +

Now, when an rr:template, rr:constant or rml:reference is provided, +the two collections related to id "a" cannot be generated separately since they would share the same head node IRI or bank node identifier, thus generating an ill-formed collection. Therefore, the processor must concatenate the two collections related to id "a". +With the following predicate mapping:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rr:template "list/{id}" ;
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

The processor must generate the following output:

+
:a ex:with :list/a . :list/a rdf:first "1" ; rdf:rest ("2" "3" "7" "8" "9") .
+:b ex:with :list/b . :list/b rdf:first "4" ; rdf:rest ("5" "6") .
+ +

It is assumed that a processor will concatenate the collections or containers while respecting the order of the iterations as provided by the logical source.

+

6.4.2 Named collections or containers generated by a multi-valued gather map

Let's consider the following input document:

+
{ 
+  "id": "myid",
+  "a": [ "1" , "2" , "3" ],
+  "b": [ "4" , "5" ] 
+}
+ +

and the following mapping:

+
rr:subjectMap [ rr:template "{id}" ] ;
+
+rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+    rml:gather ( [ rml:reference "a.*" ] [ rml:reference "b.*" ]) ;
+    rml:gatherAs rdf:List ;
+    rml:strategy rml:cartesianProduct ;
+  ] ;
+] ;
+ +

The gather map has no rr:template, rr:constant nor rml:reference property. +As already illustrated, the rml:cartesianProduct strategy will generate multiple collections, yielding the output:

+
:a ex:with ("1" "4"), ("1" "5"), ("2" "4"), ("2" "5"), ("3" "4"), ("3" "5") .
+ + +

Now, when an rr:template, rr:constant or rml:reference is provided, to avoid generating ill-formed lists that would share the same head node IRI, the processor must concatenate the lists.

+

If we add an rr:template in the object map:

+
rr:objectMap [
+  rr:template "list/{id}" ;
+  rml:gather ( [ rml:reference "a.*" ] [ rml:reference "b.*" ]) ;
+  rml:gatherAs rdf:List ;
+  rml:strategy rml:cartesianProduct ;
+] ;
+ +

The processor must now generate the following output:

+
:a ex:with ("1" "4" "1" "5" "2" "4" "2" "5" "3" "4" "3" "5" ).
+ + + +

6.4.3 Named collections or containers generated across multiple iterations and with a multi-valued term map

+

An even more tricky situation combines the two previous sections, involving at the same time multiple iterations and multi-valued gather maps.

+

Let's consider the following document and mapping:

+
[ 
+  { "id": "a",  "values1": [ "1" ],       "values2": [ "a" , "b" ] },
+  { "id": "b",  "values1": [ "3" , "4" ], "values2": [ "c" , "d" ] },
+  { "id": "a",  "values1": [ "5" , "6" ], "values2": [ "e" ] } 
+]
+ +
rml:logicalSource [
+  ...
+  rml:iterator "$.*" ;
+];
+
+rr:subjectMap [ rr:template "{id}" ] ;
+
+rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rr:template "list/{id}" ;
+      rml:gather ( [ rml:reference "values1.*" ; ] [ rml:reference "values2.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

For each document, the values of values1 and values2 are appended in the same list, as per the default rml:append strategy. +Furthermore, the lists generated for id "a" must be concatenated since they share the same head node IRI, as explained in the multiple iterations case. +The expected output is:

+
:a ex:with :list/a .
+:list/a rdf:first "1" ; rdf:rest ("a" "b" "5" "6" "e") .
+:b ex:with :list/b .
+:list/b rdf:first "3" ; rdf:rest ("4" "c" "d") .
+ +

Now let's change the default strategy to rml:cartesianProduct:

+
rr:objectMap [
+    rr:template "list/{id}" ;
+    rml:gather ( [ rml:reference "values1.*" ; ] [ rml:reference "values2.*" ; ] ) ;
+    rml:gatherAs rdf:List ;
+    rml:strategy rml:cartesianProduct ;
+] ;
+ +

Each iteration will now yield multiple lists by combining the values of values1 and values2.

+

For the document with id "b", there are ("3" "c") ("3" "d") ("4" "c") ("4" "d"). +But since the template generates the same IRI for all of them, they must be concatenated into a single list: ("3" "c" "3" "d" "4" "c" "4" "d"), as explained in the multi-valued gather map case.

+

Similarly, for the documents with id "a", the result is: ("1" "a" "1" "b") and ("5" "e" "6" "e"). +But again, these lists must be concatenated since they share the same head node IRI, as explained in the multiple iterations case.

+

Therefore, the processor must now generate the following output:

+
:a ex:with :list/a .
+:list/a rdf:first "1" ; rdf:rest ("a" "1" "b" "5" "e" "6" "e") .
+:b ex:with :list/b .
+:list/b rdf:first "3" ; rdf:rest ("c" "3" "d" "4" "c" "4" "d") .
+ +

7. Examples (Informative)

In this section, we present additional examples and describe the expected output.

+

7.1 Dealing with empty collections and containers

+

By default, rml:allowEmptyListAndContainer is false. +Thus, processing the following JSON document with the predicate object map provided in the running example would not yield any result for the document with "id": "d".

+
[ 
+  { "id": "a",  "values": [ "1" , "2" , "3" ] },
+  { "id": "b",  "values": [ "4" , "5" , "6" ] },
+  { "id": "c",  "values": [ "7" , "8" , "9" ] },
+  { "id": "d",  "values": [] } 
+]
+ +

However, when we override the value for this property and set it to true:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rml:allowEmptyListAndContainer true ;
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

the predicate object map will generate:

+
:a ex:with ("1" "2" "3") .
+:b ex:with ("4" "5" "6") .
+:c ex:with ("7" "8" "9") .
+:d ex:with () .
+ +

There is one special case when dealing with empty collections. Since rdf:nil is reserved for the empty list, an RML processor MUST replace each IRI or blank node that is an empty list with rdf:nil. +In other words, when the following predicate object map is used:

+
rr:predicateObjectMap [
+  rr:predicate ex:with ;
+  rr:objectMap [
+      rr:template "list/{id}" ;
+      rml:allowEmptyListAndContainer true ;
+      rml:gather ( [ rml:reference "values.*" ; ] ) ;
+      rml:gatherAs rdf:List ;
+  ] ;
+] ;
+ +

then the document with "id": "d" entails an empty list, that is a list whose head node is rdf:nil and therefore has no IRI. +We expect the following output where

+
:a ex:with :list/a .
+:list/a rdf:first "1" ; rdf:rest ("2" "3") .
+:b ex:with :list/b .
+:list/b rdf:first "4" ; rdf:rest ("5" "6") .
+:c ex:with :list/c .
+:list/c rdf:first "7" ; rdf:rest ("8" "9") .
+:d ex:with () .
+ + +

7.2 Relational data example

In this section, we use the following relational database and document for our example.

+

Table BOOK:

+ + + + + + + + + + + + + + + +
IDTITLE
1Frankenstein
2The Long Earth
+

Table AUTHOR:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IDTITLEFNAMELNAMEBOOKID
1MaryShelley1
2SirTerryPratchett2
3StephenBaxter2
4
+

The following mapping will relate instances of authors to names. The names of authors are, for the sake of the example, represented as bags containing a title, first name, and lastname.

+
<#AuthorTM>
+    rr:logicalTable [ rr:tableName "AUTHOR" ; ] ;
+    rr:subjectMap [ rr:template "/person/{ID}" ; ] ;
+    rr:predicateObjectMap [
+        rr:predicate ex:name ;
+        rr:objectMap [
+            rml:reference "ID" ; rr:termType rr:BlankNode ;
+            rml:gather ( 
+                [ rml:reference "TITLE" ]  [ rml:reference "FNAME" ]  [ rml:reference "LNAME" ] 
+            ) ;
+            rml:gatherAs rdf:Bag ;
+        ] ;
+    ] ;
+.
+ +

In this example we generate, for each row in table AUTHOR, an blank node of type rdf:Bag. Each such bag "gathers" values from different term maps. The execution of this mapping will produce the following result:

+
:person/1 ex:name [ a rdf:Bag; rdf:_1 "Mary"; rdf:_2 "Shelley" ] . 
+:person/2 ex:name [ a rdf:Bag; rdf:_1 "Sir"; rdf:_2 "Terry"; rdf:_3 "Pratchett" ] . 
+:person/3 ex:name [ a rdf:Bag; rdf:_1 "Stephen"; rdf:_2 "Baxter" ] .
+ +

While not shown in this example, different term maps allow to collect terms of different types: resources, literals, typed or language-tagged literals, etc. The fourth record in the table did not generate a bag, since each term map in the gather map did not yield a value. +By default, empty lists and containers are withheld. One does have the possibility to keep those with rml:allowEmptyListAndContainer`.

+

7.3 Using referencing object map

+

Continuing with the relational data example, here we relate books to authors with a rr:parentTriplesMap. The authors of a book are represented as a list.

+
<#BookTM>
+    rr:logicalTable [ rr:tableName "BOOK" ; ] ;
+    rr:subjectMap [ rr:template "/book/{ID}" ; ] ;
+    rr:predicateObjectMap [
+        rr:predicate ex:writtenBy ;
+        rr:objectMap [
+            rml:reference "ID" ; rr:termType rr:BlankNode ;
+            rml:gather ( 
+                [ 
+                    rr:parentTriplesMap <#AuthorTM>;
+                    rr:joinCondition [ rr:child "ID" ; rr:parent "BOOKID" ; ] ;
+                ] 
+            ) ;
+            rml:gatherAs rdf:List;
+        ] ;
+    ] ;
+.
+ +

Intuitively, we will join each record (or iteration) with data from the parent triples map. The join may yield one or more results, which are then gathered into a list. The execution of this mapping will produce the following RDF:

+
:book/1 ex:writtenby ( :person/1 ) . 
+:book/2 ex:writtenby ( :person/2 :person/3 ) .
+ +

In RML, it is assumed that each term map is multi-valued. That this, each term map may return one or more values. The default behavior is to append the values in the order of the term maps appearing in the gather map.

+

7.4 Using a gather map in a subject map

Here we exemplify the use of a term map in a subject map. Continuing with the JSON file from the running example, the following mapping generates an RDF sequence whose head node is used to state provenance information on that sequence:

+
<#TM> a rr:TriplesMap;
+  rml:logicalSource [
+    rml:source "data.json" ;
+    rml:referenceFormulation ql:JSONPath ;
+    rml:iterator "$.*" ;
+  ];
+
+  rr:subjectMap [
+    rr:template "seq/{id}" ;
+    rml:gather ( [ rml:reference "values.*" ; ] ) ;
+    rml:gatherAs rdf:Seq ;  
+  ] ;
+  
+  rr:predicateObjectMap [
+    rr:predicate prov:wasDerivedFrom ;
+    rr:object  ;
+  ] .
+
+ +

The expected result is:

+
  :seq/a rdf:_1 "1" ; rdf:_2 "2" ; rdf:_3 "3" .
+  :seq/a prov:wasDerivedFrom  .
+  
+  :seq/b rdf:_1 "4" ; rdf:_2 "5" ; rdf:_3 "6" .
+  :seq/b prov:wasDerivedFrom  .
+  
+  :seq/c rdf:_1 "7" ; rdf:_2 "8" ; rdf:_3 "9" .
+  :seq/c prov:wasDerivedFrom  .
+
+ + + +

A. References

A.1 Normative references

+ +
[R2RML]
+ R2RML: RDB to RDF Mapping Language. W3C. 27 September 2012. W3C Recommendation. URL: https://www.w3.org/TR/r2rml/ +
[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 +
[RML]
+ RDF Mapping Language. https://rml.io. 06 October 2020. Unofficial draft. URL: https://rml.io/specs/rml/ +
[Turtle]
+ RDF 1.1 Turtle. W3C. 25 February 2014. W3C Recommendation. URL: https://www.w3.org/TR/turtle/ +
+

A.2 Informative references

+ +
[RDF11-Concepts]
+ RDF 1.1 Concepts and Abstract Syntax. W3C. 25 February 2014. W3C Recommendation. URL: https://www.w3.org/TR/rdf11-concepts/ +
+
\ No newline at end of file diff --git a/spec/docs/index.html b/spec/docs/index.html index 6c7fc03..a7d3103 100644 --- a/spec/docs/index.html +++ b/spec/docs/index.html @@ -1,6 +1,6 @@ - + - +