Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions rdflib/plugins/serializers/nquads.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import warnings
from typing import IO, Any, Optional

from rdflib.graph import ConjunctiveGraph, Graph
from rdflib.graph import DATASET_DEFAULT_GRAPH_ID, ConjunctiveGraph, Graph
from rdflib.plugins.serializers.nt import _quoteLiteral
from rdflib.serializer import Serializer
from rdflib.term import Literal
Expand Down Expand Up @@ -45,17 +45,18 @@ def serialize(


def _nq_row(triple, context):
graph_name = context.n3() if context and context != DATASET_DEFAULT_GRAPH_ID else ""
if isinstance(triple[2], Literal):
return "%s %s %s %s .\n" % (
triple[0].n3(),
triple[1].n3(),
_quoteLiteral(triple[2]),
context.n3(),
graph_name,
)
else:
return "%s %s %s %s .\n" % (
triple[0].n3(),
triple[1].n3(),
triple[2].n3(),
context.n3(),
graph_name,
)
39 changes: 39 additions & 0 deletions test/test_serializers/test_nquads_default_graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from rdflib import Dataset
from rdflib.compare import isomorphic


def test_nquads_default_graph():
data = """
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

{
<urn:test> <http://www.w3.org/ns/prov#generatedAtTime> "2012-04-09"^^xsd:date .
}

<urn:test> {
<http://greggkellogg.net/foaf#me> a <http://xmlns.com/foaf/0.1/Person> ;
<http://xmlns.com/foaf/0.1/knows> "http://manu.sporny.org/about#manu" ;
<http://xmlns.com/foaf/0.1/name> "Gregg Kellogg" .

<http://manu.sporny.org/about#manu> a <http://xmlns.com/foaf/0.1/Person> ;
<http://xmlns.com/foaf/0.1/knows> "http://greggkellogg.net/foaf#me" ;
<http://xmlns.com/foaf/0.1/name> "Manu Sporny" .
}
"""

ds = Dataset()
ds.parse(data=data, format="trig")
output = ds.serialize(format="nquads")

# The internal RDFLib default graph identifier should not appear in the output.
assert "<urn:x-rdflib:default>" not in output

# Ensure dataset round-trip still works.
ds2 = Dataset()
ds2.parse(data=output, format="nquads")
for graph in ds.graphs():
assert isomorphic(graph, ds2.graph(graph.identifier)), print(
f"{graph.identifier} not isomorphic"
)
Loading