diff --git a/engine/src/main/java/com/arcadedb/query/select/Select.java b/engine/src/main/java/com/arcadedb/query/select/Select.java index 8eac1a5e49c..6cf82cd184c 100644 --- a/engine/src/main/java/com/arcadedb/query/select/Select.java +++ b/engine/src/main/java/com/arcadedb/query/select/Select.java @@ -263,7 +263,20 @@ else if (parsedLeft instanceof String string && string.startsWith("#")) else throw new IllegalArgumentException("Unsupported value " + parsedLeft); - final SelectOperator parsedOperator = SelectOperator.byName(condition.getString(1)); + final String parsedOperatorName = condition.getString(1); + final SelectOperator parsedOperator = SelectOperator.byName(parsedOperatorName); + if (parsedOperator == null) + throw new IllegalArgumentException("Unsupported operator '" + parsedOperatorName + "' in condition " + condition); + + // #8059: 'not' IS UNARY - IT NEGATES ITS LEFT OPERAND AND ITS RIGHT IS ALWAYS null (SEE SelectOperator.not) - + // WHILE A JSON CONDITION IS BY CONSTRUCTION THE BINARY TRIPLE [left, operator, right]. THERE IS NO WELL-DEFINED + // READING OF 'X not Y', AND THE TREE THIS USED TO BUILD FOR IT WAS EXECUTED AS A NEGATION OF A LEFT OPERAND WITH + // A RIGHT OPERAND SILENTLY DROPPED. REFUSE IT HERE INSTEAD OF HANDING THE CALLER A QUIETLY WRONG RESULT SET: A + // NEGATION IS EXPRESSED WITH THE COMPLEMENTARY OPERATOR ('<>', 'is null', 'is not null', ...) + if (parsedOperator == SelectOperator.not) + throw new IllegalArgumentException( + "Operator 'not' is unary and cannot be used in a JSON condition, which is always [left, operator, right]. " + + "Use the complementary operator instead (for example '<>' for '=', 'is null' for 'is not null')"); if (parsedOperator.logicOperator) setLogic(parsedOperator); @@ -353,14 +366,27 @@ SelectWhereLeftBlock setLogic(final SelectOperator newLogicOperator) { lastTreeElement.getParent().setRight(newNode); lastTreeElement = newTreeElement; } else { - // OR+ OPERATOR + // OR+ OPERATOR: THE NEW OPERATOR DOES NOT BIND MORE TIGHTLY THAN THE ONE ALREADY THERE, SO THE CURRENT + // SUBTREE IS PUSHED DOWN AND BECOMES THE LEFT CHILD OF A NODE CARRYING THE NEW OPERATOR final SelectTreeNode currentParent = lastTreeElement.getParent(); + // #8047: READ THE GRANDPARENT *BEFORE* THE SelectTreeNode CONSTRUCTOR RE-PARENTS currentParent UNDER newNode. + // THE CONSTRUCTOR ALREADY DOES TWO OF THE THREE THINGS THIS BRANCH NEEDS - IT SETS currentParent.parent TO + // newNode AND, THROUGH SelectTreeNode.setParent, MOVES THE GRANDPARENT'S OWN CHILD POINTER OVER TO newNode - + // SO THE ONLY THING LEFT IS newNode'S UPWARD LINK. READING currentParent.getParent() *AFTER* THE CONSTRUCTOR + // HANDED BACK newNode ITSELF, SO THE CALL REDUCED TO newNode.setParent(newNode) AND INSTALLED A SELF-PARENT + // CYCLE. THAT CYCLE THEN DEFEATED THE *NEXT* RE-PARENTING - setParent REWIRES THE GRANDPARENT BY TESTING + // this.parent.left/right == this, AND ON A SELF-PARENTED NODE BOTH TESTS COMPARE THE NODE AGAINST ITS OWN + // CHILDREN AND FAIL - SO THE NEXT NODE, AND EVERYTHING APPENDED TO IT, DANGLED OFF THE TREE rootTreeElement + // REFERS TO AND THE EXECUTOR NEVER SAW IT. FROM THE FIFTH CONDITION ON, AN 'OR' FOLLOWED BY THREE OR MORE + // 'AND's SILENTLY DISCARDED EVERY REMAINING CONDITION AND THE QUERY RETURNED MORE ROWS THAN THE PREDICATE + // ALLOWS + final SelectTreeNode grandParent = currentParent.getParent(); currentParent.setRight(newTreeElement); final SelectTreeNode newNode = new SelectTreeNode(currentParent, newLogicOperator, null); if (rootTreeElement.equals(currentParent)) rootTreeElement = newNode; else - newNode.setParent(currentParent.getParent()); + newNode.setParent(grandParent); lastTreeElement = currentParent; } } diff --git a/engine/src/main/java/com/arcadedb/query/select/SelectExecutor.java b/engine/src/main/java/com/arcadedb/query/select/SelectExecutor.java index 5cfe12342e4..9abf480e9fd 100644 --- a/engine/src/main/java/com/arcadedb/query/select/SelectExecutor.java +++ b/engine/src/main/java/com/arcadedb/query/select/SelectExecutor.java @@ -687,27 +687,9 @@ private void filterWithIndexesFinalNode(final SelectTreeNode node, final List + * The union of the cursors {@link #filterWithIndexesFinalNode} builds is the ONLY candidate set the query ever + * evaluates ({@link #lookForIndexes} feeds it straight into {@link #buildIterator}), so a cursor is admissible + * only when every record that could satisfy the whole WHERE is guaranteed to be inside that union. Two ancestors + * can break that guarantee, and #8048 showed both were only checked one level up: + * + * A {@code run} ancestor (the synthetic root {@link Select#compile} adds) and an {@code and} ancestor impose no + * condition: an {@code and} narrows, so a cursor covering one conjunct is always a superset of the conjunction. + * + * @return {@code true} when no ancestor forbids the cursor + */ + private boolean isCursorSoundOnPath(final SelectTreeNode leaf) { + SelectTreeNode child = leaf; + for (SelectTreeNode ancestor = leaf.getParent(); ancestor != null; ancestor = ancestor.getParent()) { + if (ancestor.operator == SelectOperator.not) + return false; + + if (ancestor.operator == SelectOperator.or) { + // THE SIBLING IS THE CHILD THAT IS NOT THE ONE WE CAME UP THROUGH. A NON-node SIBLING (OR A MISSING ONE) + // CAN NEVER BE ANSWERED BY AN INDEX, SO IT DISQUALIFIES THIS BRANCH JUST AS AN UN-INDEXED ONE WOULD + final Object sibling = ancestor.right == child ? ancestor.left : ancestor.right; + if (!(sibling instanceof SelectTreeNode siblingNode) || !isTheNodeFullyIndexed(siblingNode)) + return false; + } + + child = ancestor; + } + return true; + } + /** * Considers a fully indexed node when both properties are indexed or only one with an AND operator. */ @@ -808,12 +834,22 @@ private boolean isTheNodeFullyIndexed(final SelectTreeNode node) { final boolean rightIsIndexed = isTheNodeFullyIndexed((SelectTreeNode) node.right); if (node.operator.equals(SelectOperator.and)) - // AND: ONE OR BOTH MEANS INDEXED + // AND: ONE OR BOTH MEANS INDEXED - THE CURSOR FOR EITHER CONJUNCT ALREADY CONTAINS EVERY RECORD SATISFYING + // THE CONJUNCTION, AND evaluateWhere() NARROWS IT DOWN return leftIsIndexed || rightIsIndexed; else if (node.operator.equals(SelectOperator.or)) - return leftIsIndexed || rightIsIndexed; + // #8048: OR NEEDS *BOTH*. THIS ARM USED TO CARRY THE SAME EXPRESSION AS THE and ARM ABOVE, WHOSE "ONE OR + // BOTH MEANS INDEXED" COMMENT IS THE RULE FOR AND ONLY. WITH ||, A COMPOSITE SIBLING LIKE (b = 1 or a = 2) + // REPORTED ITSELF FULLY INDEXED ON THE STRENGTH OF a = 2 ALONE, THE LEAF ON THE OTHER SIDE OF THE OUTER OR + // GOT ITS CURSOR, AND EVERY RECORD MATCHING b = 1 ONLY WAS NEVER EVEN LOOKED AT + return leftIsIndexed && rightIsIndexed; else if (node.operator.equals(SelectOperator.not)) - return leftIsIndexed; + // #8048/#8059: NEVER. A CURSOR UNDER A NEGATION IS THE SET OF RECORDS THE NEGATION REJECTS (#6575), SO + // filterWithIndexesFinalNode() REFUSES TO BUILD ONE FOR ANY LEAF BELOW A not - AND A BRANCH THAT CONTRIBUTES + // NO CURSOR IS EXACTLY WHAT AN or SIBLING MUST NOT BE TOLD IS "INDEXED". REPORTING leftIsIndexed HERE WAS + // THE #6577 DEFECT IN A DIFFERENT SHAPE: or(a = 1, not (b = 2)) DROPPED THE WHOLE NEGATED BRANCH. THE + // RECURSION ABOVE STILL RAN, SO THE LEAF UNDERNEATH KEEPS THE node.index SIDE EFFECT IT ALWAYS HAD + return false; } return false; } diff --git a/engine/src/main/java/com/arcadedb/query/select/SelectOperator.java b/engine/src/main/java/com/arcadedb/query/select/SelectOperator.java index f36743ed5a6..15adc7c8f62 100644 --- a/engine/src/main/java/com/arcadedb/query/select/SelectOperator.java +++ b/engine/src/main/java/com/arcadedb/query/select/SelectOperator.java @@ -55,10 +55,22 @@ Object eval(final Document record, final Object left, final Object right) { } }, + /** + * UNARY: NEGATES ITS LEFT OPERAND, {@code right} IS ALWAYS {@code null} (SEE + * {@code new SelectTreeNode(operand, SelectOperator.not, null)}, THE SHAPE EVERY IN-TREE USE BUILDS). + *

+ * #8059: THE BODY USED TO BE {@code left == Boolean.FALSE} - A REFERENCE COMPARISON AGAINST THE *UNEVALUATED* + * OPERAND, WHICH IN A REAL TREE IS A SelectTreeNode AND NEVER Boolean.FALSE, SO THE WHOLE EXPRESSION ANSWERED + * false FOR EVERY RECORD AND THE QUERY RETURNED NOTHING. EVERY OTHER OPERATOR ROUTES ITS OPERANDS THROUGH + * SelectExecutor.evaluateValue(); THIS ONE DID NOT. + */ not("not", true, 2) { @Override Object eval(final Document record, final Object left, final Object right) { - return left == Boolean.FALSE; + final Object leftValue = SelectExecutor.evaluateValue(record, left); + if (leftValue instanceof Boolean booleanValue) + return !booleanValue; + throw new IllegalArgumentException("A boolean operand was expected by 'not' but '" + leftValue + "' was returned"); } }, @@ -76,35 +88,66 @@ Object eval(final Document record, final Object left, final Object right) { } }, + /** + * #8049: AN ORDERING COMPARISON AGAINST A MISSING OR NULL OPERAND IS false, NEVER true. + *

