• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

apache / iotdb / #10018

07 Sep 2023 05:00AM UTC coverage: 47.717% (+0.03%) from 47.691%
#10018

push

travis_ci

web-flow
Pipe: Fix ConcurrentModificationException caused by concurrently iterating through CachedSchemaPatternMatcher.extractors when an PipeHeartbeatEvent is being assigned (#11074) (#11075)

* try to fix ConcurrentModificationException when assigning PipeHeartbeatEvent

* Update CachedSchemaPatternMatcher.java

---------

Co-authored-by: 马子坤 <55695098+DanielWang2035@users.noreply.github.com>
(cherry picked from commit ac0dd9d31)

1 of 1 new or added line in 1 file covered. (100.0%)

80262 of 168204 relevant lines covered (47.72%)

0.48 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

27.8
/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one
3
 * or more contributor license agreements.  See the NOTICE file
4
 * distributed with this work for additional information
5
 * regarding copyright ownership.  The ASF licenses this file
6
 * to you under the Apache License, Version 2.0 (the
7
 * "License"); you may not use this file except in compliance
8
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing,
13
 * software distributed under the License is distributed on an
14
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
 * KIND, either express or implied.  See the License for the
16
 * specific language governing permissions and limitations
17
 * under the License.
18
 */
19

20
package org.apache.iotdb.db.queryengine.plan.parser;
21

22
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
23
import org.apache.iotdb.common.rpc.thrift.TTimedQuota;
24
import org.apache.iotdb.common.rpc.thrift.ThrottleType;
25
import org.apache.iotdb.commons.auth.entity.PrivilegeType;
26
import org.apache.iotdb.commons.cluster.NodeStatus;
27
import org.apache.iotdb.commons.conf.IoTDBConstant;
28
import org.apache.iotdb.commons.cq.TimeoutPolicy;
29
import org.apache.iotdb.commons.path.PartialPath;
30
import org.apache.iotdb.commons.schema.filter.SchemaFilter;
31
import org.apache.iotdb.commons.schema.filter.SchemaFilterFactory;
32
import org.apache.iotdb.commons.utils.PathUtils;
33
import org.apache.iotdb.db.conf.IoTDBConfig;
34
import org.apache.iotdb.db.conf.IoTDBDescriptor;
35
import org.apache.iotdb.db.exception.sql.SemanticException;
36
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser;
37
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.ConstantContext;
38
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.CountDatabasesContext;
39
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.CountDevicesContext;
40
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.CountNodesContext;
41
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.CountTimeseriesContext;
42
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.CreateFunctionContext;
43
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.DropFunctionContext;
44
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.ExpressionContext;
45
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.GroupByAttributeClauseContext;
46
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.IdentifierContext;
47
import org.apache.iotdb.db.qp.sql.IoTDBSqlParser.ShowFunctionsContext;
48
import org.apache.iotdb.db.qp.sql.IoTDBSqlParserBaseVisitor;
49
import org.apache.iotdb.db.queryengine.common.header.ColumnHeaderConstant;
50
import org.apache.iotdb.db.queryengine.execution.operator.window.WindowType;
51
import org.apache.iotdb.db.queryengine.plan.analyze.ExpressionAnalyzer;
52
import org.apache.iotdb.db.queryengine.plan.expression.Expression;
53
import org.apache.iotdb.db.queryengine.plan.expression.ExpressionType;
54
import org.apache.iotdb.db.queryengine.plan.expression.binary.AdditionExpression;
55
import org.apache.iotdb.db.queryengine.plan.expression.binary.CompareBinaryExpression;
56
import org.apache.iotdb.db.queryengine.plan.expression.binary.DivisionExpression;
57
import org.apache.iotdb.db.queryengine.plan.expression.binary.EqualToExpression;
58
import org.apache.iotdb.db.queryengine.plan.expression.binary.GreaterEqualExpression;
59
import org.apache.iotdb.db.queryengine.plan.expression.binary.GreaterThanExpression;
60
import org.apache.iotdb.db.queryengine.plan.expression.binary.LessEqualExpression;
61
import org.apache.iotdb.db.queryengine.plan.expression.binary.LessThanExpression;
62
import org.apache.iotdb.db.queryengine.plan.expression.binary.LogicAndExpression;
63
import org.apache.iotdb.db.queryengine.plan.expression.binary.LogicOrExpression;
64
import org.apache.iotdb.db.queryengine.plan.expression.binary.ModuloExpression;
65
import org.apache.iotdb.db.queryengine.plan.expression.binary.MultiplicationExpression;
66
import org.apache.iotdb.db.queryengine.plan.expression.binary.NonEqualExpression;
67
import org.apache.iotdb.db.queryengine.plan.expression.binary.SubtractionExpression;
68
import org.apache.iotdb.db.queryengine.plan.expression.binary.WhenThenExpression;
69
import org.apache.iotdb.db.queryengine.plan.expression.leaf.ConstantOperand;
70
import org.apache.iotdb.db.queryengine.plan.expression.leaf.NullOperand;
71
import org.apache.iotdb.db.queryengine.plan.expression.leaf.TimeSeriesOperand;
72
import org.apache.iotdb.db.queryengine.plan.expression.leaf.TimestampOperand;
73
import org.apache.iotdb.db.queryengine.plan.expression.multi.FunctionExpression;
74
import org.apache.iotdb.db.queryengine.plan.expression.multi.builtin.BuiltInScalarFunctionHelperFactory;
75
import org.apache.iotdb.db.queryengine.plan.expression.other.CaseWhenThenExpression;
76
import org.apache.iotdb.db.queryengine.plan.expression.ternary.BetweenExpression;
77
import org.apache.iotdb.db.queryengine.plan.expression.unary.InExpression;
78
import org.apache.iotdb.db.queryengine.plan.expression.unary.IsNullExpression;
79
import org.apache.iotdb.db.queryengine.plan.expression.unary.LikeExpression;
80
import org.apache.iotdb.db.queryengine.plan.expression.unary.LogicNotExpression;
81
import org.apache.iotdb.db.queryengine.plan.expression.unary.NegationExpression;
82
import org.apache.iotdb.db.queryengine.plan.expression.unary.RegularExpression;
83
import org.apache.iotdb.db.queryengine.plan.statement.AuthorType;
84
import org.apache.iotdb.db.queryengine.plan.statement.Statement;
85
import org.apache.iotdb.db.queryengine.plan.statement.StatementType;
86
import org.apache.iotdb.db.queryengine.plan.statement.component.FillComponent;
87
import org.apache.iotdb.db.queryengine.plan.statement.component.FillPolicy;
88
import org.apache.iotdb.db.queryengine.plan.statement.component.FromComponent;
89
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByComponent;
90
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByConditionComponent;
91
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByCountComponent;
92
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByLevelComponent;
93
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupBySessionComponent;
94
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByTagComponent;
95
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByTimeComponent;
96
import org.apache.iotdb.db.queryengine.plan.statement.component.GroupByVariationComponent;
97
import org.apache.iotdb.db.queryengine.plan.statement.component.HavingCondition;
98
import org.apache.iotdb.db.queryengine.plan.statement.component.IntoComponent;
99
import org.apache.iotdb.db.queryengine.plan.statement.component.IntoItem;
100
import org.apache.iotdb.db.queryengine.plan.statement.component.NullOrdering;
101
import org.apache.iotdb.db.queryengine.plan.statement.component.OrderByComponent;
102
import org.apache.iotdb.db.queryengine.plan.statement.component.OrderByKey;
103
import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering;
104
import org.apache.iotdb.db.queryengine.plan.statement.component.ResultColumn;
105
import org.apache.iotdb.db.queryengine.plan.statement.component.ResultSetFormat;
106
import org.apache.iotdb.db.queryengine.plan.statement.component.SelectComponent;
107
import org.apache.iotdb.db.queryengine.plan.statement.component.SortItem;
108
import org.apache.iotdb.db.queryengine.plan.statement.component.WhereCondition;
109
import org.apache.iotdb.db.queryengine.plan.statement.crud.DeleteDataStatement;
110
import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertStatement;
111
import org.apache.iotdb.db.queryengine.plan.statement.crud.LoadTsFileStatement;
112
import org.apache.iotdb.db.queryengine.plan.statement.crud.QueryStatement;
113
import org.apache.iotdb.db.queryengine.plan.statement.literal.BooleanLiteral;
114
import org.apache.iotdb.db.queryengine.plan.statement.literal.DoubleLiteral;
115
import org.apache.iotdb.db.queryengine.plan.statement.literal.Literal;
116
import org.apache.iotdb.db.queryengine.plan.statement.literal.LongLiteral;
117
import org.apache.iotdb.db.queryengine.plan.statement.literal.StringLiteral;
118
import org.apache.iotdb.db.queryengine.plan.statement.metadata.AlterTimeSeriesStatement;
119
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CountDatabaseStatement;
120
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CountDevicesStatement;
121
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CountLevelTimeSeriesStatement;
122
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CountNodesStatement;
123
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CountTimeSeriesStatement;
124
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CountTimeSlotListStatement;
125
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CreateAlignedTimeSeriesStatement;
126
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CreateContinuousQueryStatement;
127
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CreateFunctionStatement;
128
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CreatePipePluginStatement;
129
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CreateTimeSeriesStatement;
130
import org.apache.iotdb.db.queryengine.plan.statement.metadata.CreateTriggerStatement;
131
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DatabaseSchemaStatement;
132
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DeleteDatabaseStatement;
133
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DeleteTimeSeriesStatement;
134
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DropContinuousQueryStatement;
135
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DropFunctionStatement;
136
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DropPipePluginStatement;
137
import org.apache.iotdb.db.queryengine.plan.statement.metadata.DropTriggerStatement;
138
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetRegionIdStatement;
139
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetSeriesSlotListStatement;
140
import org.apache.iotdb.db.queryengine.plan.statement.metadata.GetTimeSlotListStatement;
141
import org.apache.iotdb.db.queryengine.plan.statement.metadata.MigrateRegionStatement;
142
import org.apache.iotdb.db.queryengine.plan.statement.metadata.SetTTLStatement;
143
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowChildNodesStatement;
144
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowChildPathsStatement;
145
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowClusterStatement;
146
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowConfigNodesStatement;
147
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowContinuousQueriesStatement;
148
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowDataNodesStatement;
149
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowDatabaseStatement;
150
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowDevicesStatement;
151
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowFunctionsStatement;
152
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowPipePluginsStatement;
153
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowRegionStatement;
154
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowTTLStatement;
155
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowTimeSeriesStatement;
156
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowTriggersStatement;
157
import org.apache.iotdb.db.queryengine.plan.statement.metadata.ShowVariablesStatement;
158
import org.apache.iotdb.db.queryengine.plan.statement.metadata.UnSetTTLStatement;
159
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.CreateModelStatement;
160
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.DropModelStatement;
161
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowModelsStatement;
162
import org.apache.iotdb.db.queryengine.plan.statement.metadata.model.ShowTrailsStatement;
163
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipeStatement;
164
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.DropPipeStatement;
165
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.ShowPipesStatement;
166
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.StartPipeStatement;
167
import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.StopPipeStatement;
168
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.ActivateTemplateStatement;
169
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.AlterSchemaTemplateStatement;
170
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.CreateSchemaTemplateStatement;
171
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.DeactivateTemplateStatement;
172
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.DropSchemaTemplateStatement;
173
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.SetSchemaTemplateStatement;
174
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.ShowNodesInSchemaTemplateStatement;
175
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.ShowPathSetTemplateStatement;
176
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.ShowPathsUsingTemplateStatement;
177
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.ShowSchemaTemplateStatement;
178
import org.apache.iotdb.db.queryengine.plan.statement.metadata.template.UnsetSchemaTemplateStatement;
179
import org.apache.iotdb.db.queryengine.plan.statement.metadata.view.AlterLogicalViewStatement;
180
import org.apache.iotdb.db.queryengine.plan.statement.metadata.view.CreateLogicalViewStatement;
181
import org.apache.iotdb.db.queryengine.plan.statement.metadata.view.DeleteLogicalViewStatement;
182
import org.apache.iotdb.db.queryengine.plan.statement.metadata.view.ShowLogicalViewStatement;
183
import org.apache.iotdb.db.queryengine.plan.statement.sys.AuthorStatement;
184
import org.apache.iotdb.db.queryengine.plan.statement.sys.ClearCacheStatement;
185
import org.apache.iotdb.db.queryengine.plan.statement.sys.ExplainStatement;
186
import org.apache.iotdb.db.queryengine.plan.statement.sys.FlushStatement;
187
import org.apache.iotdb.db.queryengine.plan.statement.sys.KillQueryStatement;
188
import org.apache.iotdb.db.queryengine.plan.statement.sys.LoadConfigurationStatement;
189
import org.apache.iotdb.db.queryengine.plan.statement.sys.MergeStatement;
190
import org.apache.iotdb.db.queryengine.plan.statement.sys.SetSystemStatusStatement;
191
import org.apache.iotdb.db.queryengine.plan.statement.sys.ShowQueriesStatement;
192
import org.apache.iotdb.db.queryengine.plan.statement.sys.ShowVersionStatement;
193
import org.apache.iotdb.db.queryengine.plan.statement.sys.quota.SetSpaceQuotaStatement;
194
import org.apache.iotdb.db.queryengine.plan.statement.sys.quota.SetThrottleQuotaStatement;
195
import org.apache.iotdb.db.queryengine.plan.statement.sys.quota.ShowSpaceQuotaStatement;
196
import org.apache.iotdb.db.queryengine.plan.statement.sys.quota.ShowThrottleQuotaStatement;
197
import org.apache.iotdb.db.schemaengine.template.TemplateAlterOperationType;
198
import org.apache.iotdb.db.utils.DateTimeUtils;
199
import org.apache.iotdb.db.utils.constant.SqlConstant;
200
import org.apache.iotdb.trigger.api.enums.TriggerEvent;
201
import org.apache.iotdb.trigger.api.enums.TriggerType;
202
import org.apache.iotdb.tsfile.common.conf.TSFileDescriptor;
203
import org.apache.iotdb.tsfile.common.constant.TsFileConstant;
204
import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
205
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
206
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
207
import org.apache.iotdb.tsfile.read.common.TimeRange;
208

209
import com.google.common.collect.ImmutableSet;
210
import org.antlr.v4.runtime.tree.TerminalNode;
211

212
import java.io.FileNotFoundException;
213
import java.net.URI;
214
import java.net.URISyntaxException;
215
import java.time.ZoneId;
216
import java.util.ArrayList;
217
import java.util.Arrays;
218
import java.util.HashMap;
219
import java.util.HashSet;
220
import java.util.LinkedHashSet;
221
import java.util.List;
222
import java.util.Map;
223
import java.util.Set;
224
import java.util.function.BiConsumer;
225
import java.util.function.Consumer;
226
import java.util.stream.Collectors;
227

228
import static org.apache.iotdb.db.queryengine.plan.optimization.LimitOffsetPushDown.canPushDownLimitOffsetToGroupByTime;
229
import static org.apache.iotdb.db.queryengine.plan.optimization.LimitOffsetPushDown.pushDownLimitOffsetToTimeParameter;
230
import static org.apache.iotdb.db.schemaengine.SchemaConstant.ALL_RESULT_NODES;
231
import static org.apache.iotdb.db.utils.constant.SqlConstant.CAST_FUNCTION;
232
import static org.apache.iotdb.db.utils.constant.SqlConstant.CAST_TYPE;
233
import static org.apache.iotdb.db.utils.constant.SqlConstant.REPLACE_FROM;
234
import static org.apache.iotdb.db.utils.constant.SqlConstant.REPLACE_FUNCTION;
235
import static org.apache.iotdb.db.utils.constant.SqlConstant.REPLACE_TO;
236
import static org.apache.iotdb.db.utils.constant.SqlConstant.ROUND_FUNCTION;
237
import static org.apache.iotdb.db.utils.constant.SqlConstant.ROUND_PLACES;
238
import static org.apache.iotdb.db.utils.constant.SqlConstant.SUBSTRING_FUNCTION;
239
import static org.apache.iotdb.db.utils.constant.SqlConstant.SUBSTRING_IS_STANDARD;
240
import static org.apache.iotdb.db.utils.constant.SqlConstant.SUBSTRING_LENGTH;
241
import static org.apache.iotdb.db.utils.constant.SqlConstant.SUBSTRING_START;
242

243
/** Parse AST to Statement. */
244
public class ASTVisitor extends IoTDBSqlParserBaseVisitor<Statement> {
1✔
245

246
  private static final IoTDBConfig CONFIG = IoTDBDescriptor.getInstance().getConfig();
1✔
247

248
  private static final String DELETE_RANGE_ERROR_MSG =
249
      "For delete statement, where clause can only contain atomic expressions like : "
250
          + "time > XXX, time <= XXX, or two atomic expressions connected by 'AND'";
251
  private static final String DELETE_ONLY_SUPPORT_TIME_EXP_ERROR_MSG =
252
      "For delete statement, where clause can only contain time expressions, "
253
          + "value filter is not currently supported.";
254

255
  private static final String GROUP_BY_COMMON_ONLY_ONE_MSG =
256
      "Only one of group by time or group by variation/series/session can be supported at a time";
257

258
  private static final String LIMIT_CONFIGURATION_ENABLED_ERROR_MSG =
259
      "Limit configuration is not enabled, please enable it first.";
260

261
  private static final String IGNORENULL = "IgnoreNull";
262
  private ZoneId zoneId;
263

264
  private boolean useWildcard = false;
1✔
265

266
  private boolean lastLevelUseWildcard = false;
1✔
267

268
  public void setZoneId(ZoneId zoneId) {
269
    this.zoneId = zoneId;
1✔
270
  }
1✔
271

272
  /** Top Level Description. */
273
  @Override
274
  public Statement visitSingleStatement(IoTDBSqlParser.SingleStatementContext ctx) {
275
    Statement statement = visit(ctx.statement());
1✔
276
    if (ctx.DEBUG() != null) {
1✔
277
      statement.setDebug(true);
×
278
    }
279
    return statement;
1✔
280
  }
281

282
  /** Data Definition Language (DDL). */
283

284
  // Create Timeseries ========================================================================
285
  @Override
286
  public Statement visitCreateNonAlignedTimeseries(
287
      IoTDBSqlParser.CreateNonAlignedTimeseriesContext ctx) {
288
    CreateTimeSeriesStatement createTimeSeriesStatement = new CreateTimeSeriesStatement();
1✔
289
    createTimeSeriesStatement.setPath(parseFullPath(ctx.fullPath()));
1✔
290
    if (ctx.attributeClauses() != null) {
1✔
291
      parseAttributeClausesForCreateNonAlignedTimeSeries(
1✔
292
          ctx.attributeClauses(), createTimeSeriesStatement);
1✔
293
    }
294
    return createTimeSeriesStatement;
1✔
295
  }
296

297
  @Override
298
  public Statement visitCreateAlignedTimeseries(IoTDBSqlParser.CreateAlignedTimeseriesContext ctx) {
299
    CreateAlignedTimeSeriesStatement createAlignedTimeSeriesStatement =
1✔
300
        new CreateAlignedTimeSeriesStatement();
301
    createAlignedTimeSeriesStatement.setDevicePath(parseFullPath(ctx.fullPath()));
1✔
302
    parseAlignedMeasurements(ctx.alignedMeasurements(), createAlignedTimeSeriesStatement);
1✔
303
    return createAlignedTimeSeriesStatement;
1✔
304
  }
305

306
  public void parseAlignedMeasurements(
307
      IoTDBSqlParser.AlignedMeasurementsContext ctx,
308
      CreateAlignedTimeSeriesStatement createAlignedTimeSeriesStatement) {
309
    for (int i = 0; i < ctx.nodeNameWithoutWildcard().size(); i++) {
1✔
310
      createAlignedTimeSeriesStatement.addMeasurement(
1✔
311
          parseNodeNameWithoutWildCard(ctx.nodeNameWithoutWildcard(i)));
1✔
312
      parseAttributeClausesForCreateAlignedTimeSeries(
1✔
313
          ctx.attributeClauses(i), createAlignedTimeSeriesStatement);
1✔
314
    }
315
  }
1✔
316

317
  public void parseAttributeClausesForCreateNonAlignedTimeSeries(
318
      IoTDBSqlParser.AttributeClausesContext ctx,
319
      CreateTimeSeriesStatement createTimeSeriesStatement) {
320
    if (ctx.aliasNodeName() != null) {
1✔
321
      createTimeSeriesStatement.setAlias(parseNodeName(ctx.aliasNodeName().nodeName()));
×
322
    }
323

324
    Map<String, String> props = new HashMap<>();
1✔
325
    TSDataType dataType = parseDataTypeAttribute(ctx);
1✔
326
    if (dataType != null) {
1✔
327
      props.put(
1✔
328
          IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase(),
1✔
329
          dataType.toString().toLowerCase());
1✔
330
    }
331
    List<IoTDBSqlParser.AttributePairContext> attributePairs = ctx.attributePair();
1✔
332
    if (ctx.attributePair(0) != null) {
1✔
333
      for (IoTDBSqlParser.AttributePairContext attributePair : attributePairs) {
×
334
        props.put(
×
335
            parseAttributeKey(attributePair.attributeKey()).toLowerCase(),
×
336
            parseAttributeValue(attributePair.attributeValue()).toLowerCase());
×
337
      }
×
338
    }
339

340
    createTimeSeriesStatement.setProps(props);
1✔
341
    checkPropsInCreateTimeSeries(createTimeSeriesStatement);
1✔
342

343
    if (ctx.tagClause() != null) {
1✔
344
      parseTagClause(ctx.tagClause(), createTimeSeriesStatement);
1✔
345
    }
346
    if (ctx.attributeClause() != null) {
1✔
347
      parseAttributeClauseForTimeSeries(ctx.attributeClause(), createTimeSeriesStatement);
1✔
348
    }
349
  }
1✔
350

351
  /**
352
   * Check and set datatype, encoding, compressor.
353
   *
354
   * @throws SemanticException if encoding or dataType meets error handling
355
   */
356
  private void checkPropsInCreateTimeSeries(CreateTimeSeriesStatement createTimeSeriesStatement) {
357
    Map<String, String> props = createTimeSeriesStatement.getProps();
1✔
358
    if (props != null
1✔
359
        && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase())) {
1✔
360
      String datatypeString =
1✔
361
          props.get(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase()).toUpperCase();
1✔
362
      try {
363
        createTimeSeriesStatement.setDataType(TSDataType.valueOf(datatypeString));
1✔
364
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE.toLowerCase());
1✔
365
      } catch (Exception e) {
×
366
        throw new SemanticException(String.format("Unsupported datatype: %s", datatypeString));
×
367
      }
1✔
368
    }
369
    if (createTimeSeriesStatement.getDataType() == null) {
1✔
370
      throw new SemanticException("datatype must be declared");
×
371
    }
372

373
    final IoTDBDescriptor ioTDBDescriptor = IoTDBDescriptor.getInstance();
1✔
374
    createTimeSeriesStatement.setEncoding(
1✔
375
        ioTDBDescriptor.getDefaultEncodingByType(createTimeSeriesStatement.getDataType()));
1✔
376
    if (props != null
1✔
377
        && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase())) {
1✔
378
      String encodingString =
×
379
          props.get(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase()).toUpperCase();
×
380
      try {
381
        createTimeSeriesStatement.setEncoding(TSEncoding.valueOf(encodingString));
×
382
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase());
×
383
      } catch (Exception e) {
×
384
        throw new SemanticException(String.format("Unsupported encoding: %s", encodingString));
×
385
      }
×
386
    }
387

388
    createTimeSeriesStatement.setCompressor(
1✔
389
        TSFileDescriptor.getInstance().getConfig().getCompressor());
1✔
390
    if (props != null
1✔
391
        && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase())) {
1✔
392
      String compressionString =
×
393
          props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase()).toUpperCase();
×
394
      try {
395
        createTimeSeriesStatement.setCompressor(CompressionType.valueOf(compressionString));
×
396
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase());
×
397
      } catch (Exception e) {
×
398
        throw new SemanticException(
×
399
            String.format("Unsupported compression: %s", compressionString));
×
400
      }
×
401
    } else if (props != null
1✔
402
        && props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase())) {
1✔
403
      String compressorString =
×
404
          props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase()).toUpperCase();
×
405
      try {
406
        createTimeSeriesStatement.setCompressor(CompressionType.valueOf(compressorString));
×
407
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase());
×
408
      } catch (Exception e) {
×
409
        throw new SemanticException(String.format("Unsupported compression: %s", compressorString));
×
410
      }
×
411
    }
412
    createTimeSeriesStatement.setProps(props);
1✔
413
  }
1✔
414

415
  public void parseAttributeClausesForCreateAlignedTimeSeries(
416
      IoTDBSqlParser.AttributeClausesContext ctx,
417
      CreateAlignedTimeSeriesStatement createAlignedTimeSeriesStatement) {
418
    if (ctx.aliasNodeName() != null) {
1✔
419
      createAlignedTimeSeriesStatement.addAliasList(parseNodeName(ctx.aliasNodeName().nodeName()));
×
420
    } else {
421
      createAlignedTimeSeriesStatement.addAliasList(null);
1✔
422
    }
423

424
    TSDataType dataType = parseDataTypeAttribute(ctx);
1✔
425
    createAlignedTimeSeriesStatement.addDataType(dataType);
1✔
426

427
    Map<String, String> props = new HashMap<>();
1✔
428
    if (ctx.attributePair() != null) {
1✔
429
      for (int i = 0; i < ctx.attributePair().size(); i++) {
1✔
430
        props.put(
×
431
            parseAttributeKey(ctx.attributePair(i).attributeKey()).toLowerCase(),
×
432
            parseAttributeValue(ctx.attributePair(i).attributeValue()));
×
433
      }
434
    }
435

436
    TSEncoding encoding = IoTDBDescriptor.getInstance().getDefaultEncodingByType(dataType);
1✔
437
    if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase())) {
1✔
438
      String encodingString =
×
439
          props.get(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase()).toUpperCase();
×
440
      try {
441
        encoding = TSEncoding.valueOf(encodingString);
×
442
        createAlignedTimeSeriesStatement.addEncoding(encoding);
×
443
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase());
×
444
      } catch (Exception e) {
×
445
        throw new SemanticException(String.format("unsupported encoding: %s", encodingString));
×
446
      }
