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

apache / iotdb / #10010

06 Sep 2023 08:07AM UTC coverage: 47.643% (+0.03%) from 47.611%
#10010

push

travis_ci

web-flow
[IOTDB-6138] Fix the support of negative timestamp (#11033)

75 of 75 new or added lines in 18 files covered. (100.0%)

80513 of 168994 relevant lines covered (47.64%)

0.48 hits per line

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

27.86
/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.commons.schema.SchemaConstant.ALL_RESULT_NODES;
229
import static org.apache.iotdb.db.queryengine.plan.optimization.LimitOffsetPushDown.canPushDownLimitOffsetToGroupByTime;
230
import static org.apache.iotdb.db.queryengine.plan.optimization.LimitOffsetPushDown.pushDownLimitOffsetToTimeParameter;
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 (!PrivilegeType.valueOf(privilege.toUpperCase()).isPathRelevant()) {
×
2282
        pathRelevant = false;
×
2283
        errorPrivilegeName = privilege.toUpperCase();
×
2284
        break;
×
2285
      }
2286
    }
2287
    if (!(pathRelevant
×
2288
        || (nodeNameList.size() == 1
×
2289
            && nodeNameList.contains(new PartialPath(ALL_RESULT_NODES))))) {
×
2290
      throw new SemanticException(
×
2291
          String.format(
×
2292
              "path independent privilege: [%s] can only be set on path: root.**",
2293
              errorPrivilegeName));
2294
    }
2295
  }
×
2296

2297
  // Revoke Role From User
2298

2299
  @Override
2300
  public Statement visitRevokeRoleFromUser(IoTDBSqlParser.RevokeRoleFromUserContext ctx) {
2301
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.REVOKE_USER_ROLE);
×
2302
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2303
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2304
    return authorStatement;
×
2305
  }
2306

2307
  // Drop User
2308

2309
  @Override
2310
  public Statement visitDropUser(IoTDBSqlParser.DropUserContext ctx) {
2311
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.DROP_USER);
×
2312
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2313
    return authorStatement;
×
2314
  }
2315

2316
  // Drop Role
2317

2318
  @Override
2319
  public Statement visitDropRole(IoTDBSqlParser.DropRoleContext ctx) {
2320
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.DROP_ROLE);
×
2321
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2322
    return authorStatement;
×
2323
  }
2324

2325
  // List Users
2326

2327
  @Override
2328
  public Statement visitListUser(IoTDBSqlParser.ListUserContext ctx) {
2329
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_USER);
×
2330
    if (ctx.roleName != null) {
×
2331
      authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2332
    }
2333
    return authorStatement;
×
2334
  }
2335

2336
  // List Roles
2337

2338
  @Override
2339
  public Statement visitListRole(IoTDBSqlParser.ListRoleContext ctx) {
2340
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_ROLE);
×
2341
    if (ctx.userName != null) {
×
2342
      authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2343
    }
2344
    return authorStatement;
×
2345
  }
2346

2347
  // List Privileges
2348

2349
  @Override
2350
  public Statement visitListPrivilegesUser(IoTDBSqlParser.ListPrivilegesUserContext ctx) {
2351
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_USER_PRIVILEGE);
×
2352
    authorStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
2353
    List<PartialPath> nodeNameList =
×
2354
        ctx.prefixPath().stream().map(this::parsePrefixPath).collect(Collectors.toList());
×
2355
    authorStatement.setNodeNameList(nodeNameList);
×
2356
    return authorStatement;
×
2357
  }
2358

2359
  // List Privileges of Roles On Specific Path
2360

2361
  @Override
2362
  public Statement visitListPrivilegesRole(IoTDBSqlParser.ListPrivilegesRoleContext ctx) {
2363
    AuthorStatement authorStatement = new AuthorStatement(AuthorType.LIST_ROLE_PRIVILEGE);
×
2364
    authorStatement.setRoleName(parseIdentifier(ctx.roleName.getText()));
×
2365
    List<PartialPath> nodeNameList =
×
2366
        ctx.prefixPath().stream().map(this::parsePrefixPath).collect(Collectors.toList());
×
2367
    authorStatement.setNodeNameList(nodeNameList);
×
2368
    return authorStatement;
×
2369
  }
2370

2371
  private String[] parsePrivilege(IoTDBSqlParser.PrivilegesContext ctx) {
2372
    List<IoTDBSqlParser.PrivilegeValueContext> privilegeList = ctx.privilegeValue();
×
2373
    List<String> privileges = new ArrayList<>();
×
2374
    for (IoTDBSqlParser.PrivilegeValueContext privilegeValue : privilegeList) {
×
2375
      privileges.add(privilegeValue.getText());
×
2376
    }
×
2377
    return privileges.toArray(new String[0]);
×
2378
  }
2379

2380
  // Create database
2381
  @Override
2382
  public Statement visitCreateDatabase(IoTDBSqlParser.CreateDatabaseContext ctx) {
2383
    DatabaseSchemaStatement databaseSchemaStatement =
×
2384
        new DatabaseSchemaStatement(DatabaseSchemaStatement.DatabaseSchemaStatementType.CREATE);
2385
    PartialPath path = parsePrefixPath(ctx.prefixPath());
×
2386
    databaseSchemaStatement.setDatabasePath(path);
×
2387
    if (ctx.databaseAttributesClause() != null) {
×
2388
      parseDatabaseAttributesClause(databaseSchemaStatement, ctx.databaseAttributesClause());
×
2389
    }
2390
    return databaseSchemaStatement;
×
2391
  }
