options { STATIC = false; ERROR_REPORTING = true; JAVA_UNICODE_ESCAPE = true; UNICODE_INPUT = false; IGNORE_CASE = true; DEBUG_PARSER = false; DEBUG_LOOKAHEAD = false; DEBUG_TOKEN_MANAGER = false; } PARSER_BEGIN(SQLParser) package org.teiid.query.parser; import java.math.BigInteger; import java.util.*; import org.teiid.core.types.*; import org.teiid.core.util.StringUtil; import org.teiid.core.util.PropertiesUtils; import org.teiid.query.QueryPlugin; import org.teiid.query.sql.LanguageObject; import org.teiid.query.sql.proc.*; import org.teiid.query.sql.symbol.*; import org.teiid.query.metadata.*; import org.teiid.metadata.*; import org.teiid.metadata.BaseColumn.NullType; import org.teiid.language.Like.MatchMode; import org.teiid.translator.*; import org.teiid.query.sql.lang.*; /** *

The SQLParser is a JavaCC-generated parser that reads a SQL string and produces a * Query object. The SQLParser.java file is generated by JavaCC from the SQLParser.jj * file. WARNING: DO NOT MODIFY the SQLParser.java file as it will be * regenerated from the .jj file and your changes will be lost!

*/ @SuppressWarnings({"nls", "unused"}) public class SQLParser extends SQLParserUtil { private void jj_add_error_token ( int kind, int pos) { if (pos >= 100) return; if (pos == jj_endpos + 1) { jj_lasttokens[jj_endpos++] = kind; } else if (jj_endpos != 0) { jj_expentry = new int[jj_endpos]; for (int i = 0; i < jj_endpos; i++) { jj_expentry[i] = jj_lasttokens[i]; } boolean exists = false; for (java.util.Iterator e = jj_expentries.iterator(); e.hasNext();) { int[] oldentry = (int[])(e.next()); if (oldentry.length == jj_expentry.length) { exists = true; for (int i = 0; i < jj_expentry.length; i++) { if (oldentry[i] != jj_expentry[i]) { exists = false; break; } } if (exists) break; } } if (!exists) jj_expentries.add(jj_expentry); if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; } } } // end class PARSER_END(SQLParser) TOKEN_MGR_DECLS : { int commentNestingDepth; } SKIP : { " " | "\t" | "\n" | "\r" } MORE : { "/*" { commentNestingDepth = 1 ; } : IN_MULTI_LINE_COMMENT } MORE : { "/*" { commentNestingDepth += 1 ; } } SPECIAL_TOKEN : { "*/" { commentNestingDepth -= 1; SwitchTo( commentNestingDepth==0 ? DEFAULT : IN_MULTI_LINE_COMMENT ) ; } } MORE : { < ~[] > } SPECIAL_TOKEN: { } TOKEN: /* Data types */ { | | | | | | | | | | | | | | | | | | | | | | | } TOKEN: /* Functions with special syntax */ { | } TOKEN : /* Reserved words */ { | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | } TOKEN : /* SQL/XML Reserved words */ { | | | | | | | | | | | | | | | | | | } TOKEN : /* SQL/MED Reserved words */ { | | | | | | | | | | | | } TOKEN : /* NonReserved words */ { | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | } /* name=all in group identifier */ TOKEN : { < ALL_IN_GROUP: > } /* name=identifier */ TOKEN : { < ID: ( )* > } TOKEN : { < #QUOTED_ID: | ("\"" (("\"\"") | ~["\""] )+ "\"") > } TOKEN : { < #ID_PART: (("_" | "@" | "#" | ) ( | "_" | )*) > } /* name=escaped function */ TOKEN : { < ESCAPEDFUNCTION: "{" "fn" > } /* name=escaped join */ TOKEN : { < ESCAPEDJOIN: "{" "oj" > } /* name=escaped type */ TOKEN : { < ESCAPEDTYPE: "{" ("d" | "t" | "ts" | "b") > } /* name=decimal numeric literal */ TOKEN : { < DECIMALVAL: ()* > } /* name=approximate numeric literal */ TOKEN : { < FLOATVAL: ["e", "E"] (|)? > } /* name=string literal */ TOKEN : { < STRINGVAL: (("N"|"E")? "'" ( ("''") | ~["'"] )* "'") > } TOKEN : { < #LETTER: (["a"-"z","A"-"Z"] | ["\u0153"-"\ufffd"]) > } TOKEN : { < #DIGIT: ["0"-"9"] > } /* name=unsigned integer literal */ TOKEN : { < UNSIGNEDINTEGER: ()+ > } /* name=binary string literal */ TOKEN : { < BINARYSTRINGVAL: ("X"|"x" "'" ( )+ "'") > } TOKEN : { < #HEXIT: (["a"-"f","A"-"F"] | ) > } TOKEN : { | | | | | | | | "> | | "> | ="> | | | | | | | | | | } /* name=string description=A string literal value. Use '' to escape ' in the string. example=[source,sql]\n----\n'a string'\n----\n\n[source,sql]\n----\n'it''s a string'\n----\n */ String stringVal() : { Token t = null; } { t = { return normalizeStringLiteral(t.image); } } /* name=non-reserved identifier description=Allows non-reserved keywords to be parsed as identifiers example=SELECT *COUNT* FROM ... */ Token nonReserved() : { } { (||||||||basicNonReserved()) { return getToken(0); } } Token basicNonReserved() : { } { (|||||||||||||||| ||||||||||||||| |||||||||| ||||||||||| ||||||||||
|| |||||||||||| |||||||||||||||| |||||||| ||||||||) { return getToken(0); } } /* name=Unqualified identifier description=Unqualified name of a single entity. example=[source,sql]\n----\n"tbl"\n----\n */ String unqualifiedId() : { } { { return normalizeId(getToken(0).image, ParseInfo.REQUIRE_UNQUALIFIED_NAMES); } | nonReserved() { return getToken(0).image; } } /* name=identifier description=Partial or full name of a single entity. example=[source,sql]\n----\ntbl.col\n----\n\n[source,sql]\n----\n"tbl"."col"\n----\n */ String id(Boolean nonAlias) : { } { { String id = normalizeId(getToken(0).image); if (nonAlias != null) { return validateName(id, nonAlias); } return id; } | nonReserved() { return getToken(0).image; } } /* TODO: createProcedure should not be here, but is due to all of the legacy tests unused=true */ Command command(ParseInfo info) : { Command command = null; } { (LOOKAHEAD(2) command = createProcedure(info) | command = userCommand(info) | command = callableStatement(info) | command = explainCommand(info) ) [] { return command; } } /* name=create trigger description=Creates a trigger action on the given target. example=[source,sql]\n----\nCREATE TRIGGER ON vw INSTEAD OF INSERT AS FOR EACH ROW BEGIN ATOMIC ... END\n----\n */ Command createTrigger(ParseInfo info, boolean ddl) : { String target = null; TriggerAction triggerAction = null; Token event = null; boolean after = false; String name = null; } { [name = id(Boolean.TRUE)] target = id(null) { if (ddl) { String rawId = getToken(0).image; if (rawId.indexOf('.') >= 0 && (!(rawId.startsWith("\"") && rawId.endsWith("\"")) || rawId.substring(1, rawId.length()-1).indexOf("\"") >= 0)) { //this is not fully correct, but catches all cases except for identifiers containing a quote character throw new ParseException(QueryPlugin.Util.getString("SQLParser.ddl_id_unqualified", rawId)); //$NON-NLS-1$ } } } (( )|( {after = true;})) (event = | event = | event = ) triggerAction = forEachRowTriggerAction(info) { AlterTrigger alterTrigger = new AlterTrigger(); alterTrigger.setTarget(new GroupSymbol(target)); alterTrigger.setDefinition(triggerAction); alterTrigger.setEvent(Table.TriggerEvent.valueOf(event.image.toUpperCase())); alterTrigger.setCreate(true); alterTrigger.setAfter(after); alterTrigger.setName(name); return alterTrigger; } } /* name=alter description=Alter the given target. example=[source,sql]\n----\nALTER VIEW vw AS SELECT col FROM tbl\n----\n */ Command alter(ParseInfo info) : { String target = null; QueryCommand command = null; Statement stmt = null; TriggerAction triggerAction = null; Token comment = null; Token event = null; Boolean enabled = null; boolean after = false; String name = null; } { ( ( target = id(null) { comment = getToken(1).specialToken; } command = queryExpression(info)) { if (comment != null) { command.setCacheHint(getQueryCacheOption(comment.image)); } AlterView alterView = new AlterView(); alterView.setTarget(new GroupSymbol(target)); alterView.setDefinition(command); return alterView; } | ( target = id(null) { comment = getToken(1).specialToken; } stmt = statement(info)) { CreateProcedureCommand cup = new CreateProcedureCommand(asBlock(stmt)); if (comment != null) { cup.setCacheHint(getQueryCacheOption(comment.image)); } AlterProcedure alterProc = new AlterProcedure(); alterProc.setTarget(new GroupSymbol(target)); alterProc.setDefinition(cup); return alterProc; } | ( [name = id(Boolean.TRUE)] target = id(null) (( )|( {after = true;})) (event = | event = | event = ) (( triggerAction = forEachRowTriggerAction(info)) | {enabled=true;}| {enabled=false;})) { AlterTrigger alterTrigger = new AlterTrigger(); alterTrigger.setTarget(new GroupSymbol(target)); alterTrigger.setDefinition(triggerAction); alterTrigger.setEvent(Table.TriggerEvent.valueOf(event.image.toUpperCase())); if (enabled != null) { alterTrigger.setEnabled(enabled); } alterTrigger.setName(name); alterTrigger.setAfter(after); return alterTrigger; } ) } /* name=for each row trigger action description=Defines an action to perform on each row. example=[source,sql]\n----\nFOR EACH ROW BEGIN ATOMIC ... END\n----\n */ TriggerAction forEachRowTriggerAction(ParseInfo info) : { Block b = new Block(); b.setAtomic(true); Statement stmt = null; } { ( LOOKAHEAD(1) ( [] ( stmt = statement(info) { b.addStatement(stmt); } )* ) | stmt = statement(info) { b = asBlock(stmt); b.setAtomic(true); } ) { return new TriggerAction(b); } } /* name=explain description=Returns the query plan for the statement example=EXPLAIN select 1 index=true */ Command explainCommand(ParseInfo info) : { Command command = null; ExplainCommand explain = new ExplainCommand(); Token comment = null; } { [LOOKAHEAD(2) explainOption(info, explain) ( explainOption(info, explain))* ] { comment = getToken(1).specialToken; } command = userCommand(info) { if (comment != null) { command.setCacheHint(getQueryCacheOption(comment.image)); } explain.setCommand(command); return explain; } } /* name=explain option description=Option for the explain statement example=FORMAT YAML */ void explainOption(ParseInfo info, ExplainCommand explain) : { boolean val = true; ExplainCommand.Format format = null; } { ( [ |( {val=false;}) ] {explain.setAnalyze(val);} ) |( [ ( {format=ExplainCommand.Format.XML;}) |( {format=ExplainCommand.Format.TEXT;}) |( {format=ExplainCommand.Format.YAML;}) ] {explain.setFormat(format);} ) } /* name=directly executable statement description=A statement that can be executed at runtime. example=[source,sql]\n----\nSELECT * FROM tbl\n----\n index=true */ Command userCommand(ParseInfo info) : { Command command = null; SourceHint sourceHint = null; Block block = null; } { (command = queryExpression(info) | command = storedProcedure(info, 1) | { sourceHint = getSourceHint(this); } command = insert(info) | { sourceHint = getSourceHint(this); } command = update(info) | { sourceHint = getSourceHint(this); } command = delete(info) | command = dropTable(info) | LOOKAHEAD(2) command = createTempTable(info) | LOOKAHEAD(2) command = createForeignTempTable(info) | command = alter(info) | command = createTrigger(info, false) | block = compoundStatement(info) {command = new CreateProcedureCommand(block);} ) { setSourceHint(sourceHint, command); return command; } } /* name=drop table description=Drop the given table. example=[source,sql]\n----\nDROP TABLE #temp\n----\n */ Command dropTable(ParseInfo info) : { Drop drop = new Drop(); String table = null; } { table = id(null) { drop.setTable(new GroupSymbol(table)); return drop; } } /* name=create temporary table description=Creates a temporary table. example=[source,sql]\n----\nCREATE LOCAL TEMPORARY TABLE tmp (col integer)\n----\n */ Command createTempTable(ParseInfo info) : { Create create = new Create(); String table = null; String pkId = null; Column col = null; List pk = null; } { []
table = unqualifiedId() { create.setTable(new GroupSymbol(table)); } col = tableElement(info) { create.getColumns().add(col); } (LOOKAHEAD(2) col = tableElement(info) { create.getColumns().add(col); } )* [ pk = columnList(true, true) { create.getPrimaryKey().addAll(pk); } ] [ {create.setCommitAction(Create.CommitAction.PRESERVE_ROWS);} ] { return create; } } /* name=temporary table element description=Defines a temporary table column. example=[source,sql]\n----\ncol string NOT NULL\n----\n */ Column tableElement(ParseInfo info) : { String element = null; ParsedDataType type = null; boolean autoIncrement = false; //TODO: once we support udts, then this will need to inherit the nullability from the type boolean notNull = false; } { element = id(Boolean.TRUE) ( type = parseBasicDataType() | { type = new ParsedDataType("INTEGER"); autoIncrement = true; notNull = true; } ) [ { notNull = true; }] { Column c = new Column(); c.setName(element); c.setRuntimeType(type.type); c.setAutoIncremented(autoIncrement); c.setNullType(notNull?NullType.No_Nulls:NullType.Nullable); return c; } } /* name=raise error statement description=Raises an error with the given message. example=[source,sql]\n----\nERROR 'something went wrong'\n----\n */ RaiseStatement errorStatement(ParseInfo info) : { Expression errMsg = null; } { errMsg = expression(info) { ExceptionExpression ee = new ExceptionExpression(); ee.setMessage(errMsg); return new RaiseStatement(ee); } } /* name=raise statement description=Raises an error or warning with the given message. example=[source,sql]\n----\nRAISE SQLEXCEPTION 'something went wrong'\n----\n */ RaiseStatement raiseStatement(ParseInfo info) : { Expression err = null; boolean warning = false; } { [ {warning = true;}] err = exceptionReference(info) { return new RaiseStatement(err, warning); } } /* name=exception reference description=a reference to an exception example=[source,sql]\n----\nSQLEXCEPTION 'something went wrong' SQLSTATE '00X', 2\n----\n */ Expression exceptionReference(ParseInfo info) : { String id = null; Expression ex; } { id = id(null) {return new ElementSymbol(id);} | ex = exception(info) { return ex; } } /* name=sql exception description=creates a sql exception or warning with the specified message, state, and code example=[source,sql]\n----\nSQLEXCEPTION 'something went wrong' SQLSTATE '00X', 2\n----\n */ Expression exception(ParseInfo info) : { Expression err = null; Expression sqlState = null; Expression errCode = null; Expression parent = null; } { err = commonValueExpression(info) [ sqlState = commonValueExpression(info) [ errCode = commonValueExpression(info)] ] [ parent = exceptionReference(info)] { ExceptionExpression ee = new ExceptionExpression(); ee.setMessage(err); ee.setSqlState(sqlState); ee.setErrorCode(errCode); ee.setParent(parent); return ee; } } /* name=statement description=A procedure statement. example=[source,sql]\n----\nIF (x = 5) BEGIN ... END\n----\n */ Statement statement(ParseInfo info) : { Statement stmt = null; String label = null; } { ( LOOKAHEAD(2) ([label = id(null) ] ( stmt = loopStatement(info) | stmt = whileStatement(info) | stmt = compoundStatement(info) ) { ((Statement.Labeled)stmt).setLabel(label); } ) | ( stmt = ifStatement(info) | stmt = delimitedStatement(info) ) ) { return stmt; } } /* name=delimited statement description=A procedure statement terminated by ;. example=[source,sql]\n----\nSELECT * FROM tbl;\n----\n */ Statement delimitedStatement(ParseInfo info) : { Statement stmt = null; } { (LOOKAHEAD(2) stmt = assignStatement(info) | stmt = sqlStatement(info) | stmt = errorStatement(info) | stmt = raiseStatement(info) | stmt = declareStatement(info) | stmt = branchingStatement(info) | stmt = returnStatement(info) ) { return stmt; } } /* name=compound statement description=A procedure statement block contained in BEGIN END. example=[source,sql]\n----\nBEGIN NOT ATOMIC ... END\n----\n */ Block compoundStatement(ParseInfo info) : { Statement stmt = null; Block block = new Block(); Boolean atomic = null; String eId = null; } { [[ {atomic = Boolean.FALSE;}] {if (atomic == null) {atomic = Boolean.TRUE;}}] (LOOKAHEAD(2) stmt = statement(info) { block.addStatement(stmt, false); } )* [ eId = id(Boolean.FALSE) {block.setExceptionGroup(eId);} ( stmt = statement(info) { block.addStatement(stmt, true); } )* ] { if (atomic != null) { block.setAtomic(atomic); } return block; } } /* name=branching statement description=A procedure branching control statement, which typically specifies a label to return control to. example=[source,sql]\n----\nBREAK x\n----\n */ BranchingStatement branchingStatement(ParseInfo info) : { BranchingStatement breakStmt = new BranchingStatement(); Token mode = null; String label = null; } { ( ( (mode = | mode = ) [label = id(null)] ) | (mode = label = id(null)) ) { breakStmt.setMode(BranchingStatement.BranchingMode.valueOf(mode.image.toUpperCase())); breakStmt.setLabel(label); return breakStmt; } } /* name=return statement description=A return statement. example=[source,sql]\n----\nRETURN 1\n----\n */ ReturnStatement returnStatement(ParseInfo info) : { Expression ex = null; } { [ex = expression(info)] { return new ReturnStatement(ex); } } /* name=while statement description=A procedure while statement that executes until its condition is false. example=[source,sql]\n----\nWHILE (var) BEGIN ... END\n----\n */ WhileStatement whileStatement(ParseInfo info) : { WhileStatement whileStmt = null; Criteria criteria = null; Statement stmt = null; } { criteria = criteria(info) stmt = statement(info) { whileStmt = new WhileStatement(criteria, asBlock(stmt)); return whileStmt; } } /* name=loop statement description=A procedure loop statement that executes over the given cursor. example=[source,sql]\n----\nLOOP ON (SELECT * FROM tbl) AS x BEGIN ... END\n----\n */ LoopStatement loopStatement(ParseInfo info) : { LoopStatement loopStmt = null; String cursor = null; QueryCommand query = null; Statement stmt = null; } { query = queryExpression(info) cursor = id(null) stmt = statement(info) { loopStmt = new LoopStatement(asBlock(stmt), query, cursor); return loopStmt; } } /* name=if statement description=A procedure loop statement that executes over the given cursor. example=[source,sql]\n----\nIF (boolVal) BEGIN variables.x = 1 END ELSE BEGIN variables.x = 2 END\n----\n */ IfStatement ifStatement(ParseInfo info) : { IfStatement ifStmt = null; Criteria criteria = null; Statement ifStatement = null; Statement elseStatement = null; String groupID = null; String groupID2 = null; boolean not = false; } { criteria = criteria(info) ifStatement = statement(info) //else blocks will be associated with the closest if block [LOOKAHEAD(1) elseStatement = statement(info)] { ifStmt = new IfStatement(criteria, asBlock(ifStatement)); ifStmt.setElseBlock(asBlock(elseStatement)); return ifStmt; } } /* name=declare statement description=A procedure declaration statement that creates a variable and optionally assigns a value. example=[source,sql]\n----\nDECLARE STRING x = 'a'\n----\n */ DeclareStatement declareStatement(ParseInfo info) : { DeclareStatement declStmt = null; String var = null; ParsedDataType type = null; ElementSymbol variableID = null; LanguageObject value = null; } { (type = parseDataType() | {type = new ParsedDataType(getToken(0).image);}) var = id(null) { variableID = new ElementSymbol(var); } [ value = assignStatementOperand(info) ] { if (value instanceof Expression) { return new DeclareStatement(variableID, type.type, (Expression)value); } if (value instanceof QueryCommand) { return new DeclareStatement(variableID, type.type, new ScalarSubquery((QueryCommand)value)); } return new DeclareStatement(variableID, type.type, (Command)value); } } /* name=assignment statement description=Assigns a variable a value in a procedure. example=[source,sql]\n----\nx = 'b'\n----\n */ Statement assignStatement(ParseInfo info) : { LanguageObject value = null; String var = null; ElementSymbol elementID = null; boolean returnable=true; } { var = id(null) { elementID = new ElementSymbol(var); } (value = assignStatementOperand(info) | (value = storedProcedure(info, 2) [(| {returnable = false;}) ]) { StoredProcedure storedProcedure = (StoredProcedure)value; SPParameter parameter = new SPParameter(1, SPParameter.RETURN_VALUE, "return"); //$NON-NLS-1$ parameter.setExpression(elementID); storedProcedure.setParameter(parameter); storedProcedure.setCalledWithReturn(true); CommandStatement cs = new CommandStatement(storedProcedure); cs.setReturnable(returnable); return cs; } ) { if (value instanceof Expression) { return new AssignmentStatement(elementID, (Expression)value); } if (value instanceof QueryCommand) { return new AssignmentStatement(elementID, (QueryCommand)value); } return new AssignmentStatement(elementID, (Command)value); } } /* name=assignment statement operand description=A value or command that can be used in an assignment. {note}All assignments except for expression are deprecated.{note} */ LanguageObject assignStatementOperand(ParseInfo info) : { LanguageObject value = null; } { ( LOOKAHEAD() (value = insert(info)) | //deprecated value = update(info) | //deprecated value = delete(info) | //deprecated LOOKAHEAD(1) value = expression(info) | value = queryExpression(info) | //deprecated should be a scalar subquery value = exception(info) ) { return value; } } /* name=data statement description=A procedure statement that executes a SQL statement. An update statement can have its update count accessed via the ROWCOUNT variable. */ CommandStatement sqlStatement(ParseInfo info) : { Command cmd = null; String var = null; ElementSymbol elementID = null; StoredProcedure storedProcedure = null; boolean returnable = true; } { (LOOKAHEAD(2) cmd = userCommand(info) | cmd = dynamicCommand(info) ) [(| {returnable = false;}) ] { CommandStatement cs = new CommandStatement(cmd); cs.setReturnable(returnable); return cs; } } /* unused=true */ CreateProcedureCommand createProcedure(ParseInfo info) : { CreateProcedureCommand procCmd = new CreateProcedureCommand(); Statement stmt = null; } { [] stmt = statement(info) { procCmd.setBlock(asBlock(stmt)); return procCmd; } } /* name=procedure body definition description=Defines a procedure body on a Procedure metadata object. example=[source,sql]\n----\nBEGIN ... END\n----\n unused=true */ CreateProcedureCommand procedureBodyCommand(ParseInfo info) : { CreateProcedureCommand procCmd = new CreateProcedureCommand(); Statement stmt = null; } { [LOOKAHEAD(2) [] ] stmt = statement(info) { procCmd.setBlock(asBlock(stmt)); return procCmd; } } /* name=dynamic data statement description=A procedure statement that can execute arbitrary sql. example=[source,sql]\n----\nEXECUTE IMMEDIATE 'SELECT * FROM tbl' AS x STRING INTO #temp\n----\n */ DynamicCommand dynamicCommand(ParseInfo info) : { Expression sql = null; String groupID = null; GroupSymbol group = null; int updateCount = 0; List elements = null; SetClauseList using = null; DynamicCommand dcStmt = new DynamicCommand(); SetClauseList setClauseList = null; } { (|) [(|)] sql = expression(info) { dcStmt.setSql(sql); } [ elements = createElementsWithTypes(info) [ groupID = id(null) { group = new GroupSymbol(groupID); } ] { dcStmt.setIntoGroup(group); List symbols = new ArrayList(elements.size()); for (TableFunctionReference.ProjectedColumn col : elements) { symbols.add(col.getSymbol()); } dcStmt.setAsColumns(symbols); dcStmt.setAsClauseSet(true); } ] [ using = setClauseList(true, info) { dcStmt.setUsing(using); } ] [ (updateCount = intVal() | { updateCount = 2; }) ] { dcStmt.setUpdatingModelCount(updateCount); return dcStmt; } } /* name=set clause list description=A list of value assignments. example=[source,sql]\n----\ncol1 = 'x', col2 = 'y' ...\n----\n */ SetClauseList setClauseList(boolean shortName, ParseInfo info) : { SetClauseList using = new SetClauseList(); String element = null; Expression value = null; } { element = id(shortName?Boolean.TRUE:null) value = expression(info) { ElementSymbol symbol = new ElementSymbol(element); using.addClause(symbol, value); } ( element = id(null) value = expression(info) { symbol = new ElementSymbol(element); using.addClause(symbol, value); } )* { return using; } } /* name=typed element list description=A list of typed elements. example=[source,sql]\n----\ncol1 string, col2 integer ...\n----\n */ List createElementsWithTypes(ParseInfo info) : { String element = null; ParsedDataType type = null; List elements = new ArrayList(); } { element = id(Boolean.TRUE) type = parseBasicDataType() { TableFunctionReference.ProjectedColumn symbol = new TableFunctionReference.ProjectedColumn(element, type.type); elements.add(symbol); } (LOOKAHEAD(2) element = id(Boolean.TRUE) type = parseBasicDataType() { symbol = new TableFunctionReference.ProjectedColumn(element, type.type); elements.add(symbol); } )* { return elements; } } /* name=callable statement description=A callable statement defined using JDBC escape syntax. example=[source,sql]\n----\n{? = CALL proc}\n----\n index=true */ StoredProcedure callableStatement(ParseInfo info) : { StoredProcedure storedProcedure = new StoredProcedure(); storedProcedure.setCallableStatement(true); String procName = null; Option option = null; SPParameter parameter = null; int parameterIndex = 1; List values = null; } { [ { parameter = new SPParameter(parameterIndex++, SPParameter.RETURN_VALUE, "return"); //$NON-NLS-1$ storedProcedure.setParameter(parameter); storedProcedure.setCalledWithReturn(true); } ] procName = id(null) { storedProcedure.setProcedureName(procName); } //parameters [ (LOOKAHEAD(2) executeNamedParams(info, storedProcedure, parameterIndex) | [values = expressionList(info) { convertToParameters(values, storedProcedure, parameterIndex); }] ) ] [option = option(info) { storedProcedure.setOption(option); } ] { return storedProcedure; } } /* name=call statement description=Executes the procedure with the given parameters. example=[source,sql]\n----\nCALL proc('a', 1)\n----\n */ StoredProcedure storedProcedure(ParseInfo info, int startIndex) : { String procName = null; Option option = null; List values = null; StoredProcedure storedProcedure = new StoredProcedure(); SourceHint sourceHint = null; } { { sourceHint = getSourceHint(this); } ( ( | | ) procName = id(null) { storedProcedure.setProcedureName(procName); } //parameters ( LOOKAHEAD(2) executeNamedParams(info, storedProcedure, startIndex) | [values = expressionList(info) { convertToParameters(values, storedProcedure, startIndex); }] ) ) [option = option(info) { storedProcedure.setOption(option); } ] { storedProcedure.setSourceHint(sourceHint); return storedProcedure; } } /* name=named parameter list description=A list of named parameters. example=[source,sql]\n----\nparam1 => 'x', param2 => 1\n----\n */ void executeNamedParams(ParseInfo info, StoredProcedure storedProcedure, int parameterIndex) : { String name = null; Expression value = null; SPParameter parameter = null; } { { storedProcedure.setDisplayNamedParameters(true); } (name=id(null) [] value = expression(info) { parameter = new SPParameter(parameterIndex++, value); parameter.setName(name); parameter.setParameterType(SPParameter.IN); storedProcedure.setParameter(parameter); parameter = null; } ( name=id(null) [] value = expression(info) { parameter = new SPParameter(parameterIndex++, value); parameter.setName(name); parameter.setParameterType(SPParameter.IN); storedProcedure.setParameter(parameter); parameter = null; } )* ) } /* name=insert statement description=Inserts values into the given target. example=[source,sql]\n----\nINSERT INTO tbl (col1, col2) VALUES ('a', 1)\n----\n */ Insert insert(ParseInfo info) : { Insert insert = new Insert(); boolean upsert = false; String group = null; List values = null; List columns = null; Option option = null; QueryCommand query = null; } { (|{upsert=true;}|{upsert=true;}) group = id(null) [LOOKAHEAD( id(null)) columns = columnList(false, true) { insert.setVariables(columns); }] query = queryExpression(info) { insert.setQueryExpression(query); } [ option = option(info) { insert.setOption(option); } ] { // Store group insert.setGroup(new GroupSymbol(group) ); insert.setUpsert(upsert); return insert; } } /* name=expression list description=A list of expressions. example=[source,sql]\n----\ncol1, 'a', ...\n----\n */ ArrayList expressionList(ParseInfo info) : { ArrayList rowVals = new ArrayList(4); Expression value = null; } { value = expression(info) { rowVals.add(value); } ( value = expression(info) { rowVals.add(value); } )* { return rowVals; } } /* name=update statement description=Update values in the given target. example=[source,sql]\n----\nUPDATE tbl SET (col1 = 'a') WHERE col2 = 1\n----\n */ Update update(ParseInfo info) : { Update update = new Update(); String group = null; SetClauseList setClauseList = null; Criteria criteria = null; Option option = null; String aliasID = null; } { group = id(null) [[] aliasID=id(Boolean.FALSE)] setClauseList = setClauseList(false, info) { update.setChangeList(setClauseList); } [ criteria = where(info) ] [option = option(info) { update.setOption(option); } ] { // Store group if(aliasID != null) { update.setGroup(new GroupSymbol(aliasID, group)); } else { update.setGroup(new GroupSymbol(group)); } // Store optional criteria update.setCriteria(criteria); return update; } } /* name=delete statement description=Delete rows from the given target. example=[source,sql]\n----\nDELETE FROM tbl WHERE col2 = 1\n----\n */ Delete delete(ParseInfo info) : { String group = null; Criteria criteria = null; Delete delete = new Delete(); Option option = null; String aliasID = null; } { group = id(null) [[] aliasID=id(Boolean.FALSE)] [criteria = where(info)] [option = option(info) { delete.setOption(option); } ] { if(aliasID != null) { delete.setGroup(new GroupSymbol(aliasID, group)); } else { delete.setGroup(new GroupSymbol(group)); } delete.setCriteria(criteria); return delete; } } /* name=query expression description=A declarative query for data. example=[source,sql]\n----\nSELECT * FROM tbl WHERE col2 = 1\n----\n */ QueryCommand queryExpression(ParseInfo info) : { QueryCommand query = null; List withList = null; WithQueryCommand withQueryCommand = null; SourceHint sourceHint = null; } { [ withQueryCommand = withListElement(info) { withList = new LinkedList(); withList.add(withQueryCommand); } ( withQueryCommand = withListElement(info) { withList.add(withQueryCommand); } )* ] { sourceHint = getSourceHint(this); } query = queryExpressionBody(info) { query.setWith(withList); setSourceHint(sourceHint, query); return query; } } /* name=with list element description=A query expression for use in the enclosing query. example=[source,sql]\n----\nX (Y, Z) AS (SELECT 1, 2)\n----\n */ WithQueryCommand withListElement(ParseInfo info) : { String name = null; List columns = null; QueryCommand queryExpression = null; Token lparen = null; } { name = id(Boolean.FALSE) [ columns = columnList(true, true)] lparen = queryExpression = queryExpression(info) { WithQueryCommand result = new WithQueryCommand(new GroupSymbol(name), columns, queryExpression); parseWithHints(lparen, result); return result; } } /* name=query expression body description=The body of a query expression, which can optionally be ordered and limited. example=[source,sql]\n----\nSELECT * FROM tbl ORDER BY col1 LIMIT 1\n----\n */ QueryCommand queryExpressionBody(ParseInfo info) : { QueryCommand query = null; QueryCommand rightQuery = null; boolean all = false; Option option = null; OrderBy orderby = null; Limit limit = null; SetQuery.Operation type; } { query = queryTerm(info) ( (LOOKAHEAD( , { getToken(2).kind != JOIN } ) { type = SetQuery.Operation.UNION; } | { type = SetQuery.Operation.EXCEPT; }) [ { all = true; } | ] rightQuery = queryTerm(info) { query = addQueryToSetOperation(query, rightQuery, type, all); all = false; } ) * [orderby = orderby(info) {query.setOrderBy( orderby );}] [limit = limit(info) {query.setLimit( limit );}] [LOOKAHEAD(
name=id(null) { Query q = new Query(); q.setSelect(new Select(Arrays.asList(new MultipleElementSymbol()))); q.setFrom(new From(Arrays.asList(new UnaryFromClause(new GroupSymbol(name))))); query = q; }) | ( query=queryExpressionBody(info) ) ) { return query; } } /* name=query description=A SELECT query. example=[source,sql]\n----\nSELECT col1, max(col2) FROM tbl GROUP BY col1\n----\n */ Query query(ParseInfo info) : { Select select = null; From from = null; Into into = null; Criteria criteria = null; GroupBy groupBy = null; Criteria having = null; } { select = select(info) [into = into(info)] [from = from(info) [criteria = where(info)] [groupBy = groupBy(info)] [having = having(info)]] { // Build query from parsed pieces Query query = new Query(); query.setSelect( select ); query.setFrom( from ); query.setInto( into ); query.setCriteria(criteria); query.setGroupBy(groupBy); query.setHaving(having); return query; } } /* name=into clause description=Used to direct the query into a table. {note}This is deprecated. Use INSERT INTO with a query expression instead.{note} example=[source,sql]\n----\nINTO tbl\n----\n */ Into into(ParseInfo info) : { String groupID = null; Into into = null; } { (groupID=id(null)) { into = new Into(new GroupSymbol(groupID)); return into; } } /* name=select clause description=The columns returned by a query. Can optionally be distinct. example=[source,sql]\n----\nSELECT *\n----\n\n[source,sql]\n----\nSELECT DISTINCT a, b, c\n----\n */ Select select(ParseInfo info) : { boolean isDistinct = false; // unless DISTINCT keyword in SELECT Expression symbol = null; Select select = new Select(); } {
|) { table = true; } ] lparen = ( command = queryExpression(info) | command = storedProcedure(info, 1) ) [] aliasID = id(null) { validateQuotedName(aliasID, getToken(0).image); } { SubqueryFromClause clause = new SubqueryFromClause(aliasID, command); setFromClauseOptions(lparen, clause); clause.setLateral(table); return clause; } } /* name=table name description=A table named in the FROM clause. example=[source,sql]\n----\ntbl AS x\n----\n */ UnaryFromClause unaryFromClause(ParseInfo info) : { GroupSymbol group = null; String groupID = null; Token groupToken = null; String aliasID = null; UnaryFromClause clause = null; } { (groupID=id(null) {groupToken = getToken(0);} [ [] aliasID=id(null) { validateQuotedName(aliasID, getToken(0).image); } ]) { if(aliasID != null) { group = new GroupSymbol(aliasID, groupID); } else { group = new GroupSymbol(groupID); } clause = new UnaryFromClause(group); setFromClauseOptions(groupToken, clause); return clause; } } /* name=where clause description=Specifies a search condition example=[source,sql]\n----\nWHERE x = 'a'\n----\n */ Criteria where(ParseInfo info) : { Criteria criteria = null; } { criteria = criteria(info) { return criteria; } } /* name=condition description=A boolean expression. */ Criteria criteria(ParseInfo info) : { Criteria criteria = null; } { criteria = compoundCritOr(info) { return criteria; } } /* name=boolean value expression description=An optionally ORed boolean expression. */ Criteria compoundCritOr(ParseInfo info) : { ArrayList logicList = null; Criteria logicPart = null; Criteria logicPart1 = null; } { logicPart=compoundCritAnd(info) ( logicPart1=compoundCritAnd(info) { if (logicList == null) { logicList = new ArrayList(2); logicList.add(logicPart); } logicList.add(logicPart1); } )* { if(logicList == null) { return logicPart; } else { return new CompoundCriteria(CompoundCriteria.OR,logicList); } } } /* name=boolean term description=An optional ANDed boolean factor. */ Criteria compoundCritAnd(ParseInfo info) : { ArrayList logicList = null; Criteria logicPart = null; Criteria logicPart1 = null; } { logicPart=notCrit(info) ( logicPart1=notCrit(info) { if (logicList == null) { logicList = new ArrayList(2); logicList.add(logicPart); } logicList.add(logicPart1); } )* { if(logicList == null) { return logicPart; } else { return new CompoundCriteria(CompoundCriteria.AND,logicList); } } } /* name=boolean factor description=A boolean factor. example=[source,sql]\n----\nNOT x = 'a'\n----\n */ Criteria notCrit(ParseInfo info) : { Expression ex = null; boolean isNot = false; } { [ {isNot=true;}] ex=booleanPrimary(info) { Criteria crit = null; if (ex instanceof Criteria) { crit = (Criteria)ex; } else { crit = new ExpressionCriteria(ex); } if(isNot) { return new NotCriteria(crit); } else { return crit; } } } /* name=boolean primary description=A boolean predicate or simple expression. example=[source,sql]\n----\ncol LIKE 'a%'\n----\n */ Expression booleanPrimary(ParseInfo info) : { Expression ex = null; } { ( (ex = commonValueExpression(info) [( LOOKAHEAD(2) ex=betweenCrit(info, ex) | LOOKAHEAD(2) ex=matchCrit(info, ex) | LOOKAHEAD(2) ex=regexMatchCrit(info, ex) | ex=setCrit(info, ex) | LOOKAHEAD(()?)ex=isNullCrit(info, ex) | LOOKAHEAD(operator() (||)) ex=subqueryCompareCriteria(info, ex) | ex=compareCrit(info, ex) | ex=isDistinct(info, ex) )] ) | ex=existsCriteria(info) | ex=xmlExists(info) ) { return ex; } } /* name=comparison operator description=A comparison operator. example=[source,sql]\n----\n=\n----\n */ Token operator() : { Token operator = null; } { (operator= | operator= | operator= | operator= | operator= | operator= | operator= ) { return operator; } } /* name=is distinct description=Is Distinct Right Hand Side example=[source,sql]\n----\nIS DISTINCT FROM expression\n----\n */ IsDistinctCriteria isDistinct(ParseInfo info, Expression expression) : { Expression value = null; Token operator = null; boolean not = false; } { [ {not = true;}] value=commonValueExpression(info) { IsDistinctCriteria idc = new IsDistinctCriteria(); idc.setLeftRowValue(expression); idc.setRightRowValue(value); idc.setNegated(not); return idc; } } /* name=comparison predicate description=A value comparison. example=[source,sql]\n----\n= 'a'\n----\n */ CompareCriteria compareCrit(ParseInfo info, Expression expression) : { Expression value = null; Token operator = null; } { operator=operator() value=commonValueExpression(info) { CompareCriteria compareCriteria = new CompareCriteria(); // Set left expression compareCriteria.setLeftExpression(expression); compareCriteria.setOperator(getOperator(operator.image)); // Set value compareCriteria.setRightExpression(value); return compareCriteria; } } /* name=subquery description=A subquery. example=[source,sql]\n----\n(SELECT * FROM tbl)\n----\n */ QueryCommand subquery(ParseInfo info) : { QueryCommand subquery = null; StoredProcedure proc = null; } { ( subquery = queryExpression(info) | ( proc = storedProcedure(info, 1) //deprecated ) { subquery = new Query(new Select(Arrays.asList(new MultipleElementSymbol())), new From(Arrays.asList(new SubqueryFromClause("x", proc))), null, null, null); } ) { return subquery; } } /* name=quantified comparison predicate description=A subquery comparison. example=[source,sql]\n----\n= ANY (SELECT col FROM tbl)\n----\n */ SubqueryCompareCriteria subqueryCompareCriteria(ParseInfo info, Expression expression) : { SubqueryCompareCriteria subqueryCrit = null; QueryCommand subquery = null; Token operator = null; Token quantifier = null; ExistsCriteria.SubqueryHint hint = null; Expression expr = null; } { operator=operator() ( quantifier= | quantifier= | quantifier= ) { hint = getSubqueryHint(getToken(1)); } ( LOOKAHEAD(subquery(info)) subquery = subquery(info) | ( expr = expression(info) ) ) { subqueryCrit = new SubqueryCompareCriteria(); subqueryCrit.setLeftExpression(expression); subqueryCrit.setCommand(subquery); subqueryCrit.setArrayExpression(expr); // Set operator subqueryCrit.setOperator(getOperator(operator.image)); // Set predicate quantifier if(quantifier.image.equalsIgnoreCase("any")) { //$NON-NLS-1$ subqueryCrit.setPredicateQuantifier(SubqueryCompareCriteria.ANY); } else if(quantifier.image.equalsIgnoreCase("some")) { //$NON-NLS-1$ subqueryCrit.setPredicateQuantifier(SubqueryCompareCriteria.SOME); } else if(quantifier.image.equalsIgnoreCase("all")) { //$NON-NLS-1$ subqueryCrit.setPredicateQuantifier(SubqueryCompareCriteria.ALL); } subqueryCrit.setSubqueryHint(hint); return subqueryCrit; } } /* name=match predicate description=Matches based upon a pattern. example=[source,sql]\n----\nLIKE 'a_'\n----\n */ MatchCriteria matchCrit(ParseInfo info, Expression expression) : { Character esc = null; Expression value = null; boolean negated = false; boolean similar = false; Token t = null; } { [ {negated = true;}] (|( {similar = true;})) {t = getToken(1);} value=commonValueExpression(info) [ esc = charVal(info, "LIKE/SIMILAR TO ESCAPE") | ( esc = charVal(info, "LIKE/SIMILAR TO ESCAPE") ) ] { MatchCriteria matchcriteria = new MatchCriteria(expression, value); matchcriteria.setNegated(negated); if(esc == null && ((value instanceof Constant && t.image != null && t.image.startsWith("E'")) || info.isBackslashDefaultMatchEscape())) { esc = '\\'; } if (esc != null) { matchcriteria.setEscapeChar(esc.charValue()); } matchcriteria.setMode(similar?MatchMode.SIMILAR:MatchMode.LIKE); return matchcriteria; } } /* name=like regex predicate description=A regular expression match. example=[source,sql]\n----\nLIKE_REGEX 'a.*b'\n----\n */ MatchCriteria regexMatchCrit(ParseInfo info, Expression expression) : { Expression value = null; boolean negated = false; } { [ {negated = true;}] value=commonValueExpression(info) { MatchCriteria matchcriteria = new MatchCriteria(expression, value); matchcriteria.setNegated(negated); matchcriteria.setMode(MatchMode.REGEX); return matchcriteria; } } /* name=character description=A single character. example=[source,sql]\n----\n'a'\n----\n */ Character charVal(ParseInfo info, String type) : { String escStr = null; } { escStr=stringVal() { if (escStr.length() != 1) { throw new ParseException(QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30398, type, escStr)); //$NON-NLS-1$ } return Character.valueOf(escStr.charAt(0)); } } /* name=between predicate description=A comparison between two values. example=[source,sql]\n----\nBETWEEN 1 AND 5\n----\n */ BetweenCriteria betweenCrit(ParseInfo info, Expression expression) : { Expression lowerExpression = null, upperExpression = null; boolean negated = false; } { [ {negated=true;}] lowerExpression = commonValueExpression(info) upperExpression = commonValueExpression(info) { BetweenCriteria criteria = new BetweenCriteria(expression, lowerExpression, upperExpression); criteria.setNegated(negated); return criteria; } } /* name=is null predicate description=A null test. example=[source,sql]\n----\nIS NOT NULL\n----\n */ IsNullCriteria isNullCrit(ParseInfo info, Expression expression) : { boolean negated = false; IsNullCriteria criteria = null; } { [ {negated = true;}] { criteria = new IsNullCriteria(expression); criteria.setNegated(negated); return criteria; } } /* name=in predicate description=A comparison with multiple values. example=[source,sql]\n----\nIN (1, 5)\n----\n */ AbstractSetCriteria setCrit(ParseInfo info, Expression expression) : { Expression value = null; List setList = new ArrayList(); QueryCommand command = null; ExistsCriteria.SubqueryHint hint = null; boolean negated = false; AbstractSetCriteria criteria = null; } { [ {negated = true;}] ( LOOKAHEAD(subquery(info)) { hint = getSubqueryHint(getToken(1)); } (command = subquery(info)) | ( value = commonValueExpression(info) { setList.add(value); } ( value = commonValueExpression(info) { setList.add(value); } )* ) ) { if (command != null) { SubquerySetCriteria ssc = new SubquerySetCriteria(expression, command); ssc.setSubqueryHint(hint); criteria = ssc; } else { criteria = new SetCriteria(expression, setList); } criteria.setNegated(negated); return criteria; } } /* name=exists predicate description=A test if rows exist. example=[source,sql]\n----\nEXISTS (SELECT col FROM tbl)\n----\n */ ExistsCriteria existsCriteria(ParseInfo info) : { QueryCommand subquery = null; ExistsCriteria.SubqueryHint hint = null; } { { hint = getSubqueryHint(getToken(1)); } subquery = subquery(info) { ExistsCriteria existsCrit = new ExistsCriteria(subquery); existsCrit.setSubqueryHint(hint); return existsCrit; } } /* name=group by clause description=Defines the grouping columns example=[source,sql]\n----\nGROUP BY col1, col2\n----\n */ GroupBy groupBy(ParseInfo info) : { List expressions = null; boolean rollup = false; } { ( expressions = expressionList(info) { rollup = true; } | expressions = expressionList(info) ) { GroupBy result = new GroupBy(expressions); result.setRollup(rollup); return result; } } /* name=having clause description=Search condition applied after grouping. example=[source,sql]\n----\nHAVING max(col1) = 5\n----\n */ Criteria having(ParseInfo info) : { Criteria criteria = null; } { criteria = criteria(info) { return criteria; } } /* name=order by clause description=Specifices row ordering. example=[source,sql]\n----\nORDER BY x, y DESC\n----\n */ OrderBy orderby(ParseInfo info) : { OrderBy orderby = new OrderBy(); OrderByItem item = null; } { item = sortSpecification(info) { orderby.getOrderByItems().add(item); } ( item = sortSpecification(info) { orderby.getOrderByItems().add(item); } )* { return orderby; } } /* name=sort specification description=Defines how to sort on a particular expression example=[source,sql]\n----\ncol1 NULLS FIRST\n----\n */ OrderByItem sortSpecification(ParseInfo info) : { Expression ex = null; boolean ascending = true; org.teiid.language.SortSpecification.NullOrdering nullOrdering = null; } { ex=sortKey(info) [ | {ascending=false;}] [ ( {nullOrdering=org.teiid.language.SortSpecification.NullOrdering.FIRST;} | {nullOrdering=org.teiid.language.SortSpecification.NullOrdering.LAST;})] { OrderByItem item = new OrderByItem(ex, ascending); if (nullOrdering != null) { item.setNullOrdering(nullOrdering); } return item; } } /* name=sort key description=A sort expression. example=[source,sql]\n----\ncol1\n----\n */ Expression sortKey(ParseInfo info) : { Expression ex = null; } { ex=expression(info) { //legacy support check for positional constants if (ex instanceof Constant) { boolean valid = false; Constant c = (Constant)ex; if (c.getValue() instanceof Integer) { Integer val = (Integer)c.getValue(); valid = val.intValue() > 0; } if (!valid) { throw new ParseException(QueryPlugin.Util.getString("SQLParser.non_position_constant", ex)); //$NON-NLS-1$ } } return ex; } } /* name=integer parameter description=A literal integer or parameter reference to an integer. example=[source,sql]\n----\n?\n----\n */ Expression intParam(ParseInfo info) : { Expression ex = null; Integer val = null; } { val = intVal() { return new Constant(val, DataTypeManager.DefaultDataClasses.INTEGER); } | ex = unsignedValueExpressionPrimary(info) { return ex; } } /* name=limit clause description=Limits and/or offsets the resultant rows. example=[source,sql]\n----\nLIMIT 2\n----\n */ Limit limit(ParseInfo info) : { Expression limit = null; Expression offset = null; Token t = null; } { {t = getToken(1);} (( offset = intParam(info) [( limit = intParam(info))| ( limit = intParam(info) {Expression temp = limit; limit = offset; offset = temp;})]) { if (limit == null) { limit = offset; offset = null; } } | ( offset = intParam(info) (|) [limit = fetchLimit(info)]) | (limit = fetchLimit(info))) { Limit result = new Limit(offset, limit); result.setStrict(!isNonStrictHint(t)); return result; } } /* name=fetch clause description=ANSI limit. example=[source,sql]\n----\nFETCH FIRST 1 ROWS ONLY\n----\n */ Expression fetchLimit(ParseInfo info) : { Expression limit = null; } { ( | ) [limit = intParam(info)] (|) { if (limit == null) { return new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER); } return limit; } } /* name=option clause description=Specifies query options. example=[source,sql]\n----\nOPTION MAKEDEP tbl\n----\n */ Option option(ParseInfo info) : { String id = null; Token nocache = null; Option option = new Option(); Option.MakeDep makedep = null; } {
resource = id(null) {on = Database.ResourceType.TABLE;} [ [[{isConstraint=false;}] {if (isConstraint == null) isConstraint=true;}] condition = stringVal()]) | ( resource = id(null) {on = Database.ResourceType.FUNCTION;}) | ( resource = id(null) {on = Database.ResourceType.PROCEDURE;} [ [[{isConstraint=true;}] {if (isConstraint == null) isConstraint=true;}] condition = stringVal()]) | ( resource = id(null) {on = Database.ResourceType.SCHEMA;}) | ( resource = id(null) {on = Database.ResourceType.COLUMN;} [ [ maskOrder = intVal()] mask = stringVal()] [ (LOOKAHEAD(criteria(ParseInfo.DEFAULT_INSTANCE)) booleanExpr = criteria(ParseInfo.DEFAULT_INSTANCE) | condition = stringVal())] ) ) ) | ( {privileges.add(Permission.Privilege.ALL_PRIVILEGES);}) | (
{privileges.add(Permission.Privilege.TEMPORARY_TABLE);}) | ( {privileges.add(Permission.Privilege.USAGE); on = Database.ResourceType.LANGUAGE;} resource=id(null)) ) ( to = id(null) { if (privileges.isEmpty() && condition == null && mask == null) { throw new MetadataException(QueryPlugin.Util.getString("SQLParser.empty_grant_revoke")); } permission.setResourceName(resource); permission.setPrivileges(privileges); permission.setResourceType(on); if (booleanExpr != null) { condition = booleanExpr.toString(); } if (mask != null) { permission.setMask(mask); if (maskOrder != -1) { permission.setMaskOrder(maskOrder); } } if(condition != null) { permission.setCondition(condition, isConstraint); } grant.setRole(to); grant.setPermission(permission); dbStore.grantCreated(grant); } ) } /* name=Revoke GRANT description=Revokes GRANT for a role example=[source,sql]\n----\nREVOKE SELECT ON TABLE x.y TO role\n----\n */ void revokeGrant(DatabaseStore dbStore) : { Database.ResourceType on= null; Grant grant = new Grant(); String resource = null; String mask = null; String condition = null; String to = null; ArrayList privileges = new ArrayList(); Permission permission = new Permission(); } { (( [readGrantTypes(privileges) ( readGrantTypes(privileges))*] (
resource = id(null) {on = Database.ResourceType.TABLE;} [ {condition = "";}] | resource = id(null) {on = Database.ResourceType.FUNCTION;} | resource = id(null) {on = Database.ResourceType.PROCEDURE;} [ {condition = "";} ] | resource = id(null) {on = Database.ResourceType.SCHEMA;} | resource = id(null) {on = Database.ResourceType.COLUMN;} [ {mask = "";} ] ) ) | ( {privileges.add(Permission.Privilege.ALL_PRIVILEGES);}) | (
{privileges.add(Permission.Privilege.TEMPORARY_TABLE);}) | ( {privileges.add(Permission.Privilege.USAGE); on = Database.ResourceType.LANGUAGE;} resource=id(null)) ) ( to = id(null) { if (privileges.isEmpty() && condition == null && mask == null) { throw new MetadataException(QueryPlugin.Util.getString("SQLParser.empty_grant_revoke")); } permission.setResourceName(resource); permission.setRevokePrivileges(privileges); permission.setResourceType(on); if (mask != null) { permission.setMask(mask); } if(condition != null) { permission.setCondition(condition, null); } grant.setRole(to); grant.setPermission(permission); dbStore.grantRevoked(grant); } ) } /* name=create server description=Defines a connection to a source example=[source,sql]\n----\nCREATE SERVER "h2-connector" FOREIGN DATA WRAPPER h2 OPTIONS ("resource-name" 'java:/accounts-ds');\n----\n */ void createServer(DatabaseStore dbStore) : { String serverName = null; String type = null; String version = null; Server server = null; String wrapperName = null; } { ( serverName = unqualifiedId() { server = new Server(serverName); } ) [ ( type = stringVal() { server.setType(type); } ) ] [ ( version = stringVal() { server.setVersion(version); } ) ] (( )|) ( wrapperName = unqualifiedId() { server.setDataWrapper(wrapperName); } ) [ optionsClause(server, dbStore.getCurrentNamespaceContainer()) { OptionsUtil.setOptions(server); } ] { dbStore.serverCreated(server); } } /* name=drop server description=Defines dropping connection to foreign source example=[source,sql]\n----\nDROP SERVER server_name\n----\n */ void dropServer(DatabaseStore dbStore) : { String serverName = null; } { ( serverName = id(null) { dbStore.serverDropped(serverName); } ) } /* name=create procedure description=Defines a procedure or function invocation. example=[source,sql]\n----\nCREATE FOREIGN PROCEDURE proc (param STRING) RETURNS STRING\n----\n */ CreateProcedureCommand createDDLProcedure(DatabaseStore dbStore, ParseInfo info) : { Procedure proc = null; CreateProcedureCommand procCmd = new CreateProcedureCommand(); Statement stmt = null; ParsedDataType returnDataType = null; Token comment = null; Column c = new Column(); MetadataFactory factory = null; String serverName = null; FunctionMethod fm = null; boolean virtual = true; boolean function = false; String procName = null; } { [ | {virtual = false;}]( | {function = true;}) procName = unqualifiedId() //the below is optional because to allow the designer based metadata ( { factory = DatabaseStore.createMF(dbStore); proc = factory.addProcedure(procName); } [procedureParameter(factory, proc) ( procedureParameter(factory, proc))*] [ [optionsClause(c, factory)] (([
] procedureRsColumn(factory, proc) ( procedureRsColumn(factory, proc))* ) | returnDataType = parseDataType()) ] [ optionsClause(proc, factory) { OptionsUtil.setOptions(proc); } ] [ { comment = getToken(1); } stmt = statement(info)]) { proc.setVirtual(virtual); proc.setFunction(function); if (stmt != null){ if (!virtual) { throw new MetadataException(QueryPlugin.Util.getString("SQLParser.function_def", procName)); } proc.setQueryPlan(getFullComment(comment, true) + stmt.toString()); } if (returnDataType != null){ BaseColumn result = addProcColumn(factory, proc, "return", returnDataType, false); result.setProperties(c.getProperties()); } else if (proc.getResultSet() != null) { proc.getResultSet().setProperties(c.getProperties()); } if (function && proc.getQueryPlan() == null) { fm = replaceProcedureWithFunction(factory, proc); if (fm != null) { dbStore.functionCreated(fm); } } else { dbStore.procedureCreated(proc); } return procCmd; } } /* name=drop procedure description=Drops a table or view. example=[source,sql]\n----\nDROP FOREIGN TABLE table-name\n----\n */ void dropProcedure(DatabaseStore dbStore) : { String procedureName = null; Boolean virtual = null; boolean function = false; } { [ {virtual = true;}| {virtual = false;}]( | {function = true;}) procedureName = id(null) { if (function){ dbStore.functionDropped(procedureName, virtual); } else { dbStore.procedureDropped(procedureName, virtual); } } } /* name=procedure parameter description=A procedure or function parameter example=[source,sql]\n----\nOUT x INTEGER\n----\n */ void procedureParameter(MetadataFactory factory, Procedure proc) : { String name = null; ParsedDataType type = null; ProcedureParameter.Type ppType = ProcedureParameter.Type.In; ProcedureParameter param = null; Expression defaultValue = null; boolean notNull = false; boolean vararg = false; } { [LOOKAHEAD(1) (( {ppType = ProcedureParameter.Type.In ;}) |( {ppType = ProcedureParameter.Type.Out;}) |( {ppType = ProcedureParameter.Type.InOut;}) |( {ppType = ProcedureParameter.Type.In ; vararg = true;}))] name = id(Boolean.TRUE) type = parseDataType() [ {notNull = true;}] [ { if (ppType != ProcedureParameter.Type.Out) { throw new ParseException(QueryPlugin.Util.getString("SQLParser.param_out", proc.getName(), name)); } ppType = ProcedureParameter.Type.ReturnValue; if (!RESULT_ANY_POSITION && !proc.getParameters().isEmpty()) { throw new ParseException(QueryPlugin.Util.getString("SQLParser.param_result_first", proc.getName(), name)); } } ] { param = factory.addProcedureParameter(name, type.type, ppType, proc); setTypeInfo(type, param); if (notNull) { param.setNullType(Column.NullType.No_Nulls); } if (vararg) { param.setVarArg(vararg); } } [ defaultValue = expression(ParseInfo.DEFAULT_INSTANCE) {setDefault(param, defaultValue);}] [optionsClause(param, factory) { OptionsUtil.setOptions(param); } ] } /* name=procedure result column description=A procedure result column. example=[source,sql]\n----\nx INTEGER\n----\n */ void procedureRsColumn(MetadataFactory factory, Procedure proc) : { String name = null; ParsedDataType type = null; boolean notNull = false; BaseColumn column = null; } { name = id(Boolean.TRUE) type = parseDataType() { column = addProcColumn(factory, proc, name, type, true); } [ {column.setNullType(Column.NullType.No_Nulls);}] [optionsClause(column, factory) { OptionsUtil.setOptions(column); } ] } /* name=create table description=Defines a table or view. example=[source,sql]\n----\nCREATE VIEW vw AS SELECT 1\n----\n */ void createTable(DatabaseStore dbStore) : { } { (createView(dbStore) | createForeignOrGloablTable(dbStore)) } /* name=create foreign or global temporary table description=Defines a foreign or global temporary table. example=[source,sql]\n----\nFOREIGN TABLE ft (col integer)\n----\n */ void createForeignOrGloablTable(DatabaseStore dbStore) : { boolean globalTemp = false; String tableName = null; Table table = null; Token comment = null; Command query = null; MetadataFactory factory = null; } { ( (
) | (
{globalTemp = true;}) ) tableName = unqualifiedId() { factory = DatabaseStore.createMF(dbStore); table = factory.addTable(tableName); table.setVirtual(globalTemp); if (globalTemp) { table.setTableType(Table.Type.TemporaryTable); } } createTableBody(table, factory) { dbStore.tableCreated(table); } } /* name=create view description=Defines a view. example=[source,sql]\n----\nVIEW vw AS SELECT 1\n----\n */ void createView(DatabaseStore dbStore) : { String tableName = null; Table table = null; Token comment = null; Command query = null; MetadataFactory factory = null; } { [] tableName = unqualifiedId() { factory = DatabaseStore.createMF(dbStore); table = factory.addTable(tableName); table.setVirtual(true); } (createViewBody(table, factory) | [optionsClause(table, factory) { OptionsUtil.setOptions(table); } ]) { comment = getToken(1); } query = queryExpression(ParseInfo.DEFAULT_INSTANCE) { table.setSelectTransformation(getFullComment(comment, true) + query.toString()); } { dbStore.tableCreated(table); } } /* name=drop table description=Drops a table or view. example=[source,sql]\n----\nDROP VIEW name\n----\n */ void dropTableView(DatabaseStore dbStore) : { boolean view = false; boolean globalTemp = false; String tableName = null; } { ( (
) | ([] {view = true;}) | (
{globalTemp = true; view = true;}) ) tableName = id(null) { dbStore.tableDropped(tableName, globalTemp, view); } } /* name=create foreign temp table description=Defines a foreign temp table example=[source,sql]\n----\nCREATE FOREIGN TEMPORARY TABLE t (x string) ON z\n----\n */ Create createForeignTempTable(ParseInfo info) : { Table table = null; String tableName = null; String model = null; MetadataFactory factory = getTempMetadataFactory(); } { []
tableName = unqualifiedId() { table = new Table(); //need to set a dummy/stable uuid table.setUUID("tid:0"); table.setTableType(Table.Type.TemporaryTable); table.setName(tableName); } createTableBody(table, factory) model = id(null) { Create create = new Create(); create.setTableMetadata(table); create.setOn(model); return create; } } /* name=create table body description=Defines a table. example=[source,sql]\n----\n(x string) OPTIONS (CARDINALITY 100)\n----\n */ void createTableBody(Table table, MetadataFactory factory) : { } { createColumn(factory, table) ( (LOOKAHEAD(2) tableConstraint(factory, table) | createColumn(factory, table)) )* [optionsClause(table, factory) { OptionsUtil.setOptions(table); } ] { if (table.getColumns() != null && !table.supportsUpdate()) { for (Column c : table.getColumns()) { c.setUpdatable(false); } } } } /* name=create view body description=Defines a view. example=[source,sql]\n----\n(x) OPTIONS (CARDINALITY 100)\n----\n */ void createViewBody(Table table, MetadataFactory factory) : { } { createViewColumn(factory, table) ( (LOOKAHEAD(2) tableConstraint(factory, table) | createViewColumn(factory, table)) )* [optionsClause(table, factory) { OptionsUtil.setOptions(table); } ] { if (table.getColumns() != null && !table.supportsUpdate()) { for (Column c : table.getColumns()) { c.setUpdatable(false); } } } } /* name=table constraint description=Defines a constraint on a table or view. example=[source,sql]\n----\nFOREIGN KEY (a, b) REFERENCES tbl (x, y)\n----\n */ void tableConstraint(MetadataFactory factory, Table table) : { String name = null; AbstractMetadataRecord constraint = null; } { [ name = id(null)] (constraint = primaryKey(factory, table, name) | constraint = constraint(factory, table, name, ParseInfo.DEFAULT_INSTANCE) | constraint = foreignKey(factory, table, name) ) [optionsClause(constraint, factory) { OptionsUtil.setCommonProperties(constraint, constraint.getProperties()); }] } /* name=foreign key description=Defines the foreign key referential constraint. example=[source,sql]\n----\nFOREIGN KEY (a, b) REFERENCES tbl (x, y)\n----\n */ AbstractMetadataRecord foreignKey(MetadataFactory factory, Table table, String name) : { List columnNames = null; String viewName = null; Table reference = null; KeyRecord pk = null; Column column = null; List pkColumnNames = null; KeyRecord key = null; } { columnNames = columnList(true, false) viewName = id(null) [pkColumnNames = columnList(true, false)] { return factory.addForeignKey(name != null?name:("FK"+table.getForeignKeys().size()), columnNames, pkColumnNames, viewName, table); } } /* name=primary key description=Defines the primary key. example=[source,sql]\n----\nPRIMARY KEY (a, b)\n----\n */ AbstractMetadataRecord primaryKey(MetadataFactory factory, Table table, String name) : { List columnNames = null; Column column = null; KeyRecord key = null; } { columnNames = columnList(true, false) { if (table.getPrimaryKey() != null){ throw new MetadataException(QueryPlugin.Util.getString("SQLParser.pk_exists", table.getName())); } return factory.addPrimaryKey(name!=null?name:"PK", columnNames, table); } } /* name=other constraints description=Defines ACCESSPATTERN and UNIQUE constraints and INDEXes. example=[source,sql]\n----\nUNIQUE (a)\n----\n */ AbstractMetadataRecord constraint(MetadataFactory factory, Table table, String name, ParseInfo info) : { KeyRecord keyrecord = null; Column column = null; List columnNames = null; Token type = null; KeyRecord key = null; List expressions = null; } { (( type = | type = ) columnNames = columnList(true, false) { if (type.image.equalsIgnoreCase("UNIQUE")) { return factory.addIndex(name != null?name:("UNIQUE"+table.getUniqueKeys().size()), false, columnNames, table); } else if (type.image.equalsIgnoreCase("ACCESSPATTERN")) { return factory.addAccessPattern(name != null?name:("AP"+table.getAccessPatterns().size()), columnNames, table); } }) | ( type = expressions = expressionList(info) { return addFBI(factory, expressions, table, name); } ) } /* name=column list description=A list of column names. example=[source,sql]\n----\n(a, b)\n----\n */ List columnList(boolean validate, boolean asElementSymbols) : { ArrayList list = new ArrayList(); String id = null; } { id = id(validate?Boolean.TRUE:null) { if (asElementSymbols) { list.add(new ElementSymbol(id)); } else { list.add(id); } } ( id = id(validate?Boolean.TRUE:null) { if (asElementSymbols) { list.add(new ElementSymbol(id)); } else { list.add(id); } } )* { return list; } } /* name=table element description=Defines a table column. example=[source,sql]\n----\nx INTEGER NOT NULL\n----\n */ void createColumn(MetadataFactory factory, Table table) : { String element = null; ParsedDataType type = null; boolean autoIncrement = false; boolean notNull = false; Expression defaultValue = null; Column column = null; List columnName = new ArrayList(); } { element = id(Boolean.TRUE) ( { type = new ParsedDataType("INTEGER"); autoIncrement = true; notNull = true; } | ( type = parseDataType() [ { notNull = true; }] [ { autoIncrement = true; }] ) ) postCreateColumn(factory, table, element, type, autoIncrement, notNull) } /* name=view element description=Defines a view column with optional type. example=[source,sql]\n----\nx INTEGER NOT NULL\n----\n */ void createViewColumn(MetadataFactory factory, Table table) : { String element = null; ParsedDataType type = null; boolean autoIncrement = false; boolean notNull = false; } { element = id(Boolean.TRUE) [( { type = new ParsedDataType("INTEGER"); autoIncrement = true; notNull = true; } | ( type = parseDataType() [ { notNull = true; }] [ { autoIncrement = true; }] ) )] postCreateColumn(factory, table, element, type, autoIncrement, notNull) } /* name=post create column description=Common options trailing a column example=[source,sql]\n----\nPRIMARY KEY\n----\n */ void postCreateColumn(MetadataFactory factory, Table table, String element, ParsedDataType type, boolean autoIncrement, boolean notNull) : { Column column = null; List columnName = new ArrayList(); Expression defaultValue = null; } { { boolean inferType = false; if (type == null) { type = new ParsedDataType("STRING"); inferType = true; } column = factory.addColumn(element, type.type, table); column.setUpdatable(true); setTypeInfo(type, column); columnName.add(element); if (inferType) { column.setProperty(MetadataValidator.UNTYPED, "true"); } } [inlineConstraint(factory, table, columnName)] [ defaultValue = expression(ParseInfo.DEFAULT_INSTANCE) {setDefault(column, defaultValue);}] [optionsClause(column, factory) { OptionsUtil.setOptions(column); } ] { if (notNull) { column.setNullType(Column.NullType.No_Nulls); } column.setAutoIncremented(autoIncrement); } } /* name=inline constraint description=Defines a constraint on a single column example=[source,sql]\n----\nx INTEGER PRIMARY KEY\n----\n */ void inlineConstraint(MetadataFactory factory, Table table, List columnName) : { } { ( { if (table.getPrimaryKey() != null) { throw new MetadataException(QueryPlugin.Util.getString("SQLParser.pk_exists", table.getName())); } factory.addPrimaryKey("PK", columnName, table); }) | ( { factory.addIndex("UNIQUE"+table.getUniqueKeys().size(), false, columnName, table); }) | ( { factory.addIndex("INDEX"+table.getIndexes().size(), true, columnName, table); }) } /* name=options clause description=A list of statement options. example=[source,sql]\n----\nOPTIONS ('x' 'y', 'a' 'b')\n----\n */ void optionsClause(AbstractMetadataRecord record, NamespaceContainer namespaceContainer) : { } { optionPair(record, namespaceContainer) ( optionPair(record, namespaceContainer))* } /* name=option pair description=An option key/value pair. example=[source,sql]\n----\n'key' 'value'\n----\n */ void optionPair(AbstractMetadataRecord record, NamespaceContainer namespaceContainer) : { Constant value = null; String key = null; Token t = null; String strVal = null; } { key = id(null) (value = nonNumericLiteral() | [strVal = plusMinus()] value = unsignedNumericLiteral(strVal)) { String val = MetadataFactory.resolvePropertyKey(key); if (!value.isNull()) { val = value.getValue().toString(); } record.setProperty(key, val); } } /* name=alter option pair description=Alter An option key/value pair. example=[source,sql]\n----\n'key' 'value'\n----\n */ void alterOptionPair(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { Constant value = null; String key = null; Token t = null; String strVal = null; } { key = id(null) (value = nonNumericLiteral() | [strVal = plusMinus()] value = unsignedNumericLiteral(strVal)) { String val = null; if (!value.isNull()) { val = value.getValue().toString(); } dbStore.addOrSetOption(objectName, type, key, val, true); } } void alterStatement(DatabaseStore dbStore) : { boolean virtual = false; } { ( LOOKAHEAD(3) alterTable(dbStore, ParseInfo.DEFAULT_INSTANCE) | alterProcedure(dbStore, ParseInfo.DEFAULT_INSTANCE) | alterTrigger(dbStore, ParseInfo.DEFAULT_INSTANCE) | alterServer(dbStore) | alterTranslator(dbStore) | alterDatabase(dbStore) ) } /* name=ALTER TABLE description=alters options of database example=[source,sql]\n----\nALTER TABLE foo ADD COLUMN x xml\n----\n */ void alterTable(DatabaseStore dbStore, ParseInfo info) : { String objectName = null; QueryCommand command = null; Token comment = null; boolean virtual = false; } { ( ([] objectName = id(null) {virtual = true;}) | ([]
objectName = id(null)) ) ( ( { comment = getToken(1).specialToken; } command = queryExpression(info) { if (comment != null) { command.setCacheHint(getQueryCacheOption(comment.image)); } dbStore.setViewDefinition(objectName, command.toString()); } ) | LOOKAHEAD(2) alterAddColumn(objectName, Database.ResourceType.TABLE, dbStore) | alterAddConstraint(objectName, Database.ResourceType.TABLE, dbStore) | alterOptionsList(objectName, Database.ResourceType.TABLE, dbStore) | alterDropColumn(objectName, Database.ResourceType.TABLE, dbStore) | ( alterColumn(objectName, Database.ResourceType.TABLE, Database.ResourceType.COLUMN, dbStore)) | ( (alterRenameTable(objectName, Database.ResourceType.TABLE, dbStore) | ( alterRenameColumn(objectName, Database.ResourceType.TABLE, dbStore))))) } /* name=RENAME Table description=alters table name example=[source,sql]\n----\nALTER TABLE foo RENAME TO BAR;\n----\n */ void alterRenameTable(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { String id = null; } { id = id(null) { dbStore.modifyTableName(objectName, type, id); } } /* name=ADD constraint description=alters table and adds a constraint example=[source,sql]\n----\nADD PRIMARY KEY (ID)\n----\n */ void alterAddConstraint(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { Database.ResourceType childType = Database.ResourceType.COLUMN; MetadataFactory factory = DatabaseStore.createMF(dbStore); Table table = dbStore.getTableForCreateColumn(objectName, type); } { tableConstraint(factory, table) } /* name=ADD column description=alters table and adds a column example=[source,sql]\n----\nADD COLUMN bar type OPTIONS (ADD updatable true)\n----\n */ void alterAddColumn(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { Database.ResourceType childType = Database.ResourceType.COLUMN; MetadataFactory factory = null; Table table = null; } { { factory = DatabaseStore.createMF(dbStore); table = dbStore.getTableForCreateColumn(objectName, type); } createColumn(factory, table) } /* name=DROP column description=alters table and adds a column example=[source,sql]\n----\nDROP COLUMN bar\n----\n */ void alterDropColumn(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { MetadataFactory factory = null; Table table = null; String childName = null; Column column = null; } { childName = id(null) { dbStore.removeColumn(objectName, type, childName); } } /* name=alter column options description=alters a set of column options example=[source,sql]\n----\nALTER COLUMN bar OPTIONS (ADD updatable true)\n----\n */ void alterColumn(String objectName, Database.ResourceType type, Database.ResourceType childType, DatabaseStore dbStore) : { String childName = null; ParsedDataType datatype = null; boolean autoIncrement = false; boolean notNull = false; } { childName = id(null) (( ( { datatype = new ParsedDataType("INTEGER"); autoIncrement = true; notNull = true; } | ( datatype = parseDataType() [ { notNull = true; }] [ { autoIncrement = true; }] ) ) { dbStore.alterBaseColumn(objectName, type, childName, datatype, autoIncrement, notNull); } ) | alterChildOptionsList(objectName, type, childName, childType, dbStore)) } /* name=rename column options description=renames either a table column or procedure's parameter name example=[source,sql]\n----\nRENAME COLUMN bar TO foo\n----\n */ void alterRenameColumn(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { String oldName = null; String newName = null; } { oldName = id(null) newName = id(null) { dbStore.renameBaseColumn(objectName, type, oldName, newName); } } /* name=ALTER PROCEDURE description=alters options of database example=[source,sql]\n----\nALTER PROCEDURE foo OPTIONS (ADD x y)\n----\n */ void alterProcedure(DatabaseStore dbStore, ParseInfo info) : { String objectName = null; Statement stmt = null; Token comment = null; boolean virtual = true; } { [|{virtual=false;}] objectName = id(null) (( { comment = getToken(1).specialToken; } stmt = statement(info) { CreateProcedureCommand cup = new CreateProcedureCommand(asBlock(stmt)); if (comment != null) { cup.setCacheHint(getQueryCacheOption(comment.image)); } dbStore.setProcedureDefinition(objectName, cup.toString()); } ) | alterOptionsList(objectName, Database.ResourceType.PROCEDURE, dbStore) | ( alterColumn(objectName, Database.ResourceType.PROCEDURE, Database.ResourceType.PARAMETER, dbStore)) | ( alterRenameColumn(objectName, Database.ResourceType.PROCEDURE, dbStore))) } /* name=ALTER TRIGGER description=alters options of table triggers example=[source,sql]\n----\nALTER TRIGGER ON vw INSTEAD OF INSERT ENABLED\n----\n */ void alterTrigger(DatabaseStore dbStore, ParseInfo info) : { String objectName = null; Boolean enabled = null; Token event = null; TriggerAction triggerAction = null; } { objectName = id(null) (event = | event = | event = ) ( triggerAction = forEachRowTriggerAction(info) | {enabled=true;} | {enabled=false;}) { if (enabled != null){ dbStore.enableTableTriggerPlan(objectName, Table.TriggerEvent.valueOf(event.image.toUpperCase()), enabled); } else { dbStore.setTableTriggerPlan(null, objectName, Table.TriggerEvent.valueOf(event.image.toUpperCase()), triggerAction.toString(), false); } } } /* name=ALTER SERVER description=alters options of database example=[source,sql]\n----\nALTER SERVER foo OPTIONS (ADD x y)\n----\n */ void alterServer(DatabaseStore dbStore) : { String objectName = null; } { objectName = id(null) (alterOptionsList(objectName, Database.ResourceType.SERVER, dbStore)) } /* name=ALTER DATA WRAPPER description=alters options of data wrapper example=[source,sql]\n----\nALTER DATA WRAPPER foo OPTIONS (ADD x y)\n----\n */ void alterTranslator(DatabaseStore dbStore) : { String objectName = null; } { (( )|) objectName = id(null) (alterOptionsList(objectName, Database.ResourceType.DATAWRAPPER, dbStore)) } /* name=ALTER DATABASE description=alters options of database example=[source,sql]\n----\nALTER DATABASE foo OPTIONS (ADD x y)\n----\n */ void alterDatabase(DatabaseStore dbStore) : { String objectName = null; } { objectName = id(null) (alterOptionsList(objectName, Database.ResourceType.DATABASE, dbStore)) } /* name=alter options list description=a list of alterations to options example=[source,sql]\n----\nOPTIONS (ADD updatable true)\n----\n */ void alterOptionsList(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { } { (addSetOption(objectName, type, dbStore) | dropOption(objectName, type, dbStore)) ( (addSetOption(objectName, type, dbStore) | dropOption(objectName, type, dbStore)))* } /* name=drop option description=drop option example=[source,sql]\n----\nDROP updatable\n----\n */ void dropOption(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { String key = null; } { key = id(null) { dbStore.removeOption(objectName, type, key); } } /* name=add set option description=add or set an option pair example=[source,sql]\n----\nADD updatable true\n----\n */ void addSetOption(String objectName, Database.ResourceType type, DatabaseStore dbStore) : { } { (|) alterOptionPair(objectName, type, dbStore) } /* name=alter child options list description=a list of alterations to options example=[source,sql]\n----\nOPTIONS (ADD updatable true)\n----\n */ void alterChildOptionsList(String objectName, Database.ResourceType type, String childName, Database.ResourceType childType, DatabaseStore dbStore) : { } { (addSetChildOption(objectName, type, childName, childType, dbStore) | dropChildOption(objectName, type, childName, childType, dbStore)) ( (addSetChildOption(objectName, type, childName, childType, dbStore) | dropChildOption(objectName, type, childName, childType, dbStore)))* } /* name=drop option description=drop option example=[source,sql]\n----\nDROP updatable\n----\n */ void dropChildOption(String objectName, Database.ResourceType type, String childName, Database.ResourceType childType, DatabaseStore dbStore) : { String key = null; } { key = id(null) { dbStore.removeOption(objectName, type, childName, childType, key); } } /* name=add set child option description=add or set an option pair example=[source,sql]\n----\nADD updatable true\n----\n */ void addSetChildOption(String objectName, Database.ResourceType type, String childName, Database.ResourceType childType, DatabaseStore dbStore) : { } { (|) alterChildOptionPair(objectName, type, childName, childType, dbStore) } /* name=alter child option pair description=Alter An option key/value pair. example=[source,sql]\n----\n'key' 'value'\n----\n */ void alterChildOptionPair(String objectName, Database.ResourceType type, String childName, Database.ResourceType childType, DatabaseStore dbStore) : { Constant value = null; String key = null; Token t = null; String strVal = null; } { key = id(null) (value = nonNumericLiteral() | [strVal = plusMinus()] value = unsignedNumericLiteral(strVal)) { String val = null; if (!value.isNull()) { val = value.getValue().toString(); } dbStore.addOrSetOption(objectName, type, childName, childType, key, val, true); } } /* name=Import foreign schema description=imports schema metadata from server example=[source,sql]\n----\nIMPORT FOREIGN SCHEMA foo FROM SERVER bar\n----\n */ void importSchema(DatabaseStore dbStore) : { String foreignSchemaName = null; String serverType = null; String schemaName = null; String serverName = null; String importIntoSchemaName = null; ArrayList includeTables = new ArrayList(); ArrayList excludeTables = new ArrayList(); Server server = new Server("__temp__"); } { [ foreignSchemaName = id(null)] //[( identifierList(includeTables) ) | ( identifierList(excludeTables) )] ({serverType = "native";}|) serverName = id(null) schemaName = id(null) [optionsClause(server, dbStore.getCurrentNamespaceContainer()) { OptionsUtil.setOptions(server); } ] { if (serverType == null){ serverType = serverName; serverName = null; } dbStore.importSchema(schemaName, serverType, serverName, foreignSchemaName, includeTables, excludeTables, server.getProperties()); } } /* name=Import VDB description=imports another VDB into current database example=[source,sql]\n----\nIMPORT DATABASE vdb VERSION '1.2.3' WITH ACCESS CONTROL\n----\n */ void importDatabase(DatabaseStore dbStore) : { String dbName = null; String version = null; boolean importAccessControls = false; } { dbName = id(null) version = stringVal() [ {importAccessControls=true;}] { dbStore.importDatabase(dbName, version, importAccessControls); } } /* name=identifier list */ void identifierList(List strings) : { String name = null; } { name = id(null) { strings.add(name); } ( name = id(null) { strings.add(name); } )* } /* name=grant type */ void readGrantTypes(ArrayList privileges) : { } {