×
447
    } else {
×
448
      createAlignedTimeSeriesStatement.addEncoding(encoding);
1✔
449
    }
450

451
    CompressionType compressor = TSFileDescriptor.getInstance().getConfig().getCompressor();
1✔
452
    if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase())) {
1✔
453
      String compressorString =
×
454
          props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase()).toUpperCase();
×
455
      try {
456
        compressor = CompressionType.valueOf(compressorString);
×
457
        createAlignedTimeSeriesStatement.addCompressor(compressor);
×
458
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase());
×
459
      } catch (Exception e) {
×
460
        throw new SemanticException(String.format("unsupported compressor: %s", compressorString));
×
461
      }
×
462
    } else if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase())) {
1✔
463
      String compressionString =
×
464
          props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase()).toUpperCase();
×
465
      try {
466
        compressor = CompressionType.valueOf(compressionString);
×
467
        createAlignedTimeSeriesStatement.addCompressor(compressor);
×
468
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase());
×
469
      } catch (Exception e) {
×
470
        throw new SemanticException(
×
471
            String.format("unsupported compression: %s", compressionString));
×
472
      }
×
473
    } else {
×
474
      createAlignedTimeSeriesStatement.addCompressor(compressor);
1✔
475
    }
476

477
    if (props.size() > 0) {
1✔
478
      throw new SemanticException("create aligned timeseries: property is not supported yet.");
×
479
    }
480

481
    if (ctx.tagClause() != null) {
1✔
482
      parseTagClause(ctx.tagClause(), createAlignedTimeSeriesStatement);
×
483
    } else {
484
      createAlignedTimeSeriesStatement.addTagsList(null);
1✔
485
    }
486

487
    if (ctx.attributeClause() != null) {
1✔
488
      parseAttributeClauseForTimeSeries(ctx.attributeClause(), createAlignedTimeSeriesStatement);
×
489
    } else {
490
      createAlignedTimeSeriesStatement.addAttributesList(null);
1✔
491
    }
492
  }
1✔
493

494
  // Tag & Property & Attribute
495

496
  public void parseTagClause(IoTDBSqlParser.TagClauseContext ctx, Statement statement) {
497
    Map<String, String> tags = extractMap(ctx.attributePair(), ctx.attributePair(0));
1✔
498
    if (statement instanceof CreateTimeSeriesStatement) {
1✔
499
      ((CreateTimeSeriesStatement) statement).setTags(tags);
1✔
500
    } else if (statement instanceof CreateAlignedTimeSeriesStatement) {
×
501
      ((CreateAlignedTimeSeriesStatement) statement).addTagsList(tags);
×
502
    } else if (statement instanceof AlterTimeSeriesStatement) {
×
503
      ((AlterTimeSeriesStatement) statement).setTagsMap(tags);
×
504
    }
505
  }
1✔
506

507
  public void parseAttributeClauseForTimeSeries(
508
      IoTDBSqlParser.AttributeClauseContext ctx, Statement statement) {
509
    Map<String, String> attributes = extractMap(ctx.attributePair(), ctx.attributePair(0));
1✔
510
    if (statement instanceof CreateTimeSeriesStatement) {
1✔
511
      ((CreateTimeSeriesStatement) statement).setAttributes(attributes);
1✔
512
    } else if (statement instanceof CreateAlignedTimeSeriesStatement) {
×
513
      ((CreateAlignedTimeSeriesStatement) statement).addAttributesList(attributes);
×
514
    } else if (statement instanceof AlterTimeSeriesStatement) {
×
515
      ((AlterTimeSeriesStatement) statement).setAttributesMap(attributes);
×
516
    }
517
  }
1✔
518

519
  // Alter Timeseries ========================================================================
520

521
  @Override
522
  public Statement visitAlterTimeseries(IoTDBSqlParser.AlterTimeseriesContext ctx) {
523
    AlterTimeSeriesStatement alterTimeSeriesStatement = new AlterTimeSeriesStatement();
×
524
    alterTimeSeriesStatement.setPath(parseFullPath(ctx.fullPath()));
×
525
    parseAlterClause(ctx.alterClause(), alterTimeSeriesStatement);
×
526
    return alterTimeSeriesStatement;
×
527
  }
528

529
  private void parseAlterClause(
530
      IoTDBSqlParser.AlterClauseContext ctx, AlterTimeSeriesStatement alterTimeSeriesStatement) {
531
    Map<String, String> alterMap = new HashMap<>();
×
532
    // Rename
533
    if (ctx.RENAME() != null) {
×
534
      alterTimeSeriesStatement.setAlterType(AlterTimeSeriesStatement.AlterType.RENAME);
×
535
      alterMap.put(parseAttributeKey(ctx.beforeName), parseAttributeKey(ctx.currentName));
×
536
    } else if (ctx.SET() != null) {
×
537
      // Set
538
      alterTimeSeriesStatement.setAlterType(AlterTimeSeriesStatement.AlterType.SET);
×
539
      setMap(ctx, alterMap);
×
540
    } else if (ctx.DROP() != null) {
×
541
      // Drop
542
      alterTimeSeriesStatement.setAlterType(AlterTimeSeriesStatement.AlterType.DROP);
×
543
      for (int i = 0; i < ctx.attributeKey().size(); i++) {
×
544
        alterMap.put(parseAttributeKey(ctx.attributeKey().get(i)), null);
×
545
      }
546
    } else if (ctx.TAGS() != null) {
×
547
      // Add tag
548
      alterTimeSeriesStatement.setAlterType((AlterTimeSeriesStatement.AlterType.ADD_TAGS));
×
549
      setMap(ctx, alterMap);
×
550
    } else if (ctx.ATTRIBUTES() != null) {
×
551
      // Add attribute
552
      alterTimeSeriesStatement.setAlterType(AlterTimeSeriesStatement.AlterType.ADD_ATTRIBUTES);
×
553
      setMap(ctx, alterMap);
×
554
    } else {
555
      // Upsert
556
      alterTimeSeriesStatement.setAlterType(AlterTimeSeriesStatement.AlterType.UPSERT);
×
557
      if (ctx.aliasClause() != null) {
×
558
        parseAliasClause(ctx.aliasClause(), alterTimeSeriesStatement);
×
559
      }
560
      if (ctx.tagClause() != null) {
×
561
        parseTagClause(ctx.tagClause(), alterTimeSeriesStatement);
×
562
      }
563
      if (ctx.attributeClause() != null) {
×
564
        parseAttributeClauseForTimeSeries(ctx.attributeClause(), alterTimeSeriesStatement);
×
565
      }
566
    }
567
    alterTimeSeriesStatement.setAlterMap(alterMap);
×
568
  }
×
569

570
  public void parseAliasClause(
571
      IoTDBSqlParser.AliasClauseContext ctx, AlterTimeSeriesStatement alterTimeSeriesStatement) {
572
    if (alterTimeSeriesStatement != null && ctx.ALIAS() != null) {
×
573
      alterTimeSeriesStatement.setAlias(parseAliasNode(ctx.alias()));
×
574
    }
575
  }
×
576

577
  // Drop Timeseries ======================================================================
578

579
  @Override
580
  public Statement visitDropTimeseries(IoTDBSqlParser.DropTimeseriesContext ctx) {
581
    DeleteTimeSeriesStatement deleteTimeSeriesStatement = new DeleteTimeSeriesStatement();
×
582
    List<PartialPath> partialPaths = new ArrayList<>();
×
583
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
584
      partialPaths.add(parsePrefixPath(prefixPathContext));
×
585
    }
×
586
    deleteTimeSeriesStatement.setPathPatternList(partialPaths);
×
587
    return deleteTimeSeriesStatement;
×
588
  }
589

590
  // Show Timeseries ========================================================================
591

592
  @Override
593
  public Statement visitShowTimeseries(IoTDBSqlParser.ShowTimeseriesContext ctx) {
594
    boolean orderByHeat = ctx.LATEST() != null;
×
595
    ShowTimeSeriesStatement showTimeSeriesStatement;
596
    if (ctx.prefixPath() != null) {
×
597
      showTimeSeriesStatement =
×
598
          new ShowTimeSeriesStatement(parsePrefixPath(ctx.prefixPath()), orderByHeat);
×
599
    } else {
600
      showTimeSeriesStatement =
×
601
          new ShowTimeSeriesStatement(
602
              new PartialPath(SqlConstant.getSingleRootArray()), orderByHeat);
×
603
    }
604
    if (ctx.timeseriesWhereClause() != null) {
×
605
      SchemaFilter schemaFilter = parseTimeseriesWhereClause(ctx.timeseriesWhereClause());
×
606
      showTimeSeriesStatement.setSchemaFilter(schemaFilter);
×
607
    }
608
    if (ctx.rowPaginationClause() != null) {
×
609
      if (ctx.rowPaginationClause().limitClause() != null) {
×
610
        showTimeSeriesStatement.setLimit(parseLimitClause(ctx.rowPaginationClause().limitClause()));
×
611
      }
612
      if (ctx.rowPaginationClause().offsetClause() != null) {
×
613
        showTimeSeriesStatement.setOffset(
×
614
            parseOffsetClause(ctx.rowPaginationClause().offsetClause()));
×
615
      }
616
    }
617
    return showTimeSeriesStatement;
×
618
  }
619

620
  private SchemaFilter parseTimeseriesWhereClause(IoTDBSqlParser.TimeseriesWhereClauseContext ctx) {
621
    if (ctx.timeseriesContainsExpression() != null) {
×
622
      // path contains filter
623
      return SchemaFilterFactory.createPathContainsFilter(
×
624
          parseStringLiteral(ctx.timeseriesContainsExpression().value.getText()));
×
625
    } else if (ctx.columnEqualsExpression() != null) {
×
626
      return parseColumnEqualsExpressionContext(ctx.columnEqualsExpression());
×
627
    } else {
628
      // tag filter
629
      if (ctx.tagContainsExpression() != null) {
×
630
        return SchemaFilterFactory.createTagFilter(
×
631
            parseAttributeKey(ctx.tagContainsExpression().attributeKey()),
×
632
            parseStringLiteral(ctx.tagContainsExpression().value.getText()),
×
633
            true);
634
      } else {
635
        return SchemaFilterFactory.createTagFilter(
×
636
            parseAttributeKey(ctx.tagEqualsExpression().attributeKey()),
×
637
            parseAttributeValue(ctx.tagEqualsExpression().attributeValue()),
×
638
            false);
639
      }
640
    }
641
  }
642

643
  private SchemaFilter parseColumnEqualsExpressionContext(
644
      IoTDBSqlParser.ColumnEqualsExpressionContext ctx) {
645
    String column = parseAttributeKey(ctx.attributeKey());
×
646
    String value = parseAttributeValue(ctx.attributeValue());
×
647
    if (column.equalsIgnoreCase(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE)) {
×
648
      try {
649
        TSDataType dataType = TSDataType.valueOf(value.toUpperCase());
×
650
        return SchemaFilterFactory.createDataTypeFilter(dataType);
×
651
      } catch (Exception e) {
×
652
        throw new SemanticException(String.format("unsupported datatype: %s", value));
×
653
      }
654
    } else {
655
      throw new SemanticException("unexpected filter key");
×
656
    }
657
  }
658

659
  // SHOW DATABASES
660

661
  @Override
662
  public Statement visitShowDatabases(IoTDBSqlParser.ShowDatabasesContext ctx) {
663
    ShowDatabaseStatement showDatabaseStatement;
664

665
    // Parse prefixPath
666
    if (ctx.prefixPath() != null) {
×
667
      showDatabaseStatement = new ShowDatabaseStatement(parsePrefixPath(ctx.prefixPath()));
×
668
    } else {
669
      showDatabaseStatement =
×
670
          new ShowDatabaseStatement(new PartialPath(SqlConstant.getSingleRootArray()));
×
671
    }
672

673
    // Is detailed
674
    showDatabaseStatement.setDetailed(ctx.DETAILS() != null);
×
675

676
    return showDatabaseStatement;
×
677
  }
678

679
  // Show Devices ========================================================================
680

681
  @Override
682
  public Statement visitShowDevices(IoTDBSqlParser.ShowDevicesContext ctx) {
683
    ShowDevicesStatement showDevicesStatement;
684
    if (ctx.prefixPath() != null) {
×
685
      showDevicesStatement = new ShowDevicesStatement(parsePrefixPath(ctx.prefixPath()));
×
686
    } else {
687
      showDevicesStatement =
×
688
          new ShowDevicesStatement(new PartialPath(SqlConstant.getSingleRootArray()));
×
689
    }
690
    if (ctx.devicesWhereClause() != null) {
×
691
      showDevicesStatement.setSchemaFilter(parseDevicesWhereClause(ctx.devicesWhereClause()));
×
692
    }
693

694
    if (ctx.rowPaginationClause() != null) {
×
695
      if (ctx.rowPaginationClause().limitClause() != null) {
×
696
        showDevicesStatement.setLimit(parseLimitClause(ctx.rowPaginationClause().limitClause()));
×
697
      }
698
      if (ctx.rowPaginationClause().offsetClause() != null) {
×
699
        showDevicesStatement.setOffset(parseOffsetClause(ctx.rowPaginationClause().offsetClause()));
×
700
      }
701
    }
702
    // show devices with database
703
    if (ctx.WITH() != null) {
×
704
      showDevicesStatement.setSgCol(true);
×
705
    }
706
    return showDevicesStatement;
×
707
  }
708

709
  private SchemaFilter parseDevicesWhereClause(IoTDBSqlParser.DevicesWhereClauseContext ctx) {
710
    // path contains filter
711
    return SchemaFilterFactory.createPathContainsFilter(
×
712
        parseStringLiteral(ctx.deviceContainsExpression().value.getText()));
×
713
  }
714

715
  // Count Devices ========================================================================
716

717
  @Override
718
  public Statement visitCountDevices(CountDevicesContext ctx) {
719
    PartialPath path;
720
    if (ctx.prefixPath() != null) {
×
721
      path = parsePrefixPath(ctx.prefixPath());
×
722
    } else {
723
      path = new PartialPath(SqlConstant.getSingleRootArray());
×
724
    }
725
    return new CountDevicesStatement(path);
×
726
  }
727

728
  // Count TimeSeries ========================================================================
729
  @Override
730
  public Statement visitCountTimeseries(CountTimeseriesContext ctx) {
731
    Statement statement;
732
    PartialPath path;
733
    if (ctx.prefixPath() != null) {
×
734
      path = parsePrefixPath(ctx.prefixPath());
×
735
    } else {
736
      path = new PartialPath(SqlConstant.getSingleRootArray());
×
737
    }
738
    if (ctx.INTEGER_LITERAL() != null) {
×
739
      int level = Integer.parseInt(ctx.INTEGER_LITERAL().getText());
×
740
      statement = new CountLevelTimeSeriesStatement(path, level);
×
741
    } else {
×
742
      statement = new CountTimeSeriesStatement(path);
×
743
    }
744
    if (ctx.timeseriesWhereClause() != null) {
×
745
      SchemaFilter schemaFilter = parseTimeseriesWhereClause(ctx.timeseriesWhereClause());
×
746
      if (statement instanceof CountTimeSeriesStatement) {
×
747
        ((CountTimeSeriesStatement) statement).setSchemaFilter(schemaFilter);
×
748
      } else if (statement instanceof CountLevelTimeSeriesStatement) {
×
749
        ((CountLevelTimeSeriesStatement) statement).setSchemaFilter(schemaFilter);
×
750
      }
751
    }
752
    return statement;
×
753
  }
754

755
  // Count Nodes ========================================================================
756
  @Override
757
  public Statement visitCountNodes(CountNodesContext ctx) {
758
    PartialPath path;
759
    if (ctx.prefixPath() != null) {
×
760
      path = parsePrefixPath(ctx.prefixPath());
×
761
    } else {
762
      path = new PartialPath(SqlConstant.getSingleRootArray());
×
763
    }
764
    int level = Integer.parseInt(ctx.INTEGER_LITERAL().getText());
×
765
    return new CountNodesStatement(path, level);
×
766
  }
767

768
  // Count StorageGroup ========================================================================
769
  @Override
770
  public Statement visitCountDatabases(CountDatabasesContext ctx) {
771
    PartialPath path;
772
    if (ctx.prefixPath() != null) {
×
773
      path = parsePrefixPath(ctx.prefixPath());
×
774
    } else {
775
      path = new PartialPath(SqlConstant.getSingleRootArray());
×
776
    }
777
    return new CountDatabaseStatement(path);
×
778
  }
779

780
  // Show version
781
  @Override
782
  public Statement visitShowVersion(IoTDBSqlParser.ShowVersionContext ctx) {
783
    return new ShowVersionStatement();
×
784
  }
785

786
  // Create Function
787
  @Override
788
  public Statement visitCreateFunction(CreateFunctionContext ctx) {
789
    if (ctx.uriClause() == null) {
×
790
      return new CreateFunctionStatement(
×
791
          parseIdentifier(ctx.udfName.getText()),
×
792
          parseStringLiteral(ctx.className.getText()),
×
793
          false);
794
    } else {
795
      String uriString = parseAndValidateURI(ctx.uriClause());
×
796
      return new CreateFunctionStatement(
×
797
          parseIdentifier(ctx.udfName.getText()),
×
798
          parseStringLiteral(ctx.className.getText()),
×
799
          true,
800
          uriString);
801
    }
802
  }
803

804
  private String parseAndValidateURI(IoTDBSqlParser.UriClauseContext ctx) {
805
    String uriString = parseStringLiteral(ctx.uri().getText());
×
806
    try {
807
      new URI(uriString);
×
808
    } catch (URISyntaxException e) {
×
809
      throw new SemanticException(String.format("Invalid URI: %s", uriString));
×
810
    }
×
811
    return uriString;
×
812
  }
813

814
  // Drop Function
815
  @Override
816
  public Statement visitDropFunction(DropFunctionContext ctx) {
817
    return new DropFunctionStatement(parseIdentifier(ctx.udfName.getText()));
×
818
  }
819

820
  // Show Functions
821
  @Override
822
  public Statement visitShowFunctions(ShowFunctionsContext ctx) {
823
    return new ShowFunctionsStatement();
×
824
  }
825

826
  // Create Trigger =====================================================================
827
  @Override
828
  public Statement visitCreateTrigger(IoTDBSqlParser.CreateTriggerContext ctx) {
829
    if (ctx.triggerEventClause().DELETE() != null) {
×
830
      throw new SemanticException("Trigger does not support DELETE as TRIGGER_EVENT for now.");
×
831
    }
832
    if (ctx.triggerType() == null) {
×
833
      throw new SemanticException("Please specify trigger type: STATELESS or STATEFUL.");
×
834
    }
835
    Map<String, String> attributes = new HashMap<>();
×
836
    if (ctx.triggerAttributeClause() != null) {
×
837
      for (IoTDBSqlParser.TriggerAttributeContext triggerAttributeContext :
838
          ctx.triggerAttributeClause().triggerAttribute()) {
×
839
        attributes.put(
×
840
            parseAttributeKey(triggerAttributeContext.key),
×
841
            parseAttributeValue(triggerAttributeContext.value));
×
842
      }
×
843
    }
844
    if (ctx.uriClause() == null) {
×
845
      return new CreateTriggerStatement(
×
846
          parseIdentifier(ctx.triggerName.getText()),
×
847
          parseStringLiteral(ctx.className.getText()),
×
848
          "",
849
          false,
850
          ctx.triggerEventClause().BEFORE() != null
×
851
              ? TriggerEvent.BEFORE_INSERT
×
852
              : TriggerEvent.AFTER_INSERT,
×
853
          ctx.triggerType().STATELESS() != null ? TriggerType.STATELESS : TriggerType.STATEFUL,
×
854
          parsePrefixPath(ctx.prefixPath()),
×
855
          attributes);
856
    } else {
857
      String uriString = parseAndValidateURI(ctx.uriClause());
×
858
      return new CreateTriggerStatement(
×
859
          parseIdentifier(ctx.triggerName.getText()),
×
860
          parseStringLiteral(ctx.className.getText()),
×
861
          uriString,
862
          true,
863
          ctx.triggerEventClause().BEFORE() != null
×
864
              ? TriggerEvent.BEFORE_INSERT
×
865
              : TriggerEvent.AFTER_INSERT,
×
866
          ctx.triggerType().STATELESS() != null ? TriggerType.STATELESS : TriggerType.STATEFUL,
×
867
          parsePrefixPath(ctx.prefixPath()),
×
868
          attributes);
869
    }
870
  }
871

872
  // Drop Trigger =====================================================================
873
  @Override
874
  public Statement visitDropTrigger(IoTDBSqlParser.DropTriggerContext ctx) {
875
    return new DropTriggerStatement(parseIdentifier(ctx.triggerName.getText()));
×
876
  }
877

878
  // Show Trigger =====================================================================
879
  @Override
880
  public Statement visitShowTriggers(IoTDBSqlParser.ShowTriggersContext ctx) {
881
    return new ShowTriggersStatement();
×
882
  }
883

884
  // Create PipePlugin =====================================================================
885
  @Override
886
  public Statement visitCreatePipePlugin(IoTDBSqlParser.CreatePipePluginContext ctx) {
887
    return new CreatePipePluginStatement(
×
888
        ctx.pluginName.getText(),
×
889
        parseStringLiteral(ctx.className.getText()),
×
890
        parseAndValidateURI(ctx.uriClause()));
×
891
  }
892

893
  // Drop PipePlugin =====================================================================
894
  @Override
895
  public Statement visitDropPipePlugin(IoTDBSqlParser.DropPipePluginContext ctx) {
896
    return new DropPipePluginStatement(ctx.pluginName.getText());
×
897
  }
898

899
  // Show PipePlugins =====================================================================
900
  @Override
901
  public Statement visitShowPipePlugins(IoTDBSqlParser.ShowPipePluginsContext ctx) {
902
    return new ShowPipePluginsStatement();
×
903
  }
904

905
  // Show Child Paths =====================================================================
906
  @Override
907
  public Statement visitShowChildPaths(IoTDBSqlParser.ShowChildPathsContext ctx) {
908
    if (ctx.prefixPath() != null) {
×
909
      return new ShowChildPathsStatement(parsePrefixPath(ctx.prefixPath()));
×
910
    } else {
911
      return new ShowChildPathsStatement(new PartialPath(SqlConstant.getSingleRootArray()));
×
912
    }
913
  }
914

915
  // Show Child Nodes =====================================================================
916
  @Override
917
  public Statement visitShowChildNodes(IoTDBSqlParser.ShowChildNodesContext ctx) {
918
    if (ctx.prefixPath() != null) {
×
919
      return new ShowChildNodesStatement(parsePrefixPath(ctx.prefixPath()));
×
920
    } else {
921
      return new ShowChildNodesStatement(new PartialPath(SqlConstant.getSingleRootArray()));
×
922
    }
923
  }
924

925
  // Create CQ =====================================================================
926
  @Override
927
  public Statement visitCreateContinuousQuery(IoTDBSqlParser.CreateContinuousQueryContext ctx) {
928
    CreateContinuousQueryStatement statement = new CreateContinuousQueryStatement();
×
929

930
    statement.setCqId(parseIdentifier(ctx.cqId.getText()));
×
931

932
    QueryStatement queryBodyStatement =
×
933
        (QueryStatement) visitSelectStatement(ctx.selectStatement());
×
934
    queryBodyStatement.setCqQueryBody(true);
×
935
    statement.setQueryBodyStatement(queryBodyStatement);
×
936

937
    if (ctx.resampleClause() != null) {
×
938
      parseResampleClause(ctx.resampleClause(), statement);
×
939
    } else {
940
      QueryStatement queryStatement = statement.getQueryBodyStatement();
×
941
      if (!queryStatement.isGroupByTime()) {
×
942
        throw new SemanticException(
×
943
            "CQ: At least one of the parameters `every_interval` and `group_by_interval` needs to be specified.");
944
      }
945

946
      long interval = queryStatement.getGroupByTimeComponent().getInterval();
×
947
      statement.setEveryInterval(interval);
×
948
      statement.setStartTimeOffset(interval);
×
949
    }
950

951
    if (ctx.timeoutPolicyClause() != null) {
×
952
      parseTimeoutPolicyClause(ctx.timeoutPolicyClause(), statement);
×
953
    }
954

955
    return statement;
×
956
  }
957

958
  private void parseResampleClause(
959
      IoTDBSqlParser.ResampleClauseContext ctx, CreateContinuousQueryStatement statement) {
960
    if (ctx.EVERY() != null) {
×
961
      statement.setEveryInterval(
×
962
          DateTimeUtils.convertDurationStrToLong(ctx.everyInterval.getText()));
×
963
    } else {
964
      QueryStatement queryStatement = statement.getQueryBodyStatement();
×
965
      if (!queryStatement.isGroupByTime()) {
×
966
        throw new SemanticException(
×
967
            "CQ: At least one of the parameters `every_interval` and `group_by_interval` needs to be specified.");
968
      }
969
      statement.setEveryInterval(queryStatement.getGroupByTimeComponent().getInterval());
×
970
    }
971

972
    if (ctx.BOUNDARY() != null) {
×
973
      statement.setBoundaryTime(parseTimeValue(ctx.boundaryTime, DateTimeUtils.currentTime()));
×
974
    }
975

976
    if (ctx.RANGE() != null) {
×
977
      statement.setStartTimeOffset(
×
978
          DateTimeUtils.convertDurationStrToLong(ctx.startTimeOffset.getText()));
×
979
      if (ctx.endTimeOffset != null) {
×
980
        statement.setEndTimeOffset(
×
981
            DateTimeUtils.convertDurationStrToLong(ctx.endTimeOffset.getText()));
×
982
      }
983
    } else {
984
      statement.setStartTimeOffset(statement.getEveryInterval());
×
985
    }
986
  }
