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
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.arcadedb.exception.CommandExecutionException;
import com.arcadedb.exception.SchemaException;
import com.arcadedb.exception.TimeoutException;
import com.arcadedb.exception.TypeMismatchException;
import com.arcadedb.graph.Edge;
import com.arcadedb.graph.GraphEngine;
import com.arcadedb.graph.MutableEdge;
Expand Down Expand Up @@ -335,22 +336,38 @@ private Vertex asVertex(Object currentFrom) {
rid = result.getProperty("rid");
if (rid != null)
currentFrom = rid;
else if (result.isElement())
// a record that is not a vertex: refused below by its RID and kind, not by the JSON of its whole content
currentFrom = result.getElement().get();
else
throw new CommandExecutionException("Invalid vertex for edge creation: " + result);
throw new TypeMismatchException("Invalid vertex for edge creation: " + result);
}
}

// An endpoint that is not a vertex is the caller's mistake: it is refused with a TypeMismatchException, a client error for
// every protocol, and a message of our own. Casting the record to a vertex raised a ClassCastException instead, which
// reached the client as a raw Java exception under an HTTP 500 (#12425)
if (currentFrom instanceof Vertex vertex)
return vertex;
else if (currentFrom instanceof Document document)
return document.asVertex();
else if (RID.is(currentFrom))
return getContext().getDatabase().newRID(currentFrom.toString()).asVertex();

throw new CommandExecutionException(
if (currentFrom instanceof Document document)
throw new TypeMismatchException(notAVertexMessage(document));

// A RID given as text, or as the @rid of a projection: the record it names is read and judged like any other endpoint, so
// a document is refused as the wrong kind of record and not answered as a record that does not exist
if (RID.is(currentFrom))
return asVertex(getContext().getDatabase().newRID(currentFrom.toString()).getRecord());

throw new TypeMismatchException(
"Invalid vertex for edge creation: " + (currentFrom == null ? "null" : currentFrom.toString()));
}

private static String notAVertexMessage(final Document document) {
final RID identity = document.getIdentity();
return "Invalid vertex for edge creation: the " + (document instanceof Edge ? "edge" : "document")
+ (identity != null ? " " + identity : "") + " is not a vertex";
}

