Skip to content

Commit 8fe1394

Browse files
authored
Fix SPARQLResultsTSVWriter to quote xsd:string literals (#5262)
2 parents 18f1bef + 089f326 commit 8fe1394

2 files changed

Lines changed: 25 additions & 11 deletions

File tree

core/queryresultio/text/src/main/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLResultsTSVWriter.java

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -194,21 +194,15 @@ private void writeLiteral(Literal lit) throws IOException {
194194
// Append the literal's language
195195
writer.write("@");
196196
writer.write(lit.getLanguage().get());
197-
} else if (!XSD.STRING.equals(datatype) || !xsdStringToPlainLiteral()) {
198-
writer.write("\"");
199-
writer.write(encoded);
200-
writer.write("\"");
201-
// Append the literal's datatype
202-
writer.write("^^");
203-
writeURI(datatype);
204-
} else if (!label.isEmpty() && encoded.equals(label) && label.charAt(0) != '<' && label.charAt(0) != '_'
205-
&& !label.matches("^[\\+\\-]?[\\d\\.].*")) {
206-
// no need to include double quotes
207-
writer.write(encoded);
208197
} else {
209198
writer.write("\"");
210199
writer.write(encoded);
211200
writer.write("\"");
201+
// Append the literal's datatype if it's not xsd:string or if xsdStringToPlainLiteral is false
202+
if (!XSD.STRING.equals(datatype) || !xsdStringToPlainLiteral()) {
203+
writer.write("^^");
204+
writeURI(datatype);
205+
}
212206
}
213207
}
214208

core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVCustomTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,26 @@ public void testSES2126QuotedLiteralIntegerAsStringImplicitType() throws Excepti
6969
assertEquals("?test\n\"1\"\n", result);
7070
}
7171

72+
@Test
73+
public void testQuotedXSDStringLiteral() throws Exception {
74+
List<String> bindingNames = List.of("test");
75+
TupleQueryResult tqr = new IteratingTupleQueryResult(bindingNames,
76+
List.of(new ListBindingSet(bindingNames,
77+
SimpleValueFactory.getInstance().createLiteral("example", XSD.STRING))));
78+
String result = writeTupleResult(tqr);
79+
assertEquals("?test\n\"example\"\n", result);
80+
}
81+
82+
@Test
83+
public void testQuotedXSDStringLiteralWithSpecialCharacters() throws Exception {
84+
List<String> bindingNames = List.of("test");
85+
TupleQueryResult tqr = new IteratingTupleQueryResult(bindingNames,
86+
List.of(new ListBindingSet(bindingNames, SimpleValueFactory.getInstance()
87+
.createLiteral("example\twith\nspecial\"characters", XSD.STRING))));
88+
String result = writeTupleResult(tqr);
89+
assertEquals("?test\n\"example\\twith\\nspecial\\\"characters\"\n", result);
90+
}
91+
7292
private String writeTupleResult(TupleQueryResult tqr)
7393
throws IOException, TupleQueryResultHandlerException, QueryEvaluationException {
7494
ByteArrayOutputStream output = new ByteArrayOutputStream();

0 commit comments

Comments
 (0)