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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions docs/release-26.8.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -1660,3 +1660,95 @@ An index that already exists on disk is unaffected either way - the page size is
a builder.

**Full Changelog**: https://github.com/ArcadeData/arcadedb/compare/26.7.2...26.8.1

## `CREATE INDEX IF NOT EXISTS` no longer reports success for an index that is not the one asked for

`IF NOT EXISTS` matched a pre-existing index on the indexed property set alone. The property set is what the index
name is derived from, and it says nothing about what the index does, so a `NOTUNIQUE` index answered "already there"
to a request for a `UNIQUE` one:

```sql
CREATE INDEX ON T (Scalar) NOTUNIQUE;
CREATE INDEX IF NOT EXISTS ON T (Scalar) UNIQUE; -- reported success, created no constraint
INSERT INTO T SET Scalar = 'x';
INSERT INTO T SET Scalar = 'x'; -- accepted
```

Schema-migration DDL uses `IF NOT EXISTS` precisely so it can be re-applied, so tightening an index from `NOTUNIQUE`
to `UNIQUE` did nothing while the application carried on believing a uniqueness constraint protected its data. Issue
#5675. The same statement without the guard reported the clash, which is what made the guard the thing suppressing an
error the server already knew how to raise.

`IF NOT EXISTS` is now satisfied only when the existing index provides what was asked for: the same index kind, and a
uniqueness constraint at least as strong.

- A `UNIQUE` index still satisfies a `NOTUNIQUE` request. It indexes exactly the same keys, so the statement stays the
no-op it was, and it is never weakened into a plain index.
- A `NOTUNIQUE` index no longer satisfies a `UNIQUE` request. The statement is refused, naming both definitions.
- An index of a different KIND on the same properties - a `FULL_TEXT` index where a range index was asked for, or the
reverse - is refused for the same reason. That one was silent too.

### An existing index is never dropped implicitly any more

The refusal is the answer even in the case the request could technically be granted by rebuilding. Underneath,
`TypeIndexBuilder.create()` with `withIgnoreIfExists(true)` used to drop the existing index and rebuild it with the
requested definition. That is not a recoverable operation: if the rebuild then fails on the data already stored - two
records sharing the key the new index has to keep unique - the type is left with **no index at all** and an error. On
an index the type only inherited it took away the parent type's index instead, which is issue #4083.

So `withIgnoreIfExists` now means only what it says. Callers that genuinely mean "make this the definition" opt in
explicitly:

```java
database.getSchema().buildTypeIndex("T", new String[] { "Scalar" })
.withType(Schema.INDEX_TYPE.LSM_TREE).withUnique(true)
.withReplaceIfIncompatible(true) // new: may take away the plain index on those properties
.create();
```

and even then the replacement is undone if the new index cannot be built, so a failed upgrade costs an error rather
than an index. An inherited index is still never replaced.

### Cypher: a uniqueness constraint over a plain index still upgrades it

`CREATE CONSTRAINT ... REQUIRE ... IS UNIQUE` and `... IS NODE KEY` are statements about the data rather than requests
to create an index if one is missing, so they are the callers that opt into the replacement above. Neo4j keeps the
range index and the constraint as two separate objects; ArcadeDB has one index per property set and a unique index
covers both roles, so the upgrade is the equivalent end state and a Neo4j migration script that creates indexes and
then constraints keeps working. Cypher's own `CREATE INDEX` does not opt in: it finds a unique index sufficient and
leaves it alone rather than replacing it with a plain one.

### A manual index name that already names a different index

Reachable only through `CREATE INDEX <name> IF NOT EXISTS ...`, since the auto-derived name is built from the property
list. A name that already belongs to an index on other properties used to satisfy the guard; it is now reported, since
two different property sets under one name are two different indexes.

### The index kind is now read before the existing-index lookup

`TypeIndexBuilder.create()` validates `indexType` at the top, because deciding whether the index already on those
properties covers the request needs to know what the request is. One embedded-API shape changes as a result: a builder
with **no** `withType(...)` and `withIgnoreIfExists(true)` used to hand back the existing index on those properties,
and now raises `DatabaseMetadataException` the way it always did when no index was there. Every in-tree caller sets the
type; a get-or-create helper that relied on omitting it has to pass the type it expects.