×
987

988
  private void parseTimeoutPolicyClause(
989
      IoTDBSqlParser.TimeoutPolicyClauseContext ctx, CreateContinuousQueryStatement statement) {
990
    if (ctx.DISCARD() != null) {
×
991
      statement.setTimeoutPolicy(TimeoutPolicy.DISCARD);
×
992
    }
993
  }
×
994

995
  // Drop CQ =====================================================================
996
  @Override
997
  public Statement visitDropContinuousQuery(IoTDBSqlParser.DropContinuousQueryContext ctx) {
998
    return new DropContinuousQueryStatement(parseIdentifier(ctx.cqId.getText()));
×
999
  }
1000

1001
  // Show CQs =====================================================================
1002
  @Override
1003
  public Statement visitShowContinuousQueries(IoTDBSqlParser.ShowContinuousQueriesContext ctx) {
1004
    return new ShowContinuousQueriesStatement();
×
1005
  }
1006

1007
  // Create Logical View
1008
  @Override
1009
  public Statement visitCreateLogicalView(IoTDBSqlParser.CreateLogicalViewContext ctx) {
1010
    CreateLogicalViewStatement createLogicalViewStatement = new CreateLogicalViewStatement();
×
1011
    // parse target
1012
    parseViewTargetPaths(
×
1013
        ctx.viewTargetPaths(),
×
1014
        createLogicalViewStatement::setTargetFullPaths,
×
1015
        createLogicalViewStatement::setTargetPathsGroup,
×
1016
        createLogicalViewStatement::setTargetIntoItem);
×
1017
    // parse source
1018
    parseViewSourcePaths(
×
1019
        ctx.viewSourcePaths(),
×
1020
        createLogicalViewStatement::setSourceFullPaths,
×
1021
        createLogicalViewStatement::setSourcePathsGroup,
×
1022
        createLogicalViewStatement::setSourceQueryStatement);
×
1023

1024
    return createLogicalViewStatement;
×
1025
  }
1026

1027
  @Override
1028
  public Statement visitDropLogicalView(IoTDBSqlParser.DropLogicalViewContext ctx) {
1029
    DeleteLogicalViewStatement deleteLogicalViewStatement = new DeleteLogicalViewStatement();
×
1030
    List<PartialPath> partialPaths = new ArrayList<>();
×
1031
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
1032
      partialPaths.add(parsePrefixPath(prefixPathContext));
×
1033
    }
×
1034
    deleteLogicalViewStatement.setPathPatternList(partialPaths);
×
1035
    return deleteLogicalViewStatement;
×
1036
  }
1037

1038
  @Override
1039
  public Statement visitShowLogicalView(IoTDBSqlParser.ShowLogicalViewContext ctx) {
1040
    ShowLogicalViewStatement showLogicalViewStatement;
1041
    if (ctx.prefixPath() != null) {
×
1042
      showLogicalViewStatement = new ShowLogicalViewStatement(parsePrefixPath(ctx.prefixPath()));
×
1043
    } else {
1044
      showLogicalViewStatement =
×
1045
          new ShowLogicalViewStatement(new PartialPath(SqlConstant.getSingleRootArray()));
×
1046
    }
1047
    if (ctx.timeseriesWhereClause() != null) {
×
1048
      SchemaFilter schemaFilter = parseTimeseriesWhereClause(ctx.timeseriesWhereClause());
×
1049
      showLogicalViewStatement.setSchemaFilter(schemaFilter);
×
1050
    }
1051
    if (ctx.rowPaginationClause() != null) {
×
1052
      if (ctx.rowPaginationClause().limitClause() != null) {
×
1053
        showLogicalViewStatement.setLimit(
×
1054
            parseLimitClause(ctx.rowPaginationClause().limitClause()));
×
1055
      }
1056
      if (ctx.rowPaginationClause().offsetClause() != null) {
×
1057
        showLogicalViewStatement.setOffset(
×
1058
            parseOffsetClause(ctx.rowPaginationClause().offsetClause()));
×
1059
      }
1060
    }
1061
    return showLogicalViewStatement;
×
1062
  }
1063

1064
  @Override
1065
  public Statement visitRenameLogicalView(IoTDBSqlParser.RenameLogicalViewContext ctx) {
1066
    throw new SemanticException("Renaming view is not supported.");
×
1067
  }
1068

1069
  @Override
1070
  public Statement visitAlterLogicalView(IoTDBSqlParser.AlterLogicalViewContext ctx) {
1071
    if (ctx.alterClause() == null) {
×
1072
      AlterLogicalViewStatement alterLogicalViewStatement = new AlterLogicalViewStatement();
×
1073
      // parse target
1074
      parseViewTargetPaths(
×
1075
          ctx.viewTargetPaths(),
×
1076
          alterLogicalViewStatement::setTargetFullPaths,
×
1077
          alterLogicalViewStatement::setTargetPathsGroup,
×
1078
          intoItem -> {
1079
            if (intoItem != null) {
×
1080
              throw new SemanticException(
×
1081
                  "Can not use char '$' or into item in alter view statement.");
1082
            }
1083
          });
×
1084
      // parse source
1085
      parseViewSourcePaths(
×
1086
          ctx.viewSourcePaths(),
×
1087
          alterLogicalViewStatement::setSourceFullPaths,
×
1088
          alterLogicalViewStatement::setSourcePathsGroup,
×
1089
          alterLogicalViewStatement::setSourceQueryStatement);
×
1090

1091
      return alterLogicalViewStatement;
×
1092
    } else {
1093
      AlterTimeSeriesStatement alterTimeSeriesStatement = new AlterTimeSeriesStatement(true);
×
1094
      alterTimeSeriesStatement.setPath(parseFullPath(ctx.fullPath()));
×
1095
      parseAlterClause(ctx.alterClause(), alterTimeSeriesStatement);
×
1096
      if (alterTimeSeriesStatement.getAlias() != null) {
×
1097
        throw new SemanticException("View doesn't support alias.");
×
1098
      }
1099
      return alterTimeSeriesStatement;
×
1100
    }
1101
  }
1102

1103
  // parse suffix paths in logical view with into item
1104
  private PartialPath parseViewPrefixPathWithInto(IoTDBSqlParser.PrefixPathContext ctx) {
1105
    List<IoTDBSqlParser.NodeNameContext> nodeNames = ctx.nodeName();
×
1106
    String[] path = new String[nodeNames.size() + 1];
×
1107
    path[0] = ctx.ROOT().getText();
×
1108
    for (int i = 0; i < nodeNames.size(); i++) {
×
1109
      path[i + 1] = parseNodeStringInIntoPath(nodeNames.get(i).getText());
×
1110
    }
1111
    return new PartialPath(path);
×
1112
  }
1113

1114
  private PartialPath parseViewSuffixPatWithInto(IoTDBSqlParser.ViewSuffixPathsContext ctx) {
1115
    List<IoTDBSqlParser.NodeNameWithoutWildcardContext> nodeNamesWithoutStar =
×
1116
        ctx.nodeNameWithoutWildcard();
×
1117
    String[] nodeList = new String[nodeNamesWithoutStar.size()];
×
1118
    for (int i = 0; i < nodeNamesWithoutStar.size(); i++) {
×
1119
      nodeList[i] = parseNodeStringInIntoPath(nodeNamesWithoutStar.get(i).getText());
×
1120
    }
1121
    return new PartialPath(nodeList);
×
1122
  }
1123

1124
  private PartialPath parseViewSuffixPath(IoTDBSqlParser.ViewSuffixPathsContext ctx) {
1125
    List<IoTDBSqlParser.NodeNameWithoutWildcardContext> nodeNamesWithoutStar =
×
1126
        ctx.nodeNameWithoutWildcard();
×
1127
    String[] nodeList = new String[nodeNamesWithoutStar.size()];
×
1128
    for (int i = 0; i < nodeNamesWithoutStar.size(); i++) {
×
1129
      nodeList[i] = parseNodeNameWithoutWildCard(nodeNamesWithoutStar.get(i));
×
1130
    }
1131
    return new PartialPath(nodeList);
×
1132
  }
1133

1134
  // parse target paths in CreateLogicalView statement
1135
  private void parseViewTargetPaths(
1136
      IoTDBSqlParser.ViewTargetPathsContext ctx,
1137
      Consumer<List<PartialPath>> setTargetFullPaths,
1138
      BiConsumer<PartialPath, List<PartialPath>> setTargetPathsGroup,
1139
      Consumer<IntoItem> setTargetIntoItem) {
1140
    // full paths
1141
    if (ctx.fullPath() != null && !ctx.fullPath().isEmpty()) {
×
1142
      List<IoTDBSqlParser.FullPathContext> fullPathContextList = ctx.fullPath();
×
1143
      List<PartialPath> pathList = new ArrayList<>();
×
1144
      for (IoTDBSqlParser.FullPathContext pathContext : fullPathContextList) {
×
1145
        pathList.add(parseFullPath(pathContext));
×
1146
      }
×
1147
      setTargetFullPaths.accept(pathList);
×
1148
    }
1149
    // prefix path and suffix paths
1150
    if (ctx.prefixPath() != null
×
1151
        && ctx.viewSuffixPaths() != null
×
1152
        && !ctx.viewSuffixPaths().isEmpty()) {
×
1153
      IoTDBSqlParser.PrefixPathContext prefixPathContext = ctx.prefixPath();
×
1154
      List<IoTDBSqlParser.ViewSuffixPathsContext> suffixPathContextList = ctx.viewSuffixPaths();
×
1155
      List<PartialPath> suffixPathList = new ArrayList<>();
×
1156
      PartialPath prefixPath = null;
×
1157
      boolean isMultipleCreating = false;
×
1158
      try {
1159
        prefixPath = parsePrefixPath(prefixPathContext);
×
1160
        for (IoTDBSqlParser.ViewSuffixPathsContext suffixPathContext : suffixPathContextList) {
×
1161
          suffixPathList.add(parseViewSuffixPath(suffixPathContext));
×
1162
        }
×
1163
      } catch (SemanticException e) {
×
1164
        // there is '$', '{', '}' in this statement
1165
        isMultipleCreating = true;
×
1166
        suffixPathList.clear();
×
1167
      }
×
1168
      if (!isMultipleCreating) {
×
1169
        setTargetPathsGroup.accept(prefixPath, suffixPathList);
×
1170
      } else {
1171
        prefixPath = parseViewPrefixPathWithInto(prefixPathContext);
×
1172
        for (IoTDBSqlParser.ViewSuffixPathsContext suffixPathContext : suffixPathContextList) {
×
1173
          suffixPathList.add(parseViewSuffixPatWithInto(suffixPathContext));
×
1174
        }
×
1175
        List<String> intoMeasurementList = new ArrayList<>();
×
1176
        for (PartialPath path : suffixPathList) {
×
1177
          intoMeasurementList.add(path.toString());
×
1178
        }
×
1179
        IntoItem intoItem = new IntoItem(prefixPath, intoMeasurementList, false);
×
1180
        setTargetIntoItem.accept(intoItem);
×
1181
      }
1182
    }
1183
  }
×
1184

1185
  // parse source paths in CreateLogicalView statement
1186
  private void parseViewSourcePaths(
1187
      IoTDBSqlParser.ViewSourcePathsContext ctx,
1188
      Consumer<List<PartialPath>> setSourceFullPaths,
1189
      BiConsumer<PartialPath, List<PartialPath>> setSourcePathsGroup,
1190
      Consumer<QueryStatement> setSourceQueryStatement) {
1191
    // full paths
1192
    if (ctx.fullPath() != null && !ctx.fullPath().isEmpty()) {
×
1193
      List<IoTDBSqlParser.FullPathContext> fullPathContextList = ctx.fullPath();
×
1194
      List<PartialPath> pathList = new ArrayList<>();
×
1195
      for (IoTDBSqlParser.FullPathContext pathContext : fullPathContextList) {
×
1196
        pathList.add(parseFullPath(pathContext));
×
1197
      }
×
1198
      setSourceFullPaths.accept(pathList);
×
1199
    }
1200
    // prefix path and suffix paths
1201
    if (ctx.prefixPath() != null
×
1202
        && ctx.viewSuffixPaths() != null
×
1203
        && !ctx.viewSuffixPaths().isEmpty()) {
×
1204
      IoTDBSqlParser.PrefixPathContext prefixPathContext = ctx.prefixPath();
×
1205
      PartialPath prefixPath = parsePrefixPath(prefixPathContext);
×
1206
      List<IoTDBSqlParser.ViewSuffixPathsContext> suffixPathContextList = ctx.viewSuffixPaths();
×
1207
      List<PartialPath> suffixPathList = new ArrayList<>();
×
1208
      for (IoTDBSqlParser.ViewSuffixPathsContext suffixPathContext : suffixPathContextList) {
×
1209
        suffixPathList.add(parseViewSuffixPath(suffixPathContext));
×
1210
      }
×
1211
      setSourcePathsGroup.accept(prefixPath, suffixPathList);
×
1212
    }
1213
    if (ctx.selectClause() != null && ctx.fromClause() != null) {
×
1214
      QueryStatement queryStatement = new QueryStatement();
×
1215
      queryStatement.setSelectComponent(parseSelectClause(ctx.selectClause(), queryStatement));
×
1216
      queryStatement.setFromComponent(parseFromClause(ctx.fromClause()));
×
1217
      setSourceQueryStatement.accept(queryStatement);
×
1218
    }
1219
  }
×
1220

1221
  // Create Model =====================================================================
1222
  @Override
1223
  public Statement visitCreateModel(IoTDBSqlParser.CreateModelContext ctx) {
1224
    CreateModelStatement createModelStatement = new CreateModelStatement();
×
1225
    createModelStatement.setModelId(parseIdentifier(ctx.modelId.getText()));
×
1226
    createModelStatement.setAuto(ctx.AUTO() != null);
×
1227

1228
    Map<String, String> attributes = new HashMap<>();
×
1229
    for (IoTDBSqlParser.AttributePairContext attribute : ctx.attributePair()) {
×
1230
      attributes.put(
×
1231
          parseAttributeKey(attribute.key).toLowerCase(), parseAttributeValue(attribute.value));
×
1232
    }
×
1233
    createModelStatement.setAttributes(attributes);
×
1234

1235
    createModelStatement.setQueryStatement(
×
1236
        (QueryStatement) visitSelectStatement(ctx.selectStatement()));
×
1237
    return createModelStatement;
×
1238
  }
1239

1240
  // Drop Model =====================================================================
1241
  @Override
1242
  public Statement visitDropModel(IoTDBSqlParser.DropModelContext ctx) {
1243
    return new DropModelStatement(parseIdentifier(ctx.modelId.getText()));
×
1244
  }
1245

1246
  // Show Models =====================================================================
1247
  @Override
1248
  public Statement visitShowModels(IoTDBSqlParser.ShowModelsContext ctx) {
1249
    return new ShowModelsStatement();
×
1250
  }
1251

1252
  // Show Trails =====================================================================
1253
  @Override
1254
  public Statement visitShowTrails(IoTDBSqlParser.ShowTrailsContext ctx) {
1255
    return new ShowTrailsStatement(parseIdentifier(ctx.modelId.getText()));
×
1256
  }
1257

1258
  /** Data Manipulation Language (DML). */
1259

1260
  // Select Statement ========================================================================
1261
  @Override
1262
  public Statement visitSelectStatement(IoTDBSqlParser.SelectStatementContext ctx) {
1263
    QueryStatement queryStatement = new QueryStatement();
1✔
1264

1265
    // parse SELECT & FROM
1266
    queryStatement.setSelectComponent(parseSelectClause(ctx.selectClause(), queryStatement));
1✔
1267
    queryStatement.setFromComponent(parseFromClause(ctx.fromClause()));
1✔
1268

1269
    // parse INTO
1270
    if (ctx.intoClause() != null) {
1✔
1271
      queryStatement.setIntoComponent(parseIntoClause(ctx.intoClause()));
1✔
1272
    }
1273

1274
    // parse WHERE
1275
    if (ctx.whereClause() != null) {
1✔
1276
      queryStatement.setWhereCondition(parseWhereClause(ctx.whereClause()));
1✔
1277
    }
1278

1279
    // parse GROUP BY
1280
    if (ctx.groupByClause() != null) {
1✔
1281
      Set<String> groupByKeys = new HashSet<>();
1✔
1282
      List<IoTDBSqlParser.GroupByAttributeClauseContext> groupByAttributes =
1✔
1283
          ctx.groupByClause().groupByAttributeClause();
1✔
1284
      for (IoTDBSqlParser.GroupByAttributeClauseContext groupByAttribute : groupByAttributes) {
1✔
1285
        if (groupByAttribute.TIME() != null || groupByAttribute.interval != null) {
1✔
1286
          if (groupByKeys.contains("COMMON")) {
1✔
1287
            throw new SemanticException(GROUP_BY_COMMON_ONLY_ONE_MSG);
×
1288
          }
1289

1290
          groupByKeys.add("COMMON");
1✔
1291
          queryStatement.setGroupByTimeComponent(parseGroupByTimeClause(groupByAttribute));
1✔
1292
        } else if (groupByAttribute.LEVEL() != null) {
1✔
1293
          if (groupByKeys.contains("LEVEL")) {
1✔
1294
            throw new SemanticException("duplicated group by key: LEVEL");
×
1295
          }
1296

1297
          groupByKeys.add("LEVEL");
1✔
1298
          queryStatement.setGroupByLevelComponent(parseGroupByLevelClause(groupByAttribute));
1✔
1299
        } else if (groupByAttribute.TAGS() != null) {
1✔
1300
          if (groupByKeys.contains("TAGS")) {
1✔
1301
            throw new SemanticException("duplicated group by key: TAGS");
×
1302
          }
1303

1304
          groupByKeys.add("TAGS");
1✔
1305
          queryStatement.setGroupByTagComponent(parseGroupByTagClause(groupByAttribute));
1✔
1306
        } else if (groupByAttribute.VARIATION() != null) {
1✔
1307
          if (groupByKeys.contains("COMMON")) {
1✔
1308
            throw new SemanticException(GROUP_BY_COMMON_ONLY_ONE_MSG);
×
1309
          }
1310

1311
          groupByKeys.add("COMMON");
1✔
1312
          queryStatement.setGroupByComponent(
1✔
1313
              parseGroupByClause(groupByAttribute, WindowType.VARIATION_WINDOW));
1✔
1314
        } else if (groupByAttribute.CONDITION() != null) {
×
1315
          if (groupByKeys.contains("COMMON")) {
×
1316
            throw new SemanticException(GROUP_BY_COMMON_ONLY_ONE_MSG);
×
1317
          }
1318

1319
          groupByKeys.add("COMMON");
×
1320
          queryStatement.setGroupByComponent(
×
1321
              parseGroupByClause(groupByAttribute, WindowType.CONDITION_WINDOW));
×
1322
        } else if (groupByAttribute.SESSION() != null) {
×
1323
          if (groupByKeys.contains("COMMON")) {
×
1324
            throw new SemanticException(GROUP_BY_COMMON_ONLY_ONE_MSG);
×
1325
          }
1326

1327
          groupByKeys.add("COMMON");
×
1328
          queryStatement.setGroupByComponent(
×
1329
              parseGroupByClause(groupByAttribute, WindowType.SESSION_WINDOW));
×
1330
        } else if (groupByAttribute.COUNT() != null) {
×
1331
          if (groupByKeys.contains("COMMON")) {
×
1332
            throw new SemanticException(GROUP_BY_COMMON_ONLY_ONE_MSG);
×
1333
          }
1334

1335
          groupByKeys.add("COMMON");
×
1336
          queryStatement.setGroupByComponent(
×
1337
              parseGroupByClause(groupByAttribute, WindowType.COUNT_WINDOW));
×
1338

1339
        } else {
1340
          throw new SemanticException("Unknown GROUP BY type.");
×
1341
        }
1342
      }
1✔
1343
    }
1344

1345
    // parse HAVING
1346
    if (ctx.havingClause() != null) {
1✔
1347
      queryStatement.setHavingCondition(parseHavingClause(ctx.havingClause()));
1✔
1348
    }
1349

1350
    // parse ORDER BY
1351
    if (ctx.orderByClause() != null) {
1✔
1352
      queryStatement.setOrderByComponent(
1✔
1353
          parseOrderByClause(
1✔
1354
              ctx.orderByClause(),
1✔
1355
              ImmutableSet.of(OrderByKey.TIME, OrderByKey.DEVICE, OrderByKey.TIMESERIES)));
1✔
1356
    }
1357

1358
    // parse FILL
1359
    if (ctx.fillClause() != null) {
1✔
1360
      queryStatement.setFillComponent(parseFillClause(ctx.fillClause()));
1✔
1361
    }
1362

1363
    // parse ALIGN BY
1364
    if (ctx.alignByClause() != null) {
1✔
1365
      queryStatement.setResultSetFormat(parseAlignBy(ctx.alignByClause()));
1✔
1366
    }
1367

1368
    if (ctx.paginationClause() != null) {
1✔
1369
      // parse SLIMIT & SOFFSET
1370
      if (ctx.paginationClause().seriesPaginationClause() != null) {
1✔
1371
        if (ctx.paginationClause().seriesPaginationClause().slimitClause() != null) {
1✔
1372
          queryStatement.setSeriesLimit(
1✔
1373
              parseSLimitClause(ctx.paginationClause().seriesPaginationClause().slimitClause()));
1✔
1374
        }
1375
        if (ctx.paginationClause().seriesPaginationClause().soffsetClause() != null) {
1✔
1376
          queryStatement.setSeriesOffset(
1✔
1377
              parseSOffsetClause(ctx.paginationClause().seriesPaginationClause().soffsetClause()));
1✔
1378
        }
1379
      }
1380

1381
      // parse LIMIT & OFFSET
1382
      if (ctx.paginationClause().rowPaginationClause() != null) {
1✔
1383
        if (ctx.paginationClause().rowPaginationClause().limitClause() != null) {
1✔
1384
          queryStatement.setRowLimit(
1✔
1385
              parseLimitClause(ctx.paginationClause().rowPaginationClause().limitClause()));
1✔
1386
        }
1387
        if (ctx.paginationClause().rowPaginationClause().offsetClause() != null) {
1✔
1388
          queryStatement.setRowOffset(
1✔
1389
              parseOffsetClause(ctx.paginationClause().rowPaginationClause().offsetClause()));
1✔
1390
        }
1391
        if (canPushDownLimitOffsetToGroupByTime(queryStatement)) {
1✔
1392
          pushDownLimitOffsetToTimeParameter(queryStatement);
1✔
1393
        }
1394
      }
1395
    }
1396

1397
    queryStatement.setUseWildcard(useWildcard);
1✔
1398
    queryStatement.setLastLevelUseWildcard(lastLevelUseWildcard);
1✔
1399
    return queryStatement;
1✔
1400
  }
1401

1402
  // ---- Select Clause
1403
  private SelectComponent parseSelectClause(
1404
      IoTDBSqlParser.SelectClauseContext ctx, QueryStatement queryStatement) {
1405
    SelectComponent selectComponent = new SelectComponent(zoneId);
1✔
1406

1407
    // parse LAST
1408
    if (ctx.LAST() != null) {
1✔
1409
      selectComponent.setHasLast(true);
1✔
1410
    }
1411

1412
    // parse resultColumn
1413
    Map<String, Expression> aliasToColumnMap = new HashMap<>();
1✔
1414
    for (IoTDBSqlParser.ResultColumnContext resultColumnContext : ctx.resultColumn()) {
1✔
1415
      ResultColumn resultColumn = parseResultColumn(resultColumnContext);
1✔
1416
      // __endTime shouldn't be included in resultColumns
1417
      if (resultColumn.getExpression().getExpressionString().equals(ColumnHeaderConstant.ENDTIME)) {
1✔
1418
        queryStatement.setOutputEndTime(true);
×
1419
        continue;
×
1420
      }
1421
      if (resultColumn.hasAlias()) {
1✔
1422
        String alias = resultColumn.getAlias();
1✔
1423
        if (aliasToColumnMap.containsKey(alias)) {
1✔
1424
          throw new SemanticException("duplicate alias in select clause");
×
1425
        }
1426
        aliasToColumnMap.put(alias, resultColumn.getExpression());
1✔
1427
      }
1428
      selectComponent.addResultColumn(resultColumn);
1✔
1429
    }
1✔
1430
    selectComponent.setAliasToColumnMap(aliasToColumnMap);
1✔
1431

1432
    return selectComponent;
1✔
1433
  }
1434

1435
  private ResultColumn parseResultColumn(IoTDBSqlParser.ResultColumnContext resultColumnContext) {
1436
    Expression expression = parseExpression(resultColumnContext.expression(), false);
1✔
1437
    if (expression.isConstantOperand()) {
1✔
1438
      throw new SemanticException("Constant operand is not allowed: " + expression);
×
1439
    }
1440
    String alias = null;
1✔
1441
    if (resultColumnContext.AS() != null) {
1✔
1442
      alias = parseAlias(resultColumnContext.alias());
1✔
1443
    }
1444
    ResultColumn.ColumnType columnType =
1✔
1445
        ExpressionAnalyzer.identifyOutputColumnType(expression, true);
1✔
1446
    return new ResultColumn(expression, alias, columnType);
1✔
1447
  }
1448

1449
  // ---- From Clause
