{@inheritDoc}

@see org.modeshape.sequencer.ddl.StandardDdlParser#parseCreateViewStatement(org.modeshape.sequencer.ddl.DdlTokenStream,
org.modeshape.sequencer.ddl.node.AstNode)
425892
@Override
    protected AstNode parseCreateViewStatement( DdlTokenStream tokens,
                                                AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        markStartOfStatement(tokens);
        // CREATE [OR REPLACE]
        // [[NO] FORCE] VIEW [schema.] view
        // [ ( { alias [ inline_constraint... ]
        // | out_of_line_constraint
        // }
        // [, { alias [ inline_constraint...]
        // | out_of_line_constraint
        // }
        // ]
        // )
        // | object_view_clause
        // | XMLType_view_clause
        // ]
        // AS subquery [ subquery_restriction_clause ] ;

        // NOTE: the query expression along with the CHECK OPTION clause require no SQL statement terminator.
        // So the CHECK OPTION clause will NOT

        String stmtType = "CREATE";
        tokens.consume("CREATE");
        if (tokens.canConsume("OR", "REPLACE")) {
            stmtType = stmtType + SPACE + "OR REPLACE";
        } else if (tokens.canConsume("NO", "FORCE")) {
            stmtType = stmtType + SPACE + "NO FORCE";
        } else if (tokens.canConsume("FORCE")) {
            stmtType = stmtType + SPACE + "FORCE";
        }

        tokens.consume("VIEW");
        stmtType = stmtType + SPACE + "VIEW";

        String name = parseName(tokens);

        AstNode createViewNode = nodeFactory().node(name, parentNode, TYPE_CREATE_VIEW_STATEMENT);

        // CONSUME COLUMNS
        parseColumnNameList(tokens, createViewNode, TYPE_COLUMN_REFERENCE);

        // (object_view_clause)
        //
        // OF [ schema. ] type_name
        // { WITH OBJECT IDENTIFIER
        // { DEFAULT | ( attribute [, attribute ]... ) }
        // | UNDER [ schema. ] superview
        // }
        // ( { out_of_line_constraint
        // | attribute { inline_constraint }...
        // } [, { out_of_line_constraint
        // | attribute { inline_constraint }...
        // }
        // ]...
        // )

        // (XMLType_view_clause)
        //
        // OF XMLTYPE [ XMLSchema_spec ]
        // WITH OBJECT IDENTIFIER
        // { DEFAULT | ( expr [, expr ]...) }

        // Basically, if next token matches "OF", then parse until token matches "AS"

        if (tokens.matches("OF")) {
            do {
                tokens.consume();
            } while (!tokens.matches("AS"));
        }

        tokens.consume("AS");

        String queryExpression = parseUntilTerminator(tokens);

        createViewNode.setProperty(CREATE_VIEW_QUERY_EXPRESSION, queryExpression);

        markEndOfStatement(tokens, createViewNode);

        return createViewNode;
    }
1273794
private void maybeCollapseIntoForStatements(Node n, Node parent) {
    // Only SCRIPT, BLOCK, and LABELs can have FORs that can be collapsed into.
    // LABELs are not supported here.
    if (parent == null || !NodeUtil.isStatementBlock(parent)) {
      return;
    }

    // Is the current node something that can be in a for loop initializer?
    if (!n.isExprResult() && !n.isVar()) {
      return;
    }

    // Is the next statement a valid FOR?
    Node nextSibling = n.getNext();
    if (nextSibling == null) {
      return;
    } else if (nextSibling.isForIn() || nextSibling.isForOf()) {
      Node forNode = nextSibling;
      Node forVar = forNode.getFirstChild();
      if (forVar.isName()
          && n.isVar() && n.hasOneChild()) {
        Node name = n.getFirstChild();
        if (!name.hasChildren()
            && forVar.getString().equals(name.getString())) {
          // OK, the names match, and the var declaration does not have an
          // initializer. Move it into the loop.
          parent.removeChild(n);
          forNode.replaceChild(forVar, n);
          compiler.reportChangeToEnclosingScope(parent);
        }
      }
    } else if (nextSibling.isVanillaFor() && nextSibling.getFirstChild().isEmpty()) {

      // Does the current node contain an in operator?  If so, embedding
      // the expression in a for loop can cause some JavaScript parsers (such
      // as the PlayStation 3's browser based on Access's NetFront
      // browser) to fail to parse the code.
      // See bug 1778863 for details.
      if (NodeUtil.containsType(n, Token.IN)) {
        return;
      }

      // Move the current node into the FOR loop initializer.
      Node forNode = nextSibling;
      Node oldInitializer = forNode.getFirstChild();
      parent.removeChild(n);

      Node newInitializer;
      if (n.isVar()) {
        newInitializer = n;
      } else {
        // Extract the expression from EXPR_RESULT node.
        checkState(n.hasOneChild(), n);
        newInitializer = n.getFirstChild();
        n.removeChild(newInitializer);
      }

      forNode.replaceChild(oldInitializer, newInitializer);

      compiler.reportChangeToEnclosingScope(forNode);
    }
  }