2392

2393
  @Override
2394
  public Statement visitAlterDatabase(IoTDBSqlParser.AlterDatabaseContext ctx) {
2395
    DatabaseSchemaStatement databaseSchemaStatement =
×
2396
        new DatabaseSchemaStatement(DatabaseSchemaStatement.DatabaseSchemaStatementType.ALTER);
2397
    PartialPath path = parsePrefixPath(ctx.prefixPath());
×
2398
    databaseSchemaStatement.setDatabasePath(path);
×
2399
    parseDatabaseAttributesClause(databaseSchemaStatement, ctx.databaseAttributesClause());
×
2400
    return databaseSchemaStatement;
×
2401
  }
2402

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

2430
  @Override
2431
  public Statement visitSetTTL(IoTDBSqlParser.SetTTLContext ctx) {
2432
    SetTTLStatement setTTLStatement = new SetTTLStatement();
1✔
2433
    PartialPath path = parsePrefixPath(ctx.prefixPath());
1✔
2434
    long ttl = Long.parseLong(ctx.INTEGER_LITERAL().getText());
1✔
2435
    setTTLStatement.setDatabasePath(path);
1✔
2436
    setTTLStatement.setTTL(ttl);
1✔
2437
    return setTTLStatement;
1✔
2438
  }
2439

2440
  @Override
2441
  public Statement visitUnsetTTL(IoTDBSqlParser.UnsetTTLContext ctx) {
2442
    UnSetTTLStatement unSetTTLStatement = new UnSetTTLStatement();
1✔
2443
    PartialPath partialPath = parsePrefixPath(ctx.prefixPath());
1✔
2444
    unSetTTLStatement.setDatabasePath(partialPath);
1✔
2445
    return unSetTTLStatement;
1✔
2446
  }
2447

2448
  @Override
2449
  public Statement visitShowTTL(IoTDBSqlParser.ShowTTLContext ctx) {
2450
    ShowTTLStatement showTTLStatement = new ShowTTLStatement();
1✔
2451
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
1✔
2452
      PartialPath partialPath = parsePrefixPath(prefixPathContext);
1✔
2453
      showTTLStatement.addPathPatterns(partialPath);
1✔
2454
    }
1✔
2455
    return showTTLStatement;
1✔
2456
  }
2457

2458
  @Override
2459
  public Statement visitShowAllTTL(IoTDBSqlParser.ShowAllTTLContext ctx) {
2460
    ShowTTLStatement showTTLStatement = new ShowTTLStatement();
1✔
2461
    showTTLStatement.setAll(true);
1✔
2462
    return showTTLStatement;
1✔
2463
  }
2464

2465
  @Override
2466
  public Statement visitShowVariables(IoTDBSqlParser.ShowVariablesContext ctx) {
2467
    return new ShowVariablesStatement();
×
2468
  }
2469

2470
  @Override
2471
  public Statement visitShowCluster(IoTDBSqlParser.ShowClusterContext ctx) {
2472
    ShowClusterStatement showClusterStatement = new ShowClusterStatement();
×
2473
    if (ctx.DETAILS() != null) {
×
2474
      showClusterStatement.setDetails(true);
×
2475
    }
2476
    return showClusterStatement;
×
2477
  }
2478

2479
  @Override
2480
  public Statement visitDropDatabase(IoTDBSqlParser.DropDatabaseContext ctx) {
2481
    DeleteDatabaseStatement dropDatabaseStatement = new DeleteDatabaseStatement();
×
2482
    List<IoTDBSqlParser.PrefixPathContext> prefixPathContexts = ctx.prefixPath();
×
2483
    List<String> paths = new ArrayList<>();
×
2484
    for (IoTDBSqlParser.PrefixPathContext prefixPathContext : prefixPathContexts) {
×
2485
      paths.add(parsePrefixPath(prefixPathContext).getFullPath());
×
2486
    }
×
2487
    dropDatabaseStatement.setPrefixPath(paths);
×
2488
    return dropDatabaseStatement;
×
2489
  }
2490

2491
  // Explain ========================================================================
2492
  @Override
2493
  public Statement visitExplain(IoTDBSqlParser.ExplainContext ctx) {
2494
    QueryStatement queryStatement = (QueryStatement) visitSelectStatement(ctx.selectStatement());
×
2495
    return new ExplainStatement(queryStatement);
×
2496
  }
2497

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

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