1450
  private FromComponent parseFromClause(IoTDBSqlParser.FromClauseContext ctx) {
1451
    FromComponent fromComponent = new FromComponent();
1✔
1452
    List<IoTDBSqlParser.PrefixPathContext> prefixFromPaths = ctx.prefixPath();
1✔
1453
    for (IoTDBSqlParser.PrefixPathContext prefixFromPath : prefixFromPaths) {
1✔
1454
      PartialPath path = parsePrefixPath(prefixFromPath);
1✔
1455
      fromComponent.addPrefixPath(path);
1✔
1456
    }
1✔
1457
    return fromComponent;
1✔
1458
  }
1459

1460
  // ---- Into Clause
1461
  private IntoComponent parseIntoClause(IoTDBSqlParser.IntoClauseContext ctx) {
1462
    List<IntoItem> intoItems = new ArrayList<>();
1✔
1463
    for (IoTDBSqlParser.IntoItemContext intoItemContext : ctx.intoItem()) {
1✔
1464
      intoItems.add(parseIntoItem(intoItemContext));
1✔
1465
    }
1✔
1466
    return new IntoComponent(intoItems);
1✔
1467
  }
1468

1469
  private IntoItem parseIntoItem(IoTDBSqlParser.IntoItemContext intoItemContext) {
1470
    boolean isAligned = intoItemContext.ALIGNED() != null;
1✔
1471
    PartialPath intoDevice = parseIntoPath(intoItemContext.intoPath());
1✔
1472
    List<String> intoMeasurements =
1✔
1473
        intoItemContext.nodeNameInIntoPath().stream()
1✔
1474
            .map(this::parseNodeNameInIntoPath)
1✔
1475
            .collect(Collectors.toList());
1✔
1476
    return new IntoItem(intoDevice, intoMeasurements, isAligned);
1✔
1477
  }
1478

1479
  private PartialPath parseIntoPath(IoTDBSqlParser.IntoPathContext intoPathContext) {
1480
    if (intoPathContext instanceof IoTDBSqlParser.FullPathInIntoPathContext) {
1✔
1481
      return parseFullPathInIntoPath((IoTDBSqlParser.FullPathInIntoPathContext) intoPathContext);
1✔
1482
    } else {
1483
      List<IoTDBSqlParser.NodeNameInIntoPathContext> nodeNames =
1✔
1484
          ((IoTDBSqlParser.SuffixPathInIntoPathContext) intoPathContext).nodeNameInIntoPath();
1✔
1485
      String[] path = new String[nodeNames.size()];
1✔
1486
      for (int i = 0; i < nodeNames.size(); i++) {
1✔
1487
        path[i] = parseNodeNameInIntoPath(nodeNames.get(i));
1✔
1488
      }
1489
      return new PartialPath(path);
1✔
1490
    }
1491
  }
1492

1493
  // ---- Where Clause
1494
  private WhereCondition parseWhereClause(IoTDBSqlParser.WhereClauseContext ctx) {
1495
    Expression predicate = parseExpression(ctx.expression(), true);
1✔
1496
    return new WhereCondition(predicate);
1✔
1497
  }
1498

1499
  // ---- Group By Clause
1500
  private GroupByTimeComponent parseGroupByTimeClause(
1501
      IoTDBSqlParser.GroupByAttributeClauseContext ctx) {
1502
    GroupByTimeComponent groupByTimeComponent = new GroupByTimeComponent();
1✔
1503

1504
    // Parse time range
1505
    if (ctx.timeRange() != null) {
1✔
1506
      parseTimeRangeForGroupByTime(ctx.timeRange(), groupByTimeComponent);
1✔
1507
      groupByTimeComponent.setLeftCRightO(ctx.timeRange().LS_BRACKET() != null);
1✔
1508
    }
1509

1510
    // Parse time interval
1511
    groupByTimeComponent.setInterval(
1✔
1512
        parseTimeIntervalOrSlidingStep(ctx.interval.getText(), true, groupByTimeComponent));
1✔
1513
    if (groupByTimeComponent.getInterval() <= 0) {
1✔
1514
      throw new SemanticException(
×
1515
          "The second parameter time interval should be a positive integer.");
1516
    }
1517

1518
    // parse sliding step
1519
    if (ctx.step != null) {
1✔
1520
      groupByTimeComponent.setSlidingStep(
1✔
1521
          parseTimeIntervalOrSlidingStep(ctx.step.getText(), false, groupByTimeComponent));
1✔
1522
    } else {
1523
      groupByTimeComponent.setSlidingStep(groupByTimeComponent.getInterval());
1✔
1524
      groupByTimeComponent.setSlidingStepByMonth(groupByTimeComponent.isIntervalByMonth());
1✔
1525
    }
1526

1527
    return groupByTimeComponent;
1✔
1528
  }
1529

1530
  /**
1531
   * Parse time range (startTime and endTime) in group by time.
1532
   *
1533
   * @throws SemanticException if startTime is larger or equals to endTime in timeRange
1534
   */
1535
  private void parseTimeRangeForGroupByTime(
1536
      IoTDBSqlParser.TimeRangeContext timeRange, GroupByTimeComponent groupByClauseComponent) {
1537
    long currentTime = DateTimeUtils.currentTime();
1✔
1538
    long startTime = parseTimeValue(timeRange.timeValue(0), currentTime);
1✔
1539
    long endTime = parseTimeValue(timeRange.timeValue(1), currentTime);
1✔
1540
    groupByClauseComponent.setStartTime(startTime);
1✔
1541
    groupByClauseComponent.setEndTime(endTime);
1✔
1542
    if (startTime >= endTime) {
1✔
1543
      throw new SemanticException("Start time should be smaller than endTime in GroupBy");
×
1544
    }
1545
  }
1✔
1546

1547
  /**
1548
   * parse time interval or sliding step in group by query.
1549
   *
1550
   * @param duration represent duration string like: 12d8m9ns, 1y1d, etc.
1551
   * @return time in milliseconds, microseconds, or nanoseconds depending on the profile
1552
   */
1553
  private long parseTimeIntervalOrSlidingStep(
1554
      String duration, boolean isParsingTimeInterval, GroupByTimeComponent groupByTimeComponent) {
1555
    if (duration.toLowerCase().contains("mo")) {
1✔
1556
      if (isParsingTimeInterval) {
×
1557
        groupByTimeComponent.setIntervalByMonth(true);
×
1558
      } else {
1559
        groupByTimeComponent.setSlidingStepByMonth(true);
×
1560
      }
1561
    }
1562
    return DateTimeUtils.convertDurationStrToLong(duration);
1✔
1563
  }
1564

1565
  private GroupByComponent parseGroupByClause(
1566
      GroupByAttributeClauseContext ctx, WindowType windowType) {
1567

1568
    boolean ignoringNull = true;
1✔
1569
    if (ctx.attributePair() != null
1✔
1570
        && !ctx.attributePair().isEmpty()
×
1571
        && ctx.attributePair().key.getText().equalsIgnoreCase(IGNORENULL)) {
×
1572
      ignoringNull = Boolean.parseBoolean(ctx.attributePair().value.getText());
×
1573
    }
1574
    List<ExpressionContext> expressions = ctx.expression();
1✔
1575
    if (windowType == WindowType.VARIATION_WINDOW) {
1✔
1576
      ExpressionContext expressionContext = expressions.get(0);
1✔
1577
      GroupByVariationComponent groupByVariationComponent = new GroupByVariationComponent();
1✔
1578
      groupByVariationComponent.setControlColumnExpression(
1✔
1579
          parseExpression(expressionContext, true));
1✔
1580
      groupByVariationComponent.setDelta(
1✔
1581
          ctx.delta == null ? 0 : Double.parseDouble(ctx.delta.getText()));
1✔
1582
      groupByVariationComponent.setIgnoringNull(ignoringNull);
1✔
1583
      return groupByVariationComponent;
1✔
1584
    } else if (windowType == WindowType.CONDITION_WINDOW) {
×
1585
      ExpressionContext conditionExpressionContext = expressions.get(0);
×
1586
      GroupByConditionComponent groupByConditionComponent = new GroupByConditionComponent();
×
1587
      groupByConditionComponent.setControlColumnExpression(
×
1588
          parseExpression(conditionExpressionContext, true));
×
1589
      if (expressions.size() == 2) {
×
1590
        groupByConditionComponent.setKeepExpression(parseExpression(expressions.get(1), true));
×
1591
      }
1592
      groupByConditionComponent.setIgnoringNull(ignoringNull);
×
1593
      return groupByConditionComponent;
×
1594
    } else if (windowType == WindowType.SESSION_WINDOW) {
×
1595
      long interval = DateTimeUtils.convertDurationStrToLong(ctx.timeInterval.getText());
×
1596
      return new GroupBySessionComponent(interval);
×
1597
    } else if (windowType == WindowType.COUNT_WINDOW) {
×
1598
      ExpressionContext countExpressionContext = expressions.get(0);
×
1599
      long countNumber = Long.parseLong(ctx.countNumber.getText());
×
1600
      GroupByCountComponent groupByCountComponent = new GroupByCountComponent(countNumber);
×
1601
      groupByCountComponent.setControlColumnExpression(
×
1602
          parseExpression(countExpressionContext, true));
×
1603
      groupByCountComponent.setIgnoringNull(ignoringNull);
×
1604
      return groupByCountComponent;
×
1605
    } else {
1606
      throw new SemanticException("Unsupported window type");
×
1607
    }
1608
  }
1609

1610
  private GroupByLevelComponent parseGroupByLevelClause(
1611
      IoTDBSqlParser.GroupByAttributeClauseContext ctx) {
1612
    GroupByLevelComponent groupByLevelComponent = new GroupByLevelComponent();
1✔
1613
    int[] levels = new int[ctx.INTEGER_LITERAL().size()];
1✔
1614
    for (int i = 0; i < ctx.INTEGER_LITERAL().size(); i++) {
1✔
1615
      levels[i] = Integer.parseInt(ctx.INTEGER_LITERAL().get(i).getText());
1✔
1616
    }
1617
    groupByLevelComponent.setLevels(levels);
1✔
1618
    return groupByLevelComponent;
1✔
1619
  }
1620

1621
  private GroupByTagComponent parseGroupByTagClause(
1622
      IoTDBSqlParser.GroupByAttributeClauseContext ctx) {
1623
    Set<String> tagKeys = new LinkedHashSet<>();
1✔
1624
    for (IdentifierContext identifierContext : ctx.identifier()) {
1✔
1625
      String key = parseIdentifier(identifierContext.getText());
1✔
1626
      if (tagKeys.contains(key)) {
1✔
1627
        throw new SemanticException("duplicated key in GROUP BY TAGS: " + key);
1✔
1628
      }
1629
      tagKeys.add(key);
1✔
1630
    }
1✔
1631
    return new GroupByTagComponent(new ArrayList<>(tagKeys));
1✔
1632
  }
1633

1634
  // ---- Having Clause
1635
  private HavingCondition parseHavingClause(IoTDBSqlParser.HavingClauseContext ctx) {
1636
    Expression predicate = parseExpression(ctx.expression(), true);
1✔
1637
    return new HavingCondition(predicate);
1✔
1638
  }
1639

1640
  // ---- Order By Clause
1641
  // all SortKeys should be contained by limitSet
1642
  private OrderByComponent parseOrderByClause(
1643
      IoTDBSqlParser.OrderByClauseContext ctx, ImmutableSet<String> limitSet) {
1644
    OrderByComponent orderByComponent = new OrderByComponent();
1✔
1645
    Set<String> sortKeySet = new HashSet<>();
1✔
1646
    for (IoTDBSqlParser.OrderByAttributeClauseContext orderByAttributeClauseContext :
1647
        ctx.orderByAttributeClause()) {
1✔
1648
      // if the order by clause is unique, then the following sort keys will be ignored
1649
      if (orderByComponent.isUnique()) {
1✔
1650
        break;
×
1651
      }
1652
      SortItem sortItem = parseOrderByAttributeClause(orderByAttributeClauseContext, limitSet);
1✔
1653

1654
      String sortKey = sortItem.getSortKey();
1✔
1655
      if (sortKeySet.contains(sortKey)) {
1✔
1656
        continue;
×
1657
      } else {
1658
        sortKeySet.add(sortKey);
1✔
1659
      }
1660

1661
      if (sortItem.isExpression()) {
1✔
1662
        orderByComponent.addExpressionSortItem(sortItem);
1✔
1663
      } else {
1664
        orderByComponent.addSortItem(sortItem);
1✔
1665
      }
1666
    }
1✔
1667
    return orderByComponent;
1✔
1668
  }
1669

1670
  private SortItem parseOrderByAttributeClause(
1671
      IoTDBSqlParser.OrderByAttributeClauseContext ctx, ImmutableSet<String> limitSet) {
1672
    if (ctx.sortKey() != null) {
1✔
1673
      String sortKey = ctx.sortKey().getText().toUpperCase();
1✔
1674
      if (!limitSet.contains(sortKey)) {
1✔
1675
        throw new SemanticException(
×
1676
            String.format("ORDER BY: sort key[%s] is not contained in '%s'", sortKey, limitSet));
×
1677
      }
1678
      return new SortItem(sortKey, ctx.DESC() != null ? Ordering.DESC : Ordering.ASC);
1✔
1679
    } else {
1680
      Expression sortExpression = parseExpression(ctx.expression(), true);
1✔
1681
      return new SortItem(
1✔
1682
          sortExpression,
1683
          ctx.DESC() != null ? Ordering.DESC : Ordering.ASC,
1✔
1684
          ctx.FIRST() != null ? NullOrdering.FIRST : NullOrdering.LAST);
1✔
1685
    }
1686
  }
1687

1688
  // ---- Fill Clause
1689
  public FillComponent parseFillClause(IoTDBSqlParser.FillClauseContext ctx) {
1690
    FillComponent fillComponent = new FillComponent();
1✔
1691
    if (ctx.LINEAR() != null) {
1✔
1692
      fillComponent.setFillPolicy(FillPolicy.LINEAR);
1✔
1693
    } else if (ctx.PREVIOUS() != null) {
1✔
1694
      fillComponent.setFillPolicy(FillPolicy.PREVIOUS);
1✔
1695
    } else if (ctx.constant() != null) {
1✔
1696
      fillComponent.setFillPolicy(FillPolicy.VALUE);
1✔
1697
      Literal fillValue = parseLiteral(ctx.constant());
1✔
1698
      fillComponent.setFillValue(fillValue);
1✔
1699
    } else {
1✔
1700
      throw new SemanticException("Unknown FILL type.");
×
1701
    }
1702
    return fillComponent;
1✔
1703
  }
1704

1705
  private Literal parseLiteral(ConstantContext constantContext) {
1706
    String text = constantContext.getText();
1✔
1707
    if (constantContext.boolean_literal() != null) {
1✔
1708
      return new BooleanLiteral(text);
×
1709
    } else if (constantContext.STRING_LITERAL() != null) {
1✔
1710
      return new StringLiteral(parseStringLiteral(text));
×
1711
    } else if (constantContext.INTEGER_LITERAL() != null) {
1✔
1712
      return new LongLiteral(text);
1✔
1713
    } else if (constantContext.realLiteral() != null) {
×
1714
      return new DoubleLiteral(text);
×
1715
    } else if (constantContext.dateExpression() != null) {
×
1716
      return new LongLiteral(parseDateExpression(constantContext.dateExpression()));
×
1717
    } else {
1718
      throw new SemanticException("Unsupported constant value in FILL: " + text);
×
1719
    }
1720
  }
1721

1722
  // parse LIMIT & OFFSET
1723
  private long parseLimitClause(IoTDBSqlParser.LimitClauseContext ctx) {
1724
    long limit;
1725
    try {
1726
      limit = Long.parseLong(ctx.INTEGER_LITERAL().getText());
1✔
1727
    } catch (NumberFormatException e) {
×
1728
      throw new SemanticException("Out of range. LIMIT <N>: N should be Int64.");
×
1729
    }
1✔
1730
    if (limit <= 0) {
1✔
1731
      throw new SemanticException("LIMIT <N>: N should be greater than 0.");
×
1732
    }
1733
    return limit;
1✔
1734
  }
1735

1736
  private long parseOffsetClause(IoTDBSqlParser.OffsetClauseContext ctx) {
1737
    long offset;
1738
    try {
1739
      offset = Long.parseLong(ctx.INTEGER_LITERAL().getText());
1✔
1740
    } catch (NumberFormatException e) {
×
1741
      throw new SemanticException(
×
1742
          "Out of range. OFFSET <OFFSETValue>: OFFSETValue should be Int64.");
1743
    }
1✔
1744
    if (offset < 0) {
1✔
1745
      throw new SemanticException("OFFSET <OFFSETValue>: OFFSETValue should >= 0.");
×
1746
    }
1747
    return offset;
1✔
1748
  }
1749

1750
  // parse SLIMIT & SOFFSET
1751
  private int parseSLimitClause(IoTDBSqlParser.SlimitClauseContext ctx) {
1752
    int slimit;
1753
    try {
1754
      slimit = Integer.parseInt(ctx.INTEGER_LITERAL().getText());
1✔
1755
    } catch (NumberFormatException e) {
×
1756
      throw new SemanticException("Out of range. SLIMIT <SN>: SN should be Int32.");
×
1757
    }
1✔
1758
    if (slimit <= 0) {
1✔
1759
      throw new SemanticException("SLIMIT <SN>: SN should be greater than 0.");
×
1760
    }
1761
    return slimit;
1✔
1762
  }
1763

1764
  // parse SOFFSET
1765
  public int parseSOffsetClause(IoTDBSqlParser.SoffsetClauseContext ctx) {
1766
    int soffset;
1767
    try {
1768
      soffset = Integer.parseInt(ctx.INTEGER_LITERAL().getText());
1✔
1769
    } catch (NumberFormatException e) {
×
1770
      throw new SemanticException(
×
1771
          "Out of range. SOFFSET <SOFFSETValue>: SOFFSETValue should be Int32.");
1772
    }
1✔
1773
    if (soffset < 0) {
1✔
1774
      throw new SemanticException("SOFFSET <SOFFSETValue>: SOFFSETValue should >= 0.");
×
1775
    }
1776
    return soffset;
1✔
1777
  }
1778

1779
  // ---- Align By Clause
1780
  private ResultSetFormat parseAlignBy(IoTDBSqlParser.AlignByClauseContext ctx) {
1781
    if (ctx.DEVICE() != null) {
1✔
1782
      return ResultSetFormat.ALIGN_BY_DEVICE;
1✔
1783
    } else {
1784
      return ResultSetFormat.ALIGN_BY_TIME;
×
1785
    }
1786
  }
1787

1788
  // Insert Statement ========================================================================
1789

1790
  @Override
1791
  public Statement visitInsertStatement(IoTDBSqlParser.InsertStatementContext ctx) {
1792
    InsertStatement insertStatement = new InsertStatement();
1✔
1793
    insertStatement.setDevice(parsePrefixPath(ctx.prefixPath()));
1✔
1794
    boolean isTimeDefault = parseInsertColumnSpec(ctx.insertColumnsSpec(), insertStatement);
1✔
1795
    parseInsertValuesSpec(ctx.insertValuesSpec(), insertStatement, isTimeDefault);
1✔
1796
    insertStatement.setAligned(ctx.ALIGNED() != null);
1✔
1797
    return insertStatement;
1✔
1798
  }
1799

1800
  private boolean parseInsertColumnSpec(
1801
      IoTDBSqlParser.InsertColumnsSpecContext ctx, InsertStatement insertStatement) {
1802
    List<String> measurementList = new ArrayList<>();
1✔
1803
    for (IoTDBSqlParser.NodeNameWithoutWildcardContext measurementName :
1804
        ctx.nodeNameWithoutWildcard()) {
1✔
1805
      measurementList.add(parseNodeNameWithoutWildCard(measurementName));
1✔
1806
    }
1✔
1807
    insertStatement.setMeasurementList(measurementList.toArray(new String[0]));
1✔
1808
    return (ctx.TIME() == null && ctx.TIMESTAMP() == null);
1✔
1809
  }
1810

1811
  private void parseInsertValuesSpec(
1812
      IoTDBSqlParser.InsertValuesSpecContext ctx,
1813
      InsertStatement insertStatement,
1814
      boolean isTimeDefault) {
1815
    List<IoTDBSqlParser.InsertMultiValueContext> insertMultiValues = ctx.insertMultiValue();
1✔
1816
    List<String[]> valuesList = new ArrayList<>();
1✔
1817
    long[] timeArray = new long[insertMultiValues.size()];
1✔
1818
    for (int i = 0; i < insertMultiValues.size(); i++) {
1✔
1819
      // parse timestamp
1820
      long timestamp;
1821
      List<String> valueList = new ArrayList<>();
1✔
1822

1823
      if (insertMultiValues.get(i).timeValue() != null) {
1✔
1824
        if (isTimeDefault) {
1✔
1825
          if (insertMultiValues.size() != 1) {
×
1826
            throw new SemanticException("need timestamps when insert multi rows");
×
1827
          }
1828
          valueList.add(insertMultiValues.get(i).timeValue().getText());
×
1829
          timestamp = DateTimeUtils.currentTime();
×
1830
        } else {
1831
          timestamp =
1✔
1832
              parseTimeValue(insertMultiValues.get(i).timeValue(), DateTimeUtils.currentTime());
1✔
1833
        }
1834
      } else {
1835
        if (!isTimeDefault) {
×
1836
          throw new SemanticException(
×
1837
              "the measurementList's size is not consistent with the valueList's size");
1838
        }
1839
        if (insertMultiValues.size() != 1) {
×
1840
          throw new SemanticException("need timestamps when insert multi rows");
×
1841
        }
1842
        timestamp = parseDateFormat(SqlConstant.NOW_FUNC);
×
1843
      }
1844
      timeArray[i] = timestamp;
1✔
1845

1846
      // parse values
1847
      List<IoTDBSqlParser.MeasurementValueContext> values =
1✔
1848
          insertMultiValues.get(i).measurementValue();
1✔
1849
      for (IoTDBSqlParser.MeasurementValueContext value : values) {
1✔
1850
        for (IoTDBSqlParser.ConstantContext constant : value.constant()) {
1✔
1851
          if (constant.STRING_LITERAL() != null) {
1✔
1852
            valueList.add(parseStringLiteralInInsertValue(constant.getText()));
×
1853
          } else {
1854
            valueList.add(constant.getText());
1✔
1855
          }
1856
        }
1✔
1857
      }
1✔
1858
      valuesList.add(valueList.toArray(new String[0]));
1✔
1859
    }
1860
    insertStatement.setTimes(timeArray);
1✔
1861
    insertStatement.setValuesList(valuesList);
1✔
1862
  }
1✔
1863

1864
  // Load File
1865

1866
  @Override
1867
  public Statement visitLoadFile(IoTDBSqlParser.LoadFileContext ctx) {
1868
    try {
1869
      LoadTsFileStatement loadTsFileStatement =
×
1870
          new LoadTsFileStatement(parseStringLiteral(ctx.fileName.getText()));
×
1871
      if (ctx.loadFileAttributeClauses() != null) {
×
1872
        for (IoTDBSqlParser.LoadFileAttributeClauseContext attributeContext :
1873
            ctx.loadFileAttributeClauses().loadFileAttributeClause()) {
×
1874
          parseLoadFileAttributeClause(loadTsFileStatement, attributeContext);
×
1875
        }
×
1876
      }
1877
      return loadTsFileStatement;
×
1878
    } catch (FileNotFoundException e) {
×
1879
      throw new SemanticException(e.getMessage());
×
1880
    }
1881
  }
1882

1883
  /**
1884
   * Used for parsing load tsfile, context will be one of "SCHEMA, LEVEL, METADATA", and maybe
1885
   * followed by a recursion property statement.
1886
   *
1887
   * @param loadTsFileStatement the result statement, setting by clause context
1888
   * @param ctx context of property statement
1889
   * @throws SemanticException if AUTOREGISTER | SGLEVEL | VERIFY are not specified
1890
   */
1891
  private void parseLoadFileAttributeClause(
1892
      LoadTsFileStatement loadTsFileStatement, IoTDBSqlParser.LoadFileAttributeClauseContext ctx) {
1893
    if (ctx.ONSUCCESS() != null) {
×
1894
      loadTsFileStatement.setDeleteAfterLoad(ctx.DELETE() != null);
×
1895
    } else if (ctx.SGLEVEL() != null) {
×
1896
      loadTsFileStatement.setDatabaseLevel(Integer.parseInt(ctx.INTEGER_LITERAL().getText()));
×
1897
    } else if (ctx.VERIFY() != null) {
×
1898
      loadTsFileStatement.setVerifySchema(Boolean.parseBoolean(ctx.boolean_literal().getText()));
×
1899
    } else {
1900
      throw new SemanticException(
×
1901
          String.format(
×
1902
              "Load tsfile format %s error, please input AUTOREGISTER | SGLEVEL | VERIFY.",
1903
              ctx.getText()));
×
1904
    }
1905
  }
×
1906

1907
  /** Common Parsers. */
1908

1909
  // IoTDB Objects ========================================================================
1910
  private PartialPath parseFullPath(IoTDBSqlParser.FullPathContext ctx) {
1911
    List<IoTDBSqlParser.NodeNameWithoutWildcardContext> nodeNamesWithoutStar =
1✔
1912
        ctx.nodeNameWithoutWildcard();
1✔
1913
    String[] path = new String[nodeNamesWithoutStar.size() + 1];
1✔
1914
    int i = 0;
1✔
1915
    if (ctx.ROOT() != null) {
1✔
1916
      path[0] = ctx.ROOT().getText();
1✔
1917
    }
1918
    for (IoTDBSqlParser.NodeNameWithoutWildcardContext nodeNameWithoutStar : nodeNamesWithoutStar) {
1✔
1919
      i++;
1✔
1920
      path[i] = parseNodeNameWithoutWildCard(nodeNameWithoutStar);
1✔
1921
    }
1✔
1922
    return new PartialPath(path);
1✔
1923
  }