959183
protected Statement statement(AST node) {
        Statement statement = null;
        int type = node.getType();
        switch (type) {
            case SLIST:
            case LITERAL_finally:
                statement = statementList(node);
                break;

            case METHOD_CALL:
                statement = methodCall(node);
                break;

            case VARIABLE_DEF:
                statement = variableDef(node);
                break;

            case LABELED_STAT:
                return labelledStatement(node);

            case LITERAL_assert:
                statement = assertStatement(node);
                break;

            case LITERAL_break:
                statement = breakStatement(node);
                break;

            case LITERAL_continue:
                statement = continueStatement(node);
                break;

            case LITERAL_if:
                statement = ifStatement(node);
                break;

            case LITERAL_for:
                statement = forStatement(node);
                break;

            case LITERAL_return:
                statement = returnStatement(node);
                break;

            case LITERAL_synchronized:
                statement = synchronizedStatement(node);
                break;

            case LITERAL_switch:
                statement = switchStatement(node);
                break;

            case LITERAL_try:
                statement = tryStatement(node);
                break;

            case LITERAL_throw:
                statement = throwStatement(node);
                break;

            case LITERAL_while:
                statement = whileStatement(node);
                break;

            default:
                statement = new ExpressionStatement(expression(node));
        }
        if (statement != null) {
            configureAST(statement, node);
        }
        return statement;
    }
488444
public static PreparedStatement createTrackTable(Connection connection, String trackTableName,boolean isH2) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(trackTableName).append(" (");
            if (isH2) {
                sb.append("the_geom MULTILINESTRING CHECK ST_SRID(THE_GEOM) = 4326,");
            } else {
                sb.append("the_geom GEOMETRY(MULTILINESTRING, 4326),");
            }
            sb.append(" id INT,");
            sb.append(GPXTags.NAME.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.CMT.toLowerCase()).append(" TEXT,");
            sb.append("description").append(" TEXT,");
            sb.append(GPXTags.SRC.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.HREF.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.HREFTITLE.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.NUMBER.toLowerCase()).append(" INT,");
            sb.append(GPXTags.TYPE.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.EXTENSIONS.toLowerCase()).append(" TEXT);");
            stmt.execute(sb.toString());
        }

        //We return the preparedstatement of the route table
        StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackTableName).append(" VALUES ( ?");
        for (int i = 1; i < GpxMetadata.RTEFIELDCOUNT; i++) {
            insert.append(",?");
        }
        insert.append(");");
        return connection.prepareStatement(insert.toString());
    }
377028
public final void insertStatement() throws RecognitionException {
		int insertStatement_StartIndex = input.index();

		Token s=null;
		Token c=null;
		ParserRuleReturnScope expression11 =null;

		try {
			if ( state.backtracking>0 && alreadyParsedRule(input, 93) ) { return; }

			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:975:5: (s= 'insert' '(' expression c= ')' )
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:975:7: s= 'insert' '(' expression c= ')'
			{
			s=(Token)match(input,90,FOLLOW_90_in_insertStatement4191); if (state.failed) return;
			match(input,36,FOLLOW_36_in_insertStatement4193); if (state.failed) return;
			pushFollow(FOLLOW_expression_in_insertStatement4199);
			expression11=expression();
			state._fsp--;
			if (state.failed) return;
			c=(Token)match(input,37,FOLLOW_37_in_insertStatement4209); if (state.failed) return;
			if ( state.backtracking==0 ) {
			        JavaStatementBlockDescr d = new JavaStatementBlockDescr( (expression11!=null?input.toString(expression11.start,expression11.stop):null), JavaBlockDescr.BlockType.INSERT );
			        d.setStart( ((CommonToken)s).getStartIndex() );
			        this.addBlockDescr( d );
			        d.setEnd( ((CommonToken)c).getStopIndex() );
			    }
			}

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
			if ( state.backtracking>0 ) { memoize(input, 93, insertStatement_StartIndex); }

		}
	}