2543
  private TimeRange parseTimeRangeForDeleteTimeRange(
2544
      ExpressionType expressionType, Expression timeExpression, Expression valueExpression) {
2545
    if (!(timeExpression instanceof TimestampOperand)
×
2546
        || !(valueExpression instanceof ConstantOperand)) {
2547
      throw new SemanticException(DELETE_ONLY_SUPPORT_TIME_EXP_ERROR_MSG);
×
2548
    }
2549

2550
    if (((ConstantOperand) valueExpression).getDataType() != TSDataType.INT64) {
×
2551
      throw new SemanticException("The datatype of timestamp should be LONG.");
×
2552
    }
2553

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

2571
  /** function for parsing file path used by LOAD statement. */
2572
  public String parseFilePath(String src) {
2573
    return src.substring(1, src.length() - 1);
×
2574
  }
2575

2576
  // Expression & Predicate ========================================================================
2577

2578
  private Expression parseExpression(
2579
      IoTDBSqlParser.ExpressionContext context, boolean canUseFullPath) {
2580
    if (context.unaryInBracket != null) {
1✔
2581
      return parseExpression(context.unaryInBracket, canUseFullPath);
1✔
2582
    }
2583

2584
    if (context.expressionAfterUnaryOperator != null) {
1✔
2585
      if (context.MINUS() != null) {
×
2586
        return new NegationExpression(
×
2587
            parseExpression(context.expressionAfterUnaryOperator, canUseFullPath));
×
2588
      }
2589
      if (context.operator_not() != null) {
×
2590
        return new LogicNotExpression(
×
2591
            parseExpression(context.expressionAfterUnaryOperator, canUseFullPath));
×
2592
      }
2593
      return parseExpression(context.expressionAfterUnaryOperator, canUseFullPath);
×
2594
    }
2595

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

2641
    if (context.unaryBeforeRegularOrLikeExpression != null) {
1✔
2642
      if (context.REGEXP() != null) {
×
2643
        return parseRegularExpression(context, canUseFullPath);
×
2644
      }
2645
      if (context.LIKE() != null) {
×
2646
        return parseLikeExpression(context, canUseFullPath);
×
2647
      }
2648
      throw new UnsupportedOperationException();
×
2649
    }
2650

2651
    if (context.unaryBeforeIsNullExpression != null) {
1✔
2652
      return parseIsNullExpression(context, canUseFullPath);
×
2653
    }
2654

2655
    if (context.firstExpression != null
1✔
2656
        && context.secondExpression != null
2657
        && context.thirdExpression != null) {
2658
      Expression firstExpression = parseExpression(context.firstExpression, canUseFullPath);
×
2659
      Expression secondExpression = parseExpression(context.secondExpression, canUseFullPath);
×
2660
      Expression thirdExpression = parseExpression(context.thirdExpression, canUseFullPath);
×
2661

2662
      if (context.operator_between() != null) {
×
2663
        return new BetweenExpression(
×
2664
            firstExpression, secondExpression, thirdExpression, context.operator_not() != null);
×
2665
      }
2666
      throw new UnsupportedOperationException();
×
2667
    }
2668

2669
    if (context.unaryBeforeInExpression != null) {
1✔
2670
      return parseInExpression(context, canUseFullPath);
×
2671
    }
2672

2673
    if (context.scalarFunctionExpression() != null) {
1✔
2674
      return parseScalarFunctionExpression(context.scalarFunctionExpression(), canUseFullPath);
×
2675
    }
2676

2677
    if (context.functionName() != null) {
1✔
2678
      return parseFunctionExpression(context, canUseFullPath);
1✔
2679
    }
2680

2681
    if (context.fullPathInExpression() != null) {
1✔
2682
      return new TimeSeriesOperand(
1✔
2683
          parseFullPathInExpression(context.fullPathInExpression(), canUseFullPath));
1✔
2684
    }
2685

2686
    if (context.time != null) {
1✔
2687
      return new TimestampOperand();
1✔
2688
    }
2689

2690
    if (context.constant() != null && !context.constant().isEmpty()) {
1✔
2691
      return parseConstantOperand(context.constant(0));
1✔
2692
    }
2693

2694
    if (context.caseWhenThenExpression() != null) {
×
2695
      return parseCaseWhenThenExpression(context.caseWhenThenExpression(), canUseFullPath);
×
2696
    }
2697

2698
    throw new UnsupportedOperationException();
×
2699
  }
2700

2701
  private Expression parseScalarFunctionExpression(
2702
      IoTDBSqlParser.ScalarFunctionExpressionContext context, boolean canUseFullPath) {
2703
    if (context.CAST() != null) {
×
2704
      return parseCastFunction(context, canUseFullPath);
×
2705
    } else if (context.REPLACE() != null) {
×
2706
      return parseReplaceFunction(context, canUseFullPath);
×
2707
    } else if (context.ROUND() != null) {
×
2708
      return parseRoundFunction(context, canUseFullPath);
×
2709
    } else if (context.SUBSTRING() != null) {
×
2710
      return parseSubStrFunction(context, canUseFullPath);
×
2711
    }
2712
    throw new UnsupportedOperationException();
×
2713
  }
2714

2715
  private Expression parseCastFunction(
2716
      IoTDBSqlParser.ScalarFunctionExpressionContext castClause, boolean canUseFullPath) {
2717
    FunctionExpression functionExpression = new FunctionExpression(CAST_FUNCTION);
×
2718
    functionExpression.addExpression(parseExpression(castClause.castInput, canUseFullPath));
×
2719
    functionExpression.addAttribute(CAST_TYPE, parseAttributeValue(castClause.attributeValue()));
×
2720
    return functionExpression;
×
2721
  }
2722

2723
  private Expression parseReplaceFunction(
2724
      IoTDBSqlParser.ScalarFunctionExpressionContext replaceClause, boolean canUseFullPath) {
2725
    FunctionExpression functionExpression = new FunctionExpression(REPLACE_FUNCTION);
×
2726
    functionExpression.addExpression(parseExpression(replaceClause.text, canUseFullPath));
×
2727
    functionExpression.addAttribute(REPLACE_FROM, parseStringLiteral(replaceClause.from.getText()));
×
2728
    functionExpression.addAttribute(REPLACE_TO, parseStringLiteral(replaceClause.to.getText()));
×
2729
    return functionExpression;
×
2730
  }
2731

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

2755
  private Expression parseRoundFunction(
2756
      IoTDBSqlParser.ScalarFunctionExpressionContext roundClause, boolean canUseFullPath) {
2757
    FunctionExpression functionExpression = new FunctionExpression(ROUND_FUNCTION);
×
2758
    functionExpression.addExpression(parseExpression(roundClause.input, canUseFullPath));
×
2759
    if (roundClause.places != null) {
×
2760
      functionExpression.addAttribute(ROUND_PLACES, parseConstant(roundClause.constant()));
×
2761
    }
2762
    return functionExpression;
×
2763
  }
2764

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

2801
  private Expression parseFunctionExpression(
2802
      IoTDBSqlParser.ExpressionContext functionClause, boolean canUseFullPath) {
2803
    FunctionExpression functionExpression =
1✔
2804
        new FunctionExpression(parseIdentifier(functionClause.functionName().getText()));
1✔
2805

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

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

2842
    // check size of input expressions
2843
    // type check of input expressions is put in ExpressionTypeAnalyzer
2844
    if (functionExpression.isBuiltInAggregationFunctionExpression()) {
1✔
2845
      checkAggregationFunctionInput(functionExpression);
1✔
2846
    } else if (functionExpression.isBuiltInScalarFunction()) {
1✔
2847
      checkBuiltInScalarFunctionInput(functionExpression);
1✔
2848
    }
2849
    return functionExpression;
1✔
2850
  }
2851

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

2885
  private void checkBuiltInScalarFunctionInput(FunctionExpression functionExpression) {
2886
    BuiltInScalarFunctionHelperFactory.createHelper(functionExpression.getFunctionName())
1✔
2887
        .checkBuiltInScalarFunctionInputSize(functionExpression);
1✔
2888
  }
1✔
2889

2890
  public static void checkFunctionExpressionInputSize(
2891
      String expressionString, int actual, int... expected) {
2892
    for (int expect : expected) {
1✔
2893
      if (expect == actual) {
1✔
2894
        return;
1✔
2895
      }
2896
    }
2897
    throw new SemanticException(
×
2898
        String.format(
×
2899
            "Error size of input expressions. expression: %s, actual size: %s, expected size: %s.",
2900
            expressionString, actual, Arrays.toString(expected)));
×
2901
  }
2902

2903
  private Expression parseRegularExpression(ExpressionContext context, boolean canUseFullPath) {
2904
    return new RegularExpression(
×
2905
        parseExpression(context.unaryBeforeRegularOrLikeExpression, canUseFullPath),
×
2906
        parseStringLiteral(context.STRING_LITERAL().getText()));
×
2907
  }
2908

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

2915
  private Expression parseIsNullExpression(ExpressionContext context, boolean canUseFullPath) {
2916
    return new IsNullExpression(
×
2917
        parseExpression(context.unaryBeforeIsNullExpression, canUseFullPath),
×
2918
        context.operator_not() != null);
×
2919
  }
2920

2921
  private Expression parseInExpression(ExpressionContext context, boolean canUseFullPath) {
2922
    Expression childExpression = parseExpression(context.unaryBeforeInExpression, canUseFullPath);
×
2923
    LinkedHashSet<String> values = new LinkedHashSet<>();
×
2924
    for (ConstantContext constantContext : context.constant()) {
×
2925
      values.add(parseConstant(constantContext));
×
2926
    }
×
2927
    return new InExpression(childExpression, context.operator_not() != null, values);
×
2928
  }
2929

2930
  private String parseConstant(ConstantContext constantContext) {
2931
    String text = constantContext.getText();
×
2932
    if (constantContext.boolean_literal() != null
×
2933
        || constantContext.INTEGER_LITERAL() != null
×
2934
        || constantContext.realLiteral() != null) {
×
2935
      return text;
×
2936
    } else if (constantContext.STRING_LITERAL() != null) {
×
2937
      return parseStringLiteral(text);
×
2938
    } else if (constantContext.dateExpression() != null) {
×
2939
      return String.valueOf(parseDateExpression(constantContext.dateExpression()));
×
2940
    } else {
2941
      throw new IllegalArgumentException("Unsupported constant value: " + text);
×
2942
    }
2943
  }
2944

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

2963
  private Expression parseRealLiteral(String value) {
2964
    // 3.33 is float by default
2965
    return new ConstantOperand(
×
2966
        CONFIG.getFloatingStringInferType().equals(TSDataType.DOUBLE)
×
2967
            ? TSDataType.DOUBLE
×
2968
            : TSDataType.FLOAT,
×
2969
        value);
2970
  }
2971

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

2991
  private Long parseDateExpression(IoTDBSqlParser.DateExpressionContext ctx, long currentTime) {
2992
    long time;
2993
    time = parseDateFormat(ctx.getChild(0).getText(), currentTime);
×
2994
    for (int i = 1; i < ctx.getChildCount(); i = i + 2) {
×
2995
      if ("+".equals(ctx.getChild(i).getText())) {
×
2996
        time += DateTimeUtils.convertDurationStrToLong(time, ctx.getChild(i + 1).getText());
×
2997
      } else {
2998
        time -= DateTimeUtils.convertDurationStrToLong(time, ctx.getChild(i + 1).getText());
×
2999
      }
3000
    }
3001
    return time;
×
3002
  }
3003

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

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

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

3060
  private String parseAttributeKey(IoTDBSqlParser.AttributeKeyContext ctx) {
3061
    if (ctx.constant() != null) {
1✔
3062
      return parseStringLiteral(ctx.getText());
1✔
3063
    }
3064
    return parseIdentifier(ctx.getText());
×
3065
  }
3066

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

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

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

3095
  // Flush
3096

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

3118
  // Clear Cache
3119

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

3130
  // Load Configuration
3131

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

3144
  // Set System Status
3145

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

3164
  // Kill Query
3165
  @Override
3166
  public Statement visitKillQuery(IoTDBSqlParser.KillQueryContext ctx) {
3167
    if (ctx.queryId != null) {
×
3168
      return new KillQueryStatement(parseStringLiteral(ctx.queryId.getText()));
×
3169
    }
3170
    return new KillQueryStatement();
×
3171
  }
3172

3173
  // show query processlist
3174

3175
  @Override
3176
  public Statement visitShowQueries(IoTDBSqlParser.ShowQueriesContext ctx) {
3177
    ShowQueriesStatement showQueriesStatement = new ShowQueriesStatement();
×
3178
    // parse WHERE
3179
    if (ctx.whereClause() != null) {
×
3180
      showQueriesStatement.setWhereCondition(parseWhereClause(ctx.whereClause()));
×
3181
    }
3182

3183
    // parse ORDER BY
3184
    if (ctx.orderByClause() != null) {
×
3185
      showQueriesStatement.setOrderByComponent(
×
3186
          parseOrderByClause(
×
3187
              ctx.orderByClause(),
×
3188
              ImmutableSet.of(
×
3189
                  OrderByKey.TIME,
3190
                  OrderByKey.QUERYID,
3191
                  OrderByKey.DATANODEID,
3192
                  OrderByKey.ELAPSEDTIME,
3193
                  OrderByKey.STATEMENT)));
3194
    }
3195

3196
    // parse LIMIT & OFFSET
3197
    if (ctx.rowPaginationClause() != null) {
×
3198
      if (ctx.rowPaginationClause().limitClause() != null) {
×
3199
        showQueriesStatement.setRowLimit(parseLimitClause(ctx.rowPaginationClause().limitClause()));
×
3200
      }
3201
      if (ctx.rowPaginationClause().offsetClause() != null) {
×
3202
        showQueriesStatement.setRowOffset(
×
3203
            parseOffsetClause(ctx.rowPaginationClause().offsetClause()));
×
3204
      }
3205
    }
3206

3207
    showQueriesStatement.setZoneId(zoneId);
×
3208
    return showQueriesStatement;
×
3209
  }
3210

3211
  // show region
3212

3213
  @Override
3214
  public Statement visitShowRegions(IoTDBSqlParser.ShowRegionsContext ctx) {
3215
    ShowRegionStatement showRegionStatement = new ShowRegionStatement();
×
3216
    // TODO: Maybe add a show ConfigNode region in the future
3217
    if (ctx.DATA() != null) {
×
3218
      showRegionStatement.setRegionType(TConsensusGroupType.DataRegion);
×
3219
    } else if (ctx.SCHEMA() != null) {
×
3220
      showRegionStatement.setRegionType(TConsensusGroupType.SchemaRegion);
×
3221
    } else {
3222
      showRegionStatement.setRegionType(null);
×
3223
    }
3224

3225
    if (ctx.OF() != null) {
×
3226
      List<PartialPath> storageGroups = null;
×
3227
      if (ctx.prefixPath(0) != null) {
×
3228
        storageGroups = new ArrayList<>();
×
3229
        for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
3230
          storageGroups.add(parsePrefixPath(prefixPathContext));
×
3231
        }
×
3232
      }
3233
      showRegionStatement.setStorageGroups(storageGroups);
×
3234
    } else {
×
3235
      showRegionStatement.setStorageGroups(null);
×
3236
    }
3237

3238
    if (ctx.ON() != null) {
×
3239
      List<Integer> nodeIds = new ArrayList<>();
×
3240
      for (TerminalNode nodeid : ctx.INTEGER_LITERAL()) {
×
3241
        nodeIds.add(Integer.parseInt(nodeid.getText()));
×
3242
      }
×
3243
      showRegionStatement.setNodeIds(nodeIds);
×
3244
    } else {
×
3245
      showRegionStatement.setNodeIds(null);
×
3246
    }
3247
    return showRegionStatement;
×
3248
  }