@Override
public String prettyPrint(final int depth, final int indent) {
final String spaces = ExecutionStepInternal.getIndent(depth, indent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import com.arcadedb.database.Database;
import com.arcadedb.exception.CommandExecutionException;
import com.arcadedb.exception.CommandSQLParsingException;
import com.arcadedb.exception.SchemaException;
import com.arcadedb.graph.GraphTraversalProvider;
import com.arcadedb.graph.GraphTraversalProviderRegistry;
Expand Down Expand Up @@ -259,7 +260,7 @@ private void checkOrderByRecordAttributes() {
final String attribute = item.getRecordAttr();
if (attribute == null || isReturnedColumn(attribute))
continue;
throw new CommandExecutionException("ORDER BY " + attribute
throw new CommandSQLParsingException("ORDER BY " + attribute
+ " has no meaning on the rows of this MATCH: its RETURN builds new rows out of the matched aliases, which have no "
+ attribute + " of their own. Order by <alias>." + attribute + " or by a column of the RETURN instead, for example "
+ "RETURN a." + attribute + " AS key ... ORDER BY key");
Expand Down
8 changes: 4 additions & 4 deletions engine/src/main/java/com/arcadedb/query/sql/parser/Rid.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

import com.arcadedb.database.Identifiable;
import com.arcadedb.database.RID;
import com.arcadedb.exception.CommandExecutionException;
import com.arcadedb.exception.TypeMismatchException;
import com.arcadedb.query.sql.executor.CommandContext;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.utility.CodeUtils;
Expand Down Expand Up @@ -93,19 +93,19 @@ private static RID toRecordId(final Object result, final CommandContext context)

if (result instanceof String string) {
if (!(string.startsWith("#") && (string.contains(":"))))
throw new CommandExecutionException("Cannot convert to RID: " + result);
throw new TypeMismatchException("Cannot convert to RID: " + result);

final List<String> parts = CodeUtils.split(string.substring(1), ':', 3);
if (parts.size() != 2)
throw new CommandExecutionException("Cannot convert to RID: " + result);
throw new TypeMismatchException("Cannot convert to RID: " + result);

final int bucketId;
final long position;
try {
bucketId = Integer.parseInt(parts.getFirst());
position = Long.parseLong(parts.get(1));
} catch (final NumberFormatException e) {
throw new CommandExecutionException("Cannot convert to RID: " + result, e);
throw new TypeMismatchException("Cannot convert to RID: " + result, e);
}
return RID.create(context.getDatabase(), bucketId, position);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/*
* Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com)
* SPDX-License-Identifier: Apache-2.0
*/
package com.arcadedb.query.sql.executor;

import com.arcadedb.TestHelper;
import com.arcadedb.database.RID;
import com.arcadedb.exception.RecordNotFoundException;
import com.arcadedb.exception.TypeMismatchException;
import com.arcadedb.graph.MutableVertex;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
* Issue #12425: a graph statement refused for a mistake of the caller has to say so with a typed exception the servers
* answer as a client error (HTTP 400, Postgres 42804, Bolt VALIDATION), not with a plain {@code CommandExecutionException}
* (HTTP 500) and never with the raw {@link ClassCastException} of a record cast. A refused statement writes nothing.
*
* @author lvca (l.garulli@arcadedata.com)
*/
class Issue12425CallerMistakesInGraphStatementsTest extends TestHelper {
private RID vertexRid;
private RID otherVertexRid;
private RID documentRid;
private RID edgeRid;

@Test
void aDocumentRidLiteralAsAnEndpointIsRefusedAndNamed() {
createFixtures();

assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM " + documentRid + " TO " + vertexRid, "document", documentRid);
assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM " + vertexRid + " TO " + documentRid, "document", documentRid);
assertThat(linkCount()).isZero();
}

@Test
void aDocumentRidGivenAsAStringIsRefusedAndNamedNotAnsweredAsMissing() {
createFixtures();

// the record exists: a "record not found" would be a wrong answer, the endpoint is the wrong kind of record
assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM ? TO ?", "document", documentRid, documentRid.toString(),
vertexRid.toString());
assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM ? TO ?", "document", documentRid, vertexRid.toString(),
documentRid.toString());
assertThat(linkCount()).isZero();
}

@Test
void anEdgeAsAnEndpointIsRefusedAndNamed() {
createFixtures();

assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM " + edgeRid + " TO " + vertexRid, "edge", edgeRid);
assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM ? TO ?", "edge", edgeRid, vertexRid.toString(), edgeRid.toString());
assertThat(linkCount()).isZero();
}

@Test
void aQueryThatReturnsADocumentOrAnEdgeAsAnEndpointIsRefusedAndNamed() {
createFixtures();

assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT FROM Doc12425) TO (SELECT FROM V12425)", "document", documentRid);
assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT FROM V12425) TO (SELECT FROM Doc12425)", "document", documentRid);
assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT FROM Wire12425) TO (SELECT FROM V12425)", "edge", edgeRid);
assertThat(linkCount()).isZero();
}

@Test
void aProjectedRidOfADocumentIsRefusedAndNamed() {
createFixtures();

assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT @rid AS rid FROM Doc12425) TO (SELECT FROM V12425)", "document",
documentRid);
assertThat(linkCount()).isZero();
}

@Test
void aDocumentAmongSeveralEndpointsLeavesNoEdgeOfTheOnesBeforeIt() {
createFixtures();

// the endpoints are read one at a time: the edge to the first vertex is built before the document is reached, and the
// refused statement must not leave it behind once its transaction ends
database.begin();
try {
assertThatThrownBy(() -> drainCommand("CREATE EDGE Link12425 FROM " + vertexRid + " TO [" + otherVertexRid + ", " + documentRid + "]"))//
.isExactlyInstanceOf(TypeMismatchException.class)//
.hasMessageContaining("the document " + documentRid + " is not a vertex");
} finally {
database.rollback();
}

assertThat(linkCount()).isZero();
}

@Test
void anEndpointThatIsNotARecordAtAllIsRefused() {
createFixtures();

assertThatThrownBy(() -> inTransaction("CREATE EDGE Link12425 FROM ? TO ?", "nothing", vertexRid.toString()))//
.isExactlyInstanceOf(TypeMismatchException.class)//
.hasMessageContaining("Invalid vertex for edge creation: nothing");
assertThat(linkCount()).isZero();
}

@Test
void aRidThatNamesNothingIsStillRecordNotFound() {
createFixtures();

// not a mistake of the kind above: the RID is well-formed and the record is simply not there
assertThatThrownBy(
() -> inTransaction("CREATE EDGE Link12425 FROM ? TO ?", "#" + documentRid.getBucketId() + ":99999", vertexRid.toString()))//
.isInstanceOf(RecordNotFoundException.class);
assertThat(linkCount()).isZero();
}

@Test
void validEndpointsStillMakeTheEdge() {
createFixtures();

inTransaction("CREATE EDGE Link12425 FROM " + vertexRid + " TO " + otherVertexRid);
inTransaction("CREATE EDGE Link12425 FROM ? TO ?", otherVertexRid.toString(), vertexRid.toString());
inTransaction("CREATE EDGE Link12425 FROM (SELECT FROM V12425 WHERE k = 'a') TO (SELECT @rid FROM V12425 WHERE k = 'b')");

assertThat(linkCount()).isEqualTo(3L);
}