360930
@Override
    protected void parseNextCreateTableOption( final DdlTokenStream tokens,
                                               final AstNode tableNode ) throws ParsingException {
        final String tableProperty = tokens.consume();
        boolean processed = false;

        // if token is a number add it to previous option
        if (tableProperty.matches("\\b\\d+\\b")) {
            final List<AstNode> options = tableNode.getChildren(TYPE_STATEMENT_OPTION);

            if (!options.isEmpty()) {
                final AstNode option = options.get(options.size() - 1);
                final String currValue = (String)option.getProperty(VALUE);
                option.setProperty(VALUE, currValue + SPACE + tableProperty);
                processed = true;
            }
        }

        if (!processed) {
            final AstNode tableOption = nodeFactory().node("option", tableNode, TYPE_STATEMENT_OPTION);
            tableOption.setProperty(VALUE, tableProperty);
        }
    }
18217
String getPreparedStatementText(ControlBeanContext context, Method m, Object[] args) {
        StringBuilder sb = new StringBuilder();
        for (SqlFragment sf : _children) {
            sb.append(sf.getPreparedStatementText(context, m, args));
        }
        return sb.toString();
    }
885391
@Override
    protected AstNode parseRevokeStatement( DdlTokenStream tokens,
                                            AstNode parentNode ) throws ParsingException {
        return parseStatement(tokens, STMT_REVOKE, parentNode, TYPE_REVOKE_STATEMENT);
    }
41938
public void parse(final InsertStatement insertStatement) {
        if (!lexerEngine.skipIfEqual(getCustomizedInsertKeywords())) {
            return;
        }
        removeUnnecessaryToken(insertStatement);
        Optional<InsertValuesToken> insertValuesToken = insertStatement.findSQLToken(InsertValuesToken.class);
        Preconditions.checkState(insertValuesToken.isPresent());
        insertStatement.getSQLTokens().remove(insertValuesToken.get());
        insertStatement.addSQLToken(new InsertSetToken(insertValuesToken.get().getStartIndex()));
        do {
            SQLExpression left = basicExpressionParser.parse(insertStatement);
            Column column = null;
            if (left instanceof SQLPropertyExpression) {
                column = new Column(SQLUtil.getExactlyValue(((SQLPropertyExpression) left).getName()), insertStatement.getTables().getSingleTableName());
            }
            if (left instanceof SQLIdentifierExpression) {
                column = new Column(SQLUtil.getExactlyValue(((SQLIdentifierExpression) left).getName()), insertStatement.getTables().getSingleTableName());
            }
            if (left instanceof SQLIgnoreExpression) {
                column = new Column(SQLUtil.getExactlyValue(((SQLIgnoreExpression) left).getExpression()), insertStatement.getTables().getSingleTableName());
            }
            Preconditions.checkNotNull(column);
            lexerEngine.accept(Symbol.EQ);
            SQLExpression right = basicExpressionParser.parse(insertStatement);
            if (shardingRule.isShardingColumn(column.getName(), column.getTableName()) 
                    && (right instanceof SQLNumberExpression || right instanceof SQLTextExpression || right instanceof SQLParameterMarkerExpression)) {
                insertStatement.getRouteConditions().add(new Condition(column, right));
            }
        } while (lexerEngine.skipIfEqual(Symbol.COMMA));
        InsertValue insertValue = new InsertValue(new LinkedList<SQLExpression>());
        insertStatement.getValues().add(insertValue);
    }
841488
private final DoWhile doStatement(Data data) throws TemplateException {
	int pos = data.srcCode.getPos();

	// id
	String id = variableDec(data, false);
	if (id == null) {
	    data.srcCode.setPos(pos);
	    return null;
	}
	if (id.equalsIgnoreCase("do")) {
	    id = null;
	    if (!data.srcCode.isCurrent('{') && !data.srcCode.isCurrent(' ') && !data.srcCode.isCurrent('/')) {
		data.srcCode.setPos(pos);
		return null;
	    }
	}
	else {
	    data.srcCode.removeSpace();
	    if (!data.srcCode.forwardIfCurrent(':')) {
		data.srcCode.setPos(pos);
		return null;
	    }
	    data.srcCode.removeSpace();

	    if (!data.srcCode.forwardIfCurrent("do", '{') && !data.srcCode.forwardIfCurrent("do ") && !data.srcCode.forwardIfCurrent("do", '/')) {
		data.srcCode.setPos(pos);
		return null;
	    }
	    data.srcCode.previous();
	}

	// if(!data.srcCode.forwardIfCurrent("do",'{') && !data.srcCode.forwardIfCurrent("do ") &&
	// !data.srcCode.forwardIfCurrent("do",'/'))
	// return null;

	Position line = data.srcCode.getPosition();
	Body body = new BodyBase(data.factory);

	// data.srcCode.previous();

	Body prior = data.setParent(body);
	statement(data, body, CTX_DO_WHILE);
	data.setParent(prior);

	comments(data);
	if (!data.srcCode.forwardIfCurrent("while", '(')) throw new TemplateException(data.srcCode, "do statement must have a while at the end");

	DoWhile doWhile = new DoWhile(condition(data), body, line, data.srcCode.getPosition(), id);

	if (!data.srcCode.forwardIfCurrent(')')) throw new TemplateException(data.srcCode, "do statement must end with a [)]");

	return doWhile;
    }