3249

3250
  // show datanodes
3251

3252
  @Override
3253
  public Statement visitShowDataNodes(IoTDBSqlParser.ShowDataNodesContext ctx) {
3254
    return new ShowDataNodesStatement();
×
3255
  }
3256

3257
  // show confignodes
3258

3259
  @Override
3260
  public Statement visitShowConfigNodes(IoTDBSqlParser.ShowConfigNodesContext ctx) {
3261
    return new ShowConfigNodesStatement();
×
3262
  }
3263

3264
  // schema template
3265

3266
  @Override
3267
  public Statement visitCreateSchemaTemplate(IoTDBSqlParser.CreateSchemaTemplateContext ctx) {
3268
    String name = parseIdentifier(ctx.templateName.getText());
×
3269
    List<List<String>> measurementsList = new ArrayList<>();
×
3270
    List<List<TSDataType>> dataTypesList = new ArrayList<>();
×
3271
    List<List<TSEncoding>> encodingsList = new ArrayList<>();
×
3272
    List<List<CompressionType>> compressorsList = new ArrayList<>();
×
3273

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

3310
    return new CreateSchemaTemplateStatement(
×
3311
        name,
3312
        measurementsList,
3313
        dataTypesList,
3314
        encodingsList,
3315
        compressorsList,
3316
        ctx.ALIGNED() != null);
×
3317
  }