@ParameterizedTest
@ValueSource(strings = { "garbage", "#1", "#1:2:3", "#a:b", "#1:", "#:1" })
void aRidThatIsNotARidIsRefusedAsATypeMismatch(final String text) {
createFixtures();

assertThatThrownBy(() -> {
try (final ResultSet resultSet = database.query("sql", "MATCH {rid: '" + text + "', as: p} RETURN p")) {
while (resultSet.hasNext())
resultSet.next();
}
})//
.isExactlyInstanceOf(TypeMismatchException.class)//
.hasMessageContaining("Cannot convert to RID: " + text);
}

private void assertRefusedAsNotAVertex(final String sql, final String kind, final RID offender, final Object... parameters) {
assertThatThrownBy(() -> inTransaction(sql, parameters))//
.isExactlyInstanceOf(TypeMismatchException.class)//
.as("the refusal is a typed one, with no Java cast exception under it: %s", sql)//
.hasNoCause()//
.hasMessage("Invalid vertex for edge creation: the " + kind + " " + offender + " is not a vertex");
}

private void inTransaction(final String sql, final Object... parameters) {
database.transaction(() -> drainCommand(sql, parameters));
}

/** Runs the command to its end: the statements are lazy, and one that is not pulled does nothing. */
private void drainCommand(final String sql, final Object... parameters) {
try (final ResultSet resultSet = database.command("sql", sql, parameters)) {
while (resultSet.hasNext())
resultSet.next();
}
}

/** The count of the stored links, read by a scan: the counter {@code count(*)} answers from is not ground truth. */
private long linkCount() {
try (final ResultSet resultSet = database.query("sql", "SELECT count(@rid) AS n FROM Link12425")) {
return resultSet.next().<Number>getProperty("n").longValue();
}
}

private void createFixtures() {
database.getSchema().createVertexType("V12425");
database.getSchema().createEdgeType("Link12425");
database.getSchema().createEdgeType("Wire12425");
database.getSchema().createDocumentType("Doc12425");

database.transaction(() -> {
final MutableVertex a = database.newVertex("V12425").set("k", "a").save();
final MutableVertex b = database.newVertex("V12425").set("k", "b").save();
vertexRid = a.getIdentity();
otherVertexRid = b.getIdentity();
documentRid = database.newDocument("Doc12425").set("k", "d").save().getIdentity();
edgeRid = a.newEdge("Wire12425", b).getIdentity();
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.arcadedb.database.Identifiable;
import com.arcadedb.database.RID;
import com.arcadedb.exception.CommandExecutionException;
import com.arcadedb.exception.CommandSQLParsingException;
import com.arcadedb.exception.HeapLimitExceededException;
import com.arcadedb.exception.SchemaException;
import com.arcadedb.exception.TimeoutException;
Expand Down Expand Up @@ -492,7 +493,7 @@ void bareRidOnAProjectionIsRefused() {
for (final String direction : new String[] { "", " ASC", " DESC" })
assertThatThrownBy(() -> database.query("sql",
"MATCH {type:S, as:s}.out('R'){as:p} RETURN s.@rid AS srid, p.n AS pn ORDER BY @rid" + direction).close())//
.isInstanceOf(CommandExecutionException.class)//
.isInstanceOf(CommandSQLParsingException.class)//
.hasMessageContaining("ORDER BY @rid has no meaning on the rows of this MATCH")//
.hasMessageContaining("<alias>.@rid");
}
Expand All @@ -502,7 +503,7 @@ void bareRidOnAProjectionIsRefused() {
void bareTypeOnAProjectionIsRefused() {
orderByRecordAttributeGraph();
assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s} RETURN s.n AS n ORDER BY @type").close())//
.isInstanceOf(CommandExecutionException.class)//
.isInstanceOf(CommandSQLParsingException.class)//
.hasMessageContaining("ORDER BY @type has no meaning");
}

Expand All @@ -511,9 +512,9 @@ void bareTypeOnAProjectionIsRefused() {
void bareRidOnPathsAndPatternsIsRefused() {
orderByRecordAttributeGraph();
assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s}.out('R'){as:p} RETURN $paths ORDER BY @rid").close())//
.isInstanceOf(CommandExecutionException.class);
.isInstanceOf(CommandSQLParsingException.class);
assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s}.out('R'){as:p} RETURN $patterns ORDER BY @rid").close())//
.isInstanceOf(CommandExecutionException.class);
.isInstanceOf(CommandSQLParsingException.class);
}

/** Regression test for issue #9911. */
Expand Down
Loading
Loading