1924

1925
  private PartialPath parseFullPathInExpression(
1926
      IoTDBSqlParser.FullPathInExpressionContext ctx, boolean canUseFullPath) {
1927
    List<IoTDBSqlParser.NodeNameContext> nodeNames = ctx.nodeName();
1✔
1928
    int size = nodeNames.size();
1✔
1929
    if (ctx.ROOT() != null) {
1✔
1930
      if (!canUseFullPath) {
1✔
1931
        // now full path cannot occur in SELECT only
1932
        throw new SemanticException("Path can not start with root in select clause.");
×
1933
      }
1934
      size++;
1✔
1935
    }
1936
    String[] path = new String[size];
1✔
1937
    if (ctx.ROOT() != null) {
1✔
1938
      path[0] = ctx.ROOT().getText();
1✔
1939
      for (int i = 0; i < nodeNames.size(); i++) {
1✔
1940
        path[i + 1] = parseNodeName(nodeNames.get(i));
1✔
1941
      }
1942
    } else {
1943
      for (int i = 0; i < nodeNames.size(); i++) {
1✔
1944
        path[i] = parseNodeName(nodeNames.get(i));
1✔
1945
      }
1946
    }
1947
    if (!lastLevelUseWildcard
1✔
1948
        && !nodeNames.isEmpty()
1✔
1949
        && !nodeNames.get(nodeNames.size() - 1).wildcard().isEmpty()) {
1✔
1950
      lastLevelUseWildcard = true;
1✔
1951
    }
1952
    return new PartialPath(path);
1✔
1953
  }
1954

1955
  private PartialPath parseFullPathInIntoPath(IoTDBSqlParser.FullPathInIntoPathContext ctx) {
1956
    List<IoTDBSqlParser.NodeNameInIntoPathContext> nodeNames = ctx.nodeNameInIntoPath();
1✔
1957
    String[] path = new String[nodeNames.size() + 1];
1✔
1958
    int i = 0;
1✔
1959
    if (ctx.ROOT() != null) {
1✔
1960
      path[0] = ctx.ROOT().getText();
1✔
1961
    }
1962
    for (IoTDBSqlParser.NodeNameInIntoPathContext nodeName : nodeNames) {
1✔
1963
      i++;
1✔
1964
      path[i] = parseNodeNameInIntoPath(nodeName);
1✔
1965
    }
1✔
1966
    return new PartialPath(path);
1✔
1967
  }
1968

1969
  private PartialPath parsePrefixPath(IoTDBSqlParser.PrefixPathContext ctx) {
1970
    List<IoTDBSqlParser.NodeNameContext> nodeNames = ctx.nodeName();
1✔
1971
    String[] path = new String[nodeNames.size() + 1];
1✔
1972
    path[0] = ctx.ROOT().getText();
1✔
1973
    for (int i = 0; i < nodeNames.size(); i++) {
1✔
1974
      path[i + 1] = parseNodeName(nodeNames.get(i));
1✔
1975
    }
1976
    return new PartialPath(path);
1✔
1977
  }
1978

1979
  private String parseNodeName(IoTDBSqlParser.NodeNameContext ctx) {
1980
    if (!useWildcard && !ctx.wildcard().isEmpty()) {
1✔
1981
      useWildcard = true;
1✔
1982
    }
1983
    return parseNodeString(ctx.getText());
1✔
1984
  }
1985

1986
  private String parseNodeNameWithoutWildCard(IoTDBSqlParser.NodeNameWithoutWildcardContext ctx) {
1987
    return parseNodeString(ctx.getText());
1✔
1988
  }
1989

1990
  private String parseNodeNameInIntoPath(IoTDBSqlParser.NodeNameInIntoPathContext ctx) {
1991
    return parseNodeStringInIntoPath(ctx.getText());
1✔
1992
  }
1993

1994
  private String parseNodeString(String nodeName) {
1995
    if (nodeName.equals(IoTDBConstant.ONE_LEVEL_PATH_WILDCARD)
1✔
1996
        || nodeName.equals(IoTDBConstant.MULTI_LEVEL_PATH_WILDCARD)) {
1✔
1997
      return nodeName;
1✔
1998
    }
1999
    if (nodeName.startsWith(TsFileConstant.BACK_QUOTE_STRING)
1✔
2000
        && nodeName.endsWith(TsFileConstant.BACK_QUOTE_STRING)) {
×
2001
      return PathUtils.removeBackQuotesIfNecessary(nodeName);
×
2002
    }
2003
    checkNodeName(nodeName);
1✔
2004
    return nodeName;
1✔
2005
  }
2006

2007
  private String parseNodeStringInIntoPath(String nodeName) {
2008
    if (nodeName.equals(IoTDBConstant.DOUBLE_COLONS)) {
1✔
2009
      return nodeName;
1✔
2010
    }
2011
    if (nodeName.startsWith(TsFileConstant.BACK_QUOTE_STRING)
1✔
2012
        && nodeName.endsWith(TsFileConstant.BACK_QUOTE_STRING)) {
×
2013
      return PathUtils.removeBackQuotesIfNecessary(nodeName);
×
2014
    }
2015
    checkNodeNameInIntoPath(nodeName);
1✔
2016
    return nodeName;
1✔
2017
  }
2018

2019
  private void checkNodeName(String src) {
2020
    // node name could start with * and end with *
2021
    if (!TsFileConstant.NODE_NAME_PATTERN.matcher(src).matches()) {
1✔
2022
      throw new SemanticException(
×
2023
          String.format(
×
2024
              "%s is illegal, unquoted node name can only consist of digits, characters and underscore, or start or end with wildcard",
2025
              src));
2026
    }
2027
  }
1✔
2028

2029
  private void checkNodeNameInIntoPath(String src) {
2030
    // ${} are allowed
2031
    if (!TsFileConstant.NODE_NAME_IN_INTO_PATH_PATTERN.matcher(src).matches()) {
1✔
2032
      throw new SemanticException(
×
2033
          String.format(
×
2034
              "%s is illegal, unquoted node name in select into clause can only consist of digits, characters, $, { and }",
2035
              src));
2036
    }
2037
  }
1✔
2038

2039
  private static void checkIdentifier(String src) {
2040
    if (!TsFileConstant.IDENTIFIER_PATTERN.matcher(src).matches() || PathUtils.isRealNumber(src)) {
1✔
2041
      throw new SemanticException(
×
2042
          String.format(
×
2043
              "%s is illegal, identifier not enclosed with backticks can only consist of digits, characters and underscore.",
2044
              src));
2045
    }
2046
  }
1✔
2047

2048
  // Literals ========================================================================
2049

2050
  public long parseDateFormat(String timestampStr) {
2051
    if (timestampStr == null || "".equals(timestampStr.trim())) {
1✔
2052
      throw new SemanticException("input timestamp cannot be empty");
1✔
2053
    }
2054
    if (timestampStr.equalsIgnoreCase(SqlConstant.NOW_FUNC)) {
1✔
2055
      return DateTimeUtils.currentTime();
1✔
2056
    }
2057
    try {
2058
      return DateTimeUtils.convertDatetimeStrToLong(timestampStr, zoneId);
×
2059
    } catch (Exception e) {
×
2060
      throw new SemanticException(
×
2061
          String.format(
×
2062
              "Input time format %s error. "
2063
                  + "Input like yyyy-MM-dd HH:mm:ss, yyyy-MM-ddTHH:mm:ss or "
2064
                  + "refer to user document for more info.",
2065
              timestampStr));
2066
    }
2067
  }
2068

2069
  public long parseDateFormat(String timestampStr, long currentTime) {
2070
    if (timestampStr == null || "".equals(timestampStr.trim())) {
1✔
2071
      throw new SemanticException("input timestamp cannot be empty");
×
2072
    }
2073
    if (timestampStr.equalsIgnoreCase(SqlConstant.NOW_FUNC)) {
1✔
2074
      return currentTime;
×
2075
    }
2076
    try {
2077
      return DateTimeUtils.convertDatetimeStrToLong(timestampStr, zoneId);
1✔
2078
    } catch (Exception e) {
×
2079
      throw new SemanticException(
×
2080
          String.format(
×
2081
              "Input time format %s error. "
2082
                  + "Input like yyyy-MM-dd HH:mm:ss, yyyy-MM-ddTHH:mm:ss or "
2083
                  + "refer to user document for more info.",
2084
              timestampStr));
2085
    }
2086
  }
2087

2088
  private String parseStringLiteral(String src) {
2089
    if (2 <= src.length()) {
1✔
2090
      // do not unescape string
2091
      String unWrappedString = src.substring(1, src.length() - 1);
1✔
2092
      if (src.charAt(0) == '\"' && src.charAt(src.length() - 1) == '\"') {
1✔
2093
        // replace "" with "
2094
        String replaced = unWrappedString.replace("\"\"", "\"");
×
2095
        return replaced.length() == 0 ? "" : replaced;
×
2096
      }
2097
      if ((src.charAt(0) == '\'' && src.charAt(src.length() - 1) == '\'')) {
1✔
2098
        // replace '' with '
2099
        String replaced = unWrappedString.replace("''", "'");
1✔
2100
        return replaced.length() == 0 ? "" : replaced;
1✔
2101
      }
2102
    }
2103
    return src;
×
2104
  }
2105

2106
  private String parseStringLiteralInInsertValue(String src) {
2107
    if (2 <= src.length()
×
2108
        && ((src.charAt(0) == '\"' && src.charAt(src.length() - 1) == '\"')
×
2109
            || (src.charAt(0) == '\'' && src.charAt(src.length() - 1) == '\''))) {
×
2110
      return "'" + parseStringLiteral(src) + "'";
×
2111
    }
2112
    return src;
×
2113
  }
2114

2115
  public static String parseIdentifier(String src) {
2116
    if (src.startsWith(TsFileConstant.BACK_QUOTE_STRING)
1✔
2117
        && src.endsWith(TsFileConstant.BACK_QUOTE_STRING)) {
×
2118
      return src.substring(1, src.length() - 1)
×
2119
          .replace(TsFileConstant.DOUBLE_BACK_QUOTE_STRING, TsFileConstant.BACK_QUOTE_STRING);
×
2120
    }
2121
    checkIdentifier(src);
1✔
2122
    return src;
1✔
2123
  }
2124

2125
  // Alias
2126

2127
  /** Function for parsing Alias of ResultColumn. */
2128
  private String parseAlias(IoTDBSqlParser.AliasContext ctx) {
2129
    String alias;
2130
    if (ctx.constant() != null) {
1✔
2131
      alias = parseConstant(ctx.constant());
×
2132
    } else {
2133
      alias = parseIdentifier(ctx.identifier().getText());
1✔
2134
    }
2135
    return alias;
1✔
2136
  }
2137

2138
  /**
2139
   * Function for parsing AliasNode.
2140
   *
2141
   * @throws SemanticException if the alias pattern is not supported
2142
   */
2143
  private String parseAliasNode(IoTDBSqlParser.AliasContext ctx) {
2144
    String alias;
2145
    if (ctx.constant() != null) {
×
2146
      alias = parseConstant(ctx.constant());
×
2147
      if (PathUtils.isRealNumber(alias)
×
2148
          || !TsFileConstant.IDENTIFIER_PATTERN.matcher(alias).matches()) {
×
2149
        throw new SemanticException("Not support for this alias, Please enclose in back quotes.");
×
2150
      }
2151
    } else {
2152
      alias = parseNodeString(ctx.identifier().getText());
×
2153
    }
2154
    return alias;
×
2155
  }
2156

2157
  /** Data Control Language (DCL). */
2158

2159
  // Create User
2160
  @Override
2161
  public Statement visitCreateUser(IoTDBSqlParser.CreateUserContext ctx) {
2162
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.CREATE_USER);
×
2163
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2164
    authorStatement.setPassWord(parseStringLiteral(ctx.password.getText()));
×
2165
    return authorStatement;
×
2166
  }
2167

2168
  // Create Role
2169

2170
  @Override
2171
  public Statement visitCreateRole(IoTDBSqlParser.CreateRoleContext ctx) {
2172
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.CREATE_ROLE);
×
2173
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2174
    return authorStatement;
×
2175
  }
2176

2177
  // Alter Password
2178

2179
  @Override
2180
  public Statement visitAlterUser(IoTDBSqlParser.AlterUserContext ctx) {
2181
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.UPDATE_USER);
×
2182
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2183
    authorStatement.setNewPassword(parseStringLiteral(ctx.password.getText()));
×
2184
    return authorStatement;
×
2185
  }
2186

2187
  // Grant User Privileges
2188

2189
  @Override
2190
  public Statement visitGrantUser(IoTDBSqlParser.GrantUserContext ctx) {
2191
    String[] privileges = parsePrivilege(ctx.privileges());
×
2192
    List<PartialPath> nodeNameList =
×
2193
        ctx.prefixPath().stream()
×
2194
            .map(this::parsePrefixPath)
×
2195
            .distinct()
×
2196
            .collect(Collectors.toList());
×
2197
    checkGrantRevokePrivileges(privileges, nodeNameList);
×
2198

2199
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.GRANT_USER);
×
2200
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2201
    authorStatement.setPrivilegeList(privileges);
×
2202
    authorStatement.setNodeNameList(nodeNameList);
×
2203
    return authorStatement;
×
2204
  }
2205

2206
  // Grant Role Privileges
2207

2208
  @Override
2209
  public Statement visitGrantRole(IoTDBSqlParser.GrantRoleContext ctx) {
2210
    String[] privileges = parsePrivilege(ctx.privileges());
×
2211
    List<PartialPath> nodeNameList =
×
2212
        ctx.prefixPath().stream()
×
2213
            .map(this::parsePrefixPath)
×
2214
            .distinct()
×
2215
            .collect(Collectors.toList());
×
2216
    checkGrantRevokePrivileges(privileges, nodeNameList);
×
2217

2218
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.GRANT_ROLE);
×
2219
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2220
    authorStatement.setPrivilegeList(privileges);
×
2221
    authorStatement.setNodeNameList(nodeNameList);
×
2222
    return authorStatement;
×
2223
  }
2224

2225
  // Grant User Role
2226

2227
  @Override
2228
  public Statement visitGrantRoleToUser(IoTDBSqlParser.GrantRoleToUserContext ctx) {
2229
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.GRANT_USER_ROLE);
×
2230
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2231
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2232
    return authorStatement;
×
2233
  }
2234

2235
  // Revoke User Privileges
2236

2237
  @Override
2238
  public Statement visitRevokeUser(IoTDBSqlParser.RevokeUserContext ctx) {
2239
    String[] privileges = parsePrivilege(ctx.privileges());
×
2240
    List<PartialPath> nodeNameList =
×
2241
        ctx.prefixPath().stream()
×
2242
            .map(this::parsePrefixPath)
×
2243
            .distinct()
×
2244
            .collect(Collectors.toList());
×
2245
    checkGrantRevokePrivileges(privileges, nodeNameList);
×
2246

2247
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.REVOKE_USER);
×
2248
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2249
    authorStatement.setPrivilegeList(privileges);
×
2250
    authorStatement.setNodeNameList(nodeNameList);
×
2251
    return authorStatement;
×
2252
  }
2253

2254
  // Revoke Role Privileges
2255

2256
  @Override
2257
  public Statement visitRevokeRole(IoTDBSqlParser.RevokeRoleContext ctx) {
2258
    String[] privileges = parsePrivilege(ctx.privileges());
×
2259
    List<PartialPath> nodeNameList =
×
2260
        ctx.prefixPath().stream()
×
2261
            .map(this::parsePrefixPath)
×
2262
            .distinct()
×
2263
            .collect(Collectors.toList());
×
2264
    checkGrantRevokePrivileges(privileges, nodeNameList);
×
2265

2266
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.REVOKE_ROLE);
×
2267
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2268
    authorStatement.setPrivilegeList(privileges);
×
2269
    authorStatement.setNodeNameList(nodeNameList);
×
2270
    return authorStatement;
×
2271
  }
2272

2273
  private void checkGrantRevokePrivileges(String[] privileges, List<PartialPath> nodeNameList) {
2274
    if (nodeNameList.isEmpty()) {
×
2275
      nodeNameList.add(new PartialPath(ALL_RESULT_NODES));
×
2276
      return;
×
2277
    }
2278
    boolean pathRelevant = true;
×
2279
    String errorPrivilegeName = "";
×
2280
    for (String privilege : privileges) {
×
2281
      if ("SET_STORAGE_GROUP".equalsIgnoreCase(privilege)) {
×
2282
        privilege = PrivilegeType.CREATE_DATABASE.name();
×
2283
      }
2284
      if ("DELETE_STORAGE_GROUP".equalsIgnoreCase(privilege)) {
×
2285
        privilege = PrivilegeType.DELETE_DATABASE.name();
×
2286
      }
2287
      if (!PrivilegeType.valueOf(privilege.toUpperCase()).isPathRelevant()) {
×
2288
        pathRelevant = false;
×
2289
        errorPrivilegeName = privilege.toUpperCase();
×
2290
        break;
×
2291
      }
2292
    }
2293
    if (!(pathRelevant
×
2294
        || (nodeNameList.size() == 1
×
2295
            && nodeNameList.contains(new PartialPath(ALL_RESULT_NODES))))) {
×
2296
      throw new SemanticException(
×
2297
          String.format(
×
2298
              "path independent privilege: [%s] can only be set on path: root.**",
2299
              errorPrivilegeName));
2300
    }
2301
  }
×
2302

2303
  // Revoke Role From User
2304

2305
  @Override
2306
  public Statement visitRevokeRoleFromUser(IoTDBSqlParser.RevokeRoleFromUserContext ctx) {
2307
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.REVOKE_USER_ROLE);
×
2308
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2309
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2310
    return authorStatement;
×
2311
  }
2312

2313
  // Drop User
2314

2315
  @Override
2316
  public Statement visitDropUser(IoTDBSqlParser.DropUserContext ctx) {
2317
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.DROP_USER);
×
2318
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2319
    return authorStatement;
×
2320
  }
2321

2322
  // Drop Role
2323

2324
  @Override
2325
  public Statement visitDropRole(IoTDBSqlParser.DropRoleContext ctx) {
2326
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.DROP_ROLE);
×
2327
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2328
    return authorStatement;
×
2329
  }
2330

2331
  // List Users
2332

2333
  @Override
2334
  public Statement visitListUser(IoTDBSqlParser.ListUserContext ctx) {
2335
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_USER);
×
2336
    if (ctx.roleName != null) {
×
2337
      authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2338
    }
2339
    return authorStatement;
×
2340
  }
2341

2342
  // List Roles
2343

2344
  @Override
2345
  public Statement visitListRole(IoTDBSqlParser.ListRoleContext ctx) {
2346
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_ROLE);
×
2347
    if (ctx.userName != null) {
×
2348
      authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2349
    }
2350
    return authorStatement;
×
2351
  }
2352

2353
  // List Privileges
2354

2355
  @Override
2356
  public Statement visitListPrivilegesUser(IoTDBSqlParser.ListPrivilegesUserContext ctx) {
2357
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_USER_PRIVILEGE);
×
2358
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2359
    List<PartialPath> nodeNameList =
×
2360
        ctx.prefixPath().stream().map(this::parsePrefixPath).collect(Collectors.toList());
×
2361
    authorStatement.setNodeNameList(nodeNameList);
×
2362
    return authorStatement;
×
2363
  }
2364

2365
  // List Privileges of Roles On Specific Path
2366

2367
  @Override
2368
  public Statement visitListPrivilegesRole(IoTDBSqlParser.ListPrivilegesRoleContext ctx) {
2369
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_ROLE_PRIVILEGE);
×
2370
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2371
    List<PartialPath> nodeNameList =
×
2372
        ctx.prefixPath().stream().map(this::parsePrefixPath).collect(Collectors.toList());
×
2373
    authorStatement.setNodeNameList(nodeNameList);
×
2374
    return authorStatement;
×
2375
  }
2376

2377
  private String[] parsePrivilege(IoTDBSqlParser.PrivilegesContext ctx) {
2378
    List<IoTDBSqlParser.PrivilegeValueContext> privilegeList = ctx.privilegeValue();
×
2379
    List<String> privileges = new ArrayList<>();
×
2380
    for (IoTDBSqlParser.PrivilegeValueContext privilegeValue : privilegeList) {
×
2381
      privileges.add(privilegeValue.getText());
×
2382
    }
×
2383
    return privileges.toArray(new String[0]);
×
2384
  }
2385

2386
  // Create database
2387
  @Override
2388
  public Statement visitCreateDatabase(IoTDBSqlParser.CreateDatabaseContext ctx) {
2389
    DatabaseSchemaStatement databaseSchemaStatement =
×
2390
        new DatabaseSchemaStatement(DatabaseSchemaStatement.DatabaseSchemaStatementType.CREATE);
2391
    PartialPath path = parsePrefixPath(ctx.prefixPath());
×
2392
    databaseSchemaStatement.setDatabasePath(path);
×
2393
    if (ctx.databaseAttributesClause() != null) {
×
2394
      parseDatabaseAttributesClause(databaseSchemaStatement, ctx.databaseAttributesClause());
×
2395
    }
2396
    return databaseSchemaStatement;
×
2397
  }
2398

2399
  @Override
2400
  public Statement visitAlterDatabase(IoTDBSqlParser.AlterDatabaseContext ctx) {
2401
    DatabaseSchemaStatement databaseSchemaStatement =
×
2402
        new DatabaseSchemaStatement(DatabaseSchemaStatement.DatabaseSchemaStatementType.ALTER);
2403
    PartialPath path = parsePrefixPath(ctx.prefixPath());
×
2404
    databaseSchemaStatement.setDatabasePath(path);
×
2405
    parseDatabaseAttributesClause(databaseSchemaStatement, ctx.databaseAttributesClause());
×
2406
    return databaseSchemaStatement;
×
2407
  }
2408

2409
  private void parseDatabaseAttributesClause(
2410
      DatabaseSchemaStatement databaseSchemaStatement,
2411
      IoTDBSqlParser.DatabaseAttributesClauseContext ctx) {
2412
    for (IoTDBSqlParser.DatabaseAttributeClauseContext attribute : ctx.databaseAttributeClause()) {
×
2413
      IoTDBSqlParser.DatabaseAttributeKeyContext attributeKey = attribute.databaseAttributeKey();
×
2414
      if (attributeKey.TTL() != null) {
×
2415
        long ttl = Long.parseLong(attribute.INTEGER_LITERAL().getText());
×
2416
        databaseSchemaStatement.setTtl(ttl);
×
2417
      } else if (attributeKey.SCHEMA_REPLICATION_FACTOR() != null) {
×
2418
        int schemaReplicationFactor = Integer.parseInt(attribute.INTEGER_LITERAL().getText());
×
2419
        databaseSchemaStatement.setSchemaReplicationFactor(schemaReplicationFactor);
×
2420
      } else if (attributeKey.DATA_REPLICATION_FACTOR() != null) {
×
2421
        int dataReplicationFactor = Integer.parseInt(attribute.INTEGER_LITERAL().getText());
×
2422
        databaseSchemaStatement.setDataReplicationFactor(dataReplicationFactor);
×
2423
      } else if (attributeKey.TIME_PARTITION_INTERVAL() != null) {
×
2424
        long timePartitionInterval = Long.parseLong(attribute.INTEGER_LITERAL().getText());
×
2425
        databaseSchemaStatement.setTimePartitionInterval(timePartitionInterval);
×
2426
      } else if (attributeKey.SCHEMA_REGION_GROUP_NUM() != null) {
×
2427
        int schemaRegionGroupNum = Integer.parseInt(attribute.INTEGER_LITERAL().getText());
×
2428
        databaseSchemaStatement.setSchemaRegionGroupNum(schemaRegionGroupNum);
×
2429
      } else if (attributeKey.DATA_REGION_GROUP_NUM() != null) {
×
2430
        int dataRegionGroupNum = Integer.parseInt(attribute.INTEGER_LITERAL().getText());
×
2431
        databaseSchemaStatement.setDataRegionGroupNum(dataRegionGroupNum);
×
2432
      }
2433
    }
×
2434
  }
×
2435

2436
  @Override
2437
  public Statement visitSetTTL(IoTDBSqlParser.SetTTLContext ctx) {
2438
    SetTTLStatement setTTLStatement = new SetTTLStatement();
1✔
2439
    PartialPath path = parsePrefixPath(ctx.prefixPath());
1✔
2440
    long ttl = Long.parseLong(ctx.INTEGER_LITERAL().getText());
1✔
2441
    setTTLStatement.setDatabasePath(path);
1✔
2442
    setTTLStatement.setTTL(ttl);
1✔
2443
    return setTTLStatement;
1✔
2444
  }
2445

2446
  @Override
2447
  public Statement visitUnsetTTL(IoTDBSqlParser.UnsetTTLContext ctx) {
2448
    UnSetTTLStatement unSetTTLStatement = new UnSetTTLStatement();
1✔
2449
    PartialPath partialPath = parsePrefixPath(ctx.prefixPath());
1✔
2450
    unSetTTLStatement.setDatabasePath(partialPath);
1✔
2451
    return unSetTTLStatement;
1✔
2452
  }
2453

2454
  @Override
2455
  public Statement visitShowTTL(IoTDBSqlParser.ShowTTLContext ctx) {
2456
    ShowTTLStatement showTTLStatement = new ShowTTLStatement();
1✔
2457
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
1✔
2458
      PartialPath partialPath = parsePrefixPath(prefixPathContext);
1✔
2459
      showTTLStatement.addPathPatterns(partialPath);
1✔
2460
    }
1✔
2461
    return showTTLStatement;
1✔
2462
  }
2463

2464
  @Override
2465
  public Statement visitShowAllTTL(IoTDBSqlParser.ShowAllTTLContext ctx) {
2466
    ShowTTLStatement showTTLStatement = new ShowTTLStatement();
1✔
2467
    showTTLStatement.setAll(true);
1✔
2468
    return showTTLStatement;
1✔
2469
  }