3318

3319
  @Override
3320
  public Statement visitAlterSchemaTemplate(IoTDBSqlParser.AlterSchemaTemplateContext ctx) {
3321
    String name = parseIdentifier(ctx.templateName.getText());
×
3322
    List<String> measurements = new ArrayList<>();
×
3323
    List<TSDataType> dataTypes = new ArrayList<>();
×
3324
    List<TSEncoding> encodings = new ArrayList<>();
×
3325
    List<CompressionType> compressors = new ArrayList<>();
×
3326

3327
    for (IoTDBSqlParser.TemplateMeasurementClauseContext templateClauseContext :
3328
        ctx.templateMeasurementClause()) {
×
3329
      measurements.add(
×
3330
          parseNodeNameWithoutWildCard(templateClauseContext.nodeNameWithoutWildcard()));
×
3331
      parseAttributeClauseForSchemaTemplate(
×
3332
          templateClauseContext.attributeClauses(), dataTypes, encodings, compressors);
×
3333
    }
×
3334

3335
    return new AlterSchemaTemplateStatement(
×
3336
        name,
3337
        measurements,
3338
        dataTypes,
3339
        encodings,
3340
        compressors,
3341
        TemplateAlterOperationType.EXTEND_TEMPLATE);
3342
  }
3343

3344
  void parseAttributeClauseForSchemaTemplate(
3345
      IoTDBSqlParser.AttributeClausesContext ctx,
3346
      List<TSDataType> dataTypes,
3347
      List<TSEncoding> encodings,
3348
      List<CompressionType> compressors) {
3349
    if (ctx.aliasNodeName() != null) {
×
3350
      throw new SemanticException("Schema template: alias is not supported yet.");
×
3351
    }
3352

3353
    TSDataType dataType = parseDataTypeAttribute(ctx);
×
3354
    dataTypes.add(dataType);
×
3355

3356
    Map<String, String> props = new HashMap<>();
×
3357
    if (ctx.attributePair() != null) {
×
3358
      for (int i = 0; i < ctx.attributePair().size(); i++) {
×
3359
        props.put(
×
3360
            parseAttributeKey(ctx.attributePair(i).attributeKey()).toLowerCase(),
×
3361
            parseAttributeValue(ctx.attributePair(i).attributeValue()));
×
3362
      }
3363
    }
3364

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

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

3406
    if (props.size() > 0) {
×
3407
      throw new SemanticException("Schema template: property is not supported yet.");
×
3408
    }
3409

3410
    if (ctx.tagClause() != null) {
×
3411
      throw new SemanticException("Schema template: tag is not supported yet.");
×
3412
    }
3413

3414
    if (ctx.attributeClause() != null) {
×
3415
      throw new SemanticException("Schema template: attribute is not supported yet.");
×
3416
    }
3417
  }