+ * BinaryComparator.compareTo() IS A *SORT* ORDER AND SORTS null FIRST: compareTo(null, x) IS -1 AND + * compareTo(x, null) IS 1. READ AS A PREDICATE THAT MADE A RECORD WITHOUT THE PROPERTY SATISFY EVERY + * {@code < } AND {@code <=} ON IT, SO {@code a < 5} MATCHED RECORDS THAT CARRY NO {@code a} AT ALL - AND ONLY + * WHILE NO INDEX EXISTED ON {@code a}, BECAUSE AN INDEX HOLDS NO ENTRY FOR A RECORD THAT LACKS THE PROPERTY AND + * SelectExecutor.filterWithIndexesFinalNode() ANSWERS THE LEAF FROM A RANGE SCAN. THE SAME SELECT OVER THE SAME + * DATA THEREFORE RETURNED A DIFFERENT NUMBER OF ROWS DEPENDING ON THE PHYSICAL SCHEMA, WHICH IS THE ONE THING + * ADDING AN INDEX MUST NEVER DO. + *

+ * REJECTING null ON *EITHER* SIDE IS SQL'S OWN RULE (A COMPARISON WITH NULL IS UNKNOWN, AND UNKNOWN DOES NOT + * MATCH), IT IS WHAT {@code between} ALREADY DID ON ITS LEFT OPERAND, AND IT IS WHAT THE INDEX PATH DOES BY + * CONSTRUCTION - SO ALL FOUR DIRECTIONS, THE INDEX PLAN AND THE FULL SCAN NOW AGREE. USE {@code is null} / + * {@code is not null} TO ASK ABOUT ABSENCE. + */ lt("<", false, 1) { @Override Object eval(final Document record, final Object left, final Object right) { - return BinaryComparator.compareTo(SelectExecutor.evaluateValue(record, left), SelectExecutor.evaluateValue(record, right)) - < 0; + final Object leftValue = SelectExecutor.evaluateValue(record, left); + final Object rightValue = SelectExecutor.evaluateValue(record, right); + if (leftValue == null || rightValue == null) + return false; + return BinaryComparator.compareTo(leftValue, rightValue) < 0; } }, + /** #8049: see {@link #lt}. */ le("<=", false, 1) { @Override Object eval(final Document record, final Object left, final Object right) { - return BinaryComparator.compareTo(SelectExecutor.evaluateValue(record, left), SelectExecutor.evaluateValue(record, right)) - <= 0; + final Object leftValue = SelectExecutor.evaluateValue(record, left); + final Object rightValue = SelectExecutor.evaluateValue(record, right); + if (leftValue == null || rightValue == null) + return false; + return BinaryComparator.compareTo(leftValue, rightValue) <= 0; } }, + /** #8049: see {@link #lt}. A null LEFT was already rejected by the sort order; a null RIGHT was not. */ gt(">", false, 1) { @Override Object eval(final Document record, final Object left, final Object right) { - return BinaryComparator.compareTo(SelectExecutor.evaluateValue(record, left), SelectExecutor.evaluateValue(record, right)) - > 0; + final Object leftValue = SelectExecutor.evaluateValue(record, left); + final Object rightValue = SelectExecutor.evaluateValue(record, right); + if (leftValue == null || rightValue == null) + return false; + return BinaryComparator.compareTo(leftValue, rightValue) > 0; } }, + /** #8049: see {@link #lt} and {@link #gt}. */ ge(">=", false, 1) { @Override Object eval(final Document record, final Object left, final Object right) { - return BinaryComparator.compareTo(SelectExecutor.evaluateValue(record, left), SelectExecutor.evaluateValue(record, right)) - >= 0; + final Object leftValue = SelectExecutor.evaluateValue(record, left); + final Object rightValue = SelectExecutor.evaluateValue(record, right); + if (leftValue == null || rightValue == null) + return false; + return BinaryComparator.compareTo(leftValue, rightValue) >= 0; } }, @@ -149,8 +192,14 @@ Object eval(final Document record, final Object left, final Object right) { Object eval(final Document record, final Object left, final Object right) { final Object leftValue = SelectExecutor.evaluateValue(record, left); final Object rightValue = SelectExecutor.evaluateValue(record, right); - if (rightValue instanceof Object[] range && range.length == 2) + if (rightValue instanceof Object[] range && range.length == 2) { + // #8049: SAME RULE AS lt/le/gt/ge. THE LOWER-BOUND COMPARE ALREADY REJECTED A null LEFT FOR EVERY NON-null + // BOUND, SO THIS ONLY CLOSES THE "BOTH THE VALUE AND THE BOUND ARE null" CORNER, BUT IT MAKES THE RULE ONE + // RULE RATHER THAN AN ACCIDENT OF THE SORT ORDER + if (leftValue == null || range[0] == null || range[1] == null) + return false; return BinaryComparator.compareTo(leftValue, range[0]) >= 0 && BinaryComparator.compareTo(leftValue, range[1]) <= 0; + } throw new IllegalArgumentException("BETWEEN requires a range of two values"); } }, diff --git a/engine/src/main/java/com/arcadedb/query/select/SelectTreeNode.java b/engine/src/main/java/com/arcadedb/query/select/SelectTreeNode.java index ae04ba7f95e..9ae83dbb05f 100644 --- a/engine/src/main/java/com/arcadedb/query/select/SelectTreeNode.java +++ b/engine/src/main/java/com/arcadedb/query/select/SelectTreeNode.java @@ -66,6 +66,14 @@ public void setParent(final SelectTreeNode newParent) { if (this.parent == newParent) return; + // #8047: BELT AND BRACES. A SELF-PARENTED NODE IS NOT MERELY REDUNDANT, IT IS CORRUPTING: THE REWIRING BELOW + // TESTS this.parent.left/right == this, WHICH ON SUCH A NODE COMPARES IT AGAINST ITS OWN CHILDREN AND SILENTLY + // SKIPS THE GRANDPARENT UPDATE - THAT IS HOW Select.setLogic() LOST EVERY CONDITION AFTER THE FOURTH. IT ALSO + // MAKES ANY getParent() WALK NON-TERMINATING, WHICH SelectExecutor's OR/NOT ANCESTOR CHECK (#8048) NOW DOES. + // THE GUARD ON THE LINE ABOVE PROTECTS AGAINST setParent(this.parent), NOT AGAINST setParent(this) + if (newParent == this) + throw new IllegalArgumentException("A condition node cannot be its own parent"); + if (this.parent != null) { if (this.parent.left == this) { this.parent.left = newParent; diff --git a/engine/src/main/java/com/arcadedb/query/sql/parser/TruncateTypeStatement.java b/engine/src/main/java/com/arcadedb/query/sql/parser/TruncateTypeStatement.java index da7b7233189..8279cc5021f 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/parser/TruncateTypeStatement.java +++ b/engine/src/main/java/com/arcadedb/query/sql/parser/TruncateTypeStatement.java @@ -34,6 +34,7 @@ import com.arcadedb.schema.IndexMetadata; import com.arcadedb.schema.Schema; import com.arcadedb.schema.TypeIndexBuilder; +import com.arcadedb.schema.VertexType; import java.util.*; @@ -125,35 +126,74 @@ public ResultSet executeDDL(final CommandContext context) { final long recs = scopeHoldsLightweightEdges ? (unsafe ? 0 : countRecordsIncludingLightweightEdges(db, typeName.getStringValue())) : context.getDatabase().countType(typeName.getStringValue(), polymorphic); + // Asked of the TYPE, not of its NAME (issue #8042). This used to be typez.isSubTypeOf("V")/isSubTypeOf("E"), + // and LocalDocumentType.isSubTypeOf(String) matches by name - this type's own, then recursively its super + // types' - while ArcadeDB has no implicit root types called V and E: CREATE VERTEX TYPE Person builds a + // VertexType with an EMPTY super-type list (the V/E roots are an OrientDB inheritance, not an ArcadeDB one). + // So for every vertex and edge type a user actually creates both tests answered false, this block fell through + // with nothing to throw, and a plain TRUNCATE TYPE emptied a live type and detached every edge on + // it while the "Apply the 'UNSAFE' keyword" the message promises was never actually demanded. The sibling + // TruncateBucketStatement carries the identical guard with the identical wording and has always asked + // instanceof VertexType/EdgeType; DropTypeStatement, the third statement with an UNSAFE guard of this shape, + // asks getType() == Vertex.RECORD_TYPE - so TRUNCATE TYPE was the only one of the three asking by name. + // It also means the #7919 fix did not close what its own comment says it closes: that commit corrected the + // per-subtype COUNT below, and the check the count feeds was dead. Its regression test passed only because the + // hierarchy it builds hangs off a type it creates called `E`. if (recs > 0 && !unsafe) { - if (typez.isSubTypeOf("V")) { + if (typez instanceof VertexType) { throw new CommandExecutionException( "'TRUNCATE TYPE' command cannot be used on not empty vertex classes. Apply the 'UNSAFE' keyword to force it (at your own risk)"); - } else if (typez.isSubTypeOf("E")) { + } else if (typez instanceof EdgeType) { throw new CommandExecutionException( "'TRUNCATE TYPE' command cannot be used on not empty edge classes. Apply the 'UNSAFE' keyword to force it (at your own risk)"); } } final InternalResultSet rs = new InternalResultSet(); - final Collection subTypes = typez.getSubTypes(); - if (polymorphic && !unsafe) {// for multiple inheritance - for (final DocumentType subType : subTypes) { - // subType, not the root (issue #7919). This counted typeName on every iteration, so the loop never looked - // at a subtype at all: a polymorphic TRUNCATE of an EMPTY root with non-empty subtypes sailed past the - // check that exists to refuse it, and an empty subtype under a non-empty root was named as the reason for - // a refusal it had nothing to do with. Counted polymorphically so a non-empty grandchild is reported - // against the direct subtype it hangs from rather than escaping the loop, and through the count(*) - // push-down where the subtree holds lightweight edges, for the same reason the root's own count above does. - final long subTypeRecs = EdgeType.holdsLightweightEdges(subType) - ? countRecordsIncludingLightweightEdges(db, subType.getName()) - : context.getDatabase().countType(subType.getName(), true); - if (subTypeRecs > 0) { - if (subType.isSubTypeOf("V")) { - throw new CommandExecutionException("'TRUNCATE TYPE' command cannot be used on not empty vertex classes (" + subType.getName() + if (polymorphic && !unsafe) { + // EVERY DESCENDANT, NOT ONLY THE DIRECT ONES (found by CodeRabbit on PR #8094). getSubTypes() answers direct + // children, so a guard that walks one level down is blind to a graph type sitting behind a non-graph + // intermediate: for DocRoot -> DocMiddle -> VLeaf neither the root's own guard above nor a direct-children + // loop names a reason to refuse - DocRoot and DocMiddle are plain DocumentTypes - while the polymorphic + // scanType() below deletes VLeaf's records all the same. The scope of a POLYMORPHIC truncate is the whole + // subtree, so the guard has to read the whole subtree. The type that actually holds the records is the one + // named in the message, which is strictly more useful than #7919's "report a grandchild against the direct + // subtype it hangs from" - that phrasing existed only because a grandchild could not be reached from here. + for (final DocumentType descendant : collectPolymorphicDescendants(typez)) { + // Only a graph type can produce a refusal, so anything else is not worth counting. That matters because the + // count is not free - a bucket-record sum, or a whole count(*) query for a lightweight edge type - and the + // shape this loop exists for (#8042) is precisely a hierarchy with non-graph types in it, so the intermediate + // DocumentTypes it walks through can easily outnumber the graph types it is looking for. instanceof, not + // isSubTypeOf("V")/("E") - see the root's own guard above. + if (!(descendant instanceof VertexType) && !(descendant instanceof EdgeType)) + continue; + + // Each descendant is counted on its OWN records, NOT polymorphically, because the walk above already visits + // every one of them individually. Counting polymorphically here would charge a descendant's records to every + // graph-type ancestor between it and the root, and since the walk is pre-order that EMPTY ancestor is + // reached first - so an empty VMiddle in DocRoot -> VMiddle -> VLeaf was named as the reason for a refusal + // VLeaf's record caused (found by CodeRabbit on PR #8094). The truncate was refused either way, but the + // message pointed at the wrong type, which is the one thing this loop is for. It is also O(subtree) work per + // descendant instead of O(1). + // + // isLightweight(), not holdsLightweightEdges(): a LIGHTWEIGHT type allocates no record, so countType() + // answers 0 for it however many edges it holds (issue #7477) and only a count(*) walk can see them. A + // RECORD-BACKED type that merely has a lightweight descendant is not in that position - its own buckets are + // exactly what countType() reads - and its lightweight descendant is visited by this same loop in its own + // right. Reading holdsLightweightEdges() here would put such a type back on a count(*) it does not need. + // + // And the lightweight branch counts the type's OWN edges, not the subtree's: a plain count(*) is + // unconditionally polymorphic, so an empty LIGHTWEIGHT ancestor with a non-empty lightweight subtype was + // misattributed exactly as the record-backed case above was (found by CodeRabbit on PR #8094). + final long descendantRecs = descendant instanceof EdgeType edgeType && edgeType.isLightweight() + ? countLightweightEdgesOfExactType(db, descendant.getName()) + : context.getDatabase().countType(descendant.getName(), false); + if (descendantRecs > 0) { + if (descendant instanceof VertexType) { + throw new CommandExecutionException("'TRUNCATE TYPE' command cannot be used on not empty vertex classes (" + descendant.getName() + "). Apply the 'UNSAFE' keyword to force it (at your own risk)"); - } else if (subType.isSubTypeOf("E")) { - throw new CommandExecutionException("'TRUNCATE TYPE' command cannot be used on not empty edge classes (" + subType.getName() + } else if (descendant instanceof EdgeType) { + throw new CommandExecutionException("'TRUNCATE TYPE' command cannot be used on not empty edge classes (" + descendant.getName() + "). Apply the 'UNSAFE' keyword to force it (at your own risk)"); } } @@ -291,6 +331,31 @@ private static boolean collectTruncationScope(final DocumentType type, final boo return hasRecordBackedType; } + /** + * Every type strictly below {@code root}, depth-first in declaration order, deduplicated (found by CodeRabbit on + * PR #8094). + *

+ * A {@link LinkedHashSet}, not a List, for the reason {@link #collectTruncationScope} spells out: ArcadeDB + * supports multiple inheritance, so a diamond hierarchy reaches the same type through two different parent + * branches and would otherwise be counted - and reported - twice. The {@code add()} guard is also what terminates + * the walk on such a diamond. Insertion-ordered so the refusal names the same type on every run rather than + * whichever one a hash bucket happened to yield first. + *

+ * The root itself is deliberately excluded: its own guard runs before this one, with its own message that names + * no type. + */ + private static Set collectPolymorphicDescendants(final DocumentType root) { + final Set descendants = new LinkedHashSet<>(); + collectPolymorphicDescendants(root, descendants); + return descendants; + } + + private static void collectPolymorphicDescendants(final DocumentType type, final Set target) { + for (final DocumentType subType : type.getSubTypes()) + if (target.add(subType)) + collectPolymorphicDescendants(subType, target); + } + /** * Counts a LIGHTWEIGHT edge type's rows the way {@link com.arcadedb.query.sql.executor.CountFromTypeStep} already * does for {@code SELECT count(*)} - by running the query rather than reading {@code Database.countType()}, which @@ -304,6 +369,29 @@ private static long countRecordsIncludingLightweightEdges(final Database db, fin } } + /** + * The same count restricted to the edges of EXACTLY {@code typeName}, excluding its subtypes' (found by CodeRabbit + * on PR #8094). + *

+ * {@code SELECT count(*)} is unconditionally polymorphic, which is what the root's own guard wants and what the + * per-descendant loop must not have: that loop already visits every descendant individually, so a polymorphic + * count charges a subtype's edges to the LIGHTWEIGHT ancestor above it too, and since the walk is pre-order the + * empty ancestor is the one reached first and named in the refusal. This is the lightweight twin of the + * {@code countType(name, false)} switch in the same loop - {@code countType()} cannot stand in for it, because a + * lightweight edge allocates no record and it answers 0 however many edges the type holds (issue #7477). + *

+ * {@code @type} is bound as a PARAMETER rather than embedded: the name reaches this method from the schema, and a + * type name is free-form enough (back-tick quoting exists precisely because it can carry spaces and reserved + * words) that building the comparison by string concatenation would be the one place in this statement where a + * schema-supplied name lands inside a SQL literal. + */ + private static long countLightweightEdgesOfExactType(final Database db, final String typeName) { + try (final ResultSet rs = db.query("sql", + "SELECT count(*) AS c FROM " + Identifier.quote(typeName) + " WHERE @type = ?", typeName)) { + return rs.hasNext() ? ((Number) rs.next().getProperty("c")).longValue() : 0L; + } + } + /** * The caller owns the transaction, so this is one more operation inside it: every record is deleted in that * transaction, with the indexes maintained per record exactly as {@code DELETE FROM} does, and a {@code ROLLBACK} diff --git a/engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java b/engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java index a94f6e559bb..fdf5e931be1 100644 --- a/engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java +++ b/engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java @@ -466,29 +466,70 @@ public Set getAliases() { /** * Sets the list of aliases for the type. Any previous configuration will be lost. + *

+ * Every check and both map passes run inside the single {@link #recordFileChanges} callback, i.e. under the + * database write lock, for the same two reasons {@link #createProperty} and {@link #dropProperty} spell out and + * this method used to violate (issue #8064). {@code checkForSchemaMutation()} is a precondition check, not a + * lock, and it was the only thing here: + *

+ * A refusal part way through unwinds what this call had already reserved: the aliases are all-or-nothing, never + * a half-installed set left behind by a rejected {@code ALTER TYPE}. + *

+ * {@code recordFileChanges} saves {@code schema.json} itself, which is why the explicit + * {@code schema.saveConfiguration()} this method used to end with is gone. */ public LocalDocumentType setAliases(final Set aliases) { checkForSchemaMutation(); - final Set newAliases = new HashSet<>(aliases); - newAliases.removeAll(this.aliases); - for (String alias : newAliases) { - if (schema.existsType(alias)) - throw new SchemaException("Cannot set alias '" + alias + "' for type '" + name + "' because it is already used by type '" - + schema.getType(alias).getName() + "'"); - } - // DEREGISTER ALL PREVIOUS ALIASES - for (String alias : this.aliases) - schema.typeMap().remove(alias); + return recordFileChanges(() -> { + final Set previousAliases = this.aliases; - for (String alias : aliases) - schema.typeMap().put(alias, this); + // ONLY THE GENUINELY NEW NAMES ARE RESERVED: AN ALIAS THIS TYPE ALREADY ANSWERS TO IS ALREADY IN THE MAP + // POINTING AT US, AND putIfAbsent WOULD REPORT IT AS TAKEN - BY OURSELVES + final Set addedAliases = new HashSet<>(aliases); + addedAliases.removeAll(previousAliases); - // A copy, and an unmodifiable one: the parameter belongs to the caller. Published last so a lock-free - // instanceOf() either sees the whole previous set or the whole new one. - this.aliases = Set.copyOf(aliases); - schema.saveConfiguration(); - return this; + final List reserved = new ArrayList<>(addedAliases.size()); + try { + for (final String alias : addedAliases) { + final LocalDocumentType owner = schema.typeMap().putIfAbsent(alias, this); + if (owner != null) + // OWNED BY US MEANS IT IS THIS TYPE'S OWN NAME: EVERY ALIAS IT ALREADY CARRIES WAS FILTERED OUT ABOVE. + // SAYING "ALREADY USED BY TYPE 'X'" WITH X NAMED TWICE READS AS AN ENGINE BUG RATHER THAN AS THE + // REFUSAL IT IS, SO SAY WHICH OF THE TWO REFUSALS THIS IS + throw new SchemaException(owner == this ? + "Cannot set alias '" + alias + "' for type '" + name + "' because it is the name of the type itself" : + "Cannot set alias '" + alias + "' for type '" + name + "' because it is already used by type '" + + owner.getName() + "'"); + reserved.add(alias); + } + } catch (final RuntimeException e) { + // UNWIND ONLY WHAT THIS CALL RESERVED, AND ONLY WHILE IT STILL POINTS AT US + for (final String alias : reserved) + schema.typeMap().remove(alias, this); + throw e; + } + + // DEREGISTER ONLY THE PREVIOUS ALIASES THE NEW SET NO LONGER CARRIES, AFTER THE NEW ONES ARE IN + for (final String alias : previousAliases) + if (!aliases.contains(alias)) + schema.typeMap().remove(alias, this); + + // A copy, and an unmodifiable one: the parameter belongs to the caller. Published last so a lock-free + // instanceOf() either sees the whole previous set or the whole new one. + this.aliases = Set.copyOf(aliases); + return this; + }); } /** diff --git a/engine/src/test/java/com/arcadedb/graph/Issue7477LightweightEdgeScanTest.java b/engine/src/test/java/com/arcadedb/graph/Issue7477LightweightEdgeScanTest.java index b16915c5e77..e5bbd44bf84 100644 --- a/engine/src/test/java/com/arcadedb/graph/Issue7477LightweightEdgeScanTest.java +++ b/engine/src/test/java/com/arcadedb/graph/Issue7477LightweightEdgeScanTest.java @@ -363,7 +363,7 @@ void truncateOnALightweightEdgeTypeActuallyDeletesTheEdges() { connect("Cite", works[0], works[2]); connect("Cite", works[1], works[2]); - database.command("sql", "truncate type Cite").close(); + database.command("sql", "truncate type Cite unsafe").close(); assertThat(query("select from Cite")).as("TRUNCATE must actually reach the edges now").isEmpty(); database.transaction(() -> { @@ -380,7 +380,7 @@ void truncateOnALightweightEdgeTypeWorksInsideACallerTransactionToo() { final RID[] works = newWorks(2); connect("Cite", works[0], works[1]); - database.transaction(() -> database.command("sql", "truncate type Cite").close()); + database.transaction(() -> database.command("sql", "truncate type Cite unsafe").close()); assertThat(query("select from Cite")).isEmpty(); } @@ -392,7 +392,7 @@ void truncateOnALightweightEdgeTypeInsideACallerTransactionRollsBack() { connect("Cite", works[0], works[1]); database.begin(); - database.command("sql", "truncate type Cite").close(); + database.command("sql", "truncate type Cite unsafe").close(); assertThat(query("select from Cite")).isEmpty(); database.rollback(); @@ -420,12 +420,12 @@ void truncateOnAMixedHierarchyScopesToTheRootWithoutPolymorphicAndDeletesBothSha connect("Mentions", works[0], works[1]); connect("Quotes", works[0], works[2]); - database.command("sql", "truncate type Mentions").close(); + database.command("sql", "truncate type Mentions unsafe").close(); assertThat(query("select from Mentions")) .as("only the root's own bucket is cleared; the lightweight subtype's edge was not in scope") .hasSize(1); - database.command("sql", "truncate type Mentions polymorphic").close(); + database.command("sql", "truncate type Mentions polymorphic unsafe").close(); assertThat(query("select from Mentions")).isEmpty(); } @@ -454,7 +454,7 @@ void truncateOnALightweightLeafTypeIgnoresThePolymorphicFlag() { final RID[] works = newWorks(2); connect("Cite", works[0], works[1]); - database.command("sql", "truncate type Cite polymorphic").close(); + database.command("sql", "truncate type Cite polymorphic unsafe").close(); assertThat(query("select from Cite")).isEmpty(); } @@ -487,7 +487,7 @@ void truncateOnALightweightEdgeTypeWithAReservedWordNameStillDeletes() { assertThat(query("select from `SELECT`")).hasSize(1); - database.command("sql", "truncate type `SELECT`").close(); + database.command("sql", "truncate type `SELECT` unsafe").close(); assertThat(query("select from `SELECT`")).isEmpty(); } @@ -509,7 +509,7 @@ void truncateOnALightweightEdgeTypeDeletesEverythingAcrossSeveralBatches() { assertThat(query("select from Cite")).hasSize(works.length - 1); - database.command("sql", "truncate type Cite").close(); + database.command("sql", "truncate type Cite unsafe").close(); assertThat(query("select from Cite")).isEmpty(); database.transaction(() -> assertThat(database.lookupByRID(works[0], true).asVertex() @@ -524,9 +524,13 @@ void truncateOnALightweightEdgeTypeDeletesEverythingAcrossSeveralBatches() { * {@code Database.countType()} sums bucket record counts, and a LIGHTWEIGHT edge allocates none - so it answers 0 * for such a type no matter how many edges it holds ({@link #theCountAgreesWithTheScan} pins exactly this). The * "not empty, needs UNSAFE" guard in {@code TruncateTypeStatement} reads that same count, so a LIGHTWEIGHT edge - * type under a real {@code E} hierarchy (unlike this class's other fixtures, none of which extend {@code E} or - * {@code V} and so never exercise this guard at all) must not be able to bypass it just because the count it - * relies on lies for this storage shape (review finding on #7481). + * type must not be able to bypass it just because the count it relies on lies for this storage shape (review + * finding on #7481). + *

+ * The {@code E} super type this fixture builds is a leftover from when the guard asked + * {@code isSubTypeOf("E")} by name and this hierarchy was the only way to reach it at all. Every other truncate + * in this class needs UNSAFE now, which is the same finding seen from the other side (issue #8042). The super + * type is kept because it costs nothing and pins that the explicit hierarchy does not CHANGE the answer either. */ @Test void truncateOnALightweightEdgeTypeUnderARealEHierarchyStillRequiresUnsafeWhenNotEmpty() { diff --git a/engine/src/test/java/com/arcadedb/query/select/Issue8047SelectPrecedenceDropLosesConditionsTest.java b/engine/src/test/java/com/arcadedb/query/select/Issue8047SelectPrecedenceDropLosesConditionsTest.java new file mode 100644 index 00000000000..6344636373e --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/select/Issue8047SelectPrecedenceDropLosesConditionsTest.java @@ -0,0 +1,169 @@ +/* + * 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.select; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.schema.DocumentType; +import com.arcadedb.schema.Type; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * https://github.com/ArcadeData/arcadedb/issues/8047 + *

+ * {@code Select.setLogic()}'s "the new operator does not bind more tightly" branch re-parented the current subtree + * TWICE: the {@code SelectTreeNode} constructor already does it (and already moves the grandparent's child pointer + * over), and the branch then called {@code newNode.setParent(currentParent.getParent())} - by which point + * {@code currentParent.getParent()} IS {@code newNode}, so the call reduced to {@code newNode.setParent(newNode)} + * and installed a self-parent cycle. + *

+ * A self-parented node defeats the NEXT re-parenting: {@code setParent} rewires the grandparent by testing + * {@code this.parent.left == this} / {@code this.parent.right == this}, and on such a node both tests compare it + * against its own children and fail, so the real grandparent's {@code right} pointer never moved. The new node - + * and everything appended to it afterwards - dangled off the tree {@code rootTreeElement} refers to, and the + * executor never saw it. The shape that reaches the branch is a precedence DROP (an {@code or}) followed by three + * or more {@code and}s, so from the fifth condition on every remaining condition was discarded in silence and the + * query returned MORE rows than the predicate allows. A pure {@code and} chain and a pure {@code or} chain of any + * length were unaffected, which is why the existing tests never caught it. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +public class Issue8047SelectPrecedenceDropLosesConditionsTest extends TestHelper { + + private static final String[] PROPERTIES = { "a", "b", "c", "d", "e", "f" }; + + @Override + protected void beginTest() { + final DocumentType type = database.getSchema().createDocumentType("D"); + for (final String property : PROPERTIES) + type.createProperty(property, Type.INTEGER); + + // EVERY COMBINATION OF THE SIX 0/1 FLAGS, SO EVERY PREDICATE BELOW HAS A NON-TRIVIAL, EXACTLY KNOWN ANSWER + database.transaction(() -> { + for (int mask = 0; mask < 1 << PROPERTIES.length; mask++) { + final MutableDocument doc = database.newDocument("D"); + for (int bit = 0; bit < PROPERTIES.length; bit++) + doc.set(PROPERTIES[bit], (mask >> bit) & 1); + doc.save(); + } + }); + } + + @Test + void fifthConditionAfterAPrecedenceDropSurvivesIntoTheCompiledTree() { + // THE TREE IS THE POINT: BEFORE THE FIX THE FIVE-CONDITION SELECT COMPILED TO EXACTLY THE SAME TREE AS THE + // FOUR-CONDITION ONE, SO `and e = 1` WAS SIMPLY GONE. SelectCompiled.json() IS THE ENGINE'S OWN RENDERING OF + // THE COMPILED TREE, SO THIS NEEDS NO INSTRUMENTATION TO SEE. + final String fiveTerms = database.select().fromType("D").where()// + .property("a").eq().value(1)// + .or().property("b").eq().value(1)// + .and().property("c").eq().value(1)// + .and().property("d").eq().value(1)// + .and().property("e").eq().value(1)// + .compile().json().getJSONArray("where").toString(); + + assertThat(fiveTerms).isEqualTo( + "[[\":a\",\"=\",1],\"or\",[[[[\":b\",\"=\",1],\"and\",[\":c\",\"=\",1]],\"and\",[\":d\",\"=\",1]],\"and\",[\":e\",\"=\",1]]]"); + + final String fourTerms = database.select().fromType("D").where()// + .property("a").eq().value(1)// + .or().property("b").eq().value(1)// + .and().property("c").eq().value(1)// + .and().property("d").eq().value(1)// + .compile().json().getJSONArray("where").toString(); + + assertThat(fourTerms).isNotEqualTo(fiveTerms); + } + + @Test + void orFollowedByFourAndsCountsTheSameAsSql() { + final long native5 = database.select().fromType("D").where()// + .property("a").eq().value(1)// + .or().property("b").eq().value(1)// + .and().property("c").eq().value(1)// + .and().property("d").eq().value(1)// + .and().property("e").eq().value(1).count(); + + assertThat(native5).isEqualTo(sqlCount("a = 1 or b = 1 and c = 1 and d = 1 and e = 1")); + } + + @Test + void orFollowedByFiveAndsCountsTheSameAsSql() { + // TWO CONDITIONS PAST THE BREAKING POINT: BEFORE THE FIX BOTH `e` AND `f` WERE DROPPED + final long native6 = database.select().fromType("D").where()// + .property("a").eq().value(1)// + .or().property("b").eq().value(1)// + .and().property("c").eq().value(1)// + .and().property("d").eq().value(1)// + .and().property("e").eq().value(1)// + .and().property("f").eq().value(1).count(); + + assertThat(native6).isEqualTo(sqlCount("a = 1 or b = 1 and c = 1 and d = 1 and e = 1 and f = 1")); + } + + @Test + void andThenOrThenThreeAndsCountsTheSameAsSql() { + // THE OTHER SHAPE FROM THE ISSUE'S SWEEP: THE PRECEDENCE DROP IS NOT THE FIRST OPERATOR + final long nativeCount = database.select().fromType("D").where()// + .property("a").eq().value(1)// + .and().property("b").eq().value(1)// + .or().property("c").eq().value(1)// + .and().property("d").eq().value(1)// + .and().property("e").eq().value(1)// + .and().property("f").eq().value(1).count(); + + assertThat(nativeCount).isEqualTo(sqlCount("a = 1 and b = 1 or c = 1 and d = 1 and e = 1 and f = 1")); + } + + @Test + void pureAndAndPureOrChainsStayCorrect() { + // THE CONTROL: THESE TWO NEVER REACHED THE BROKEN BRANCH AND MUST NOT REGRESS + assertThat(database.select().fromType("D").where()// + .property("a").eq().value(1)// + .and().property("b").eq().value(1)// + .and().property("c").eq().value(1)// + .and().property("d").eq().value(1)// + .and().property("e").eq().value(1).count()).isEqualTo(sqlCount("a = 1 and b = 1 and c = 1 and d = 1 and e = 1")); + + assertThat(database.select().fromType("D").where()// + .property("a").eq().value(1)// + .or().property("b").eq().value(1)// + .or().property("c").eq().value(1)// + .or().property("d").eq().value(1)// + .or().property("e").eq().value(1).count()).isEqualTo(sqlCount("a = 1 or b = 1 or c = 1 or d = 1 or e = 1")); + } + + @Test + void aNodeCannotBecomeItsOwnParent() { + // THE CYCLE IS WHAT TURNED A REDUNDANT CALL INTO A LOST CONDITION, AND IT ALSO MAKES EVERY getParent() WALK + // NON-TERMINATING - SelectExecutor's OR/NOT ANCESTOR CHECK (#8048) DOES EXACTLY SUCH A WALK + final SelectTreeNode node = new SelectTreeNode(new SelectPropertyValue("a"), SelectOperator.eq, 1); + assertThatThrownBy(() -> node.setParent(node)).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be its own parent"); + } + + private long sqlCount(final String where) { + return ((Number) database.query("sql", "SELECT count(*) AS c FROM D WHERE " + where).nextIfAvailable().getProperty("c")) + .longValue(); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/select/Issue8048SelectIndexCursorUnderNestedOrTest.java b/engine/src/test/java/com/arcadedb/query/select/Issue8048SelectIndexCursorUnderNestedOrTest.java new file mode 100644 index 00000000000..e2efdf36c95 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/select/Issue8048SelectIndexCursorUnderNestedOrTest.java @@ -0,0 +1,182 @@ +/* + * 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.select; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.schema.DocumentType; +import com.arcadedb.schema.Schema; +import com.arcadedb.schema.Type; +import com.arcadedb.serializer.json.JSONObject; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * https://github.com/ArcadeData/arcadedb/issues/8048 + *

+ * The union of the cursors {@code SelectExecutor.filterWithIndexesFinalNode()} builds is the ONLY set of candidate + * records a native select ever evaluates, so a cursor is sound only when every record that could satisfy the WHERE + * is guaranteed to be inside it. Under an {@code or} that means both sides have to be index-answerable, and the + * method did check that - but only against the leaf's IMMEDIATE sibling. Two ways out of it, both reproduced here: + *

    + *
  1. A leaf nested one level deeper. In {@code b = 1 and a = 0 or b = 2} the tree is + * {@code or(and(b=1, a=0), b=2)}, the indexed leaf {@code a = 0} has the {@code and} as its parent, the + * {@code parent.operator == or} test was false and the cursor was built unconditionally. The candidate set + * collapsed to "records with a = 0" and every record matching {@code b = 2} was never looked at.
  2. + *
  3. A composite {@code or} sibling. {@code isTheNodeFullyIndexed()} answered {@code left || right} for an + * {@code or} node, where an OR branch is only index-answerable when BOTH of its sides are.
  4. + *
+ * The invariant under test is the one this whole code path exists to preserve: an index is a PERFORMANCE decision, + * so the same select over the same data must return the same rows with and without one. Each case is therefore run + * twice against the identical SQL - once with an {@code LSM_TREE} index on {@code a} and once with none - and the + * un-indexed run is the control that was always correct. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +public class Issue8048SelectIndexCursorUnderNestedOrTest extends TestHelper { + + private static final int CARDINALITY = 6; + + @Override + protected void beginTest() { + final DocumentType type = database.getSchema().createDocumentType("D"); + type.createProperty("a", Type.INTEGER); + type.createProperty("b", Type.INTEGER); + + database.transaction(() -> { + for (int a = 0; a < CARDINALITY; a++) + for (int b = 0; b < CARDINALITY; b++) { + final MutableDocument doc = database.newDocument("D"); + doc.set("a", a); + doc.set("b", b); + doc.save(); + } + }); + } + + @Test + void indexedLeafNestedUnderAnAndInsideAnOrDoesNotDropTheOtherBranch() { + // b = 1 and a = 0 or b = 2 -> or(and(b=1, a=0), b=2) + runWithAndWithoutIndex(() -> database.select().fromType("D").where()// + .property("b").eq().value(1)// + .and().property("a").eq().value(0)// + .or().property("b").eq().value(2).count(), "b = 1 and a = 0 or b = 2"); + } + + @Test + void indexedLeafFirstInsideTheAndBranchDoesNotDropTheOtherBranch() { + runWithAndWithoutIndex(() -> database.select().fromType("D").where()// + .property("a").eq().value(0)// + .and().property("b").eq().value(1)// + .or().property("b").eq().value(2).count(), "a = 0 and b = 1 or b = 2"); + } + + @Test + void indexedLeafInTheAndBranchOnTheRightOfTheOrDoesNotDropTheOtherBranch() { + runWithAndWithoutIndex(() -> database.select().fromType("D").where()// + .property("b").eq().value(2)// + .or().property("a").eq().value(0)// + .and().property("b").eq().value(1).count(), "b = 2 or a = 0 and b = 1"); + } + + @Test + void chainedOrsWithAnUnindexedTailDoNotDropIt() { + // a = 1 or a = 3 or b = 2: THE LEFT-NESTED or MEANS THE FIRST TWO LEAVES' IMMEDIATE SIBLING IS INDEXED, WHILE + // THE OUTER or'S OTHER BRANCH - b = 2 - IS NOT. ONLY A PATH WALK SEES THAT + runWithAndWithoutIndex(() -> database.select().fromType("D").where()// + .property("a").eq().value(1)// + .or().property("a").eq().value(3)// + .or().property("b").eq().value(2).count(), "a = 1 or a = 3 or b = 2"); + } + + @Test + void rightNestedOrSiblingIsOnlyIndexedWhenBothOfItsSidesAre() { + // a = 1 OR (b = 1 OR a = 2). THE FLUENT BUILDER CANNOT PRODUCE A RIGHT-NESTED or, BUT Select.json() CAN. + // isTheNodeFullyIndexed()'S or ARM USED TO ANSWER left || right, SO THE INNER or CALLED ITSELF FULLY INDEXED ON + // THE STRENGTH OF a = 2 ALONE AND THE OUTER a = 1 LEAF GOT ITS CURSOR + final JSONObject json = new JSONObject( + "{\"fromType\":\"D\",\"where\":[[\":a\",\"=\",1],\"or\",[[\":b\",\"=\",1],\"or\",[\":a\",\"=\",2]]]}"); + + runWithAndWithoutIndex(() -> database.select().json(json).count(), "a = 1 or (b = 1 or a = 2)"); + } + + @Test + void plainOrWithOneIndexedSideStaysCorrect() { + // THE CONTROL FROM THE ISSUE: HERE THE LEAF'S PARENT *IS* THE or, THE PRE-EXISTING GATE ALREADY FIRED AND THE + // ANSWER WAS ALWAYS RIGHT. IT MUST STAY RIGHT + runWithAndWithoutIndex(() -> database.select().fromType("D").where()// + .property("a").eq().value(0)// + .or().property("b").eq().value(2).count(), "a = 0 or b = 2"); + } + + @Test + void anIndexIsStillUsedWhenBothOrBranchesAreIndexed() { + // THE FIX MUST NOT DISABLE THE INDEX PATH ALTOGETHER: WITH BOTH PROPERTIES INDEXED, BOTH BRANCHES ARE + // ANSWERABLE AND TWO CURSORS MUST STILL BE BUILT + database.getSchema().getType("D").createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "a"); + database.getSchema().getType("D").createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "b"); + try { + final Select select = database.select().fromType("D"); + select.where().property("a").eq().value(0).or().property("b").eq().value(2).compile(); + + final SelectExecutor executor = new SelectExecutor(select); + try (var cursor = executor.lookForIndexes()) { + assertThat((Object) cursor).isNotNull(); + assertThat(executor.metrics().get("usedIndexes")).isEqualTo(2); + } + + assertThat(database.select().fromType("D").where()// + .property("a").eq().value(0)// + .or().property("b").eq().value(2).count()).isEqualTo(sqlCount("a = 0 or b = 2")); + } finally { + dropIndexesOn("a"); + dropIndexesOn("b"); + } + } + + /** + * Runs {@code nativeCount} against the identical SQL twice: once with an index on {@code a} and once without. + * Both answers have to match SQL, which also makes them match each other - the invariant an index must never + * break. + */ + private void runWithAndWithoutIndex(final java.util.function.LongSupplier nativeCount, final String sqlWhere) { + final long expected = sqlCount(sqlWhere); + + assertThat(nativeCount.getAsLong()).as("without an index on 'a': " + sqlWhere).isEqualTo(expected); + + database.getSchema().getType("D").createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "a"); + try { + assertThat(nativeCount.getAsLong()).as("with an index on 'a': " + sqlWhere).isEqualTo(expected); + } finally { + dropIndexesOn("a"); + } + } + + private void dropIndexesOn(final String property) { + for (final var index : database.getSchema().getType("D").getIndexesByProperties(property)) + database.getSchema().dropIndex(index.getName()); + } + + private long sqlCount(final String where) { + return ((Number) database.query("sql", "SELECT count(*) AS c FROM D WHERE " + where).nextIfAvailable().getProperty("c")) + .longValue(); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/select/Issue8049SelectNullOrderingComparisonTest.java b/engine/src/test/java/com/arcadedb/query/select/Issue8049SelectNullOrderingComparisonTest.java new file mode 100644 index 00000000000..d46f8a8f966 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/select/Issue8049SelectNullOrderingComparisonTest.java @@ -0,0 +1,157 @@ +/* + * 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.select; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.schema.DocumentType; +import com.arcadedb.schema.Schema; +import com.arcadedb.schema.Type; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * https://github.com/ArcadeData/arcadedb/issues/8049 + *

+ * {@code SelectOperator.lt}/{@code le} compared through {@code BinaryComparator.compareTo()}, which is a SORT order + * and answers {@code -1} for a null left operand. Read as a predicate that made a record WITHOUT the property - or + * carrying it as an explicit null - satisfy every {@code <} and {@code <=} on it, while {@code gt}/{@code ge} were + * unaffected by the same {@code -1}: the two directions disagreed. + *

+ * Worse, the answer was not even stable. When an index exists on the property, {@code filterWithIndexesFinalNode()} + * answers the leaf from a range scan, and an index holds no entry for a record that lacks the property - so the + * null-bearing records were never offered to {@code evaluateWhere()} at all. The same select over the same data + * returned 12 rows with no index and 5 with one, which is the one thing adding an index must never do. + *

+ * Each predicate below is therefore asserted three ways: against SQL, without an index, and with one. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +public class Issue8049SelectNullOrderingComparisonTest extends TestHelper { + + private static final int WITH_VALUE = 5; + private static final int WITHOUT_A = 5; + private static final int EXPLICIT_NULL = 2; + + @Override + protected void beginTest() { + final DocumentType type = database.getSchema().createDocumentType("D"); + type.createProperty("a", Type.INTEGER); + type.createProperty("tag", Type.STRING); + + database.transaction(() -> { + for (int i = 0; i < WITH_VALUE; i++) { + final MutableDocument doc = database.newDocument("D"); + doc.set("a", i); + doc.set("tag", "valued"); + doc.save(); + } + for (int i = 0; i < WITHOUT_A; i++) { + final MutableDocument doc = database.newDocument("D"); + doc.set("tag", "absent"); + doc.save(); + } + for (int i = 0; i < EXPLICIT_NULL; i++) { + final MutableDocument doc = database.newDocument("D"); + doc.set("a", null); + doc.set("tag", "null"); + doc.save(); + } + }); + } + + @Test + void lessThanDoesNotMatchRecordsWithoutTheProperty() { + assertSameWithAndWithoutIndex(() -> database.select().fromType("D").where().property("a").lt().value(5).count(), + "a < 5", WITH_VALUE); + } + + @Test + void lessThanOrEqualDoesNotMatchRecordsWithoutTheProperty() { + assertSameWithAndWithoutIndex(() -> database.select().fromType("D").where().property("a").le().value(4).count(), + "a <= 4", WITH_VALUE); + } + + @Test + void greaterThanStaysConsistent() { + assertSameWithAndWithoutIndex(() -> database.select().fromType("D").where().property("a").gt().value(-1).count(), + "a > -1", WITH_VALUE); + } + + @Test + void greaterThanOrEqualStaysConsistent() { + assertSameWithAndWithoutIndex(() -> database.select().fromType("D").where().property("a").ge().value(0).count(), + "a >= 0", WITH_VALUE); + } + + @Test + void betweenStaysConsistent() { + assertSameWithAndWithoutIndex( + () -> database.select().fromType("D").where().property("a").between().values(0, 4).count(), "a between 0 and 4", + WITH_VALUE); + } + + @Test + void isNullStillSeesEveryRecordWithoutAValue() { + // THE COMPLEMENTARY QUESTION IS THE ONE THAT ANSWERS "WHICH RECORDS HAVE NO VALUE" - IT MUST KEEP ANSWERING IT + assertThat(database.select().fromType("D").where().property("a").isNull().count()).isEqualTo( + WITHOUT_A + EXPLICIT_NULL); + assertThat(database.select().fromType("D").where().property("a").isNotNull().count()).isEqualTo(WITH_VALUE); + } + + @Test + void lessThanAndGreaterThanOrEqualAreNoLongerJointlyExhaustive() { + // THE OLD BEHAVIOUR MADE `a < 5` AND `a >= 5` COVER EVERY RECORD WHILE `a is null` WAS ALSO TRUE FOR SOME OF + // THEM. THE TWO HALVES NOW SUM TO THE RECORDS THAT ACTUALLY CARRY A VALUE, AND NO MORE + final long below = database.select().fromType("D").where().property("a").lt().value(5).count(); + final long atOrAbove = database.select().fromType("D").where().property("a").ge().value(5).count(); + assertThat(below + atOrAbove).isEqualTo(WITH_VALUE); + } + + @Test + void aNullRightOperandNeverMatches() { + // SQL'S OWN RULE: A COMPARISON WITH NULL IS UNKNOWN, AND UNKNOWN DOES NOT MATCH. compareTo(x, null) ANSWERS 1, + // SO `a > null` USED TO BE TRUE FOR EVERY RECORD CARRYING AN 'a' + assertThat(database.select().fromType("D").where().property("a").gt().value(null).count()).isZero(); + assertThat(database.select().fromType("D").where().property("a").ge().value(null).count()).isZero(); + assertThat(database.select().fromType("D").where().property("a").lt().value(null).count()).isZero(); + assertThat(database.select().fromType("D").where().property("a").le().value(null).count()).isZero(); + } + + private void assertSameWithAndWithoutIndex(final java.util.function.LongSupplier nativeCount, final String sqlWhere, + final long expected) { + assertThat(sqlCount(sqlWhere)).as("SQL baseline for " + sqlWhere).isEqualTo(expected); + assertThat(nativeCount.getAsLong()).as("native without an index: " + sqlWhere).isEqualTo(expected); + + database.getSchema().getType("D").createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "a"); + try { + assertThat(nativeCount.getAsLong()).as("native with an index: " + sqlWhere).isEqualTo(expected); + } finally { + for (final var index : database.getSchema().getType("D").getIndexesByProperties("a")) + database.getSchema().dropIndex(index.getName()); + } + } + + private long sqlCount(final String where) { + return ((Number) database.query("sql", "SELECT count(*) AS c FROM D WHERE " + where).nextIfAvailable().getProperty("c")) + .longValue(); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/select/Issue8059SelectNotOperatorTest.java b/engine/src/test/java/com/arcadedb/query/select/Issue8059SelectNotOperatorTest.java new file mode 100644 index 00000000000..da96079e71d --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/select/Issue8059SelectNotOperatorTest.java @@ -0,0 +1,161 @@ +/* + * 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.select; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.MutableDocument; +import com.arcadedb.index.MultiIndexCursor; +import com.arcadedb.schema.DocumentType; +import com.arcadedb.schema.Schema; +import com.arcadedb.schema.Type; +import com.arcadedb.serializer.json.JSONObject; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * https://github.com/ArcadeData/arcadedb/issues/8059 + *

+ * Every other operator in {@code SelectOperator} passes its operands through + * {@code SelectExecutor.evaluateValue()}, which is what turns a nested {@code SelectTreeNode} into a value. + * {@code not} did not: its body was {@code left == Boolean.FALSE}, a reference comparison against the RAW, + * unevaluated left operand. In a real tree that operand is a {@code SelectTreeNode}, never {@code Boolean.FALSE}, + * so the expression was false for every record and the whole query answered nothing. + *

+ * {@code not} is UNARY in this engine - every in-tree use builds + * {@code new SelectTreeNode(operand, SelectOperator.not, null)} - while a JSON condition is by construction the + * binary triple {@code [left, operator, right]}. {@code Select.json()} resolved {@code not} by name through + * {@code SelectOperator.byName()} and routed it through {@code setLogic()} exactly like {@code and}/{@code or}, so + * the one path that could reach it built a shape with no defined meaning and handed the caller a silently empty + * result set. It is now refused with a message that says why. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +public class Issue8059SelectNotOperatorTest extends TestHelper { + + @Override + protected void beginTest() { + final DocumentType type = database.getSchema().createDocumentType("D"); + type.createProperty("a", Type.INTEGER); + type.createProperty("b", Type.INTEGER); + type.createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "a"); + + // FOUR RECORDS, ONE PER (a, b) COMBINATION OF 0/1 + database.transaction(() -> { + for (int a = 0; a < 2; a++) + for (int b = 0; b < 2; b++) { + final MutableDocument doc = database.newDocument("D"); + doc.set("a", a); + doc.set("b", b); + doc.save(); + } + }); + } + + @Test + void notNegatesItsOperandInsteadOfAnsweringFalseForEveryRecord() { + // NOT (a = 1): TWO OF THE FOUR RECORDS CARRY a = 0. THE OLD BODY ANSWERED false FOR ALL FOUR + final Select select = database.select().fromType("D"); + final SelectTreeNode eqLeaf = new SelectTreeNode(new SelectPropertyValue("a"), SelectOperator.eq, 1); + select.rootTreeElement = new SelectTreeNode(eqLeaf, SelectOperator.not, null); + + assertThat(new SelectExecutor(select).executeCount()).isEqualTo(2); + } + + @Test + void notOverAConjunctionNegatesTheWholeConjunction() { + // NOT (a = 1 AND b = 1): THREE OF THE FOUR RECORDS FAIL THE CONJUNCTION + final Select select = database.select().fromType("D"); + final SelectTreeNode conjunction = new SelectTreeNode(new SelectTreeNode(new SelectPropertyValue("a"), SelectOperator.eq, 1), + SelectOperator.and, new SelectTreeNode(new SelectPropertyValue("b"), SelectOperator.eq, 1)); + select.rootTreeElement = new SelectTreeNode(conjunction, SelectOperator.not, null); + + assertThat(new SelectExecutor(select).executeCount()).isEqualTo(3); + } + + @Test + void anIndexedLeafBelowANotAncestorNeverBuildsACursor() { + // #8048's PATH RULE, THE not HALF: THE LEAF'S PARENT HERE IS THE and, THE not IS ONE LEVEL FURTHER UP, AND THE + // OLD DIRECT-PARENT CHECK MISSED IT. A POSITIVE CURSOR FOR a = 1 WOULD YIELD EXACTLY THE RECORDS THE NEGATION + // REJECTS, SO THE ONLY SAFE PLAN IS A FULL SCAN + final Select select = database.select().fromType("D"); + final SelectTreeNode conjunction = new SelectTreeNode(new SelectTreeNode(new SelectPropertyValue("a"), SelectOperator.eq, 1), + SelectOperator.and, new SelectTreeNode(new SelectPropertyValue("b"), SelectOperator.eq, 1)); + select.rootTreeElement = new SelectTreeNode(conjunction, SelectOperator.not, null); + + final SelectExecutor executor = new SelectExecutor(select); + final MultiIndexCursor cursor = executor.lookForIndexes(); + try { + assertThat((Object) cursor).isNull(); + assertThat(executor.metrics().get("usedIndexes")).isEqualTo(0); + } finally { + if (cursor != null) + cursor.close(); + } + } + + @Test + void aNotBranchIsNeverReportedAsIndexedToItsOrSibling() { + // a = 0 OR NOT (a = 1): THE not BRANCH CONTRIBUTES NO CURSOR, SO IT MUST NOT BE REPORTED AS "INDEXED" TO THE + // LEFT LEAF - OTHERWISE THE a = 0 CURSOR BECOMES THE WHOLE CANDIDATE SET AND THE NEGATED BRANCH IS DROPPED. + // THE PREDICATE IS SATISFIED BY EVERY RECORD WHOSE a IS NOT 1, WHICH IS THE TWO a = 0 ONES + final Select select = database.select().fromType("D"); + final SelectTreeNode notBranch = new SelectTreeNode(new SelectTreeNode(new SelectPropertyValue("a"), SelectOperator.eq, 1), + SelectOperator.not, null); + select.rootTreeElement = new SelectTreeNode(new SelectTreeNode(new SelectPropertyValue("a"), SelectOperator.eq, 0), + SelectOperator.or, notBranch); + + final SelectExecutor executor = new SelectExecutor(select); + final MultiIndexCursor cursor = executor.lookForIndexes(); + try { + assertThat((Object) cursor).isNull(); + } finally { + if (cursor != null) + cursor.close(); + } + + assertThat(new SelectExecutor(select).executeCount()).isEqualTo(2); + } + + @Test + void jsonRefusesTheBinaryNotInsteadOfReturningNothing() { + final JSONObject json = new JSONObject( + "{\"fromType\":\"D\",\"where\":[[\":a\",\"=\",1],\"not\",[\":b\",\"=\",1]]}"); + + assertThatThrownBy(() -> database.select().json(json)).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("'not' is unary"); + } + + @Test + void jsonRefusesAnUnknownOperatorInsteadOfThrowingNullPointer() { + final JSONObject json = new JSONObject("{\"fromType\":\"D\",\"where\":[[\":a\",\"=\",1],\"nand\",[\":b\",\"=\",1]]}"); + + assertThatThrownBy(() -> database.select().json(json)).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported operator 'nand'"); + } + + @Test + void theOrControlFromTheIssueStillAnswersThreeRecords() { + final JSONObject json = new JSONObject("{\"fromType\":\"D\",\"where\":[[\":a\",\"=\",1],\"or\",[\":b\",\"=\",1]]}"); + + assertThat(database.select().json(json).count()).isEqualTo(3); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/sql/executor/Issue7919TruncateNonPolymorphicGuardTest.java b/engine/src/test/java/com/arcadedb/query/sql/executor/Issue7919TruncateNonPolymorphicGuardTest.java index b19d7c8adc3..297be3650f6 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/executor/Issue7919TruncateNonPolymorphicGuardTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/executor/Issue7919TruncateNonPolymorphicGuardTest.java @@ -145,17 +145,22 @@ void nonPolymorphicTruncateOfALightweightLeafStillWorks() { } /** - * The per-subtype loop (line :122 of the issue). Reaching it needs a root that is NOT itself under {@code E} while - * a subtype is - the "multiple inheritance" case the loop's own comment names - because otherwise the whole-subtree - * check above it throws first. With the root counted instead of the subtype, the loop saw the root's zero and let a - * polymorphic truncate of a non-empty subtype through without the UNSAFE keyword it was written to demand. + * The per-subtype loop (line :122 of the issue). Reaching it needs a root whose OWN guard does not throw first, + * which means a root that is neither a vertex nor an edge type - a DOCUMENT root with a graph subtype under it, + * the "multiple inheritance" case the loop's own comment names. With the root counted instead of the subtype, the + * loop saw the root's zero and let a polymorphic truncate of a non-empty subtype through without the UNSAFE + * keyword it was written to demand. + *

+ * This fixture used to build the hierarchy around a type it created called {@code E}, because the root guard + * asked {@code isSubTypeOf("E")} by NAME and that was the only way to make it fire at all. It fires on the type + * now (issue #8042), so the arrangement that used to be a way IN to the loop became a way past it: the root's own + * guard answers first for a graph root, whatever its subtypes hold. */ @Test void thePerSubtypeSafetyCountLooksAtTheSubtypeNotTheRoot() { database.command("sql", "CREATE VERTEX TYPE Person"); - database.command("sql", "CREATE EDGE TYPE E"); - database.command("sql", "CREATE EDGE TYPE Base"); - database.command("sql", "CREATE EDGE TYPE Sub EXTENDS Base, E"); + database.command("sql", "CREATE DOCUMENT TYPE Base"); + database.command("sql", "CREATE EDGE TYPE Sub EXTENDS Base"); final RID p1, p2; database.begin(); @@ -183,30 +188,21 @@ void thePerSubtypeSafetyCountLooksAtTheSubtypeNotTheRoot() { /** * The other half of the same typo: an EMPTY subtype under a non-empty root was reported BY NAME as the reason for - * a refusal, because the count that triggered it was the root's. + * a refusal, because the count that triggered it was the root's. Same document-root shape as the test above, for + * the same reason (issue #8042). */ @Test void anEmptySubtypeIsNotBlamedForTheRootsRecords() { - database.command("sql", "CREATE VERTEX TYPE Person"); - database.command("sql", "CREATE EDGE TYPE E"); - database.command("sql", "CREATE EDGE TYPE Base"); - database.command("sql", "CREATE EDGE TYPE Sub EXTENDS Base, E"); + database.command("sql", "CREATE DOCUMENT TYPE Base"); + database.command("sql", "CREATE EDGE TYPE Sub EXTENDS Base"); - final RID p1, p2; - database.begin(); - try { - p1 = database.newVertex("Person").set("name", "p1").save().getIdentity(); - p2 = database.newVertex("Person").set("name", "p2").save().getIdentity(); - database.lookupByRID(p1, true).asVertex().modify().newEdge("Base", p2).save(); - } finally { - database.commit(); - } + database.transaction(() -> database.command("sql", "INSERT INTO Base SET name = 'b1'").close()); assertThat(database.countType("Base", false)).isEqualTo(1); assertThat(database.countType("Sub", false)).isZero(); - // Base is not under E, so the whole-subtree check does not refuse; the loop must not refuse on Sub's behalf - // either, because Sub is empty. + // Base is a document type, so its own guard does not refuse; the loop must not refuse on Sub's behalf either, + // because Sub is empty. database.command("sql", "TRUNCATE TYPE Base POLYMORPHIC").close(); assertThat(database.countType("Base", true)).isZero(); diff --git a/engine/src/test/java/com/arcadedb/query/sql/executor/Issue8042TruncateTypeGraphGuardTest.java b/engine/src/test/java/com/arcadedb/query/sql/executor/Issue8042TruncateTypeGraphGuardTest.java new file mode 100644 index 00000000000..63dc6173555 --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/sql/executor/Issue8042TruncateTypeGraphGuardTest.java @@ -0,0 +1,302 @@ +/* + * 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.exception.CommandExecutionException; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * https://github.com/ArcadeData/arcadedb/issues/8042 + *

+ * {@code TruncateTypeStatement.executeDDL} refuses to truncate a non-empty graph type unless {@code UNSAFE} is + * given, and that refusal is the only thing between {@code TRUNCATE TYPE Person} and the silent emptying of a live + * vertex type. It could not fire: the test was {@code typez.isSubTypeOf("V")}/{@code isSubTypeOf("E")}, which + * matches by NAME - this type's own, then recursively its super types' - and ArcadeDB has no implicit root types + * called {@code V} and {@code E} (that is an OrientDB inheritance). {@code CREATE VERTEX TYPE Person} builds a + * {@code VertexType} with an EMPTY super-type list, so for every vertex and edge type a user actually creates both + * tests answered false and the truncate proceeded with the documented {@code UNSAFE} escape hatch never demanded. + *

+ * The hierarchies below deliberately contain NO type called {@code V} or {@code E}, which is what the #7919 + * regression test's own hierarchy relies on and why it went on passing over a dead check. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +public class Issue8042TruncateTypeGraphGuardTest extends TestHelper { + + @Test + void aNonEmptyVertexTypeIsRefusedWithoutUnsafe() { + database.command("sql", "CREATE VERTEX TYPE Person").close(); + database.transaction(() -> database.command("sql", "INSERT INTO Person SET name = 'a'").close()); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE Person").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty vertex classes") + .hasMessageContaining("UNSAFE"); + + assertThat(count("Person")).isEqualTo(1); + } + + @Test + void aNonEmptyEdgeTypeIsRefusedWithoutUnsafe() { + database.command("sql", "CREATE VERTEX TYPE Person").close(); + database.command("sql", "CREATE EDGE TYPE Knows").close(); + database.transaction(() -> { + database.command("sql", "INSERT INTO Person SET name = 'a'").close(); + database.command("sql", "INSERT INTO Person SET name = 'b'").close(); + database.command("sql", + "CREATE EDGE Knows FROM (SELECT FROM Person WHERE name = 'a') TO (SELECT FROM Person WHERE name = 'b')").close(); + }); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE Knows").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty edge classes") + .hasMessageContaining("UNSAFE"); + + assertThat(count("Knows")).isEqualTo(1); + assertThat(count("Person")).isEqualTo(2); + } + + @Test + void unsafeStillTruncatesAVertexType() { + // THE ESCAPE HATCH THE MESSAGE NAMES HAS TO KEEP WORKING - THAT IS WHAT MAKES THE REFUSAL ACCEPTABLE + database.command("sql", "CREATE VERTEX TYPE Person").close(); + database.transaction(() -> database.command("sql", "INSERT INTO Person SET name = 'a'").close()); + + database.command("sql", "TRUNCATE TYPE Person UNSAFE").close(); + + assertThat(count("Person")).isZero(); + } + + @Test + void anEmptyVertexTypeIsStillTruncatedWithoutUnsafe() { + // THE GUARD IS KEYED ON recs > 0: AN EMPTY TYPE HAS NOTHING TO LOSE AND MUST NOT START BEING REFUSED + database.command("sql", "CREATE VERTEX TYPE Person").close(); + + database.command("sql", "TRUNCATE TYPE Person").close(); + + assertThat(count("Person")).isZero(); + } + + @Test + void aNonEmptyDocumentTypeIsStillTruncatedWithoutUnsafe() { + // THE GUARD IS ABOUT GRAPH TYPES ONLY: A PLAIN DOCUMENT TYPE HAS NO EDGES TO STRAND + database.command("sql", "CREATE DOCUMENT TYPE Doc").close(); + database.transaction(() -> database.command("sql", "INSERT INTO Doc SET name = 'a'").close()); + + database.command("sql", "TRUNCATE TYPE Doc").close(); + + assertThat(count("Doc")).isZero(); + } + + @Test + void aPolymorphicTruncateIsRefusedForANonEmptyVertexSubtype() { + // THE HALF #7919 REWROTE: THE COUNT IT CORRECTED FEEDS THIS CHECK, AND THE CHECK WAS DEAD. NO TYPE IN THIS + // HIERARCHY IS CALLED V, WHICH IS EXACTLY WHAT #7919's OWN TEST RELIED ON + database.command("sql", "CREATE VERTEX TYPE VBase").close(); + database.command("sql", "CREATE VERTEX TYPE VSub EXTENDS VBase").close(); + database.command("sql", "CREATE VERTEX TYPE VGrandSub EXTENDS VSub").close(); + database.transaction(() -> database.command("sql", "INSERT INTO VGrandSub SET x = 1").close()); + + // THE ROOT'S OWN GUARD ANSWERS FIRST HERE, BECAUSE A POLYMORPHIC countType() ALREADY SEES THE GRANDCHILD'S + // RECORD. THAT IS THE POINT: BEFORE THE FIX NEITHER THIS GUARD NOR THE PER-SUBTYPE LOOP BELOW IT COULD FIRE AT + // ALL AND THE WHOLE SUBTREE WAS EMPTIED IN SILENCE + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE VBase POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty vertex classes"); + + assertThat(count("VGrandSub")).isEqualTo(1); + + database.command("sql", "TRUNCATE TYPE VBase POLYMORPHIC UNSAFE").close(); + assertThat(count("VGrandSub")).isZero(); + } + + @Test + void theSubtypeLoopNamesTheNonEmptyVertexSubtypeUnderADocumentRoot() { + // THE ONE SHAPE THAT REACHES THE PER-SUBTYPE LOOP #7919 REWROTE: A DOCUMENT ROOT PASSES ITS OWN GUARD (IT IS + // NEITHER A VertexType NOR AN EdgeType, WHATEVER ITS POLYMORPHIC COUNT), SO THE LOOP IS WHAT HAS TO REFUSE ON + // BEHALF OF THE GRAPH SUBTYPE UNDER IT - AND IT NAMES IT + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE VChild EXTENDS DocRoot").close(); + database.transaction(() -> database.command("sql", "INSERT INTO VChild SET x = 1").close()); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty vertex classes") + .hasMessageContaining("VChild"); + + assertThat(count("VChild")).isEqualTo(1); + } + + @Test + void aGraphLeafIsFoundBehindADocumentTypeIntermediateNode() { + // getSubTypes() answers DIRECT children only, so a guard that walks one level down is blind to + // DocRoot -> DocMiddle -> VLeaf: neither the root nor DocMiddle is a graph type, so neither names a reason to + // refuse, while the polymorphic scanType() below happily deletes VLeaf's records. The scope of a POLYMORPHIC + // truncate is the whole subtree, so the guard has to read the whole subtree (CodeRabbit on PR #8094). + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE DOCUMENT TYPE DocMiddle EXTENDS DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE VLeaf EXTENDS DocMiddle").close(); + database.transaction(() -> database.command("sql", "INSERT INTO VLeaf SET x = 1").close()); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty vertex classes") + .hasMessageContaining("VLeaf"); + + assertThat(count("VLeaf")).isEqualTo(1); + + database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC UNSAFE").close(); + assertThat(count("VLeaf")).isZero(); + } + + @Test + void anEdgeLeafIsFoundBehindTwoDocumentTypeIntermediateNodes() { + // The same shape one level deeper, and on the edge arm, so the recursion is pinned rather than a single extra + // getSubTypes() hop. + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE DOCUMENT TYPE DocMiddle EXTENDS DocRoot").close(); + database.command("sql", "CREATE DOCUMENT TYPE DocLower EXTENDS DocMiddle").close(); + database.command("sql", "CREATE EDGE TYPE ELeaf EXTENDS DocLower").close(); + database.command("sql", "CREATE VERTEX TYPE Person").close(); + database.transaction(() -> { + database.command("sql", "INSERT INTO Person SET name = 'a'").close(); + database.command("sql", "INSERT INTO Person SET name = 'b'").close(); + database.command("sql", + "CREATE EDGE ELeaf FROM (SELECT FROM Person WHERE name = 'a') TO (SELECT FROM Person WHERE name = 'b')").close(); + }); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty edge classes") + .hasMessageContaining("ELeaf"); + + assertThat(count("ELeaf")).isEqualTo(1); + } + + @Test + void anEmptyGraphAncestorIsNotBlamedForItsDescendantsRecords() { + // A chain of TWO graph levels under a non-graph root. Counting each descendant polymorphically charged VLeaf's + // record to the empty VMiddle above it, and the walk reaches VMiddle first, so the refusal named the one type + // in the subtree that holds nothing (CodeRabbit on PR #8094). Refusing was right; naming VMiddle was not. + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE VMiddle EXTENDS DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE VLeaf EXTENDS VMiddle").close(); + database.transaction(() -> database.command("sql", "INSERT INTO VLeaf SET x = 1").close()); + + assertThat(count("VMiddle")).as("the intermediate holds nothing of its own").isEqualTo(1); + assertThat(database.countType("VMiddle", false)).isZero(); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty vertex classes") + .hasMessageContaining("VLeaf") + .hasMessageNotContaining("VMiddle"); + } + + @Test + void anEmptyLightweightAncestorIsNotBlamedForItsSubtypesEdges() { + // The lightweight twin of the case above. A LIGHTWEIGHT edge allocates no record, so countType() answers 0 for + // it however many edges it holds (#7477) and only a count(*) walk can see them - but count(*) is + // unconditionally polymorphic, so the empty LWAnc absorbed LWSub's edge and, being reached first, was named + // (CodeRabbit on PR #8094). A record-backed sibling is in the same subtree to pin that the two count paths + // agree on which type to blame. + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE Person").close(); + database.command("sql", "CREATE EDGE TYPE LWAnc EXTENDS DocRoot LIGHTWEIGHT").close(); + database.command("sql", "CREATE EDGE TYPE LWSub EXTENDS LWAnc LIGHTWEIGHT").close(); + database.transaction(() -> { + database.command("sql", "INSERT INTO Person SET name = 'a'").close(); + database.command("sql", "INSERT INTO Person SET name = 'b'").close(); + database.command("sql", + "CREATE EDGE LWSub FROM (SELECT FROM Person WHERE name = 'a') TO (SELECT FROM Person WHERE name = 'b')").close(); + }); + + assertThat(count("LWAnc")).as("polymorphically the ancestor sees its subtype's edge").isEqualTo(1); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty edge classes") + .hasMessageContaining("LWSub") + .hasMessageNotContaining("LWAnc"); + } + + @Test + void anEmptyLightweightAncestorWithARecordBackedSubtypeNamesTheRecordBackedOne() { + // Same shape, but the non-empty subtype is RECORD-BACKED under a lightweight ancestor: a type's own LIGHTWEIGHT + // flag is independent of its parent's, so this is a legal hierarchy and the two count paths have to agree on + // which type to name. + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE Person").close(); + database.command("sql", "CREATE EDGE TYPE LWAnc EXTENDS DocRoot LIGHTWEIGHT").close(); + database.command("sql", "CREATE EDGE TYPE HeavySub EXTENDS LWAnc").close(); + database.transaction(() -> { + database.command("sql", "INSERT INTO Person SET name = 'a'").close(); + database.command("sql", "INSERT INTO Person SET name = 'b'").close(); + database.command("sql", + "CREATE EDGE HeavySub FROM (SELECT FROM Person WHERE name = 'a') TO (SELECT FROM Person WHERE name = 'b')").close(); + }); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close()) + .isInstanceOf(CommandExecutionException.class) + .hasMessageContaining("not empty edge classes") + .hasMessageContaining("HeavySub") + .hasMessageNotContaining("LWAnc"); + } + + @Test + void anEmptyGraphLeafBehindADocumentIntermediateIsNotBlamed() { + // The recursion must not start refusing a subtree that holds nothing: only a non-empty graph descendant is a + // reason to demand UNSAFE. + database.command("sql", "CREATE DOCUMENT TYPE DocRoot").close(); + database.command("sql", "CREATE DOCUMENT TYPE DocMiddle EXTENDS DocRoot").close(); + database.command("sql", "CREATE VERTEX TYPE VLeaf EXTENDS DocMiddle").close(); + database.transaction(() -> database.command("sql", "INSERT INTO DocRoot SET x = 1").close()); + + database.command("sql", "TRUNCATE TYPE DocRoot POLYMORPHIC").close(); + + assertThat(count("DocRoot")).isZero(); + } + + @Test + void truncateTypeAndTruncateBucketNowAgreeOnTheSameVertexType() { + // THE SHORTEST STATEMENT OF THE WHOLE FINDING: TRUNCATE BUCKET REFUSED WHERE TRUNCATE TYPE DID NOT, ON THE SAME + // DATA, WITH THE SAME MESSAGE TEMPLATE + database.command("sql", "CREATE VERTEX TYPE Person BUCKETS 1").close(); + database.transaction(() -> database.command("sql", "INSERT INTO Person SET name = 'a'").close()); + + final String bucketName = database.getSchema().getType("Person").getBuckets(false).getFirst().getName(); + + assertThatThrownBy(() -> database.command("sql", "TRUNCATE BUCKET `" + bucketName + "`").close()) + .isInstanceOf(CommandExecutionException.class).hasMessageContaining("not empty vertex bucket"); + assertThatThrownBy(() -> database.command("sql", "TRUNCATE TYPE Person").close()) + .isInstanceOf(CommandExecutionException.class).hasMessageContaining("not empty vertex classes"); + + assertThat(count("Person")).isEqualTo(1); + } + + private long count(final String typeName) { + return ((Number) database.query("sql", "SELECT count(*) AS c FROM `" + typeName + "`").nextIfAvailable() + .getProperty("c")).longValue(); + } +} diff --git a/engine/src/test/java/com/arcadedb/schema/Issue8064SetAliasesAtomicReservationTest.java b/engine/src/test/java/com/arcadedb/schema/Issue8064SetAliasesAtomicReservationTest.java new file mode 100644 index 00000000000..77e574ebfbf --- /dev/null +++ b/engine/src/test/java/com/arcadedb/schema/Issue8064SetAliasesAtomicReservationTest.java @@ -0,0 +1,189 @@ +/* + * 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.schema; + +import com.arcadedb.TestHelper; +import com.arcadedb.exception.SchemaException; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * https://github.com/ArcadeData/arcadedb/issues/8064 + *

+ * {@code LocalDocumentType.setAliases} mutated the schema's shared type map with a check-then-act sequence and no + * write lock, which is the arrangement {@code rename()}, {@code createProperty} and {@code dropProperty} were just + * converted away from. Two holes in the one method: + *

    + *
  1. Check-then-put. It refused an alias already used by another type through + * {@code schema.existsType(alias)} and put the alias into {@code schema.typeMap()} several statements later, with + * nothing holding the map in between - so two concurrent {@code ALTER TYPE ... ALIASES} on different types could + * both pass the check and the second put silently won, leaving two types believing they owned one name.
  2. + *
  3. Unconditional deregistration. EVERY previous alias was removed from the map before the new set was + * installed, so a reader resolving one of those names saw it disappear even when the new set still carried it.
  4. + *
+ * The class's own comment on the {@code aliases} field already claimed the protection the method never took. + * + * @author Luca Garulli (l.garulli@arcadedata.com) + */ +public class Issue8064SetAliasesAtomicReservationTest extends TestHelper { + + private static final int CONCURRENT_ATTEMPTS = 32; + + @Test + void twoConcurrentSetAliasesOnTheSameNameCannotBothSucceed() throws Exception { + for (int attempt = 0; attempt < CONCURRENT_ATTEMPTS; attempt++) { + final String contested = "Shared" + attempt; + final LocalDocumentType first = (LocalDocumentType) database.getSchema().createDocumentType("A" + attempt); + final LocalDocumentType second = (LocalDocumentType) database.getSchema().createDocumentType("B" + attempt); + + final CountDownLatch start = new CountDownLatch(1); + final AtomicInteger succeeded = new AtomicInteger(); + final AtomicReference unexpected = new AtomicReference<>(); + + final Thread[] threads = new Thread[2]; + for (int t = 0; t < 2; t++) { + final LocalDocumentType claimant = t == 0 ? first : second; + threads[t] = new Thread(() -> { + try { + start.await(); + claimant.setAliases(Set.of(contested)); + succeeded.incrementAndGet(); + } catch (final SchemaException e) { + // THE EXPECTED LOSER'S OUTCOME + } catch (final Throwable e) { + unexpected.set(e); + } + }); + threads[t].start(); + } + + start.countDown(); + for (final Thread thread : threads) { + thread.join(TimeUnit.SECONDS.toMillis(30)); + // ASSERTED, NOT ASSUMED: A join() THAT TIMED OUT LEAVES THE CLAIMANT STILL RUNNING, AND EVERY ASSERTION + // BELOW WOULD THEN BE READING A HALF-FINISHED RESERVATION AND BLAMING IT ON THE FIX + assertThat(thread.isAlive()).as("claimant thread did not finish on attempt " + attempt).isFalse(); + } + + assertThat(unexpected.get()).as("unexpected failure on attempt " + attempt).isNull(); + assertThat(succeeded.get()).as("exactly one claimant may take '" + contested + "'").isEqualTo(1); + + // AND THE MAP AND THE TWO TYPES AGREE ON WHO WON: EXACTLY ONE OF THEM CARRIES THE ALIAS IN ITS OWN SET, AND + // THAT IS THE ONE THE NAME RESOLVES TO + final DocumentType resolved = database.getSchema().getType(contested); + assertThat(resolved).isNotNull(); + assertThat(first.getAliases().contains(contested) ^ second.getAliases().contains(contested)).isTrue(); + assertThat(resolved.getName()).isEqualTo(first.getAliases().contains(contested) ? first.getName() : second.getName()); + } + } + + @Test + void anAliasTheNewSetStillCarriesIsNeverDeregistered() { + final LocalDocumentType order = (LocalDocumentType) database.getSchema().createDocumentType("Order"); + order.setAliases(Set.of("PO", "PurchaseOrder")); + + // A SUPERSET: BOTH PREVIOUS NAMES SURVIVE, SO NEITHER MAY EVER LEAVE THE MAP + order.setAliases(Set.of("PO", "PurchaseOrder", "Ordine")); + + assertThat(database.getSchema().getType("PO").getName()).isEqualTo("Order"); + assertThat(database.getSchema().getType("PurchaseOrder").getName()).isEqualTo("Order"); + assertThat(database.getSchema().getType("Ordine").getName()).isEqualTo("Order"); + assertThat(order.getAliases()).containsExactlyInAnyOrder("PO", "PurchaseOrder", "Ordine"); + } + + @Test + void anAliasTheNewSetDropsStopsResolving() { + final LocalDocumentType order = (LocalDocumentType) database.getSchema().createDocumentType("Order"); + order.setAliases(Set.of("PO", "PurchaseOrder")); + + order.setAliases(Set.of("PO")); + + assertThat(database.getSchema().existsType("PurchaseOrder")).isFalse(); + assertThat(database.getSchema().getType("PO").getName()).isEqualTo("Order"); + assertThat(order.getAliases()).containsExactly("PO"); + + order.setAliases(Set.of()); + assertThat(database.getSchema().existsType("PO")).isFalse(); + assertThat(order.getAliases()).isEmpty(); + } + + @Test + void aRefusedCallLeavesNoHalfInstalledAliasBehind() { + final LocalDocumentType order = (LocalDocumentType) database.getSchema().createDocumentType("Order"); + database.getSchema().createDocumentType("Invoice"); + + // ONE FREE NAME AND ONE ALREADY TAKEN. WHICHEVER ORDER THE SET ITERATES IN, THE FREE ONE MUST NOT SURVIVE A + // CALL THAT WAS REFUSED - THE ALIASES ARE ALL-OR-NOTHING + assertThatThrownBy(() -> order.setAliases(new HashSet<>(Set.of("PO", "Invoice")))).isInstanceOf(SchemaException.class) + .hasMessageContaining("Invoice"); + + assertThat(order.getAliases()).isEmpty(); + assertThat(database.getSchema().existsType("PO")).isFalse(); + assertThat(database.getSchema().getType("Invoice").getName()).isEqualTo("Invoice"); + } + + @Test + void anAliasEqualToTheTypesOwnNameIsRefusedWithoutBlamingItself() { + // The type map holds the type's own name too, so putIfAbsent hands back THIS type - and the generic wording + // would name it on both sides of the sentence, which reads as an engine bug rather than as a refusal. + final LocalDocumentType order = (LocalDocumentType) database.getSchema().createDocumentType("Order"); + + assertThatThrownBy(() -> order.setAliases(Set.of("Order"))).isInstanceOf(SchemaException.class) + .hasMessageContaining("is the name of the type itself") + .hasMessageNotContaining("already used by type"); + + assertThat(order.getAliases()).isEmpty(); + assertThat(database.getSchema().getType("Order").getName()).isEqualTo("Order"); + } + + @Test + void aRefusedCallKeepsThePreviousAliasesIntact() { + final LocalDocumentType order = (LocalDocumentType) database.getSchema().createDocumentType("Order"); + order.setAliases(Set.of("PO")); + database.getSchema().createDocumentType("Invoice"); + + assertThatThrownBy(() -> order.setAliases(new HashSet<>(Set.of("PO", "Invoice")))).isInstanceOf(SchemaException.class); + + assertThat(order.getAliases()).containsExactly("PO"); + assertThat(database.getSchema().getType("PO").getName()).isEqualTo("Order"); + } + + @Test + void aliasesSurviveAReopen() { + final LocalDocumentType order = (LocalDocumentType) database.getSchema().createDocumentType("Order"); + order.setAliases(Set.of("PO", "PurchaseOrder")); + + // recordFileChanges() SAVES schema.json ITSELF, WHICH IS WHY THE EXPLICIT saveConfiguration() CALL WENT AWAY - + // THIS IS WHAT PROVES THE SAVE STILL HAPPENS + reopenDatabase(); + + assertThat(database.getSchema().getType("PO").getName()).isEqualTo("Order"); + assertThat(database.getSchema().getType("PurchaseOrder").getName()).isEqualTo("Order"); + } +}