This is an automated email from the ASF dual-hosted git repository.
JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 0e0a3e0aaa8 Match literal asterisks in table device TAG equality
filters
0e0a3e0aaa8 is described below
commit 0e0a3e0aaa8dddba1ccb751a35ed7badfee55b76
Author: DaZuiZui <[email protected]>
AuthorDate: Tue Dec 1 19:36:55 2026 +0800
Match literal asterisks in table device TAG equality filters
---
.../iotdb/relational/it/schema/IoTDBDeviceIT.java | 147 +++++++++++++++++++++
.../fetcher/cache/TableDeviceSchemaCache.java | 79 +++++++----
.../schemaregion/impl/SchemaRegionMemoryImpl.java | 5 +-
.../mtree/impl/mem/MTreeBelowSGMemoryImpl.java | 85 +++++-------
.../source/DeviceBlackListConstructorTest.java | 4 +-
.../fetcher/cache/TableDeviceSchemaCacheTest.java | 68 ++++++++++
.../mtree/impl/mem/MTreeBelowSGMemoryImplTest.java | 61 ++++++++-
.../iotdb/commons/path/ExtendedPartialPath.java | 8 ++
.../schema/filter/impl/DeviceFilterUtil.java | 17 ++-
.../schema/filter/impl/DeviceFilterUtilTest.java | 38 +++++-
10 files changed, 426 insertions(+), 86 deletions(-)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBDeviceIT.java
b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBDeviceIT.java
index 75bf4646a50..feb8336dc33 100644
---
a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBDeviceIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBDeviceIT.java
@@ -33,11 +33,13 @@ import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.sql.Connection;
+import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -55,6 +57,151 @@ public class IoTDBDeviceIT {
EnvFactory.getEnv().cleanClusterEnvironment();
}
+ @Test
+ public void testLiteralAsteriskInDeviceTag() throws SQLException {
+ final String database = "literal_tag_test";
+ final String selectRack = "select name, v from sensors where name =
'rack*'";
+ final String showRack = "show devices from sensors where name = 'rack*'";
+ final String deleteByName = "delete devices from sensors where name = ";
+ // A delete that returns a result set must execute only once, even in a
multi-node test.
+ try (final Connection connection =
EnvFactory.getEnv().getAvailableTableConnection();
+ final Statement statement = connection.createStatement()) {
+ statement.execute("create database " + database);
+ statement.execute("use " + database);
+ statement.execute("create table sensors(name string tag, v int32
field)");
+ statement.execute(
+ "insert into sensors(time, name, v) values (1, 'rack*', 10), (1,
'rack1', 20),"
+ + " (1, '*rack', 30), (1, 'xrack', 40), (1, 'demo.page.*', 50),"
+ + " (1, 'demo.page.a', 60), (1, 'demoXpageYa', 70)");
+ // Make the filtered SELECT the first lookup on non-writer DataNodes.
+ TestUtils.tableResultSetEqualTestUnordered(
+ selectRack, new String[] {"name", "v"}, new String[] {"rack*,10,"},
database);
+ TestUtils.tableResultSetEqualTestUnordered(
+ showRack, new String[] {"name"}, new String[] {"rack*,"}, database);
+
+ assertDeletedDeviceCount(statement, deleteByName + "'rack*'", 1);
+ TestUtils.tableResultSetEqualTestUnordered(
+ selectRack, new String[] {"name", "v"}, new String[0], database);
+ TestUtils.tableResultSetEqualTestUnordered(
+ showRack, new String[] {"name"}, new String[0], database);
+ assertDeletedDeviceCount(statement, deleteByName + "'rack*'", 0);
+ assertDeletedDeviceCount(statement, deleteByName + "'*'", 0);
+ assertDeletedDeviceCount(statement, deleteByName + "'**'", 0);
+ assertDeletedDeviceCount(statement, deleteByName + "'*rack'", 1);
+ assertDeletedDeviceCount(statement, deleteByName + "'demo.page.*'", 1);
+
+ TestUtils.tableResultSetEqualTestUnordered(
+ "show devices from sensors",
+ new String[] {"name"},
+ new String[] {"rack1,", "xrack,", "demo.page.a,", "demoXpageYa,"},
+ database);
+ TestUtils.tableResultSetEqualTestUnordered(
+ "select name, v from sensors",
+ new String[] {"name", "v"},
+ new String[] {"rack1,20,", "xrack,40,", "demo.page.a,60,",
"demoXpageYa,70,"},
+ database);
+ }
+ }
+
+ @Test
+ public void testLiteralAsteriskInQuotedTableName() throws SQLException {
+ final String database = "literal_table_test";
+ try (final Connection connection =
EnvFactory.getEnv().getAvailableTableConnection();
+ final Statement statement = connection.createStatement()) {
+ statement.execute("create database " + database);
+ statement.execute("use " + database);
+ statement.execute("create table \"**\"(name string tag, zone string tag,
v int32 field)");
+ statement.execute(
+ "insert into \"**\"(time, name, zone, v) values (1, 'rack*', 'z',
10), (1, 'pump', 'z', 20)");
+ statement.execute("create table sensors(name string tag, zone string
tag, v int32 field)");
+ statement.execute(
+ "insert into sensors(time, name, zone, v) values (1, 'rack*',
'other', 30)");
+
+ TestUtils.tableResultSetEqualTestUnordered(
+ "show devices from \"**\" where name = 'rack*'",
+ new String[] {"name", "zone"},
+ new String[] {"rack*,z,"},
+ database);
+ assertDeletedDeviceCount(statement, "delete devices from \"**\" where
name = 'rack*'", 1);
+ TestUtils.tableResultSetEqualTestUnordered(
+ "show devices from \"**\"",
+ new String[] {"name", "zone"},
+ new String[] {"pump,z,"},
+ database);
+ TestUtils.tableResultSetEqualTestUnordered(
+ "show devices from sensors",
+ new String[] {"name", "zone"},
+ new String[] {"rack*,other,"},
+ database);
+ }
+ }
+
+ @Test
+ public void testDeleteCachedDeviceWithTrailingNullTag() throws SQLException {
+ final String database = "cached_null_tag_test";
+ try (final Connection connection =
EnvFactory.getEnv().getAvailableTableConnection();
+ final Statement statement = connection.createStatement()) {
+ statement.execute("create database " + database);
+ statement.execute("use " + database);
+ statement.execute("create table sensors(name string tag, zone string
tag, v int32 field)");
+ statement.execute(
+ "insert into sensors(time, name, zone, v) values (1, '*', null, 10),
(1, 'plain', 'north', 20)");
+
+ // Populate the device cache on each read node with both fully specified
device IDs.
+ TestUtils.tableResultSetEqualTestUnordered(
+ "select v from sensors where name = '*' and zone is null",
+ new String[] {"v"},
+ new String[] {"10,"},
+ database);
+ TestUtils.tableResultSetEqualTestUnordered(
+ "select v from sensors where name = 'plain' and zone = 'north'",
+ new String[] {"v"},
+ new String[] {"20,"},
+ database);
+ assertDeletedDeviceCount(
+ statement, "delete devices from sensors where name = '*' and zone is
null", 1);
+ TestUtils.tableResultSetEqualTestUnordered(
+ "show devices from sensors",
+ new String[] {"name", "zone"},
+ new String[] {"plain,north,"},
+ database);
+ }
+ }
+
+ @Test
+ public void testDeleteCachedDeviceWithAllNullTagsInQuotedTable() throws
SQLException {
+ final String database = "cached_all_null_tag_test";
+ final String select = "select model, v from \"**\" where name is null";
+ final String show = "show devices from \"**\" where name is null";
+ try (final Connection connection =
EnvFactory.getEnv().getAvailableTableConnection();
+ final Statement statement = connection.createStatement()) {
+ statement.execute("create database " + database);
+ statement.execute("use " + database);
+ statement.execute(
+ "create table \"**\"(name string tag, model string attribute, v
int32 field)");
+ statement.execute("insert into \"**\"(time, name, model, v) values (1,
null, 'old', 10)");
+
+ TestUtils.tableResultSetEqualTestUnordered(
+ select, new String[] {"model", "v"}, new String[] {"old,10,"},
database);
+ assertDeletedDeviceCount(statement, "delete devices from \"**\" where
name is null", 1);
+ TestUtils.tableResultSetEqualTestUnordered(
+ show, new String[] {"name", "model"}, new String[0], database);
+
+ statement.execute("insert into \"**\"(time, name, v) values (2, null,
20)");
+ TestUtils.tableResultSetEqualTestUnordered(
+ select, new String[] {"model", "v"}, new String[] {"null,20,"},
database);
+ }
+ }
+
+ private static void assertDeletedDeviceCount(Statement statement, String
sql, int expected)
+ throws SQLException {
+ try (ResultSet deleted = statement.executeQuery(sql)) {
+ assertTrue(deleted.next());
+ assertEquals(sql, String.valueOf(expected),
deleted.getString("num_of_deleted_devices"));
+ assertFalse(deleted.next());
+ }
+ }
+
@Test
public void testDevice() throws SQLException {
try (final Connection connection =
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
index 17f691d8542..01f106bac9d 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
@@ -57,6 +57,7 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -65,8 +66,9 @@ import java.util.Optional;
import java.util.OptionalLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Predicate;
import java.util.function.ToIntFunction;
-import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import static
org.apache.iotdb.commons.conf.IoTDBConstant.ONE_LEVEL_PATH_WILDCARD;
@@ -91,6 +93,9 @@ import static
org.apache.iotdb.commons.conf.IoTDBConstant.ONE_LEVEL_PATH_WILDCAR
@ThreadSafe
public class TableDeviceSchemaCache {
+ // Table device patterns start with root.database.table.
+ private static final int FIRST_TAG_NODE_INDEX = 3;
+
private static final IoTDBConfig config =
IoTDBDescriptor.getInstance().getConfig();
private static final DataNodeMemoryConfig memoryConfig =
IoTDBDescriptor.getInstance().getMemoryConfig();
@@ -730,37 +735,40 @@ public class TableDeviceSchemaCache {
readWriteLock.writeLock().lock();
try {
final TableId firstKey = new TableId(database, tableName);
- if (patterns.isEmpty()) {
+ if (patterns.isEmpty() || patterns.get(0).getNodeLength() ==
FIRST_TAG_NODE_INDEX) {
dualKeyCache.invalidate(firstKey);
- } else {
- final List<PartialPath> multiMatchList =
- patterns.stream()
- .filter(
- idFilter -> {
- if (!idFilter.hasWildcard()) {
- final IDeviceID deviceId =
- IDeviceID.Factory.DEFAULT_FACTORY.create(
- Arrays.copyOfRange(
- idFilter.getNodes(), 2,
idFilter.getNodeLength()));
- dualKeyCache.invalidate(firstKey, deviceId);
- return false;
- }
- return true;
- })
- .collect(Collectors.toList());
+ return;
+ }
+
+ final List<Predicate<IDeviceID>> matchers = new ArrayList<>();
+ for (final PartialPath pattern : patterns) {
+ if (!pattern.hasWildcard()) {
+ final IDeviceID deviceId =
+ IDeviceID.Factory.DEFAULT_FACTORY.create(
+ Arrays.copyOfRange(pattern.getNodes(), 2,
pattern.getNodeLength()));
+ dualKeyCache.invalidate(firstKey, deviceId);
+ continue;
+ }
+
+ final ExtendedPartialPath path = (ExtendedPartialPath) pattern;
+ final int[] constrainedNodes =
+ IntStream.range(FIRST_TAG_NODE_INDEX, path.getNodeLength())
+ .filter(i -> !path.isUnconstrainedWildcard(i))
+ .toArray();
+ if (constrainedNodes.length == 0) {
+ dualKeyCache.invalidate(firstKey);
+ return;
+ }
+ matchers.add(deviceId -> matchesDeviceTags(path, constrainedNodes,
deviceId));
+ }
+ if (!matchers.isEmpty()) {
dualKeyCache.invalidate(
firstKey,
deviceId -> {
- final String[] segments = (String[]) deviceId.getSegments();
- for (int i = 1; i < segments.length; ++i) {
- for (final PartialPath path : multiMatchList) {
- final int pathIndex = i + 2;
- if (path.getNodes()[pathIndex].equals(segments[i])
- ||
path.getNodes()[pathIndex].equals(ONE_LEVEL_PATH_WILDCARD)
- && ((ExtendedPartialPath) path).match(pathIndex,
segments[i])) {
- return true;
- }
+ for (final Predicate<IDeviceID> matcher : matchers) {
+ if (matcher.test(deviceId)) {
+ return true;
}
}
return false;
@@ -771,6 +779,23 @@ public class TableDeviceSchemaCache {
}
}
+ private static boolean matchesDeviceTags(
+ final ExtendedPartialPath path, final int[] constrainedNodes, final
IDeviceID deviceId) {
+ // Device IDs start with the table and omit trailing null TAGs, which
segment() returns as null.
+ for (final int i : constrainedNodes) {
+ final String tag = (String) deviceId.segment(i - 2);
+ final String patternNode = path.getNodes()[i];
+ final boolean matches =
+ ONE_LEVEL_PATH_WILDCARD.equals(patternNode)
+ ? path.match(i, tag)
+ : Objects.equals(patternNode, tag);
+ if (!matches) {
+ return false;
+ }
+ }
+ return true;
+ }
+
@TableModel
public void invalidate(
final String database,
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/impl/SchemaRegionMemoryImpl.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/impl/SchemaRegionMemoryImpl.java
index 2a7e525ca99..1b217250c54 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/impl/SchemaRegionMemoryImpl.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/impl/SchemaRegionMemoryImpl.java
@@ -1761,13 +1761,14 @@ public class SchemaRegionMemoryImpl implements
ISchemaRegion {
public void rollbackTableDevicesBlackList(
final RollbackTableDevicesBlackListNode
rollbackTableDevicesBlackListNode)
throws MetadataException {
+ final String tableName = rollbackTableDevicesBlackListNode.getTableName();
final List<PartialPath> paths =
DeleteDevice.constructPaths(
PathUtils.unQualifyDatabaseName(databaseFullPath),
- rollbackTableDevicesBlackListNode.getTableName(),
+ tableName,
rollbackTableDevicesBlackListNode.getPatternInfo());
for (final PartialPath pattern : paths) {
- mTree.rollbackTableDeviceBlackList(pattern);
+ mTree.rollbackTableDeviceBlackList(tableName, pattern);
}
writeToMLog(rollbackTableDevicesBlackListNode);
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java
index fd2a32947c6..c724b39b37f 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImpl.java
@@ -82,6 +82,7 @@ import
org.apache.iotdb.db.storageengine.rescon.quotas.DataNodeSpaceQuotaManager
import org.apache.iotdb.db.utils.SchemaUtils;
import org.apache.iotdb.rpc.TSStatusCode;
+import org.apache.ratis.thirdparty.com.google.common.graph.Traverser;
import
org.apache.ratis.thirdparty.com.google.common.util.concurrent.ListenableFuture;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.file.metadata.IDeviceID;
@@ -110,7 +111,6 @@ import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
@@ -2026,7 +2026,8 @@ public class MTreeBelowSGMemoryImpl {
}
}
- public void rollbackTableDeviceBlackList(final PartialPath pattern) throws
MetadataException {
+ public void rollbackTableDeviceBlackList(final String tableName, final
PartialPath pattern)
+ throws MetadataException {
try (final EntityUpdater<IMemMNode> updater =
new EntityUpdater<IMemMNode>(
rootNode, pattern, store, false, SchemaConstant.ALL_MATCH_SCOPE) {
@@ -2034,7 +2035,7 @@ public class MTreeBelowSGMemoryImpl {
@Override
protected void updateEntity(final IDeviceMNode<IMemMNode> node) {
if (node.isPreDeactivateSelfOrTemplate()) {
- regionStatistics.addTableDevice(pattern.getNodes()[2]);
+ regionStatistics.addTableDevice(tableName);
node.rollbackPreDeactivateSelfOrTemplate();
}
}
@@ -2069,67 +2070,51 @@ public class MTreeBelowSGMemoryImpl {
public boolean deleteTableDevice(final String tableName, final IntConsumer
attributeDeleter)
throws MetadataException {
- if (!store.hasChild(databaseMNode, tableName)) {
+ final IMemMNode tableNode = store.getChild(databaseMNode, tableName);
+ if (tableNode == null) {
return false;
}
- final AtomicInteger memoryReleased = new AtomicInteger(0);
- try (final MNodeCollector<Void, IMemMNode> collector =
- new MNodeCollector<Void, IMemMNode>(
- databaseMNode,
- new PartialPath(new String[] {databaseMNode.getName(), tableName}),
- this.store,
- true,
- SchemaConstant.ALL_MATCH_SCOPE) {
- @Override
- protected boolean acceptInternalMatchedNode(final IMemMNode node) {
- return true;
- }
-
- @Override
- protected Void collectMNode(final IMemMNode node) {
- if (node.isDevice()) {
- attributeDeleter.accept(
- ((TableDeviceInfo<IMemMNode>)
node.getAsDeviceMNode().getDeviceInfo())
- .getAttributePointer());
- }
- memoryReleased.addAndGet(node.estimateSize());
- return null;
- }
- }) {
- collector.traverse();
- }
+ final long memoryReleased = processTableSubtree(tableNode,
attributeDeleter, true);
databaseMNode.deleteChild(tableName);
refreshAncestorsHavingDeviceDescendant(databaseMNode);
regionStatistics.resetTableDevice(tableName);
- store.releaseMemory(memoryReleased.get());
+ regionStatistics.releaseMemory(memoryReleased);
return true;
}
public boolean dropTableAttribute(final String tableName, final IntConsumer
attributeDropper)
throws MetadataException {
- if (!store.hasChild(databaseMNode, tableName)) {
+ final IMemMNode tableNode = store.getChild(databaseMNode, tableName);
+ if (tableNode == null) {
return false;
}
- final AtomicInteger memoryReleased = new AtomicInteger(0);
- try (final EntityUpdater<IMemMNode> updater =
- new EntityUpdater<IMemMNode>(
- databaseMNode,
- new PartialPath(new String[] {databaseMNode.getName(), tableName}),
- this.store,
- true,
- SchemaConstant.ALL_MATCH_SCOPE) {
- @Override
- protected void updateEntity(final IDeviceMNode<IMemMNode> node) {
- attributeDropper.accept(
- ((TableDeviceInfo<IMemMNode>)
node.getAsDeviceMNode().getDeviceInfo())
- .getAttributePointer());
- }
- }) {
- updater.update();
- }
- store.releaseMemory(memoryReleased.get());
+ processTableSubtree(tableNode, attributeDropper, false);
return true;
}
+ private long processTableSubtree(
+ final IMemMNode tableNode, final IntConsumer attributeAction, final
boolean countMemory) {
+ final long startTime = System.currentTimeMillis();
+ long memory = 0;
+ try {
+ // An all-NULL device is stored on the table node itself.
+ for (final IMemMNode node :
+ Traverser.<IMemMNode>forTree(n -> n.getChildren().values())
+ .depthFirstPreOrder(tableNode)) {
+ if (node.isDevice()) {
+ attributeAction.accept(
+ ((TableDeviceInfo<IMemMNode>)
node.getAsDeviceMNode().getDeviceInfo())
+ .getAttributePointer());
+ }
+ if (countMemory) {
+ memory += node.estimateSize();
+ }
+ }
+ return memory;
+ } finally {
+ store.recordTraverserMetric(System.currentTimeMillis() - startTime);
+ }
+ }
+
// endregion
}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/DeviceBlackListConstructorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/DeviceBlackListConstructorTest.java
index c9649b1da4c..4a6815538e8 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/DeviceBlackListConstructorTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/DeviceBlackListConstructorTest.java
@@ -78,8 +78,8 @@ public class DeviceBlackListConstructorTest {
assertEquals(3, constructor.getPreDeletedNum());
assertEquals(0, statistics.getTableDevicesNumber("t"));
}
- tree.rollbackTableDeviceBlackList(allDevices);
- tree.rollbackTableDeviceBlackList(allDevices);
+ tree.rollbackTableDeviceBlackList("t", allDevices);
+ tree.rollbackTableDeviceBlackList("t", allDevices);
assertEquals(2, statistics.getTableDevicesNumber("t"));
final DeviceBlackListConstructor noMatch = newConstructor(statistics,
true, false);
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
index a59d3683902..bab5d624fe4 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
@@ -20,6 +20,10 @@
package org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache;
import org.apache.iotdb.commons.schema.column.ColumnHeader;
+import org.apache.iotdb.commons.schema.filter.impl.DeviceFilterUtil;
+import org.apache.iotdb.commons.schema.filter.impl.singlechild.TagFilter;
+import org.apache.iotdb.commons.schema.filter.impl.values.LikeFilter;
+import org.apache.iotdb.commons.schema.filter.impl.values.PreciseFilter;
import org.apache.iotdb.commons.schema.table.TsTable;
import org.apache.iotdb.commons.schema.table.column.AttributeColumnSchema;
import org.apache.iotdb.commons.schema.table.column.FieldColumnSchema;
@@ -54,6 +58,11 @@ import java.util.OptionalLong;
import java.util.concurrent.ConcurrentHashMap;
import static
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceSchemaFetcher.convertTagValuesToDeviceID;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class TableDeviceSchemaCacheTest {
@@ -276,6 +285,65 @@ public class TableDeviceSchemaCacheTest {
Assert.assertEquals(0, cache.getMemoryUsage());
}
+ @Test
+ public void testInvalidateAllDevicesWithoutReadingTags() {
+ final TableDeviceSchemaCache cache = createTestCache();
+ final IDeviceID device = mock(IDeviceID.class);
+ when(device.getTableName()).thenReturn(table1);
+ cache.putAttributes(database1, device, Collections.emptyMap());
+ cache.putAttributes(database2, device, Collections.emptyMap());
+ Assert.assertNotNull(cache.getDeviceAttribute(database1, device));
+
+ cache.invalidate(
+ database1,
+ table1,
+ DeviceFilterUtil.convertToDevicePattern(
+ new String[] {"root", database1, table1},
+ 3,
+ Collections.singletonList(Collections.emptyList()),
+ true));
+
+ verify(device, never()).segment(anyInt());
+ Assert.assertNull(cache.getDeviceAttribute(database1, device));
+ Assert.assertNotNull(cache.getDeviceAttribute(database2, device));
+ }
+
+ @Test
+ public void testInvalidateDevicesWithSparseTagPredicates() {
+ final TableDeviceSchemaCache cache =
TableDeviceSchemaCache.createForTest(10_000L);
+ final IDeviceID literalStar = mock(IDeviceID.class);
+ when(literalStar.getTableName()).thenReturn(table1);
+ when(literalStar.segment(2)).thenReturn("*");
+ final IDeviceID otherValue = convertTagValuesToDeviceID(table1, new
String[] {"a", "plain"});
+ final IDeviceID nonNullTail =
+ convertTagValuesToDeviceID(table1, new String[] {"b", "*", "zone"});
+ final IDeviceID likeMatch = convertTagValuesToDeviceID(table1, new
String[] {"c", "rack-1"});
+ for (final IDeviceID device : Arrays.asList(literalStar, otherValue,
nonNullTail, likeMatch)) {
+ cache.putAttributes(database1, device, Collections.emptyMap());
+ Assert.assertNotNull(cache.getDeviceAttribute(database1, device));
+ }
+
+ cache.invalidate(
+ database1,
+ table1,
+ DeviceFilterUtil.convertToDevicePattern(
+ new String[] {"root", database1, table1},
+ 3,
+ Arrays.asList(
+ Arrays.asList(
+ new TagFilter(new PreciseFilter("*"), 1),
+ new TagFilter(new PreciseFilter((String) null), 2)),
+ Collections.singletonList(
+ new TagFilter(new LikeFilter("rack-%", Optional.empty()),
1))),
+ true));
+
+ verify(literalStar, never()).segment(1);
+ Assert.assertNull(cache.getDeviceAttribute(database1, literalStar));
+ Assert.assertNull(cache.getDeviceAttribute(database1, likeMatch));
+ Assert.assertNotNull(cache.getDeviceAttribute(database1, otherValue));
+ Assert.assertNotNull(cache.getDeviceAttribute(database1, nonNullTail));
+ }
+
@Test
public void testLastCache() {
final TableDeviceSchemaCache cache = createTestCache();
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImplTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImplTest.java
index c498f507f9d..9d39f9cdc23 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImplTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/mtree/impl/mem/MTreeBelowSGMemoryImplTest.java
@@ -31,6 +31,7 @@ import
org.apache.iotdb.db.exception.metadata.PathNotExistException;
import org.apache.iotdb.db.schemaengine.metric.SchemaRegionMemMetric;
import org.apache.iotdb.db.schemaengine.rescon.MemSchemaEngineStatistics;
import org.apache.iotdb.db.schemaengine.rescon.MemSchemaRegionStatistics;
+import
org.apache.iotdb.db.schemaengine.schemaregion.attribute.DeviceAttributeStore;
import
org.apache.iotdb.db.schemaengine.schemaregion.mtree.impl.mem.mnode.IMemMNode;
import
org.apache.iotdb.db.schemaengine.schemaregion.mtree.impl.mem.mnode.container.MemMNodeContainer;
import
org.apache.iotdb.db.schemaengine.schemaregion.mtree.impl.mem.mnode.impl.BasicInternalMNode;
@@ -40,6 +41,7 @@ import
org.apache.iotdb.db.schemaengine.schemaregion.mtree.traverser.collector.M
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.file.metadata.enums.CompressionType;
import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.utils.Binary;
import org.apache.tsfile.write.schema.MeasurementSchema;
import org.junit.Assert;
import org.junit.Rule;
@@ -300,6 +302,59 @@ public class MTreeBelowSGMemoryImplTest {
assertPathNotExist(mtree, new PartialPath("root.sg.t"));
}
+ @Test
+ public void testDeleteTableDeviceWithLiteralAsterisks() throws Exception {
+ final MemSchemaRegionStatistics statistics = newRegionStatistics();
+ final MTreeBelowSGMemoryImpl mtree = newMTree(statistics);
+ mtree.createOrUpdateTableDevice("**", new String[0], () -> 1, ignored ->
{});
+ mtree.createOrUpdateTableDevice("**", new String[] {"rack"}, () -> 2,
ignored -> {});
+ mtree.createOrUpdateTableDevice("other", new String[] {"rack"}, () -> 3,
ignored -> {});
+ final IMemMNode table = mtree.getNodeByPath(new PartialPath(new String[]
{"root", "sg", "**"}));
+ final long remainingMemory =
+ statistics.getRegionMemoryUsage()
+ - table.estimateSize()
+ - table.getChild("rack").estimateSize();
+
+ final List<Integer> deletedPointers = new ArrayList<>();
+ Assert.assertTrue(mtree.deleteTableDevice("**", deletedPointers::add));
+ Collections.sort(deletedPointers);
+ Assert.assertEquals(Arrays.asList(1, 2), deletedPointers);
+ Assert.assertEquals(0, statistics.getTableDevicesNumber("**"));
+ Assert.assertEquals(1, statistics.getTableDevicesNumber("other"));
+ Assert.assertEquals(remainingMemory, statistics.getRegionMemoryUsage());
+ Assert.assertTrue(mtree.getNodeByPath(new
PartialPath("root.sg.other.rack")).isDevice());
+ Assert.assertFalse(mtree.deleteTableDevice("**", deletedPointers::add));
+ }
+
+ @Test
+ public void testDropTableAttributeWithLiteralAsterisk() throws Exception {
+ final MemSchemaRegionStatistics statistics = newRegionStatistics();
+ final MTreeBelowSGMemoryImpl mtree = newMTree(statistics);
+ final DeviceAttributeStore attributes = new
DeviceAttributeStore(statistics);
+ final Binary value = new Binary(new byte[] {1});
+ final List<String> names = Collections.singletonList("label");
+ final Object[] values = {value};
+ final int tablePointer = attributes.createAttribute(names, values,
"rack*");
+ final int devicePointer = attributes.createAttribute(names, values,
"rack*");
+ final int siblingPointer = attributes.createAttribute(names, values,
"rack1");
+ mtree.createOrUpdateTableDevice("rack*", new String[0], () ->
tablePointer, ignored -> {});
+ mtree.createOrUpdateTableDevice(
+ "rack*", new String[] {"sensor"}, () -> devicePointer, ignored -> {});
+ mtree.createOrUpdateTableDevice(
+ "rack1", new String[] {"sensor"}, () -> siblingPointer, ignored -> {});
+
+ Assert.assertTrue(
+ mtree.dropTableAttribute(
+ "rack*", pointer -> attributes.removeAttribute(pointer, "label",
"rack*")));
+ Assert.assertNull(attributes.getAttributes(tablePointer, "label"));
+ Assert.assertNull(attributes.getAttributes(devicePointer, "label"));
+ Assert.assertEquals(value, attributes.getAttributes(siblingPointer,
"label"));
+ Assert.assertEquals(0, statistics.getTableAttributeMemory("rack*"));
+ Assert.assertEquals(value.ramBytesUsed(),
statistics.getTableAttributeMemory("rack1"));
+ Assert.assertEquals(2, statistics.getTableDevicesNumber("rack*"));
+ Assert.assertEquals(1, statistics.getTableDevicesNumber("rack1"));
+ }
+
@Test
public void testLeafDeviceWildcardSuffixUsesDirectMeasurementLookup() throws
Exception {
final PartialPath databasePath =
PartialPath.getQualifiedDatabasePartialPath("root.sg");
@@ -352,7 +407,11 @@ public class MTreeBelowSGMemoryImplTest {
}
private static MTreeBelowSGMemoryImpl newMTree() throws Exception {
- final MemSchemaRegionStatistics regionStatistics = newRegionStatistics();
+ return newMTree(newRegionStatistics());
+ }
+
+ private static MTreeBelowSGMemoryImpl newMTree(final
MemSchemaRegionStatistics regionStatistics)
+ throws Exception {
return new MTreeBelowSGMemoryImpl(
PartialPath.getQualifiedDatabasePartialPath("root.sg"),
node -> Collections.emptyMap(),
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/path/ExtendedPartialPath.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/path/ExtendedPartialPath.java
index 0cf68f6918c..63553340f59 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/path/ExtendedPartialPath.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/path/ExtendedPartialPath.java
@@ -27,6 +27,8 @@ import java.util.Map;
import java.util.Set;
import java.util.function.Function;
+import static
org.apache.iotdb.commons.conf.IoTDBConstant.ONE_LEVEL_PATH_WILDCARD;
+
public class ExtendedPartialPath extends PartialPath {
private final Map<Integer, List<Function<String, Boolean>>> matchFunctions =
new HashMap<>();
private final Map<Integer, Set<String>> multiExactMatchNodes = new
HashMap<>();
@@ -41,6 +43,12 @@ public class ExtendedPartialPath extends PartialPath {
return isRestrict;
}
+ public boolean isUnconstrainedWildcard(final int index) {
+ return ONE_LEVEL_PATH_WILDCARD.equals(getNodes()[index])
+ && !hasMultiExactMatch(index)
+ && !matchFunctions.containsKey(index);
+ }
+
public boolean match(final int index, final String value) {
if (multiExactMatchNodes.containsKey(index)
&& !multiExactMatchNodes.get(index).contains(value)) {
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtil.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtil.java
index 9786f2161cd..23fcc2afb9f 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtil.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtil.java
@@ -22,6 +22,7 @@ package org.apache.iotdb.commons.schema.filter.impl;
import org.apache.iotdb.commons.i18n.SchemaMessages;
import org.apache.iotdb.commons.path.ExtendedPartialPath;
import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.commons.path.PathPatternUtil;
import org.apache.iotdb.commons.schema.filter.SchemaFilter;
import org.apache.iotdb.commons.schema.filter.SchemaFilterType;
import org.apache.iotdb.commons.schema.filter.impl.singlechild.TagFilter;
@@ -61,8 +62,10 @@ public class DeviceFilterUtil {
compactNonLeadingPreciseFilters(tagColumnNum,
tagDeterminedFilterList)) {
final String[] nodes = new String[length];
Arrays.fill(nodes, ONE_LEVEL_PATH_WILDCARD);
- System.arraycopy(prefix, 0, nodes, 0, prefix.length);
final ExtendedPartialPath partialPath = new ExtendedPartialPath(nodes,
isRestrict);
+ for (int i = 0; i < prefix.length; i++) {
+ setExactNode(partialPath, i, prefix[i]);
+ }
for (final SchemaFilter schemaFilter : tagFilterList) {
if (schemaFilter.getSchemaFilterType().equals(SchemaFilterType.TAG)) {
final int index = ((TagFilter) schemaFilter).getIndex() +
prefix.length;
@@ -70,7 +73,7 @@ public class DeviceFilterUtil {
if
(childFilter.getSchemaFilterType().equals(SchemaFilterType.PRECISE)) {
// If there is a precise filter, other filters on the same id are
processed and thus
// not exist here
- nodes[index] = ((PreciseFilter) childFilter).getValue();
+ setExactNode(partialPath, index, ((PreciseFilter)
childFilter).getValue());
} else if
(childFilter.getSchemaFilterType().equals(SchemaFilterType.IN)) {
partialPath.addMultiExactMatch(index, ((InFilter)
childFilter).getValues());
} else {
@@ -90,6 +93,16 @@ public class DeviceFilterUtil {
return pathList;
}
+ private static void setExactNode(
+ final ExtendedPartialPath path, final int index, final String value) {
+ if (PathPatternUtil.hasWildcard(value)) {
+ // Keep literal identifiers and TAG values out of the path wildcard
syntax.
+ path.addMultiExactMatch(index, Collections.singleton(value));
+ } else {
+ path.getNodes()[index] = value;
+ }
+ }
+
/**
* IN predicates and OR-connected equal predicates are expanded into precise
filter branches so
* that complete device IDs can use the device cache. If a precise filter is
behind an unfixed tag
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtilTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtilTest.java
index af4c7e17e89..5ce9d9fe852 100644
---
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtilTest.java
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/schema/filter/impl/DeviceFilterUtilTest.java
@@ -50,6 +50,34 @@ public class DeviceFilterUtilTest {
private static final String[] PREFIX = new String[] {"root", "db", "table"};
private static final int TAG_COLUMN_NUM = 3;
+ @Test
+ public void testPreciseTagValuesContainingAsterisks() {
+ for (final String value : Arrays.asList("*", "**", "*meter", "meter*",
"*meter*", "me*ter")) {
+ final PartialPath pattern = convert(branch(precise(1, value))).get(0);
+ assertPreciseTransitionsAfterFirstTag(pattern, value);
+ }
+ }
+
+ @Test
+ public void testVisitLiteralAsterisksInTrailingTag() {
+ final TestNode root = new TestNode(PREFIX[0]);
+ final TestNode site =
root.addChild(PREFIX[1]).addChild(PREFIX[2]).addChild("site");
+ final TestNode parent = site.addChild("withLastTag");
+ // A device with a trailing NULL ends at the preceding tag in the tree.
+ site.addChild("withoutLastTag");
+ final List<String> literals = Arrays.asList("*", "**", "meter*", "*meter",
"[a*");
+ literals.forEach(parent::addChild);
+ parent.addChildren("meter1", "xmeter", "[abc");
+
+ for (final String literal : literals) {
+ final PartialPath pattern = convert(branch(precise(TAG_COLUMN_NUM - 1,
literal))).get(0);
+ final TestVisitor visitor = new TestVisitor(root, pattern, parent);
+ Assert.assertEquals(literal, Collections.singletonList(literal),
collect(visitor));
+ Assert.assertEquals(literal, 1, visitor.getTargetDirectLookupCount());
+ Assert.assertEquals(literal, 0,
visitor.getTargetChildrenIterationCount());
+ }
+ }
+
@Test
public void testCompactExpandedInOrOnNonLeadingTag() {
final List<PartialPath> patterns =
@@ -295,7 +323,7 @@ public class DeviceFilterUtilTest {
private int targetChildrenIterationCount;
private TestVisitor(
- final TestNode root, final ExtendedPartialPath pathPattern, final
TestNode targetParent) {
+ final TestNode root, final PartialPath pathPattern, final TestNode
targetParent) {
super(root, pathPattern, false);
this.targetParent = targetParent;
initStack();
@@ -388,8 +416,14 @@ public class DeviceFilterUtilTest {
children.put(child.getName(), child);
}
+ private TestNode addChild(final String name) {
+ final TestNode child = new TestNode(name);
+ addChild(child);
+ return child;
+ }
+
private void addChildren(final String... childNames) {
- Arrays.stream(childNames).map(TestNode::new).forEach(this::addChild);
+ Arrays.stream(childNames).forEach(this::addChild);
}
@Override