×
3418

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

3437
  @Override
3438
  public Statement visitShowSchemaTemplates(IoTDBSqlParser.ShowSchemaTemplatesContext ctx) {
3439
    return new ShowSchemaTemplateStatement();
×
3440
  }
3441

3442
  @Override
3443
  public Statement visitShowNodesInSchemaTemplate(
3444
      IoTDBSqlParser.ShowNodesInSchemaTemplateContext ctx) {
3445
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3446
    return new ShowNodesInSchemaTemplateStatement(templateName);
×
3447
  }
3448

3449
  @Override
3450
  public Statement visitSetSchemaTemplate(IoTDBSqlParser.SetSchemaTemplateContext ctx) {
3451
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3452
    return new SetSchemaTemplateStatement(templateName, parsePrefixPath(ctx.prefixPath()));
×
3453
  }
3454

3455
  @Override
3456
  public Statement visitShowPathsSetSchemaTemplate(
3457
      IoTDBSqlParser.ShowPathsSetSchemaTemplateContext ctx) {
3458
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3459
    return new ShowPathSetTemplateStatement(templateName);
×
3460
  }
3461

3462
  @Override
3463
  public Statement visitCreateTimeseriesUsingSchemaTemplate(
3464
      IoTDBSqlParser.CreateTimeseriesUsingSchemaTemplateContext ctx) {
3465
    ActivateTemplateStatement statement = new ActivateTemplateStatement();
×
3466
    statement.setPath(parsePrefixPath(ctx.prefixPath()));
×
3467
    return statement;
×
3468
  }
3469

3470
  @Override
3471
  public Statement visitShowPathsUsingSchemaTemplate(
3472
      IoTDBSqlParser.ShowPathsUsingSchemaTemplateContext ctx) {
3473
    PartialPath pathPattern;
3474
    if (ctx.prefixPath() == null) {
×
3475
      pathPattern = new PartialPath(SqlConstant.getSingleRootArray());
×
3476
    } else {
3477
      pathPattern = parsePrefixPath(ctx.prefixPath());
×
3478
    }
3479
    return new ShowPathsUsingTemplateStatement(
×
3480
        pathPattern, parseIdentifier(ctx.templateName.getText()));
×
3481
  }