2470

2471
  @Override
2472
  public Statement visitShowVariables(IoTDBSqlParser.ShowVariablesContext ctx) {
2473
    return new ShowVariablesStatement();
×
2474
  }
2475

2476
  @Override
2477
  public Statement visitShowCluster(IoTDBSqlParser.ShowClusterContext ctx) {
2478
    ShowClusterStatement showClusterStatement = new ShowClusterStatement();
×
2479
    if (ctx.DETAILS() != null) {
×
2480
      showClusterStatement.setDetails(true);
×
2481
    }
2482
    return showClusterStatement;
×
2483
  }
2484

2485
  @Override
2486
  public Statement visitDropDatabase(IoTDBSqlParser.DropDatabaseContext ctx) {
2487
    DeleteDatabaseStatement dropDatabaseStatement = new DeleteDatabaseStatement();
×
2488
    List<IoTDBSqlParser.PrefixPathContext> prefixPathContexts = ctx.prefixPath();
×
2489
    List<String> paths = new ArrayList<>();
×
2490
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : prefixPathContexts) {
×
2491
      paths.add(parsePrefixPath(prefixPathContext).getFullPath());
×
2492
    }
×
2493
    dropDatabaseStatement.setPrefixPath(paths);
×
2494
    return dropDatabaseStatement;
×
2495
  }
2496

2497
  // Explain ========================================================================
2498
  @Override
2499
  public Statement visitExplain(IoTDBSqlParser.ExplainContext ctx) {
2500
    QueryStatement queryStatement = (QueryStatement) visitSelectStatement(ctx.selectStatement());
×
2501
    return new ExplainStatement(queryStatement);
×
2502
  }
2503

2504
  @Override
2505
  public Statement visitDeleteStatement(IoTDBSqlParser.DeleteStatementContext ctx) {
2506
    DeleteDataStatement statement = new DeleteDataStatement();
×
2507
    List<IoTDBSqlParser.PrefixPathContext> prefixPaths = ctx.prefixPath();
×
2508
    List<PartialPath> pathList = new ArrayList<>();
×
2509
    for (IoTDBSqlParser.PrefixPathContext prefixPath : prefixPaths) {
×
2510
      pathList.add(parsePrefixPath(prefixPath));
×
2511
    }
×
2512
    statement.setPathList(pathList);
×
2513
    if (ctx.whereClause() != null) {
×
2514
      WhereCondition whereCondition = parseWhereClause(ctx.whereClause());
×
2515
      TimeRange timeRange = parseDeleteTimeRange(whereCondition.getPredicate());
×
2516
      statement.setTimeRange(timeRange);
×
2517
    } else {
×
2518
      statement.setTimeRange(new TimeRange(Long.MIN_VALUE, Long.MAX_VALUE));
×
2519
    }
2520
    return statement;
×
2521
  }
2522

2523
  private TimeRange parseDeleteTimeRange(Expression predicate) {
2524
    if (predicate instanceof LogicAndExpression) {
×
2525
      TimeRange leftTimeRange =
×
2526
          parseDeleteTimeRange(((LogicAndExpression) predicate).getLeftExpression());
×
2527
      TimeRange rightTimeRange =
×
2528
          parseDeleteTimeRange(((LogicAndExpression) predicate).getRightExpression());
×
2529
      return new TimeRange(
×
2530
          Math.max(leftTimeRange.getMin(), rightTimeRange.getMin()),
×
2531
          Math.min(leftTimeRange.getMax(), rightTimeRange.getMax()));
×
2532
    } else if (predicate instanceof CompareBinaryExpression) {
×
2533
      if (((CompareBinaryExpression) predicate).getLeftExpression() instanceof TimestampOperand) {
×
2534
        return parseTimeRangeForDeleteTimeRange(
×
2535
            predicate.getExpressionType(),
×
2536
            ((CompareBinaryExpression) predicate).getLeftExpression(),
×
2537
            ((CompareBinaryExpression) predicate).getRightExpression());
×
2538
      } else {
2539
        return parseTimeRangeForDeleteTimeRange(
×
2540
            predicate.getExpressionType(),
×
2541
            ((CompareBinaryExpression) predicate).getRightExpression(),
×
2542
            ((CompareBinaryExpression) predicate).getLeftExpression());
×
2543
      }
2544
    } else {
2545
      throw new SemanticException(DELETE_RANGE_ERROR_MSG);
×
2546
    }
2547
  }
2548

2549
  private TimeRange parseTimeRangeForDeleteTimeRange(
2550
      ExpressionType expressionType, Expression timeExpression, Expression valueExpression) {
2551
    if (!(timeExpression instanceof TimestampOperand)
×
2552
        || !(valueExpression instanceof ConstantOperand)) {
2553
      throw new SemanticException(DELETE_ONLY_SUPPORT_TIME_EXP_ERROR_MSG);
×
2554
    }
2555

2556
    if (((ConstantOperand) valueExpression).getDataType() != TSDataType.INT64) {
×
2557
      throw new SemanticException("The datatype of timestamp should be LONG.");
×
2558
    }
2559

2560
    long time = Long.parseLong(((ConstantOperand) valueExpression).getValueString());
×
2561
    switch (expressionType) {
×
2562
      case LESS_THAN:
2563
        return new TimeRange(Long.MIN_VALUE, time - 1);
×
2564
      case LESS_EQUAL:
2565
        return new TimeRange(Long.MIN_VALUE, time);
×
2566
      case GREATER_THAN:
2567
        return new TimeRange(time + 1, Long.MAX_VALUE);
×
2568
      case GREATER_EQUAL:
2569
        return new TimeRange(time, Long.MAX_VALUE);
×
2570
      case EQUAL_TO:
2571
        return new TimeRange(time, time);
×
2572
      default:
2573
        throw new SemanticException(DELETE_RANGE_ERROR_MSG);
×
2574
    }
2575
  }
2576

2577
  /** function for parsing file path used by LOAD statement. */
2578
  public String parseFilePath(String src) {
2579
    return src.substring(1, src.length() - 1);
×
2580
  }
2581

2582
  // Expression & Predicate ========================================================================
2583

2584
  private Expression parseExpression(
2585
      IoTDBSqlParser.ExpressionContext context, boolean canUseFullPath) {
2586
    if (context.unaryInBracket != null) {
1✔
2587
      return parseExpression(context.unaryInBracket, canUseFullPath);
1✔
2588
    }
2589

2590
    if (context.expressionAfterUnaryOperator != null) {
1✔
2591
      if (context.MINUS() != null) {
×
2592
        return new NegationExpression(
×
2593
            parseExpression(context.expressionAfterUnaryOperator, canUseFullPath));
×
2594
      }
2595
      if (context.operator_not() != null) {
×
2596
        return new LogicNotExpression(
×
2597
            parseExpression(context.expressionAfterUnaryOperator, canUseFullPath));
×
2598
      }
2599
      return parseExpression(context.expressionAfterUnaryOperator, canUseFullPath);
×
2600
    }
2601

2602
    if (context.leftExpression != null && context.rightExpression != null) {
1✔
2603
      Expression leftExpression = parseExpression(context.leftExpression, canUseFullPath);
1✔
2604
      Expression rightExpression = parseExpression(context.rightExpression, canUseFullPath);
1✔
2605
      if (context.STAR() != null) {
1✔
2606
        return new MultiplicationExpression(leftExpression, rightExpression);
1✔
2607
      }
2608
      if (context.DIV() != null) {
1✔
2609
        return new DivisionExpression(leftExpression, rightExpression);
1✔
2610
      }
2611
      if (context.MOD() != null) {
1✔
2612
        return new ModuloExpression(leftExpression, rightExpression);
1✔
2613
      }
2614
      if (context.PLUS() != null) {
1✔
2615
        return new AdditionExpression(leftExpression, rightExpression);
1✔
2616
      }
2617
      if (context.MINUS() != null) {
1✔
2618
        return new SubtractionExpression(leftExpression, rightExpression);
1✔
2619
      }
2620
      if (context.OPERATOR_GT() != null) {
1✔
2621
        return new GreaterThanExpression(leftExpression, rightExpression);
1✔
2622
      }
2623
      if (context.OPERATOR_GTE() != null) {
1✔
2624
        return new GreaterEqualExpression(leftExpression, rightExpression);
1✔
2625
      }
2626
      if (context.OPERATOR_LT() != null) {
1✔
2627
        return new LessThanExpression(leftExpression, rightExpression);
1✔
2628
      }
2629
      if (context.OPERATOR_LTE() != null) {
1✔
2630
        return new LessEqualExpression(leftExpression, rightExpression);
1✔
2631
      }
2632
      if (context.OPERATOR_DEQ() != null || context.OPERATOR_SEQ() != null) {
1✔
2633
        return new EqualToExpression(leftExpression, rightExpression);
1✔
2634
      }
2635
      if (context.OPERATOR_NEQ() != null) {
1✔
2636
        return new NonEqualExpression(leftExpression, rightExpression);
1✔
2637
      }
2638
      if (context.operator_and() != null) {
1✔
2639
        return new LogicAndExpression(leftExpression, rightExpression);
1✔
2640
      }
2641
      if (context.operator_or() != null) {
1✔
2642
        return new LogicOrExpression(leftExpression, rightExpression);
1✔
2643
      }
2644
      throw new UnsupportedOperationException();
×
2645
    }
2646

2647
    if (context.unaryBeforeRegularOrLikeExpression != null) {
1✔
2648
      if (context.REGEXP() != null) {
×
2649
        return parseRegularExpression(context, canUseFullPath);
×
2650
      }
2651
      if (context.LIKE() != null) {
×
2652
        return parseLikeExpression(context, canUseFullPath);
×
2653
      }
2654
      throw new UnsupportedOperationException();
×
2655
    }
2656

2657
    if (context.unaryBeforeIsNullExpression != null) {
1✔
2658
      return parseIsNullExpression(context, canUseFullPath);
×
2659
    }
2660

2661
    if (context.firstExpression != null
1✔
2662
        && context.secondExpression != null
2663
        && context.thirdExpression != null) {
2664
      Expression firstExpression = parseExpression(context.firstExpression, canUseFullPath);
×
2665
      Expression secondExpression = parseExpression(context.secondExpression, canUseFullPath);
×
2666
      Expression thirdExpression = parseExpression(context.thirdExpression, canUseFullPath);
×
2667

2668
      if (context.operator_between() != null) {
×
2669
        return new BetweenExpression(
×
2670
            firstExpression, secondExpression, thirdExpression, context.operator_not() != null);
×
2671
      }
2672
      throw new UnsupportedOperationException();
×
2673
    }
2674

2675
    if (context.unaryBeforeInExpression != null) {
1✔
2676
      return parseInExpression(context, canUseFullPath);
×
2677
    }
2678

2679
    if (context.scalarFunctionExpression() != null) {
1✔
2680
      return parseScalarFunctionExpression(context.scalarFunctionExpression(), canUseFullPath);
×
2681
    }
2682

2683
    if (context.functionName() != null) {
1✔
2684
      return parseFunctionExpression(context, canUseFullPath);
1✔
2685
    }
2686

2687
    if (context.fullPathInExpression() != null) {
1✔
2688
      return new TimeSeriesOperand(
1✔
2689
          parseFullPathInExpression(context.fullPathInExpression(), canUseFullPath));
1✔
2690
    }
2691

2692
    if (context.time != null) {
1✔
2693
      return new TimestampOperand();
1✔
2694
    }
2695

2696
    if (context.constant() != null && !context.constant().isEmpty()) {
1✔
2697
      return parseConstantOperand(context.constant(0));
1✔
2698
    }
2699

2700
    if (context.caseWhenThenExpression() != null) {
×
2701
      return parseCaseWhenThenExpression(context.caseWhenThenExpression(), canUseFullPath);
×
2702
    }
2703

2704
    throw new UnsupportedOperationException();
×
2705
  }
2706

2707
  private Expression parseScalarFunctionExpression(
2708
      IoTDBSqlParser.ScalarFunctionExpressionContext context, boolean canUseFullPath) {
2709
    if (context.CAST() != null) {
×
2710
      return parseCastFunction(context, canUseFullPath);
×
2711
    } else if (context.REPLACE() != null) {
×
2712
      return parseReplaceFunction(context, canUseFullPath);
×
2713
    } else if (context.ROUND() != null) {
×
2714
      return parseRoundFunction(context, canUseFullPath);
×
2715
    } else if (context.SUBSTRING() != null) {
×
2716
      return parseSubStrFunction(context, canUseFullPath);
×
2717
    }
2718
    throw new UnsupportedOperationException();
×
2719
  }
2720

2721
  private Expression parseCastFunction(
2722
      IoTDBSqlParser.ScalarFunctionExpressionContext castClause, boolean canUseFullPath) {
2723
    FunctionExpression functionExpression = new FunctionExpression(CAST_FUNCTION);
×
2724
    functionExpression.addExpression(parseExpression(castClause.castInput, canUseFullPath));
×
2725
    functionExpression.addAttribute(CAST_TYPE, parseAttributeValue(castClause.attributeValue()));
×
2726
    return functionExpression;
×
2727
  }
2728

2729
  private Expression parseReplaceFunction(
2730
      IoTDBSqlParser.ScalarFunctionExpressionContext replaceClause, boolean canUseFullPath) {
2731
    FunctionExpression functionExpression = new FunctionExpression(REPLACE_FUNCTION);
×
2732
    functionExpression.addExpression(parseExpression(replaceClause.text, canUseFullPath));
×
2733
    functionExpression.addAttribute(REPLACE_FROM, parseStringLiteral(replaceClause.from.getText()));
×
2734
    functionExpression.addAttribute(REPLACE_TO, parseStringLiteral(replaceClause.to.getText()));
×
2735
    return functionExpression;
×
2736
  }
2737

2738
  private Expression parseSubStrFunction(
2739
      IoTDBSqlParser.ScalarFunctionExpressionContext subStrClause, boolean canUseFullPath) {
2740
    FunctionExpression functionExpression = new FunctionExpression(SUBSTRING_FUNCTION);
×
2741
    IoTDBSqlParser.SubStringExpressionContext subStringExpression =
×
2742
        subStrClause.subStringExpression();
×
2743
    functionExpression.addExpression(parseExpression(subStringExpression.input, canUseFullPath));
×
2744
    if (subStringExpression.startPosition != null) {
×
2745
      functionExpression.addAttribute(SUBSTRING_START, subStringExpression.startPosition.getText());
×
2746
      if (subStringExpression.length != null) {
×
2747
        functionExpression.addAttribute(SUBSTRING_LENGTH, subStringExpression.length.getText());
×
2748
      }
2749
    }
2750
    if (subStringExpression.from != null) {
×
2751
      functionExpression.addAttribute(SUBSTRING_IS_STANDARD, "0");
×
2752
      functionExpression.addAttribute(
×
2753
          SUBSTRING_START, parseStringLiteral(subStringExpression.from.getText()));
×
2754
      if (subStringExpression.forLength != null) {
×
2755
        functionExpression.addAttribute(SUBSTRING_LENGTH, subStringExpression.forLength.getText());
×
2756
      }
2757
    }
2758
    return functionExpression;
×
2759
  }
2760

2761
  private Expression parseRoundFunction(
2762
      IoTDBSqlParser.ScalarFunctionExpressionContext roundClause, boolean canUseFullPath) {
2763
    FunctionExpression functionExpression = new FunctionExpression(ROUND_FUNCTION);
×
2764
    functionExpression.addExpression(parseExpression(roundClause.input, canUseFullPath));
×
2765
    if (roundClause.places != null) {
×
2766
      functionExpression.addAttribute(ROUND_PLACES, parseConstant(roundClause.constant()));
×
2767
    }
2768
    return functionExpression;
×
2769
  }
2770

2771
  private CaseWhenThenExpression parseCaseWhenThenExpression(
2772
      IoTDBSqlParser.CaseWhenThenExpressionContext context, boolean canUseFullPath) {
2773
    // handle CASE
2774
    Expression caseExpression = null;
×
2775
    boolean simpleCase = false;
×
2776
    if (context.caseExpression != null) {
×
2777
      caseExpression = parseExpression(context.caseExpression, canUseFullPath);
×
2778
      simpleCase = true;
×
2779
    }
2780
    // handle WHEN-THEN
2781
    List<WhenThenExpression> whenThenList = new ArrayList<>();
×
2782
    if (simpleCase) {
×
2783
      for (IoTDBSqlParser.WhenThenExpressionContext whenThenExpressionContext :
2784
          context.whenThenExpression()) {
×
2785
        Expression when = parseExpression(whenThenExpressionContext.whenExpression, canUseFullPath);
×
2786
        Expression then = parseExpression(whenThenExpressionContext.thenExpression, canUseFullPath);
×
2787
        Expression comparison = new EqualToExpression(caseExpression, when);
×
2788
        whenThenList.add(new WhenThenExpression(comparison, then));
×
2789
      }
×
2790
    } else {
2791
      for (IoTDBSqlParser.WhenThenExpressionContext whenThenExpressionContext :
2792
          context.whenThenExpression()) {
×
2793
        whenThenList.add(
×
2794
            new WhenThenExpression(
2795
                parseExpression(whenThenExpressionContext.whenExpression, canUseFullPath),
×
2796
                parseExpression(whenThenExpressionContext.thenExpression, canUseFullPath)));
×
2797
      }
×
2798
    }
2799
    // handle ELSE
2800
    Expression elseExpression = new NullOperand();
×
2801
    if (context.elseExpression != null) {
×
2802
      elseExpression = parseExpression(context.elseExpression, canUseFullPath);
×
2803
    }
2804
    return new CaseWhenThenExpression(whenThenList, elseExpression);
×
2805
  }
2806

2807
  private Expression parseFunctionExpression(
2808
      IoTDBSqlParser.ExpressionContext functionClause, boolean canUseFullPath) {
2809
    FunctionExpression functionExpression =
1✔
2810
        new FunctionExpression(parseIdentifier(functionClause.functionName().getText()));
1✔
2811

2812
    // expressions
2813
    boolean hasNonPureConstantSubExpression = false;
1✔
2814
    for (IoTDBSqlParser.ExpressionContext expression : functionClause.expression()) {
1✔
2815
      Expression subexpression = parseExpression(expression, canUseFullPath);
1✔
2816
      if (!subexpression.isConstantOperand()) {
1✔
2817
        hasNonPureConstantSubExpression = true;
1✔
2818
      }
2819
      if (subexpression instanceof EqualToExpression) {
1✔
2820
        Expression subLeftExpression = ((EqualToExpression) subexpression).getLeftExpression();
1✔
2821
        Expression subRightExpression = ((EqualToExpression) subexpression).getRightExpression();
1✔
2822
        if (subLeftExpression.isConstantOperand()
1✔
2823
            && (!(subRightExpression.isConstantOperand()
1✔
2824
                && ((ConstantOperand) subRightExpression).getDataType().equals(TSDataType.TEXT)))) {
1✔
2825
          throw new SemanticException("Attributes of functions should be quoted with '' or \"\"");
×
2826
        }
2827
        if (subLeftExpression.isConstantOperand() && subRightExpression.isConstantOperand()) {
1✔
2828
          // parse attribute
2829
          functionExpression.addAttribute(
1✔
2830
              ((ConstantOperand) subLeftExpression).getValueString(),
1✔
2831
              ((ConstantOperand) subRightExpression).getValueString());
1✔
2832
        } else {
2833
          functionExpression.addExpression(subexpression);
×
2834
        }
2835
      } else {
1✔
2836
        functionExpression.addExpression(subexpression);
1✔
2837
      }
2838
    }
1✔
2839

2840
    // It is not allowed to have function expressions like F(1, 1.0). There should be at least one
2841
    // non-pure-constant sub-expression, otherwise the timestamp of the row cannot be inferred.
2842
    if (!hasNonPureConstantSubExpression) {
1✔
2843
      throw new SemanticException(
×
2844
          "Invalid function expression, all the arguments are constant operands: "
2845
              + functionClause.getText());
×
2846
    }
2847

2848
    // check size of input expressions
2849
    // type check of input expressions is put in ExpressionTypeAnalyzer
2850
    if (functionExpression.isBuiltInAggregationFunctionExpression()) {
1✔
2851
      checkAggregationFunctionInput(functionExpression);
1✔
2852
    } else if (functionExpression.isBuiltInScalarFunction()) {
1✔
2853
      checkBuiltInScalarFunctionInput(functionExpression);
1✔
2854
    }
2855
    return functionExpression;
1✔
2856
  }
2857

2858
  private void checkAggregationFunctionInput(FunctionExpression functionExpression) {
2859
    final String functionName = functionExpression.getFunctionName().toLowerCase();
1✔
2860
    switch (functionName) {
1✔
2861
      case SqlConstant.MIN_TIME:
2862
      case SqlConstant.MAX_TIME:
2863
      case SqlConstant.COUNT:
2864
      case SqlConstant.COUNT_TIME:
2865
      case SqlConstant.MIN_VALUE:
2866
      case SqlConstant.LAST_VALUE:
2867
      case SqlConstant.FIRST_VALUE:
2868
      case SqlConstant.MAX_VALUE:
2869
      case SqlConstant.EXTREME:
2870
      case SqlConstant.AVG:
2871
      case SqlConstant.SUM:
2872
      case SqlConstant.TIME_DURATION:
2873
      case SqlConstant.MODE:
2874
        checkFunctionExpressionInputSize(
1✔
2875
            functionExpression.getExpressionString(),
1✔
2876
            functionExpression.getExpressions().size(),
1✔
2877
            1);
2878
        return;
1✔
2879
      case SqlConstant.COUNT_IF:
2880
        checkFunctionExpressionInputSize(
×
2881
            functionExpression.getExpressionString(),
×
2882
            functionExpression.getExpressions().size(),
×
2883
            2);
2884
        return;
×
2885
      default:
2886
        throw new IllegalArgumentException(
×
2887
            "Invalid Aggregation function: " + functionExpression.getFunctionName());
×
2888
    }
2889
  }
2890

2891
  private void checkBuiltInScalarFunctionInput(FunctionExpression functionExpression) {
2892
    BuiltInScalarFunctionHelperFactory.createHelper(functionExpression.getFunctionName())
1✔
2893
        .checkBuiltInScalarFunctionInputSize(functionExpression);
1✔
2894
  }
1✔
2895

2896
  public static void checkFunctionExpressionInputSize(
2897
      String expressionString, int actual, int... expected) {
2898
    for (int expect : expected) {
1✔
2899
      if (expect == actual) {
1✔
2900
        return;
1✔
2901
      }
2902
    }
2903
    throw new SemanticException(
×
2904
        String.format(
×
2905
            "Error size of input expressions. expression: %s, actual size: %s, expected size: %s.",
2906
            expressionString, actual, Arrays.toString(expected)));
×
2907
  }
2908

2909
  private Expression parseRegularExpression(ExpressionContext context, boolean canUseFullPath) {
2910
    return new RegularExpression(
×
2911
        parseExpression(context.unaryBeforeRegularOrLikeExpression, canUseFullPath),
×
2912
        parseStringLiteral(context.STRING_LITERAL().getText()));
×
2913
  }
2914

2915
  private Expression parseLikeExpression(ExpressionContext context, boolean canUseFullPath) {
2916
    return new LikeExpression(
×
2917
        parseExpression(context.unaryBeforeRegularOrLikeExpression, canUseFullPath),
×
2918
        parseStringLiteral(context.STRING_LITERAL().getText()));
×
2919
  }
2920

2921
  private Expression parseIsNullExpression(ExpressionContext context, boolean canUseFullPath) {
2922
    return new IsNullExpression(
×
2923
        parseExpression(context.unaryBeforeIsNullExpression, canUseFullPath),
×
2924
        context.operator_not() != null);
×
2925
  }
2926

2927
  private Expression parseInExpression(ExpressionContext context, boolean canUseFullPath) {
2928
    Expression childExpression = parseExpression(context.unaryBeforeInExpression, canUseFullPath);
×
2929
    LinkedHashSet<String> values = new LinkedHashSet<>();
×
2930
    for (ConstantContext constantContext : context.constant()) {
×
2931
      values.add(parseConstant(constantContext));
×
2932
    }
×
2933
    return new InExpression(childExpression, context.operator_not() != null, values);
×
2934
  }
2935

2936
  private String parseConstant(ConstantContext constantContext) {
2937
    String text = constantContext.getText();
×
2938
    if (constantContext.boolean_literal() != null
×
2939
        || constantContext.INTEGER_LITERAL() != null
×
2940
        || constantContext.realLiteral() != null) {
×
2941
      return text;
×
2942
    } else if (constantContext.STRING_LITERAL() != null) {
×
2943
      return parseStringLiteral(text);
×
2944
    } else if (constantContext.dateExpression() != null) {
×
2945
      return String.valueOf(parseDateExpression(constantContext.dateExpression()));
×
2946
    } else {
2947
      throw new IllegalArgumentException("Unsupported constant value: " + text);
×
2948
    }
2949
  }
2950

2951
  private Expression parseConstantOperand(ConstantContext constantContext) {
2952
    String text = constantContext.getText();
1✔
2953
    if (constantContext.boolean_literal() != null) {
1✔
2954
      return new ConstantOperand(TSDataType.BOOLEAN, text);
×
2955
    } else if (constantContext.STRING_LITERAL() != null) {
1✔
2956
      return new ConstantOperand(TSDataType.TEXT, parseStringLiteral(text));
1✔
2957
    } else if (constantContext.INTEGER_LITERAL() != null) {
1✔
2958
      return new ConstantOperand(TSDataType.INT64, text);
1✔
2959
    } else if (constantContext.realLiteral() != null) {
×
2960
      return parseRealLiteral(text);
×
2961
    } else if (constantContext.dateExpression() != null) {
×
2962
      return new ConstantOperand(
×
2963
          TSDataType.INT64, String.valueOf(parseDateExpression(constantContext.dateExpression())));
×
2964
    } else {
2965
      throw new SemanticException("Unsupported constant operand: " + text);
×
2966
    }
2967
  }
