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
36 changes: 30 additions & 6 deletions engine/src/main/java/com/arcadedb/schema/LocalSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -2441,24 +2441,30 @@ public boolean existsType(final String typeName) {
public void dropType(final String typeName) {
database.checkPermissionsOnDatabase(SecurityDatabaseUser.DATABASE_ACCESS.UPDATE_SCHEMA);

// THE GUARDS BELOW COMPARE THE CANONICAL NAME, NOT THE STRING THE CALLER TYPED (#8169). getType() further down
// resolves aliases, so typeName can be an alias - and comparing the raw argument let DROP TYPE <alias> walk
// straight past these checks and drop a materialized view's backing or source type out from under it.
final LocalDocumentType resolvedType = getTypeOrNull(typeName);
final String canonicalTypeName = resolvedType != null ? resolvedType.getName() : typeName;

// Prevent dropping a type that is a backing type or source type for a materialized view or continuous aggregate
synchronized (this) {
for (final MaterializedViewImpl view : materializedViews.values()) {
if (view.getBackingTypeName().equals(typeName))
if (view.getBackingTypeName().equals(canonicalTypeName))
throw new SchemaException(
"Cannot drop type '" + typeName + "' because it is the backing type for materialized view '" + view.getName() + "'. " +
"Drop the materialized view first with: DROP MATERIALIZED VIEW " + view.getName());
if (view.getSourceTypeNames().contains(typeName))
if (view.getSourceTypeNames().contains(canonicalTypeName))
throw new SchemaException(
"Cannot drop type '" + typeName + "' because it is a source type for materialized view '" + view.getName() + "'. " +
"Drop the materialized view first with: DROP MATERIALIZED VIEW " + view.getName());
}
for (final ContinuousAggregateImpl ca : continuousAggregates.values()) {
if (ca.getBackingTypeName().equals(typeName))
if (ca.getBackingTypeName().equals(canonicalTypeName))
throw new SchemaException(
"Cannot drop type '" + typeName + "' because it is the backing type for continuous aggregate '" + ca.getName() + "'. " +
"Drop the continuous aggregate first with: DROP CONTINUOUS AGGREGATE " + ca.getName());
if (ca.getSourceTypeName().equals(typeName))
if (ca.getSourceTypeName().equals(canonicalTypeName))
throw new SchemaException(
"Cannot drop type '" + typeName + "' because it is the source type for continuous aggregate '" + ca.getName() + "'. " +
"Drop the continuous aggregate first with: DROP CONTINUOUS AGGREGATE " + ca.getName());
Expand All @@ -2473,7 +2479,10 @@ public void dropType(final String typeName) {
final String previousTypeBeingDropped = typeBeingDropped;
// Covers the whole cascade below, not just the index-drop loop: dropBucket() a few lines down can also
// reach dropIndexInternal() for a leftover bucket-associated index, and the suppression must hold there too.
typeBeingDropped = typeName;
// The CANONICAL name, for the same reason the guards above use it: line ~1785 compares this against
// affectedType.getName(), so a drop that named the type by an alias suppressed nothing and reported the
// partition suitability of a type that was being dropped (#8169).
typeBeingDropped = canonicalTypeName;

try {
final LocalDocumentType type = (LocalDocumentType) database.getSchema().getType(typeName);
Expand Down Expand Up @@ -2511,7 +2520,22 @@ public void dropType(final String typeName) {
if (type instanceof LocalTimeSeriesType tsType)
tsType.drop();

if (typeMap().remove(typeName) == null)
// EVERY NAME THE TYPE ANSWERS TO GOES, NOT ONLY THE ONE THE CALLER TYPED (#8169). Two reasons, and the
// second is the damaging one:
// - getType() above resolves aliases, so typeName can BE an alias. Removing that one key would leave the
// type registered under its own name with its buckets and indexes already torn down.
// - an alias key left behind keeps the dropped instance reachable through typeMap().values(), which
// toJSON() - reached from the saveConfiguration() in the finally below - writes back into schema.json
// keyed by t.getName(), so the dropped type is re-serialised under its own name with zero
// buckets and comes back alive, unusable, at the next open. It also kept existsType(alias) answering
// true, made a later ALTER TYPE ... ALIASES refuse the alias naming a type that no longer exists, and
// left the instance in getTypes(), which is what CHECK DATABASE walks.
// remove(key, value) rather than remove(key), for the same reason setAliases() unwinds with the two-argument
// form: a name that has since been taken over by another type must not be taken away from it.
for (final String alias : type.getAliases())
typeMap().remove(alias, type);

if (!typeMap().remove(type.getName(), type))
throw new SchemaException("Type '" + typeName + "' not found");
} finally {
typeBeingDropped = previousTypeBeingDropped;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
/*
* 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 com.arcadedb.serializer.json.JSONObject;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;

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

/**
* https://github.com/ArcadeData/arcadedb/issues/8169
* <p>
* {@code LocalSchema.dropType} removed exactly one key from the schema's shared type map - the type's own name - and
* nothing anywhere removed the alias keys, which kept pointing at the dropped, bucket-less {@code LocalDocumentType}
* instance. Three consequences, in increasing order of damage:
* <ol>
* <li>{@code existsType(alias)} kept answering {@code true} and {@code getType(alias)} kept handing out the
* dropped type.</li>
* <li>A later {@code ALTER TYPE Other ALIASES <alias>} was refused naming a type that no longer existed - #8064's
* atomic {@code putIfAbsent} turned the stale entry from a silent overwrite into a hard refusal.</li>
* <li>{@code toJSON()} - reached from {@code saveConfiguration()} - iterates {@code typeMap().values()} and
* keys each entry by {@code t.getName()}, so the dropped instance, still reachable through its surviving alias
* key, was written back into {@code schema.json} under its own name with zero buckets and came back alive at
* the next open.</li>
* </ol>
* The drop also resolves its argument through {@code getType()}, which resolves aliases, so {@code DROP TYPE <alias>}
* tore down the real type's buckets and indexes and then removed only the alias key, leaving the type itself
* registered under its own name and unusable.
*
* @author Luca Garulli (l.garulli@arcadedata.com)
*/
public class Issue8169DropTypeLeavesAliasesTest extends TestHelper {

@Test
void dropTypeDeregistersTheTypeAliases() {
final DocumentType order = database.getSchema().createDocumentType("Order");
database.getSchema().createDocumentType("Invoice");
order.setAliases(Set.of("PO", "PurchaseOrder"));

assertThat(database.getSchema().existsType("PO")).isTrue();
assertThat(database.getSchema().existsType("PurchaseOrder")).isTrue();

database.getSchema().dropType("Order");

assertThat(database.getSchema().existsType("Order")).isFalse();
assertThat(database.getSchema().existsType("PO")).isFalse();
assertThat(database.getSchema().existsType("PurchaseOrder")).isFalse();
assertThat(database.getSchema().getTypeOrNull("PO")).isNull();
assertThatThrownBy(() -> database.getSchema().getType("PO")).isInstanceOf(SchemaException.class);

// THE DROPPED INSTANCE IS NO LONGER LISTED: getTypes() deduplicates typeMap().values(), but a surviving alias
// key kept the instance IN those values
assertThat(database.getSchema().getTypes()).extracting(DocumentType::getName).containsExactly("Invoice");
}

@Test
void anAliasFreedByDropTypeCanBeClaimedByAnotherType() {
final DocumentType order = database.getSchema().createDocumentType("Order");
final DocumentType invoice = database.getSchema().createDocumentType("Invoice");
order.setAliases(Set.of("PO"));

database.getSchema().dropType("Order");

// BEFORE THE FIX THIS WAS REFUSED WITH "already used by type 'Order'", NAMING A TYPE THAT NO LONGER EXISTED
invoice.setAliases(Set.of("PO"));

assertThat(database.getSchema().existsType("PO")).isTrue();
assertThat(database.getSchema().getType("PO")).isSameAs(invoice);
}

@Test
void sqlDropTypeDeregistersTheTypeAliasesAndFreesThemForAlterType() {
database.command("sql", "CREATE DOCUMENT TYPE Order");
database.command("sql", "CREATE DOCUMENT TYPE Invoice");
database.command("sql", "ALTER TYPE Order ALIASES PO");

assertThat(database.getSchema().existsType("PO")).isTrue();

database.command("sql", "DROP TYPE Order");

assertThat(database.getSchema().existsType("Order")).isFalse();
assertThat(database.getSchema().existsType("PO")).isFalse();

database.command("sql", "ALTER TYPE Invoice ALIASES PO");

assertThat(database.getSchema().getType("PO").getName()).isEqualTo("Invoice");
}

@Test
void aDroppedTypeDoesNotComeBackAfterAReopen() throws IOException {
final DocumentType order = database.getSchema().createDocumentType("Order");
database.getSchema().createDocumentType("Invoice");
order.setAliases(Set.of("PO"));

database.getSchema().dropType("Order");

// THE FILE ITSELF, not only what the reopen makes of it: toJSON() keys typeMap().values() by t.getName(), and
// the dropped instance was still in those values through its surviving alias key, so it was written back under
// its own name with an empty bucket list
final JSONObject onDisk = new JSONObject(
Files.readString(Path.of(getDatabasePath(), "schema.json"), StandardCharsets.UTF_8));
assertThat(onDisk.getJSONObject("types").keySet()).containsExactly("Invoice");

reopenDatabase();

// THE ONE THAT MATTERS MOST: the dropped instance used to be re-serialised into schema.json under its own name
// with zero buckets, so it was back - permanently - at the next open, and unusable
assertThat(database.getSchema().existsType("Order")).isFalse();
assertThat(database.getSchema().existsType("PO")).isFalse();
assertThat(database.getSchema().getTypes()).extracting(DocumentType::getName).containsExactly("Invoice");
}

@Test
void dropTypeThroughAnAliasDropsTheTypeItself() {
final DocumentType order = database.getSchema().createDocumentType("Order");
database.getSchema().createDocumentType("Invoice");
order.setAliases(Set.of("PO"));

// getType() resolves aliases, so the drop tears down the real type. It has to deregister it under every name it
// answers to, not only under the alias the caller typed
database.getSchema().dropType("PO");

assertThat(database.getSchema().existsType("PO")).isFalse();
assertThat(database.getSchema().existsType("Order")).isFalse();

reopenDatabase();

assertThat(database.getSchema().existsType("Order")).isFalse();
assertThat(database.getSchema().existsType("PO")).isFalse();
}

@Test
void dropTypeThroughAnAliasIsStillRefusedForAMaterializedViewSourceType() {
database.transaction(() -> database.getSchema().createDocumentType("Employee"));
database.transaction(() -> database.getSchema().getType("Employee").setAliases(Set.of("Emp")));
database.transaction(() -> database.newDocument("Employee").set("name", "Alice").save());
database.transaction(() -> database.getSchema().buildMaterializedView()
.withName("EmployeeView")
.withQuery("SELECT name FROM Employee")
.withRefreshMode(MaterializedViewRefreshMode.INCREMENTAL)
.create());

// The guard used to compare the caller's string against the view's source type names, so naming the type by one
// of its aliases walked straight past it and dropped the view's source type out from under it
assertThatThrownBy(() -> database.getSchema().dropType("Emp"))
.isInstanceOf(SchemaException.class)
.hasMessageContaining("EmployeeView");

assertThat(database.getSchema().existsType("Employee")).isTrue();
assertThat(database.getSchema().existsType("Emp")).isTrue();
}

@Test
void dropTypeThroughAnAliasIsStillRefusedForAContinuousAggregateSourceType() {
database.command("sql",
"CREATE TIMESERIES TYPE SensorReading TIMESTAMP ts TAGS (sensor_id STRING) FIELDS (temperature DOUBLE)");
database.getSchema().getType("SensorReading").setAliases(Set.of("Sensor"));
database.transaction(() -> database.command("sql",
"INSERT INTO SensorReading SET ts = 1000, sensor_id = 'A', temperature = 22.5"));
database.getSchema().buildContinuousAggregate()
.withName("hourly_temps")
.withQuery("SELECT sensor_id, ts.timeBucket('1h', ts) AS hour, avg(temperature) AS avg_temp "
+ "FROM SensorReading GROUP BY sensor_id, hour")
.create();

// The continuous-aggregate guard is the twin of the materialized-view one above and was bypassed the same way
assertThatThrownBy(() -> database.getSchema().dropType("Sensor"))
.isInstanceOf(SchemaException.class)
.hasMessageContaining("hourly_temps");

assertThat(database.getSchema().existsType("SensorReading")).isTrue();
assertThat(database.getSchema().existsType("Sensor")).isTrue();
}

@Test
void dropTypeThroughAnAliasIsStillRefusedForAContinuousAggregateBackingType() {
database.command("sql",
"CREATE TIMESERIES TYPE SensorReading TIMESTAMP ts TAGS (sensor_id STRING) FIELDS (temperature DOUBLE)");
database.transaction(() -> database.command("sql",
"INSERT INTO SensorReading SET ts = 1000, sensor_id = 'A', temperature = 22.5"));
final String backingTypeName = database.getSchema().buildContinuousAggregate()
.withName("hourly_temps")
.withQuery("SELECT sensor_id, ts.timeBucket('1h', ts) AS hour, avg(temperature) AS avg_temp "
+ "FROM SensorReading GROUP BY sensor_id, hour")
.create()
.getBackingType()
.getName();

database.getSchema().getType(backingTypeName).setAliases(Set.of("HourlyTemps"));

assertThatThrownBy(() -> database.getSchema().dropType("HourlyTemps"))
.isInstanceOf(SchemaException.class)
.hasMessageContaining("hourly_temps");

assertThat(database.getSchema().existsType(backingTypeName)).isTrue();
assertThat(database.getSchema().existsType("HourlyTemps")).isTrue();
}
}
Loading