A failed replacement restores the page size along with the rest of the definition, via `getPageSizeForNewFile()` - the
same accessor a rebuild uses, so a page size the current file carries but creation would refuse cannot turn the restore
into a second failure (#5713).

### BREAKING: `getOrCreateTypeIndex` no longer upgrades an incompatible index

This one surfaces at runtime rather than at compile time, so it is the change embedded callers are most likely to meet
without warning.

`LocalSchema.getOrCreateTypeIndex(...)` sets `withIgnoreIfExists(true)`, so it inherits the change above: asked for a
`UNIQUE` index where a `NOTUNIQUE` one already covers those properties, it used to drop and rebuild, and now raises
`IllegalArgumentException` naming both definitions. That is the point of the fix - the rebuild is what could leave the
type with no index - but embedded callers using it as an "ensure this index" helper across a schema change are the ones
who will meet the new exception. Either drop the old index explicitly, or build through
`buildTypeIndex(...).withReplaceIfIncompatible(true)` if replacing it really is what you mean.

The replacement restores the previous definition on failure, including a manual index name (carried on the index
metadata, the same route `CREATE INDEX <name>` uses) and the page size. It is not atomic, though: the drop and the
build are separate schema changes, so a process that dies between them leaves the type without an index on those
properties until one is created again. Only an explicit `withReplaceIfIncompatible` is exposed to that window.
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,10 @@ private void executeCreateConstraint(final CypherDDLStatement ddl, final Schema
b.withType(Schema.INDEX_TYPE.LSM_TREE);
b.withUnique(true);
b.withIgnoreIfExists(ddl.isIfNotExists());
// A constraint says what the data must satisfy, so a plain index already on the property is upgraded rather than
// reported as being in the way. Neo4j keeps the range index and the constraint as two objects; ArcadeDB has one
// index per property set, and a unique one indexes the same keys, so this is the equivalent end state (#5675).
b.withReplaceIfIncompatible(true);
if (anyUndeclared)
b.withDefaultKeyTypesForUndeclaredProperties(defaultKeyTypes);
b.create();
Expand Down Expand Up @@ -541,6 +545,9 @@ private void executeCreateConstraint(final CypherDDLStatement ddl, final Schema
b.withType(Schema.INDEX_TYPE.LSM_TREE);
b.withUnique(true);
b.withIgnoreIfExists(ddl.isIfNotExists());
// Same reasoning as the UNIQUE arm above: NODE KEY is a constraint, so it upgrades a plain index on the same
// properties instead of colliding with it.
b.withReplaceIfIncompatible(true);
if (anyUndeclared)
b.withDefaultKeyTypesForUndeclaredProperties(defaultKeyTypes);
b.create();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultInternal;
import com.arcadedb.query.sql.executor.ResultSet;
import com.arcadedb.schema.IndexBuilder;
import com.arcadedb.schema.Schema;
import com.arcadedb.schema.TypeFullTextIndexBuilder;
import com.arcadedb.schema.TypeGeoIndexBuilder;
Expand Down Expand Up @@ -166,6 +167,27 @@ else if ("UNIQUE".equalsIgnoreCase(typeAsString)) {

if (database.getSchema().existsIndex(name.getValue())) {
if (ifNotExists) {
// The name this matched on is derived from the indexed property set alone, so it says nothing about what the
// index actually does. Answering "already exists" on the name only meant a NOTUNIQUE index reported success to
// a request for a UNIQUE one, and the migration that asked for the constraint carried on without it (#5675).
final Index existing = database.getSchema().getIndexByName(name.getValue());
final List<String> requestedProperties = List.of(fields);

// Reachable only through a manual index name: the auto-derived form above is built from the type name and the
// property list, so a name match implies both already match. Index names are global, so a manual one can name
// an index on ANOTHER type, or on other properties of this one - either way it is a different index, and
// answering "already exists" would leave the requested one uncreated with nothing said about why.
if (!existing.getTypeName().equals(typeName.getStringValue())
|| !existing.getPropertyNames().equals(requestedProperties))
throw new IllegalArgumentException(
"Cannot create the index '" + name.getValue() + "' on type '" + typeName.getStringValue() + "' properties "
+ requestedProperties + " because an index with that name already exists on type '" + existing.getTypeName()
+ "' properties " + existing.getPropertyNames() + ". Drop it first or choose a different index name");

if (!IndexBuilder.satisfiesRequest(existing, indexType, unique))
throw IndexBuilder.conflictWithExistingIndex(existing, indexType, unique, typeName.getStringValue(),
requestedProperties);

final InternalResultSet rs = new InternalResultSet();
final ResultInternal result = new ResultInternal(context.getDatabase());
result.setProperty("operation", "create index");
Expand Down
106 changes: 99 additions & 7 deletions engine/src/main/java/com/arcadedb/schema/IndexBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import com.arcadedb.index.Index;
import com.arcadedb.index.lsm.LSMTreeIndexAbstract;

import java.util.List;

/**
* Builder class for index types.
*
Expand All @@ -44,15 +46,22 @@ public abstract class IndexBuilder<T extends Index> {
final Class<? extends Index> indexImplementation;
Schema.INDEX_TYPE indexType;
boolean unique;
int pageSize = PAGE_SIZE_UNSET;
LSMTreeIndexAbstract.NULL_STRATEGY nullStrategy = LSMTreeIndexAbstract.NULL_STRATEGY.SKIP;
int pageSize = PAGE_SIZE_UNSET;
LSMTreeIndexAbstract.NULL_STRATEGY nullStrategy = LSMTreeIndexAbstract.NULL_STRATEGY.SKIP;
Index.BuildIndexCallback callback;
boolean ignoreIfExists = false;
String indexName = null;
String filePath = null;
boolean ignoreIfExists = false;
/**
* Explicit permission to take away an index that does not provide what was asked for - see
* {@link #withReplaceIfIncompatible(boolean)}. Kept separate from {@link #ignoreIfExists} on purpose: "I can live
* with what is there" and "replace what is there" are different intents, and conflating them is what made a guarded
* {@code CREATE INDEX} silently rebuild an index the caller only meant to skip (issue #5675).
*/
boolean replaceIfIncompatible = false;
String indexName = null;
String filePath = null;
Type[] keyTypes;
int batchSize = BUILD_BATCH_SIZE;
int maxAttempts = 1;
int batchSize = BUILD_BATCH_SIZE;
int maxAttempts = 1;
/**
* The one and only metadata slot of the builder hierarchy. {@link TypeIndexBuilder} used to declare a field of the
* same name, which SHADOWED this one: {@code withMetadata()} wrote here while {@code create()} read there, so every
Expand All @@ -67,6 +76,69 @@ protected IndexBuilder(final DatabaseInternal database, final Class<? extends In
this.indexImplementation = indexImplementation;
}

/**
* Answers whether {@code existing} already provides everything the caller asked for, which is the only thing that
* makes an {@code IF NOT EXISTS} / {@link #withIgnoreIfExists(boolean)} request a legitimate no-op.
* <p>
* The kind of index has to match: a {@code FULL_TEXT} index on a property is not a range index on it, so answering
* success to a request for the other one leaves the caller with something it cannot use. Uniqueness is directional
* instead: a {@code UNIQUE} index indexes exactly the keys a {@code NOTUNIQUE} one would, so it covers a
* {@code NOTUNIQUE} request, while a {@code NOTUNIQUE} index does not carry the constraint a {@code UNIQUE} request
* is about - and reporting success there is what let a schema migration proceed believing a uniqueness constraint
* protected its data (issue #5675).
* <p>
* The null strategy is deliberately not part of this: unlike the kind and the uniqueness it is not structural - it
* is settable on an existing index through {@code ALTER} - so a mismatch is not a reason to refuse the statement.
* Note that a satisfied request stays a plain no-op: the requested strategy is NOT applied to the existing index,
* which is what {@code IF NOT EXISTS} asks for.
* <p>
* <b>Not compared either: the settings an index type keeps of its own</b> - vector {@code dimensions}, full-text
* analyzers, geospatial precision, collations. Two same-kind indexes configured differently still satisfy each other
* here, so a guarded {@code CREATE INDEX ... LSM_VECTOR} over an existing vector index with other dimensions stays a
* no-op. That is the same shape of surprise as issue #5675 one level down, and it is left open on purpose: those
* settings live in per-index-type {@link IndexMetadata} subclasses with no common notion of "provides at least what
* was asked for" (is a 768-dimension index acceptable to a request for 384? is a stricter analyzer?), and answering
* it needs a per-type rule rather than the structural comparison above.
*/
public static boolean satisfiesRequest(final Index existing, final Schema.INDEX_TYPE requestedType,
final boolean requestedUnique) {
if (existing.getType() != requestedType)
return false;
return existing.isUnique() || !requestedUnique;
}

/**
* Builds the error reported when an index on the same properties exists but {@link #satisfiesRequest} rejected it.
* <p>
* Refusing is the answer in every case, including the one the request could technically be granted by rebuilding:
* dropping the existing index to recreate it with the requested definition is not recoverable if the rebuild then
* fails on the data already stored - the type is left with no index at all - and on an inherited index it silently
* takes away the parent type's index (issue #4083). An explicit {@code DROP INDEX} is one statement away and leaves
* the operator in control of when the index disappears.
* <p>
* {@link IllegalArgumentException} on purpose: the HTTP layer maps it to a 400, which is what a schema request the
* server can read but cannot honour is.
*/
public static IllegalArgumentException conflictWithExistingIndex(final Index existing,
final Schema.INDEX_TYPE requestedType, final boolean requestedUnique, final String requestedTypeName,
final List<String> requestedProperties) {
final boolean inherited = !existing.getTypeName().equals(requestedTypeName);
return new IllegalArgumentException(
"Cannot create the index on type '" + requestedTypeName + "' properties " + requestedProperties + " as "
+ describeDefinition(requestedType, requestedUnique) + " because the index '" + existing.getName()
+ "' already exists on " + (inherited ? "the parent type '" + existing.getTypeName() + "' and " : "")
+ "the same properties as " + describeDefinition(existing.getType(), existing.isUnique())
+ (inherited ?
". Drop the parent index or align the definition: it is not replaced implicitly because that would take "
+ "the index away from the parent type" :
". Drop the existing index first: it is not replaced implicitly because a rebuild that the stored data "
+ "cannot satisfy would leave the type with no index at all"));
}

private static String describeDefinition(final Schema.INDEX_TYPE indexType, final boolean unique) {
return indexType + " (unique=" + unique + ")";
}

public abstract T create();

public IndexBuilder<T> withType(final Schema.INDEX_TYPE indexType) {
Expand Down Expand Up @@ -98,6 +170,26 @@ public IndexBuilder<T> withIgnoreIfExists(final boolean ignoreIfExists) {
return this;
}

/**
* Allows the index already defined on the same properties to be replaced when it does not provide what this builder
* asks for - see {@link #satisfiesRequest}. Without it such a request is refused, because a rebuild the stored data
* cannot satisfy would leave the type with no index at all.
* <p>
* Only for callers whose statement genuinely means "make this the definition", not merely "create it if missing":
* the Cypher {@code CREATE CONSTRAINT ... IS UNIQUE} over a property that already carries a plain index is the one
* in the engine today. Neo4j keeps the range index and the constraint as two separate objects there; ArcadeDB has a
* single index per property set, and a unique one indexes exactly the same keys, so upgrading it is the equivalent
* end state.
* <p>
* An index the type only INHERITS is never replaced even with this set - taking it away would silently remove the
* parent type's index (issue #4083). The replacement is also undone if the new index cannot be built, so a failed
* upgrade leaves the previous definition in place.
*/
public IndexBuilder<T> withReplaceIfIncompatible(final boolean replaceIfIncompatible) {
this.replaceIfIncompatible = replaceIfIncompatible;
return this;
}

/**
* Requests an explicit page size for the index file. Any value below 1 means "unset", leaving the choice to the
* index implementation - see {@link #getPageSize(int)}, which is the single place that resolves it. Normalising
Expand Down
Loading
Loading