2968

2969
  private Expression parseRealLiteral(String value) {
2970
    // 3.33 is float by default
2971
    return new ConstantOperand(
×
2972
        CONFIG.getFloatingStringInferType().equals(TSDataType.DOUBLE)
×
2973
            ? TSDataType.DOUBLE
×
2974
            : TSDataType.FLOAT,
×
2975
        value);
2976
  }
2977

2978
  /**
2979
   * parse time expression, which is addition and subtraction expression of duration time, now() or
2980
   * DataTimeFormat time.
2981
   *
2982
   * <p>eg. now() + 1d - 2h
2983
   */
2984
  private Long parseDateExpression(IoTDBSqlParser.DateExpressionContext ctx) {
2985
    long time;
2986
    time = parseDateFormat(ctx.getChild(0).getText());
×
2987
    for (int i = 1; i < ctx.getChildCount(); i = i + 2) {
×
2988
      if ("+".equals(ctx.getChild(i).getText())) {
×
2989
        time += DateTimeUtils.convertDurationStrToLong(time, ctx.getChild(i + 1).getText());
×
2990
      } else {
2991
        time -= DateTimeUtils.convertDurationStrToLong(time, ctx.getChild(i + 1).getText());
×
2992
      }
2993
    }
2994
    return time;
×
2995
  }
2996

2997
  private Long parseDateExpression(IoTDBSqlParser.DateExpressionContext ctx, long currentTime) {
2998
    long time;
2999
    time = parseDateFormat(ctx.getChild(0).getText(), currentTime);
×
3000
    for (int i = 1; i < ctx.getChildCount(); i = i + 2) {
×
3001
      if ("+".equals(ctx.getChild(i).getText())) {
×
3002
        time += DateTimeUtils.convertDurationStrToLong(time, ctx.getChild(i + 1).getText());
×
3003
      } else {
3004
        time -= DateTimeUtils.convertDurationStrToLong(time, ctx.getChild(i + 1).getText());
×
3005
      }
3006
    }
3007
    return time;
×
3008
  }
3009

3010
  private long parseTimeValue(IoTDBSqlParser.TimeValueContext ctx, long currentTime) {
3011
    if (ctx.INTEGER_LITERAL() != null) {
1✔
3012
      try {
3013
        if (ctx.MINUS() != null) {
1✔
3014
          return -Long.parseLong(ctx.INTEGER_LITERAL().getText());
×
3015
        }
3016
        return Long.parseLong(ctx.INTEGER_LITERAL().getText());
1✔
3017
      } catch (NumberFormatException e) {
×
3018
        throw new SemanticException(
×
3019
            String.format("Can not parse %s to long value", ctx.INTEGER_LITERAL().getText()));
×
3020
      }
3021
    } else if (ctx.dateExpression() != null) {
1✔
3022
      return parseDateExpression(ctx.dateExpression(), currentTime);
×
3023
    } else {
3024
      return parseDateFormat(ctx.datetimeLiteral().getText(), currentTime);
1✔
3025
    }
3026
  }
3027

3028
  /** Utils. */
3029
  private void setMap(IoTDBSqlParser.AlterClauseContext ctx, Map<String, String> alterMap) {
3030
    List<IoTDBSqlParser.AttributePairContext> tagsList = ctx.attributePair();
×
3031
    String key;
3032
    if (ctx.attributePair(0) != null) {
×
3033
      for (IoTDBSqlParser.AttributePairContext attributePair : tagsList) {
×
3034
        key = parseAttributeKey(attributePair.attributeKey());
×
3035
        alterMap.computeIfPresent(
×
3036
            key,
3037
            (k, v) -> {
3038
              throw new SemanticException(
×
3039
                  String.format("There's duplicate [%s] in tag or attribute clause.", k));
×
3040
            });
3041
        alterMap.put(key, parseAttributeValue(attributePair.attributeValue()));
×
3042
      }
×
3043
    }
3044
  }
×
3045

3046
  private Map<String, String> extractMap(
3047
      List<IoTDBSqlParser.AttributePairContext> attributePair2,
3048
      IoTDBSqlParser.AttributePairContext attributePair3) {
3049
    Map<String, String> tags = new HashMap<>(attributePair2.size());
1✔
3050
    if (attributePair3 != null) {
1✔
3051
      String key;
3052
      for (IoTDBSqlParser.AttributePairContext attributePair : attributePair2) {
1✔
3053
        key = parseAttributeKey(attributePair.attributeKey());
1✔
3054
        tags.computeIfPresent(
1✔
3055
            key,
3056
            (k, v) -> {
3057
              throw new SemanticException(
×
3058
                  String.format("There's duplicate [%s] in tag or attribute clause.", k));
×
3059
            });
3060
        tags.put(key, parseAttributeValue(attributePair.attributeValue()));
1✔
3061
      }
1✔
3062
    }
3063
    return tags;
1✔
3064
  }
3065

3066
  private String parseAttributeKey(IoTDBSqlParser.AttributeKeyContext ctx) {
3067
    if (ctx.constant() != null) {
1✔
3068
      return parseStringLiteral(ctx.getText());
1✔
3069
    }
3070
    return parseIdentifier(ctx.getText());
×
3071
  }
3072

3073
  private String parseAttributeValue(IoTDBSqlParser.AttributeValueContext ctx) {
3074
    if (ctx.constant() != null) {
1✔
3075
      return parseStringLiteral(ctx.getText());
1✔
3076
    }
3077
    return parseIdentifier(ctx.getText());
×
3078
  }
3079

3080
  // Merge
3081
  @Override
3082
  public Statement visitMerge(IoTDBSqlParser.MergeContext ctx) {
3083
    MergeStatement mergeStatement = new MergeStatement(StatementType.MERGE);
×
3084
    if (ctx.CLUSTER() != null && !IoTDBDescriptor.getInstance().getConfig().isClusterMode()) {
×
3085
      throw new SemanticException("MERGE ON CLUSTER is not supported in standalone mode");
×
3086
    }
3087
    mergeStatement.setOnCluster(ctx.LOCAL() == null);
×
3088
    return mergeStatement;
×
3089
  }
3090

3091
  @Override
3092
  public Statement visitFullMerge(IoTDBSqlParser.FullMergeContext ctx) {
3093
    MergeStatement mergeStatement = new MergeStatement(StatementType.FULL_MERGE);
×
3094
    if (ctx.CLUSTER() != null && !IoTDBDescriptor.getInstance().getConfig().isClusterMode()) {
×
3095
      throw new SemanticException("FULL MERGE ON CLUSTER is not supported in standalone mode");
×
3096
    }
3097
    mergeStatement.setOnCluster(ctx.LOCAL() == null);
×
3098
    return mergeStatement;
×
3099
  }
3100

3101
  // Flush
3102

3103
  @Override
3104
  public Statement visitFlush(IoTDBSqlParser.FlushContext ctx) {
3105
    FlushStatement flushStatement = new FlushStatement(StatementType.FLUSH);
×
3106
    List<PartialPath> storageGroups = null;
×
3107
    if (ctx.boolean_literal() != null) {
×
3108
      flushStatement.setSeq(Boolean.parseBoolean(ctx.boolean_literal().getText()));
×
3109
    }
3110
    if (ctx.CLUSTER() != null && !IoTDBDescriptor.getInstance().getConfig().isClusterMode()) {
×
3111
      throw new SemanticException("FLUSH ON CLUSTER is not supported in standalone mode");
×
3112
    }
3113
    flushStatement.setOnCluster(ctx.LOCAL() == null);
×
3114
    if (ctx.prefixPath(0) != null) {
×
3115
      storageGroups = new ArrayList<>();
×
3116
      for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
3117
        storageGroups.add(parsePrefixPath(prefixPathContext));
×
3118
      }
×
3119
    }
3120
    flushStatement.setStorageGroups(storageGroups);
×
3121
    return flushStatement;
×
3122
  }
3123

3124
  // Clear Cache
3125

3126
  @Override
3127
  public Statement visitClearCache(IoTDBSqlParser.ClearCacheContext ctx) {
3128
    ClearCacheStatement clearCacheStatement = new ClearCacheStatement(StatementType.CLEAR_CACHE);
×
3129
    if (ctx.CLUSTER() != null && !IoTDBDescriptor.getInstance().getConfig().isClusterMode()) {
×
3130
      throw new SemanticException("CLEAR CACHE ON CLUSTER is not supported in standalone mode");
×
3131
    }
3132
    clearCacheStatement.setOnCluster(ctx.LOCAL() == null);
×
3133
    return clearCacheStatement;
×
3134
  }
3135

3136
  // Load Configuration
3137

3138
  @Override
3139
  public Statement visitLoadConfiguration(IoTDBSqlParser.LoadConfigurationContext ctx) {
3140
    LoadConfigurationStatement loadConfigurationStatement =
×
3141
        new LoadConfigurationStatement(StatementType.LOAD_CONFIGURATION);
3142
    if (ctx.CLUSTER() != null && !IoTDBDescriptor.getInstance().getConfig().isClusterMode()) {
×
3143
      throw new SemanticException(
×
3144
          "LOAD CONFIGURATION ON CLUSTER is not supported in standalone mode");
3145
    }
3146
    loadConfigurationStatement.setOnCluster(ctx.LOCAL() == null);
×
3147
    return loadConfigurationStatement;
×
3148
  }
3149

3150
  // Set System Status
3151

3152
  @Override
3153
  public Statement visitSetSystemStatus(IoTDBSqlParser.SetSystemStatusContext ctx) {
3154
    SetSystemStatusStatement setSystemStatusStatement = new SetSystemStatusStatement();
×
3155
    if (ctx.CLUSTER() != null && !IoTDBDescriptor.getInstance().getConfig().isClusterMode()) {
×
3156
      throw new SemanticException(
×
3157
          "SET SYSTEM STATUS ON CLUSTER is not supported in standalone mode");
3158
    }
3159
    setSystemStatusStatement.setOnCluster(ctx.LOCAL() == null);
×
3160
    if (ctx.RUNNING() != null) {
×
3161
      setSystemStatusStatement.setStatus(NodeStatus.Running);
×
3162
    } else if (ctx.READONLY() != null) {
×
3163
      setSystemStatusStatement.setStatus(NodeStatus.ReadOnly);
×
3164
    } else {
3165
      throw new SemanticException("Unknown system status in set system command.");
×
3166
    }
3167
    return setSystemStatusStatement;
×
3168
  }
3169

3170
  // Kill Query
3171
  @Override
3172
  public Statement visitKillQuery(IoTDBSqlParser.KillQueryContext ctx) {
3173
    if (ctx.queryId != null) {
×
3174
      return new KillQueryStatement(parseStringLiteral(ctx.queryId.getText()));
×
3175
    }
3176
    return new KillQueryStatement();
×
3177
  }
3178

3179
  // show query processlist
3180

3181
  @Override
3182
  public Statement visitShowQueries(IoTDBSqlParser.ShowQueriesContext ctx) {
3183
    ShowQueriesStatement showQueriesStatement = new ShowQueriesStatement();
×
3184
    // parse WHERE
3185
    if (ctx.whereClause() != null) {
×
3186
      showQueriesStatement.setWhereCondition(parseWhereClause(ctx.whereClause()));
×
3187
    }
3188

3189
    // parse ORDER BY
3190
    if (ctx.orderByClause() != null) {
×
3191
      showQueriesStatement.setOrderByComponent(
×
3192
          parseOrderByClause(
×
3193
              ctx.orderByClause(),
×
3194
              ImmutableSet.of(
×
3195
                  OrderByKey.TIME,
3196
                  OrderByKey.QUERYID,
3197
                  OrderByKey.DATANODEID,
3198
                  OrderByKey.ELAPSEDTIME,
3199
                  OrderByKey.STATEMENT)));
3200
    }
3201

3202
    // parse LIMIT & OFFSET
3203
    if (ctx.rowPaginationClause() != null) {
×
3204
      if (ctx.rowPaginationClause().limitClause() != null) {
×
3205
        showQueriesStatement.setRowLimit(parseLimitClause(ctx.rowPaginationClause().limitClause()));
×
3206
      }
3207
      if (ctx.rowPaginationClause().offsetClause() != null) {
×
3208
        showQueriesStatement.setRowOffset(
×
3209
            parseOffsetClause(ctx.rowPaginationClause().offsetClause()));
×
3210
      }
3211
    }
3212

3213
    showQueriesStatement.setZoneId(zoneId);
×
3214
    return showQueriesStatement;
×
3215
  }
3216

3217
  // show region
3218

3219
  @Override
3220
  public Statement visitShowRegions(IoTDBSqlParser.ShowRegionsContext ctx) {
3221
    ShowRegionStatement showRegionStatement = new ShowRegionStatement();
×
3222
    // TODO: Maybe add a show ConfigNode region in the future
3223
    if (ctx.DATA() != null) {
×
3224
      showRegionStatement.setRegionType(TConsensusGroupType.DataRegion);
×
3225
    } else if (ctx.SCHEMA() != null) {
×
3226
      showRegionStatement.setRegionType(TConsensusGroupType.SchemaRegion);
×
3227
    } else {
3228
      showRegionStatement.setRegionType(null);
×
3229
    }
3230

3231
    if (ctx.OF() != null) {
×
3232
      List<PartialPath> storageGroups = null;
×
3233
      if (ctx.prefixPath(0) != null) {
×
3234
        storageGroups = new ArrayList<>();
×
3235
        for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
3236
          storageGroups.add(parsePrefixPath(prefixPathContext));
×
3237
        }
×
3238
      }
3239
      showRegionStatement.setStorageGroups(storageGroups);
×
3240
    } else {
×
3241
      showRegionStatement.setStorageGroups(null);
×
3242
    }
3243

3244
    if (ctx.ON() != null) {
×
3245
      List<Integer> nodeIds = new ArrayList<>();
×
3246
      for (TerminalNode nodeid : ctx.INTEGER_LITERAL()) {
×
3247
        nodeIds.add(Integer.parseInt(nodeid.getText()));
×
3248
      }
×
3249
      showRegionStatement.setNodeIds(nodeIds);
×
3250
    } else {
×
3251
      showRegionStatement.setNodeIds(null);
×
3252
    }
3253
    return showRegionStatement;
×
3254
  }
3255

3256
  // show datanodes
3257

3258
  @Override
3259
  public Statement visitShowDataNodes(IoTDBSqlParser.ShowDataNodesContext ctx) {
3260
    return new ShowDataNodesStatement();
×
3261
  }
3262

3263
  // show confignodes
3264

3265
  @Override
3266
  public Statement visitShowConfigNodes(IoTDBSqlParser.ShowConfigNodesContext ctx) {
3267
    return new ShowConfigNodesStatement();
×
3268
  }
3269

3270
  // schema template
3271

3272
  @Override
3273
  public Statement visitCreateSchemaTemplate(IoTDBSqlParser.CreateSchemaTemplateContext ctx) {
3274
    String name = parseIdentifier(ctx.templateName.getText());
×
3275
    List<List<String>> measurementsList = new ArrayList<>();
×
3276
    List<List<TSDataType>> dataTypesList = new ArrayList<>();
×
3277
    List<List<TSEncoding>> encodingsList = new ArrayList<>();
×
3278
    List<List<CompressionType>> compressorsList = new ArrayList<>();
×
3279

3280
    if (ctx.ALIGNED() != null) {
×
3281
      // aligned
3282
      List<String> measurements = new ArrayList<>();
×
3283
      List<TSDataType> dataTypes = new ArrayList<>();
×
3284
      List<TSEncoding> encodings = new ArrayList<>();
×
3285
      List<CompressionType> compressors = new ArrayList<>();
×
3286
      for (IoTDBSqlParser.TemplateMeasurementClauseContext templateClauseContext :
3287
          ctx.templateMeasurementClause()) {
×
3288
        measurements.add(
×
3289
            parseNodeNameWithoutWildCard(templateClauseContext.nodeNameWithoutWildcard()));
×
3290
        parseAttributeClauseForSchemaTemplate(
×
3291
            templateClauseContext.attributeClauses(), dataTypes, encodings, compressors);
×
3292
      }
×
3293
      measurementsList.add(measurements);
×
3294
      dataTypesList.add(dataTypes);
×
3295
      encodingsList.add(encodings);
×
3296
      compressorsList.add(compressors);
×
3297
    } else {
×
3298
      // non-aligned
3299
      for (IoTDBSqlParser.TemplateMeasurementClauseContext templateClauseContext :
3300
          ctx.templateMeasurementClause()) {
×
3301
        List<String> measurements = new ArrayList<>();
×
3302
        List<TSDataType> dataTypes = new ArrayList<>();
×
3303
        List<TSEncoding> encodings = new ArrayList<>();
×
3304
        List<CompressionType> compressors = new ArrayList<>();
×
3305
        measurements.add(
×
3306
            parseNodeNameWithoutWildCard(templateClauseContext.nodeNameWithoutWildcard()));
×
3307
        parseAttributeClauseForSchemaTemplate(
×
3308
            templateClauseContext.attributeClauses(), dataTypes, encodings, compressors);
×
3309
        measurementsList.add(measurements);
×
3310
        dataTypesList.add(dataTypes);
×
3311
        encodingsList.add(encodings);
×
3312
        compressorsList.add(compressors);
×
3313
      }
×
3314
    }
3315

3316
    return new CreateSchemaTemplateStatement(
×
3317
        name,
3318
        measurementsList,
3319
        dataTypesList,
3320
        encodingsList,
3321
        compressorsList,
3322
        ctx.ALIGNED() != null);
×
3323
  }
3324

3325
  @Override
3326
  public Statement visitAlterSchemaTemplate(IoTDBSqlParser.AlterSchemaTemplateContext ctx) {
3327
    String name = parseIdentifier(ctx.templateName.getText());
×
3328
    List<String> measurements = new ArrayList<>();
×
3329
    List<TSDataType> dataTypes = new ArrayList<>();
×
3330
    List<TSEncoding> encodings = new ArrayList<>();
×
3331
    List<CompressionType> compressors = new ArrayList<>();
×
3332

3333
    for (IoTDBSqlParser.TemplateMeasurementClauseContext templateClauseContext :
3334
        ctx.templateMeasurementClause()) {
×
3335
      measurements.add(
×
3336
          parseNodeNameWithoutWildCard(templateClauseContext.nodeNameWithoutWildcard()));
×
3337
      parseAttributeClauseForSchemaTemplate(
×
3338
          templateClauseContext.attributeClauses(), dataTypes, encodings, compressors);
×
3339
    }
×
3340

3341
    return new AlterSchemaTemplateStatement(
×
3342
        name,
3343
        measurements,
3344
        dataTypes,
3345
        encodings,
3346
        compressors,
3347
        TemplateAlterOperationType.EXTEND_TEMPLATE);
3348
  }
3349

3350
  void parseAttributeClauseForSchemaTemplate(
3351
      IoTDBSqlParser.AttributeClausesContext ctx,
3352
      List<TSDataType> dataTypes,
3353
      List<TSEncoding> encodings,
3354
      List<CompressionType> compressors) {
3355
    if (ctx.aliasNodeName() != null) {
×
3356
      throw new SemanticException("Schema template: alias is not supported yet.");
×
3357
    }
3358

3359
    TSDataType dataType = parseDataTypeAttribute(ctx);
×
3360
    dataTypes.add(dataType);
×
3361

3362
    Map<String, String> props = new HashMap<>();
×
3363
    if (ctx.attributePair() != null) {
×
3364
      for (int i = 0; i < ctx.attributePair().size(); i++) {
×
3365
        props.put(
×
3366
            parseAttributeKey(ctx.attributePair(i).attributeKey()).toLowerCase(),
×
3367
            parseAttributeValue(ctx.attributePair(i).attributeValue()));
×
3368
      }
3369
    }
3370

3371
    TSEncoding encoding = IoTDBDescriptor.getInstance().getDefaultEncodingByType(dataType);
×
3372
    if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase())) {
×
3373
      String encodingString =
×
3374
          props.get(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase()).toUpperCase();
×
3375
      try {
3376
        encoding = TSEncoding.valueOf(encodingString);
×
3377
        encodings.add(encoding);
×
3378
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_ENCODING.toLowerCase());
×
3379
      } catch (Exception e) {
×
3380
        throw new SemanticException(String.format("Unsupported encoding: %s", encodingString));
×
3381
      }
×
3382
    } else {
×
3383
      encodings.add(encoding);
×
3384
    }
3385

3386
    CompressionType compressor = TSFileDescriptor.getInstance().getConfig().getCompressor();
×
3387
    if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase())) {
×
3388
      String compressorString =
×
3389
          props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase()).toUpperCase();
×
3390
      try {
3391
        compressor = CompressionType.valueOf(compressorString);
×
3392
        compressors.add(compressor);
×
3393
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSOR.toLowerCase());
×
3394
      } catch (Exception e) {
×
3395
        throw new SemanticException(String.format("Unsupported compressor: %s", compressorString));
×
3396
      }
×
3397
    } else if (props.containsKey(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase())) {
×
3398
      String compressionString =
×
3399
          props.get(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase()).toUpperCase();
×
3400
      try {
3401
        compressor = CompressionType.valueOf(compressionString);
×
3402
        compressors.add(compressor);
×
3403
        props.remove(IoTDBConstant.COLUMN_TIMESERIES_COMPRESSION.toLowerCase());
×
3404
      } catch (Exception e) {
×
3405
        throw new SemanticException(
×
3406
            String.format("Unsupported compression: %s", compressionString));
×
3407
      }
×
3408
    } else {
×
3409
      compressors.add(compressor);
×
3410
    }
3411

3412
    if (props.size() > 0) {
×
3413
      throw new SemanticException("Schema template: property is not supported yet.");
×
3414
    }
3415

3416
    if (ctx.tagClause() != null) {
×
3417
      throw new SemanticException("Schema template: tag is not supported yet.");
×
3418
    }
3419

3420
    if (ctx.attributeClause() != null) {
×
3421
      throw new SemanticException("Schema template: attribute is not supported yet.");
×
3422
    }
3423
  }
×
3424

3425
  private TSDataType parseDataTypeAttribute(IoTDBSqlParser.AttributeClausesContext ctx) {
3426
    TSDataType dataType = null;
1✔
3427
    if (ctx.dataType != null) {
1✔
3428
      if (ctx.attributeKey() != null
1✔
3429
          && !parseAttributeKey(ctx.attributeKey())
×
3430
              .equalsIgnoreCase(IoTDBConstant.COLUMN_TIMESERIES_DATATYPE)) {
×
3431
        throw new SemanticException("Expecting datatype");
×
3432
      }
3433
      String dataTypeString = ctx.dataType.getText().toUpperCase();
1✔
3434
      try {
3435
        dataType = TSDataType.valueOf(dataTypeString);
1✔
3436
      } catch (Exception e) {
×
3437
        throw new SemanticException(String.format("Unsupported datatype: %s", dataTypeString));
×
3438
      }
1✔
3439
    }
3440
    return dataType;
1✔
3441
  }
3442

3443
  @Override
3444
  public Statement visitShowSchemaTemplates(IoTDBSqlParser.ShowSchemaTemplatesContext ctx) {
3445
    return new ShowSchemaTemplateStatement();
×
3446
  }
3447

3448
  @Override
3449
  public Statement visitShowNodesInSchemaTemplate(
3450
      IoTDBSqlParser.ShowNodesInSchemaTemplateContext ctx) {
3451
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3452
    return new ShowNodesInSchemaTemplateStatement(templateName);
×
3453
  }
3454

3455
  @Override
3456
  public Statement visitSetSchemaTemplate(IoTDBSqlParser.SetSchemaTemplateContext ctx) {
3457
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3458
    return new SetSchemaTemplateStatement(templateName, parsePrefixPath(ctx.prefixPath()));
×
3459
  }
3460

3461
  @Override
3462
  public Statement visitShowPathsSetSchemaTemplate(
3463
      IoTDBSqlParser.ShowPathsSetSchemaTemplateContext ctx) {
3464
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3465
    return new ShowPathSetTemplateStatement(templateName);
×
3466
  }
3467

3468
  @Override
3469
  public Statement visitCreateTimeseriesUsingSchemaTemplate(
3470
      IoTDBSqlParser.CreateTimeseriesUsingSchemaTemplateContext ctx) {
3471
    ActivateTemplateStatement statement = new ActivateTemplateStatement();
×
3472
    statement.setPath(parsePrefixPath(ctx.prefixPath()));
×
3473
    return statement;
×
3474
  }
3475

3476
  @Override
3477
  public Statement visitShowPathsUsingSchemaTemplate(
3478
      IoTDBSqlParser.ShowPathsUsingSchemaTemplateContext ctx) {
3479
    PartialPath pathPattern;
3480
    if (ctx.prefixPath() == null) {
×
3481
      pathPattern = new PartialPath(SqlConstant.getSingleRootArray());
×
3482
    } else {
3483
      pathPattern = parsePrefixPath(ctx.prefixPath());
×
3484
    }
3485
    return new ShowPathsUsingTemplateStatement(
×
3486
        pathPattern, parseIdentifier(ctx.templateName.getText()));
×
3487
  }
3488

3489
  @Override
3490
  public Statement visitDropTimeseriesOfSchemaTemplate(
3491
      IoTDBSqlParser.DropTimeseriesOfSchemaTemplateContext ctx) {
3492
    DeactivateTemplateStatement statement = new DeactivateTemplateStatement();
×
3493
    if (ctx.templateName != null) {
×
3494
      statement.setTemplateName(parseIdentifier(ctx.templateName.getText()));
×
3495
    }
3496
    List<PartialPath> pathPatternList = new ArrayList<>();
×
3497
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
3498
      pathPatternList.add(parsePrefixPath(prefixPathContext));
×
3499
    }