1321357
public CommonTree parseQuery(String queryString, QueryResolverDelegate resolverDelegate, QueryRendererDelegate rendererDelegate) throws ParsingException {
      IckleLexer lexer = new IckleLexer(new ANTLRStringStream(queryString));
      CommonTokenStream tokens = new CommonTokenStream(lexer);
      IckleParser parser = new IckleParser(tokens);

      try {
         // parser.statement() is the entry point for evaluation of any kind of statement
         IckleParser.statement_return r = parser.statement();

         if (parser.hasErrors()) {
            throw log.getQuerySyntaxException(queryString, parser.getErrorMessages());
         }

         CommonTree tree = (CommonTree) r.getTree();
         tree = resolve(tokens, tree, resolverDelegate);
         tree = render(tokens, tree, rendererDelegate);
         return tree;
      } catch (RecognitionException e) {
         throw log.getQuerySyntaxException(queryString, e);
      }
   }
923871
public static ParsedSql parseSqlStatement(final String sql) {
        Assert.notNull(sql, "SQL must not be null");

        Set<String> namedParameters = new HashSet<>();
        String sqlToUse = sql;
        List<ParameterHolder> parameterList = new ArrayList<>();

        char[] statement = sql.toCharArray();
        int namedParameterCount = 0;
        int unnamedParameterCount = 0;
        int totalParameterCount = 0;

        int escapes = 0;
        int i = 0;
        while (i < statement.length) {
            int skipToPosition;
            while (i < statement.length) {
                skipToPosition = skipCommentsAndQuotes(statement, i);
                if (i == skipToPosition) {
                    break;
                } else {
                    i = skipToPosition;
                }
            }
            if (i >= statement.length) {
                break;
            }
            char c = statement[i];
            if (c == ':' || c == '&') {
                int j = i + 1;
                if (j < statement.length && statement[j] == ':' && c == ':') {
                    // Postgres-style "::" casting operator should be skipped
                    i = i + 2;
                    continue;
                }
                String parameter;
                if (j < statement.length && c == ':' && statement[j] == '{') {
                    // :{x} style parameter
                    while (j < statement.length && !('}' == statement[j])) {
                        j++;
                        if (':' == statement[j] || '{' == statement[j]) {
                            throw new CommonRuntimeException("Parameter name contains invalid character '" +
                                    statement[j] + "' at position " + i + " in statement: " + sql);
                        }
                    }
                    if (j >= statement.length) {
                        throw new CommonRuntimeException(
                                "Non-terminated named parameter declaration at position " + i + " in statement: " + sql);
                    }
                    if (j - i > 3) {
                        parameter = sql.substring(i + 2, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
                    }
                    j++;
                } else {
                    while (j < statement.length && !isParameterSeparator(statement[j])) {
                        j++;
                    }
                    if (j - i > 1) {
                        parameter = sql.substring(i + 1, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
                    }
                }
                i = j - 1;
            } else {
                if (c == '\\') {
                    int j = i + 1;
                    if (j < statement.length && statement[j] == ':') {
                        // escaped ":" should be skipped
                        sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
                        escapes++;
                        i = i + 2;
                        continue;
                    }
                }
                if (c == '?') {
                    int j = i + 1;
                    if (j < statement.length && (statement[j] == '?' || statement[j] == '|' || statement[j] == '&')) {
                        // Postgres-style "??", "?|", "?&" operator should be skipped
                        i = i + 2;
                        continue;
                    }
                    unnamedParameterCount++;
                    totalParameterCount++;
                }
            }
            i++;
        }

        ParsedSql parsedSql = new ParsedSql(sqlToUse);
        parsedSql.setParameterList(parameterList);
        parsedSql.setNamedParameterCount(namedParameterCount);
        parsedSql.setUnnamedParameterCount(unnamedParameterCount);
        parsedSql.setTotalParameterCount(totalParameterCount);
        return parsedSql;
    }
517794
protected ViewQuery createQuery(String viewName) {
		return new ViewQuery()
				.dbPath(db.path())
				.designDocId(stdDesignDocumentId)
				.viewName(viewName);
	}
1027809
public final hqlParser.insertStatement_return insertStatement() throws RecognitionException {
		hqlParser.insertStatement_return retval = new hqlParser.insertStatement_return();
		retval.start = input.LT(1);

		CommonTree root_0 = null;

		Token INSERT27=null;
		ParserRuleReturnScope intoClause28 =null;
		ParserRuleReturnScope selectStatement29 =null;

		CommonTree INSERT27_tree=null;

		try {
			// hql.g:217:2: ( INSERT ^ intoClause selectStatement )
			// hql.g:217:4: INSERT ^ intoClause selectStatement
			{
			root_0 = (CommonTree)adaptor.nil();


			INSERT27=(Token)match(input,INSERT,FOLLOW_INSERT_in_insertStatement831);
			INSERT27_tree = (CommonTree)adaptor.create(INSERT27);
			root_0 = (CommonTree)adaptor.becomeRoot(INSERT27_tree, root_0);

			pushFollow(FOLLOW_intoClause_in_insertStatement834);
			intoClause28=intoClause();
			state._fsp--;

			adaptor.addChild(root_0, intoClause28.getTree());

			pushFollow(FOLLOW_selectStatement_in_insertStatement836);
			selectStatement29=selectStatement();
			state._fsp--;

			adaptor.addChild(root_0, selectStatement29.getTree());

			}

			retval.stop = input.LT(-1);

			retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
			adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
			retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
		}
		finally {
			// do for sure before leaving
		}
		return retval;
	}
597898
public void parse(final SelectStatement selectStatement) {
        if (!lexerEngine.skipIfEqual(SQLServerKeyword.TOP)) {
            return;
        }
        int beginPosition = lexerEngine.getCurrentToken().getEndPosition();
        if (!lexerEngine.skipIfEqual(Symbol.LEFT_PAREN)) {
            beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length();
        }
        SQLExpression sqlExpression = basicExpressionParser.parse(selectStatement);
        lexerEngine.skipIfEqual(Symbol.RIGHT_PAREN);
        LimitValue rowCountValue;
        if (sqlExpression instanceof SQLNumberExpression) {
            int rowCount = ((SQLNumberExpression) sqlExpression).getNumber().intValue();
            rowCountValue = new LimitValue(rowCount, -1, false);
            selectStatement.addSQLToken(new RowCountToken(beginPosition, rowCount));
        } else if (sqlExpression instanceof SQLParameterMarkerExpression) {
            rowCountValue = new LimitValue(-1, ((SQLParameterMarkerExpression) sqlExpression).getIndex(), false);
        } else {
            throw new SQLParsingException(lexerEngine);
        }
        lexerEngine.unsupportedIfEqual(SQLServerKeyword.PERCENT);
        lexerEngine.skipIfEqual(DefaultKeyword.WITH, SQLServerKeyword.TIES);
        if (null == selectStatement.getLimit()) {
            Limit limit = new Limit();
            limit.setRowCount(rowCountValue);
            selectStatement.setLimit(limit);
        } else {
            selectStatement.getLimit().setRowCount(rowCountValue);
        }
    }
220887
@NonNull
  public static CreateMaterializedViewStart createMaterializedView(
      @Nullable String keyspace, @NonNull String viewName) {
    return createMaterializedView(
        keyspace == null ? null : CqlIdentifier.fromCql(keyspace), CqlIdentifier.fromCql(viewName));
  }
806429
private void processSavedViewState() throws IOException
   {
      DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CEdl");
      VarMeta varMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta"))));
      Var2Data varData = new Var2Data(varMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data"))));
      //System.out.println(varMeta);
      //System.out.println(varData);

      InputStream is = m_inputStreamFactory.getInstance(dir, "FixedData");
      byte[] fixedData = new byte[is.available()];
      is.read(fixedData);
      //System.out.println(ByteArrayHelper.hexdump(fixedData, false, 16, ""));

      ViewStateReader reader = new ViewStateReader9();
      reader.process(m_file, varData, fixedData);
   }