3482

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

3498
  @Override
3499
  public Statement visitUnsetSchemaTemplate(IoTDBSqlParser.UnsetSchemaTemplateContext ctx) {
3500
    String templateName = parseIdentifier(ctx.templateName.getText());
×
3501
    PartialPath path = parsePrefixPath(ctx.prefixPath());
×
3502
    return new UnsetSchemaTemplateStatement(templateName, path);
×
3503
  }
3504

3505
  @Override
3506
  public Statement visitDropSchemaTemplate(IoTDBSqlParser.DropSchemaTemplateContext ctx) {
3507
    return new DropSchemaTemplateStatement(parseIdentifier(ctx.templateName.getText()));
×
3508
  }
3509

3510
  public Map<String, String> parseSyncAttributeClauses(
3511
      IoTDBSqlParser.SyncAttributeClausesContext ctx) {
3512

3513
    Map<String, String> attributes = new HashMap<>();
×
3514

3515
    List<IoTDBSqlParser.AttributePairContext> attributePairs = ctx.attributePair();
×
3516
    if (ctx.attributePair(0) != null) {
×
3517
      for (IoTDBSqlParser.AttributePairContext attributePair : attributePairs) {
×
3518
        attributes.put(
×
3519
            parseAttributeKey(attributePair.attributeKey()).toLowerCase(),
×
3520
            parseAttributeValue(attributePair.attributeValue()).toLowerCase());
×
3521
      }
×
3522
    }
3523

3524
    return attributes;
×
3525
  }
3526

3527
  // PIPE
3528

3529
  @Override
3530
  public Statement visitCreatePipe(IoTDBSqlParser.CreatePipeContext ctx) {
3531
    final CreatePipeStatement createPipeStatement =
×
3532
        new CreatePipeStatement(StatementType.CREATE_PIPE);
3533

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

3557
  private Map<String, String> parseExtractorAttributesClause(
3558
      IoTDBSqlParser.ExtractorAttributesClauseContext ctx) {
3559
    final Map<String, String> collectorMap = new HashMap<>();
×
3560
    for (IoTDBSqlParser.ExtractorAttributeClauseContext singleCtx :
3561
        ctx.extractorAttributeClause()) {
×
3562
      collectorMap.put(
×
3563
          parseStringLiteral(singleCtx.extractorKey.getText()),
×
3564
          parseStringLiteral(singleCtx.extractorValue.getText()));
×
3565
    }
×
3566
    return collectorMap;
×
3567
  }
3568

3569
  private Map<String, String> parseProcessorAttributesClause(
3570
      IoTDBSqlParser.ProcessorAttributesClauseContext ctx) {
3571
    final Map<String, String> processorMap = new HashMap<>();
×
3572
    for (IoTDBSqlParser.ProcessorAttributeClauseContext singleCtx :
3573
        ctx.processorAttributeClause()) {
×
3574
      processorMap.put(
×
3575
          parseStringLiteral(singleCtx.processorKey.getText()),
×
3576
          parseStringLiteral(singleCtx.processorValue.getText()));
×
3577
    }
×
3578
    return processorMap;
×
3579
  }
3580

3581
  private Map<String, String> parseConnectorAttributesClause(
3582
      IoTDBSqlParser.ConnectorAttributesClauseContext ctx) {
3583
    final Map<String, String> connectorMap = new HashMap<>();
×
3584
    for (IoTDBSqlParser.ConnectorAttributeClauseContext singleCtx :
3585
        ctx.connectorAttributeClause()) {
×
3586
      connectorMap.put(
×
3587
          parseStringLiteral(singleCtx.connectorKey.getText()),
×
3588
          parseStringLiteral(singleCtx.connectorValue.getText()));
×
3589
    }
×
3590
    return connectorMap;
×
3591
  }
3592

3593
  @Override
3594
  public Statement visitDropPipe(IoTDBSqlParser.DropPipeContext ctx) {
3595
    final DropPipeStatement dropPipeStatement = new DropPipeStatement(StatementType.DROP_PIPE);
×
3596

3597
    if (ctx.pipeName != null) {
×
3598
      dropPipeStatement.setPipeName(ctx.pipeName.getText());
×
3599
    } else {
3600
      throw new SemanticException("Not support for this sql in DROP PIPE, please enter pipename.");
×
3601
    }
3602

3603
    return dropPipeStatement;
×
3604
  }
3605

3606
  @Override
3607
  public Statement visitStartPipe(IoTDBSqlParser.StartPipeContext ctx) {
3608
    final StartPipeStatement startPipeStatement = new StartPipeStatement(StatementType.START_PIPE);
×
3609

3610
    if (ctx.pipeName != null) {
×
3611
      startPipeStatement.setPipeName(ctx.pipeName.getText());
×
3612
    } else {
3613
      throw new SemanticException("Not support for this sql in START PIPE, please enter pipename.");
×
3614
    }
3615

3616
    return startPipeStatement;
×
3617
  }
3618

3619
  @Override
3620
  public Statement visitStopPipe(IoTDBSqlParser.StopPipeContext ctx) {
3621
    final StopPipeStatement stopPipeStatement = new StopPipeStatement(StatementType.STOP_PIPE);
×
3622

3623
    if (ctx.pipeName != null) {
×
3624
      stopPipeStatement.setPipeName(ctx.pipeName.getText());
×
3625
    } else {
3626
      throw new SemanticException("Not support for this sql in STOP PIPE, please enter pipename.");
×
3627
    }
3628

3629
    return stopPipeStatement;
×
3630
  }
3631

3632
  @Override
3633
  public Statement visitShowPipes(IoTDBSqlParser.ShowPipesContext ctx) {
3634
    final ShowPipesStatement showPipesStatement = new ShowPipesStatement();
×
3635

3636
    if (ctx.pipeName != null) {
×
3637
      showPipesStatement.setPipeName(parseIdentifier(ctx.pipeName.getText()));
×
3638
    }
3639
    showPipesStatement.setWhereClause(ctx.CONNECTOR() != null);
×
3640

3641
    return showPipesStatement;
×
3642
  }
3643

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

3661
  @Override
3662
  public Statement visitGetSeriesSlotList(IoTDBSqlParser.GetSeriesSlotListContext ctx) {
3663
    TConsensusGroupType type =
3664
        ctx.DATA() == null ? TConsensusGroupType.SchemaRegion : TConsensusGroupType.DataRegion;
×
3665
    return new GetSeriesSlotListStatement(ctx.database.getText(), type);
×
3666
  }
3667

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

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

3708
  @Override
3709
  public Statement visitMigrateRegion(IoTDBSqlParser.MigrateRegionContext ctx) {
3710
    return new MigrateRegionStatement(
×
3711
        Integer.parseInt(ctx.regionId.getText()),
×
3712
        Integer.parseInt(ctx.fromId.getText()),
×
3713
        Integer.parseInt(ctx.toId.getText()));
×
3714
  }
3715

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

3730
    Map<String, String> quotas = new HashMap<>();
×
3731
    for (IoTDBSqlParser.AttributePairContext attributePair : ctx.attributePair()) {
×
3732
      quotas.put(
×
3733
          parseAttributeKey(attributePair.attributeKey()),
×
3734
          parseAttributeValue(attributePair.attributeValue()));
×
3735
    }
×
3736

3737
    quotas
×
3738
        .keySet()
×
3739
        .forEach(
×
3740
            quotaType -> {
3741
              switch (quotaType) {
×
3742
                case IoTDBConstant.COLUMN_DEVICES:
3743
                  break;
×
3744
                case IoTDBConstant.COLUMN_TIMESERIES:
3745
                  break;
×
3746
                case IoTDBConstant.SPACE_QUOTA_DISK:
3747
                  break;
×
3748
                default:
3749
                  throw new SemanticException("Wrong space quota type: " + quotaType);
×
3750
              }
3751
            });
×
3752

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

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

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

3859
    if (quotas.containsKey(IoTDBConstant.MEMORY_SIZE_PER_READ)) {
×
3860
      String mem = quotas.get(IoTDBConstant.MEMORY_SIZE_PER_READ);
×
3861
      if (mem.equals(IoTDBConstant.QUOTA_UNLIMITED)) {
×
3862
        setThrottleQuotaStatement.setMemLimit(IoTDBConstant.UNLIMITED_VALUE);
×
3863
      } else {
3864
        setThrottleQuotaStatement.setMemLimit(parseThrottleQuotaSizeUnit(mem));
×
3865
      }
3866
    }
3867

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

3884
  @Override
3885
  public Statement visitShowThrottleQuota(IoTDBSqlParser.ShowThrottleQuotaContext ctx) {
3886
    if (!IoTDBDescriptor.getInstance().getConfig().isQuotaEnable()) {
×
3887
      throw new SemanticException(LIMIT_CONFIGURATION_ENABLED_ERROR_MSG);
×
3888
    }
3889
    ShowThrottleQuotaStatement showThrottleQuotaStatement = new ShowThrottleQuotaStatement();
×
3890
    if (ctx.userName != null) {
×
3891
      showThrottleQuotaStatement.setUserName(parseIdentifier(ctx.userName.getText()));
×
3892
    }
3893
    return showThrottleQuotaStatement;
×
3894
  }
3895

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

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

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

3958
  @Override
3959
  public Statement visitShowSpaceQuota(IoTDBSqlParser.ShowSpaceQuotaContext ctx) {
3960
    if (!IoTDBDescriptor.getInstance().getConfig().isQuotaEnable()) {
×
3961
      throw new SemanticException(LIMIT_CONFIGURATION_ENABLED_ERROR_MSG);
×
3962
    }
3963
    ShowSpaceQuotaStatement showSpaceQuotaStatement = new ShowSpaceQuotaStatement();
×
3964
    if (ctx.prefixPath() != null) {
×
3965
      List<PartialPath> databases = new ArrayList<>();
×
3966
      for (IoTDBSqlParser.PrefixPathContext prefixPathContext : ctx.prefixPath()) {
×
3967
        databases.add(parsePrefixPath(prefixPathContext));
×
3968
      }
×
3969
      showSpaceQuotaStatement.setDatabases(databases);
×
3970
    } else {
×
3971
      showSpaceQuotaStatement.setDatabases(null);
×
3972
    }
3973
    return showSpaceQuotaStatement;
×
3974
  }
3975
}
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