×
3500
    statement.setPathPatternList(pathPatternList);
×
3501
    return statement;
×
3502
  }
3503

3504
  @Override
3505
  public Statement visitUnsetSchemaTemplate(IoTDBSqlParser.UnsetSchemaTemplateContext ctx) {
3506
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3507
    PartialPath path = parsePrefixPath(ctx.prefixPath());
×
3508
    return new UnsetSchemaTemplateStatement(templateName, path);
×
3509
  }
3510

3511
  @Override
3512
  public Statement visitDropSchemaTemplate(IoTDBSqlParser.DropSchemaTemplateContext ctx) {
3513
    return new DropSchemaTemplateStatement(parseIdentifier(ctx.templateName.getText()));
×
3514
  }
3515

3516
  public Map<String, String> parseSyncAttributeClauses(
3517
      IoTDBSqlParser.SyncAttributeClausesContext ctx) {
3518

3519
    Map<String, String> attributes = new HashMap<>();
×
3520

3521
    List<IoTDBSqlParser.AttributePairContext> attributePairs = ctx.attributePair();
×
3522
    if (ctx.attributePair(0) != null) {
×
3523
      for (IoTDBSqlParser.AttributePairContext attributePair : attributePairs) {
×
3524
        attributes.put(
×
3525
            parseAttributeKey(attributePair.attributeKey()).toLowerCase(),
×
3526
            parseAttributeValue(attributePair.attributeValue()).toLowerCase());
×
3527
      }
×
3528
    }
3529

3530
    return attributes;
×
3531
  }
3532

3533
  // PIPE
3534

3535
  @Override
3536
  public Statement visitCreatePipe(IoTDBSqlParser.CreatePipeContext ctx) {
3537
    final CreatePipeStatement createPipeStatement =
×
3538
        new CreatePipeStatement(StatementType.CREATE_PIPE);
3539

3540
    if (ctx.pipeName != null) {
×
3541
      createPipeStatement.setPipeName(ctx.pipeName.getText());
×
3542
    } else {
3543
      throw new SemanticException(
×
3544
          "Not support for this sql in CREATEPIPE, please enter pipe name.");
3545
    }
3546
    if (ctx.extractorAttributesClause() != null) {
×
3547
      createPipeStatement.setExtractorAttributes(
×
3548
          parseExtractorAttributesClause(ctx.extractorAttributesClause()));
×
3549
    } else {
3550
      createPipeStatement.setExtractorAttributes(new HashMap<>());
×
3551
    }
3552
    if (ctx.processorAttributesClause() != null) {
×
3553
      createPipeStatement.setProcessorAttributes(
×
3554
          parseProcessorAttributesClause(ctx.processorAttributesClause()));
×
3555
    } else {
3556
      createPipeStatement.setProcessorAttributes(new HashMap<>());
×
3557
    }
3558
    createPipeStatement.setConnectorAttributes(
×
3559
        parseConnectorAttributesClause(ctx.connectorAttributesClause()));
×
3560
    return createPipeStatement;
×
3561
  }
3562

3563
  private Map<String, String> parseExtractorAttributesClause(
3564
      IoTDBSqlParser.ExtractorAttributesClauseContext ctx) {
3565
    final Map<String, String> collectorMap = new HashMap<>();
×
3566
    for (IoTDBSqlParser.ExtractorAttributeClauseContext singleCtx :
3567
        ctx.extractorAttributeClause()) {
×
3568
      collectorMap.put(
×
3569
          parseStringLiteral(singleCtx.extractorKey.getText()),
×
3570
          parseStringLiteral(singleCtx.extractorValue.getText()));
×
3571
    }
×
3572
    return collectorMap;
×
3573
  }
3574

3575
  private Map<String, String> parseProcessorAttributesClause(
3576
      IoTDBSqlParser.ProcessorAttributesClauseContext ctx) {
3577
    final Map<String, String> processorMap = new HashMap<>();
×
3578
    for (IoTDBSqlParser.ProcessorAttributeClauseContext singleCtx :
3579
        ctx.processorAttributeClause()) {
×
3580
      processorMap.put(
×
3581
          parseStringLiteral(singleCtx.processorKey.getText()),
×
3582
          parseStringLiteral(singleCtx.processorValue.getText()));
×
3583
    }
×
3584
    return processorMap;
×
3585
  }
3586

3587
  private Map<String, String> parseConnectorAttributesClause(
3588
      IoTDBSqlParser.ConnectorAttributesClauseContext ctx) {
3589
    final Map<String, String> connectorMap = new HashMap<>();
×
3590
    for (IoTDBSqlParser.ConnectorAttributeClauseContext singleCtx :
3591
        ctx.connectorAttributeClause()) {
×
3592
      connectorMap.put(
×
3593
          parseStringLiteral(singleCtx.connectorKey.getText()),
×
3594
          parseStringLiteral(singleCtx.connectorValue.getText()));
×
3595
    }
×
3596
    return connectorMap;
×
3597
  }
3598

3599
  @Override
3600
  public Statement visitDropPipe(IoTDBSqlParser.DropPipeContext ctx) {
3601
    final DropPipeStatement dropPipeStatement = new DropPipeStatement(StatementType.DROP_PIPE);
×
3602

3603
    if (ctx.pipeName != null) {
×
3604
      dropPipeStatement.setPipeName(ctx.pipeName.getText());
×
3605
    } else {
3606
      throw new SemanticException("Not support for this sql in DROP PIPE, please enter pipename.");
×
3607
    }
3608

3609
    return dropPipeStatement;
×
3610
  }
3611

3612
  @Override
3613
  public Statement visitStartPipe(IoTDBSqlParser.StartPipeContext ctx) {
3614
    final StartPipeStatement startPipeStatement = new StartPipeStatement(StatementType.START_PIPE);
×
3615

3616
    if (ctx.pipeName != null) {
×
3617
      startPipeStatement.setPipeName(ctx.pipeName.getText());
×
3618
    } else {
3619
      throw new SemanticException("Not support for this sql in START PIPE, please enter pipename.");
×
3620
    }
3621

3622
    return startPipeStatement;
×
3623
  }
3624

3625
  @Override
3626
  public Statement visitStopPipe(IoTDBSqlParser.StopPipeContext ctx) {
3627
    final StopPipeStatement stopPipeStatement = new StopPipeStatement(StatementType.STOP_PIPE);
×
3628

3629
    if (ctx.pipeName != null) {
×
3630
      stopPipeStatement.setPipeName(ctx.pipeName.getText());
×
3631
    } else {
3632
      throw new SemanticException("Not support for this sql in STOP PIPE, please enter pipename.");
×
3633
    }
3634

3635
    return stopPipeStatement;
×
3636
  }
3637

3638
  @Override
3639
  public Statement visitShowPipes(IoTDBSqlParser.ShowPipesContext ctx) {
3640
    final ShowPipesStatement showPipesStatement = new ShowPipesStatement();
×
3641

3642
    if (ctx.pipeName != null) {
×
3643
      showPipesStatement.setPipeName(parseIdentifier(ctx.pipeName.getText()));
×
3644
    }
3645
    showPipesStatement.setWhereClause(ctx.CONNECTOR() != null);
×
3646

3647
    return showPipesStatement;
×
3648
  }
3649

3650
  @Override
3651
  public Statement visitGetRegionId(IoTDBSqlParser.GetRegionIdContext ctx) {
3652
    TConsensusGroupType type =
3653
        ctx.DATA() == null ? TConsensusGroupType.SchemaRegion : TConsensusGroupType.DataRegion;
×
3654
    GetRegionIdStatement getRegionIdStatement = new GetRegionIdStatement(type);
×
3655
    if (ctx.database != null) {
×
3656
      getRegionIdStatement.setDatabase(ctx.database.getText());
×
3657
    } else {
3658
      getRegionIdStatement.setDevice(ctx.device.getText());
×
3659
    }
3660
    if (ctx.time != null) {
×
3661
      long timestamp = parseTimeValue(ctx.time, DateTimeUtils.currentTime());
×
3662
      getRegionIdStatement.setTimeStamp(timestamp);
×
3663
    }
3664
    return getRegionIdStatement;
×
3665
  }
3666

3667
  @Override
3668
  public Statement visitGetSeriesSlotList(IoTDBSqlParser.GetSeriesSlotListContext ctx) {
3669
    TConsensusGroupType type =
3670
        ctx.DATA() == null ? TConsensusGroupType.SchemaRegion : TConsensusGroupType.DataRegion;
×
3671
    return new GetSeriesSlotListStatement(ctx.database.getText(), type);
×
3672
  }
3673

3674
  @Override
3675
  public Statement visitGetTimeSlotList(IoTDBSqlParser.GetTimeSlotListContext ctx) {
3676
    GetTimeSlotListStatement getTimeSlotListStatement = new GetTimeSlotListStatement();
×
3677
    if (ctx.database != null) {
×
3678
      getTimeSlotListStatement.setDatabase(ctx.database.getText());
×
3679
    } else if (ctx.device != null) {
×
3680
      getTimeSlotListStatement.setDevice(ctx.device.getText());
×
3681
    } else if (ctx.regionId != null) {
×
3682
      getTimeSlotListStatement.setRegionId(Integer.parseInt(ctx.regionId.getText()));
×
3683
    }
3684
    if (ctx.startTime != null) {
×
3685
      long timestamp = parseTimeValue(ctx.startTime, DateTimeUtils.currentTime());
×
3686
      getTimeSlotListStatement.setStartTime(timestamp);
×
3687
    }
3688
    if (ctx.endTime != null) {
×
3689
      long timestamp = parseTimeValue(ctx.endTime, DateTimeUtils.currentTime());
×
3690
      getTimeSlotListStatement.setEndTime(timestamp);
×
3691
    }
3692
    return getTimeSlotListStatement;
×
3693
  }
3694

3695
  @Override
3696
  public Statement visitCountTimeSlotList(IoTDBSqlParser.CountTimeSlotListContext ctx) {
3697
    CountTimeSlotListStatement countTimeSlotListStatement = new CountTimeSlotListStatement();
×
3698
    if (ctx.database != null) {
×
3699
      countTimeSlotListStatement.setDatabase(ctx.database.getText());
×
3700
    } else if (ctx.device != null) {
×
3701
      countTimeSlotListStatement.setDevice(ctx.device.getText());
×
3702
    } else if (ctx.regionId != null) {
×
3703
      countTimeSlotListStatement.setRegionId(Integer.parseInt(ctx.regionId.getText()));
×
3704
    }
3705
    if (ctx.startTime != null) {
×
3706
      countTimeSlotListStatement.setStartTime(Long.parseLong(ctx.startTime.getText()));
×
3707
    }
3708
    if (ctx.endTime != null) {
×
3709
      countTimeSlotListStatement.setEndTime(Long.parseLong(ctx.endTime.getText()));
×
3710
    }
3711
    return countTimeSlotListStatement;
×
3712
  }
3713

3714
  @Override
3715
  public Statement visitMigrateRegion(IoTDBSqlParser.MigrateRegionContext ctx) {
3716
    return new MigrateRegionStatement(
×
3717
        Integer.parseInt(ctx.regionId.getText()),
×
3718
        Integer.parseInt(ctx.fromId.getText()),
×
3719
        Integer.parseInt(ctx.toId.getText()));
×
3720
  }
3721

3722
  // Quota
3723
  @Override
3724
  public Statement visitSetSpaceQuota(IoTDBSqlParser.SetSpaceQuotaContext ctx) {
3725
    if (!IoTDBDescriptor.getInstance().getConfig().isQuotaEnable()) {
×
3726
      throw new SemanticException(LIMIT_CONFIGURATION_ENABLED_ERROR_MSG);
×
3727
    }
3728
    SetSpaceQuotaStatement setSpaceQuotaStatement = new SetSpaceQuotaStatement();
×
3729
    List<IoTDBSqlParser.PrefixPathContext> prefixPathContexts = ctx.prefixPath();
×
3730
    List<String> paths = new ArrayList<>();
×
3731
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : prefixPathContexts) {
×
3732
      paths.add(parsePrefixPath(prefixPathContext).getFullPath());
×
3733
    }
×
3734
    setSpaceQuotaStatement.setPrefixPathList(paths);
×
3735

3736
    Map<String, String> quotas = new HashMap<>();
×
3737
    for (IoTDBSqlParser.AttributePairContext attributePair : ctx.attributePair()) {
×
3738
      quotas.put(
×
3739
          parseAttributeKey(attributePair.attributeKey()),
×
3740
          parseAttributeValue(attributePair.attributeValue()));
×
3741
    }
×
3742

3743
    quotas
×
3744
        .keySet()
×
3745
        .forEach(
×
3746
            quotaType -> {
3747
              switch (quotaType) {
×
3748
                case IoTDBConstant.COLUMN_DEVICES:
3749
                  break;
×
3750
                case IoTDBConstant.COLUMN_TIMESERIES:
3751
                  break;
×
3752
                case IoTDBConstant.SPACE_QUOTA_DISK:
3753
                  break;
×
3754
                default:
3755
                  throw new SemanticException("Wrong space quota type: " + quotaType);
×
3756
              }
3757
            });
×
3758

3759
    if (quotas.containsKey(IoTDBConstant.COLUMN_DEVICES)) {
×
3760
      if (quotas.get(IoTDBConstant.COLUMN_DEVICES).equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3761
        setSpaceQuotaStatement.setDeviceNum(IoTDBConstant.UNLIMITED_VALUE);
×
3762
      } else if (Long.parseLong(quotas.get(IoTDBConstant.COLUMN_DEVICES)) <= 0) {
×
3763
        throw new SemanticException("Please set the number of devices greater than 0");
×
3764
      } else {
3765
        setSpaceQuotaStatement.setDeviceNum(
×
3766
            Long.parseLong(quotas.get(IoTDBConstant.COLUMN_DEVICES)));
×
3767
      }
3768
    }
3769
    if (quotas.containsKey(IoTDBConstant.COLUMN_TIMESERIES)) {
×
3770
      if (quotas.get(IoTDBConstant.COLUMN_TIMESERIES).equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3771
        setSpaceQuotaStatement.setTimeSeriesNum(IoTDBConstant.UNLIMITED_VALUE);
×
3772
      } else if (Long.parseLong(quotas.get(IoTDBConstant.COLUMN_TIMESERIES)) <= 0) {
×
3773
        throw new SemanticException("Please set the number of timeseries greater than 0");
×
3774
      } else {
3775
        setSpaceQuotaStatement.setTimeSeriesNum(
×
3776
            Long.parseLong(quotas.get(IoTDBConstant.COLUMN_TIMESERIES)));
×
3777
      }
3778
    }
3779
    if (quotas.containsKey(IoTDBConstant.SPACE_QUOTA_DISK)) {
×
3780
      if (quotas.get(IoTDBConstant.SPACE_QUOTA_DISK).equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3781
        setSpaceQuotaStatement.setDiskSize(IoTDBConstant.UNLIMITED_VALUE);
×
3782
      } else {
3783
        setSpaceQuotaStatement.setDiskSize(
×
3784
            parseSpaceQuotaSizeUnit(quotas.get(IoTDBConstant.SPACE_QUOTA_DISK)));
×
3785
      }
3786
    }
3787
    return setSpaceQuotaStatement;
×
3788
  }
3789

3790
  @Override
3791
  public Statement visitSetThrottleQuota(IoTDBSqlParser.SetThrottleQuotaContext ctx) {
3792
    if (!IoTDBDescriptor.getInstance().getConfig().isQuotaEnable()) {
×
3793
      throw new SemanticException(LIMIT_CONFIGURATION_ENABLED_ERROR_MSG);
×
3794
    }
3795
    if (parseIdentifier(ctx.userName.getText()).equals(IoTDBConstant.PATH_ROOT)) {
×
3796
      throw new SemanticException("Cannot set throttle quota for user root.");
×
3797
    }
3798
    SetThrottleQuotaStatement setThrottleQuotaStatement = new SetThrottleQuotaStatement();
×
3799
    setThrottleQuotaStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
3800
    Map<String, String> quotas = new HashMap<>();
×
3801
    Map<ThrottleType, TTimedQuota> throttleLimit = new HashMap<>();
×
3802
    for (IoTDBSqlParser.AttributePairContext attributePair : ctx.attributePair()) {
×
3803
      quotas.put(
×
3804
          parseAttributeKey(attributePair.attributeKey()),
×
3805
          parseAttributeValue(attributePair.attributeValue()));
×
3806
    }
×
3807
    if (quotas.containsKey(IoTDBConstant.REQUEST_NUM_PER_UNIT_TIME)) {
×
3808
      TTimedQuota timedQuota;
3809
      String request = quotas.get(IoTDBConstant.REQUEST_NUM_PER_UNIT_TIME);
×
3810
      if (request.equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3811
        timedQuota = new TTimedQuota(IoTDBConstant.SEC, Long.MAX_VALUE);
×
3812
      } else {
3813
        String[] split = request.toLowerCase().split(IoTDBConstant.REQ_SPLIT_UNIT);
×
3814
        if (Long.parseLong(split[0]) < 0) {
×
3815
          throw new SemanticException("Please set the number of requests greater than 0");
×
3816
        }
3817
        timedQuota =
×
3818
            new TTimedQuota(parseThrottleQuotaTimeUnit(split[1]), Long.parseLong(split[0]));
×
3819
      }
3820
      if (quotas.get(IoTDBConstant.REQUEST_TYPE) == null) {
×
3821
        throttleLimit.put(ThrottleType.REQUEST_NUMBER, timedQuota);
×
3822
      } else {
3823
        switch (quotas.get(IoTDBConstant.REQUEST_TYPE)) {
×
3824
          case IoTDBConstant.REQUEST_TYPE_READ:
3825
            throttleLimit.put(ThrottleType.READ_NUMBER, timedQuota);
×
3826
            break;
×
3827
          case IoTDBConstant.REQUEST_TYPE_WRITE:
3828
            throttleLimit.put(ThrottleType.WRITE_NUMBER, timedQuota);
×
3829
            break;
×
3830
          default:
3831
            throw new SemanticException(
×
3832
                "Please set the correct request type: " + quotas.get(IoTDBConstant.REQUEST_TYPE));
×
3833
        }
3834
      }
3835
    }
3836

3837
    if (quotas.containsKey(IoTDBConstant.REQUEST_SIZE_PER_UNIT_TIME)) {
×
3838
      TTimedQuota timedQuota;
3839
      String size = quotas.get(IoTDBConstant.REQUEST_SIZE_PER_UNIT_TIME);
×
3840
      if (size.equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3841
        timedQuota = new TTimedQuota(IoTDBConstant.SEC, Long.MAX_VALUE);
×
3842
      } else {
3843
        String[] split = size.toLowerCase().split("/");
×
3844
        timedQuota =
×
3845
            new TTimedQuota(
3846
                parseThrottleQuotaTimeUnit(split[1]), parseThrottleQuotaSizeUnit(split[0]));
×
3847
      }
3848
      if (quotas.get(IoTDBConstant.REQUEST_TYPE) == null) {
×
3849
        throttleLimit.put(ThrottleType.REQUEST_SIZE, timedQuota);
×
3850
      } else {
3851
        switch (quotas.get(IoTDBConstant.REQUEST_TYPE)) {
×
3852
          case IoTDBConstant.REQUEST_TYPE_READ:
3853
            throttleLimit.put(ThrottleType.READ_SIZE, timedQuota);
×
3854
            break;
×
3855
          case IoTDBConstant.REQUEST_TYPE_WRITE:
3856
            throttleLimit.put(ThrottleType.WRITE_SIZE, timedQuota);
×
3857
            break;
×
3858
          default:
3859
            throw new SemanticException(
×
3860
                "Please set the correct request type: " + quotas.get(IoTDBConstant.REQUEST_TYPE));
×
3861
        }
3862
      }
3863
    }
3864

3865
    if (quotas.containsKey(IoTDBConstant.MEMORY_SIZE_PER_READ)) {
×
3866
      String mem = quotas.get(IoTDBConstant.MEMORY_SIZE_PER_READ);
×
3867
      if (mem.equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3868
        setThrottleQuotaStatement.setMemLimit(IoTDBConstant.UNLIMITED_VALUE);
×
3869
      } else {
3870
        setThrottleQuotaStatement.setMemLimit(parseThrottleQuotaSizeUnit(mem));
×
3871
      }
3872
    }
3873

3874
    if (quotas.containsKey(IoTDBConstant.CPU_NUMBER_PER_READ)) {
×
3875
      String cpuLimit = quotas.get(IoTDBConstant.CPU_NUMBER_PER_READ);
×
3876
      if (cpuLimit.contains(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3877
        setThrottleQuotaStatement.setCpuLimit(IoTDBConstant.UNLIMITED_VALUE);
×
3878
      } else {
3879
        int cpuNum = Integer.parseInt(cpuLimit);
×
3880
        if (cpuNum <= 0) {
×
3881
          throw new SemanticException("Please set the number of cpu greater than 0");
×
3882
        }
3883
        setThrottleQuotaStatement.setCpuLimit(cpuNum);
×
3884
      }
3885
    }
3886
    setThrottleQuotaStatement.setThrottleLimit(throttleLimit);
×
3887
    return setThrottleQuotaStatement;
×
3888
  }
3889

3890
  @Override
3891
  public Statement visitShowThrottleQuota(IoTDBSqlParser.ShowThrottleQuotaContext ctx) {
3892
    if (!IoTDBDescriptor.getInstance().getConfig().isQuotaEnable()) {
×
3893
      throw new SemanticException(LIMIT_CONFIGURATION_ENABLED_ERROR_MSG);
×
3894
    }
3895
    ShowThrottleQuotaStatement showThrottleQuotaStatement = new ShowThrottleQuotaStatement();
×
3896
    if (ctx.userName != null) {
×
3897
      showThrottleQuotaStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
3898
    }
3899
    return showThrottleQuotaStatement;
×
3900
  }
3901

3902
  private long parseThrottleQuotaTimeUnit(String timeUnit) {
3903
    switch (timeUnit.toLowerCase()) {
×
3904
      case IoTDBConstant.SEC_UNIT:
3905
        return IoTDBConstant.SEC;
×
3906
      case IoTDBConstant.MIN_UNIT:
3907
        return IoTDBConstant.MIN;
×
3908
      case IoTDBConstant.HOUR_UNIT:
3909
        return IoTDBConstant.HOUR;
×
3910
      case IoTDBConstant.DAY_UNIT:
3911
        return IoTDBConstant.DAY;
×
3912
      default:
3913
        throw new SemanticException(
×
3914
            "When setting the request, the unit is incorrect. Please use 'sec', 'min', 'hour', 'day' as the unit");
3915
    }
3916
  }
3917

3918
  private long parseThrottleQuotaSizeUnit(String data) {
3919
    String unit = data.substring(data.length() - 1);
×
3920
    long size = Long.parseLong(data.substring(0, data.length() - 1));
×
3921
    if (size <= 0) {
×
3922
      throw new SemanticException("Please set the size greater than 0");
×
3923
    }
3924
    switch (unit.toUpperCase()) {
×
3925
      case IoTDBConstant.B_UNIT:
3926
        return size;
×
3927
      case IoTDBConstant.KB_UNIT:
3928
        return size * IoTDBConstant.KB;
×
3929
      case IoTDBConstant.MB_UNIT:
3930
        return size * IoTDBConstant.MB;
×
3931
      case IoTDBConstant.GB_UNIT:
3932
        return size * IoTDBConstant.GB;
×
3933
      case IoTDBConstant.TB_UNIT:
3934
        return size * IoTDBConstant.TB;
×
3935
      case IoTDBConstant.PB_UNIT:
3936
        return size * IoTDBConstant.PB;
×
3937
      default:
3938
        throw new SemanticException(
×
3939
            "When setting the size/time, the unit is incorrect. Please use 'B', 'K', 'M', 'G', 'P', 'T' as the unit");
3940
    }
3941
  }
3942

3943
  private long parseSpaceQuotaSizeUnit(String data) {
3944
    String unit = data.substring(data.length() - 1);
×
3945
    long disk = Long.parseLong(data.substring(0, data.length() - 1));
×
3946
    if (disk <= 0) {
×
3947
      throw new SemanticException("Please set the disk size greater than 0");
×
3948
    }
3949
    switch (unit.toUpperCase()) {
×
3950
      case IoTDBConstant.MB_UNIT:
3951
        return disk;
×
3952
      case IoTDBConstant.GB_UNIT:
3953
        return disk * IoTDBConstant.KB;
×
3954
      case IoTDBConstant.TB_UNIT:
3955
        return disk * IoTDBConstant.MB;
×
3956
      case IoTDBConstant.PB_UNIT:
3957
        return disk * IoTDBConstant.GB;
×
3958
      default:
3959
        throw new SemanticException(
×
3960
            "When setting the disk size, the unit is incorrect. Please use 'M', 'G', 'P', 'T' as the unit");
3961
    }
3962
  }
3963

3964
  @Override
3965
  public Statement visitShowSpaceQuota(IoTDBSqlParser.ShowSpaceQuotaContext ctx) {
3966
    if (!IoTDBDescriptor.getInstance().getConfig().isQuotaEnable()) {
×
3967
      throw new SemanticException(LIMIT_CONFIGURATION_ENABLED_ERROR_MSG);
×
3968
    }
3969
    ShowSpaceQuotaStatement showSpaceQuotaStatement = new ShowSpaceQuotaStatement();
×
3970
    if (ctx.prefixPath() != null) {
×
3971
      List<PartialPath> databases = new ArrayList<>();
×
3972
      for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
3973
        databases.add(parsePrefixPath(prefixPathContext));
×
3974
      }
×
3975
      showSpaceQuotaStatement.setDatabases(databases);
×
3976
    } else {
×
3977
      showSpaceQuotaStatement.setDatabases(null);
×
3978
    }
3979
    return showSpaceQuotaStatement;
×
3980
  }
3981
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc