Java Code Examples for com.alibaba.druid.sql.ast.SQLName

The following examples show how to use com.alibaba.druid.sql.ast.SQLName. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public boolean visit(MySqlDeleteStatement x) {
    setAliasMap();

    setMode(x, Mode.Delete);

    accept(x.getFrom());
    accept(x.getUsing());
    x.getTableSource().accept(this);

    if (x.getTableSource() instanceof SQLExprTableSource) {
        SQLName tableName = (SQLName) ((SQLExprTableSource) x.getTableSource()).getExpr();
        String ident = tableName.toString();
        setCurrentTable(x, ident);

        TableStat stat = this.getTableStat(ident,ident);
        stat.incrementDeleteCount();
    }

    accept(x.getWhere());

    accept(x.getOrderBy());
    accept(x.getLimit());

    return false;
}
 
Example 2
private static boolean hasColumn(SQLStatement statement){
    for (SQLTableElement tableElement : ((SQLCreateTableStatement)statement).getTableElementList()) {
        SQLName sqlName = null;
        if (tableElement instanceof SQLColumnDefinition) {
            sqlName = ((SQLColumnDefinition)tableElement).getName();
        }
        if (sqlName != null) {
            String simpleName = sqlName.getSimpleName();
            simpleName = StringUtil.removeBackquote(simpleName);
            if (tableElement instanceof SQLColumnDefinition && "_slot".equalsIgnoreCase(simpleName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 3
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean visit(MySqlDeleteStatement x) {
    aliasMap.clear();
    accept(x.getFrom());
    accept(x.getUsing());
    x.getTableSource().accept(this);

    if (x.getTableSource() instanceof SQLExprTableSource) {
        SQLName tableName = (SQLName) ((SQLExprTableSource) x.getTableSource()).getExpr();
        currentTable = tableName.toString();
    }

    accept(x.getWhere());

    accept(x.getOrderBy());
    accept(x.getLimit());

    return false;
}
 
Example 4
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean visit(SQLUpdateStatement x) {
    aliasMap.clear();
    SQLName identName = x.getTableName();
    if (identName != null) {
        String ident = identName.toString();
        currentTable = ident;

        putAliasToMap(ident, ident.replace("`", ""));
        String alias = x.getTableSource().getAlias();
        if (alias != null) {
            putAliasToMap(alias, ident.replace("`", ""));
        }
    } else {
        x.getTableSource().accept(this);
    }

    accept(x.getItems());
    accept(x.getWhere());

    return false;
}
 
Example 5
Source Project: dble   Source File: DruidAlterTableParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * this function is check if the name is the important column in any tables
 * true -- the column influence some important column
 * false -- safe
 */
private boolean influenceKeyColumn(SQLName name, SchemaConfig schema, String tableName) {
    String columnName = name.toString();
    Map<String, TableConfig> tableConfig = schema.getTables();
    TableConfig changedTable = tableConfig.get(tableName);
    if (changedTable == null) {
        return false;
    }
    if (columnName.equalsIgnoreCase(changedTable.getPartitionColumn()) ||
            columnName.equalsIgnoreCase(changedTable.getJoinKey())) {
        return true;
    }
    // Traversal all the table node to find if some table is the child table of the changedTale
    for (Map.Entry<String, TableConfig> entry : tableConfig.entrySet()) {
        TableConfig tb = entry.getValue();
        if (tb.getParentTC() != null &&
                tableName.equalsIgnoreCase(tb.getParentTC().getName()) &&
                columnName.equalsIgnoreCase(tb.getParentKey())) {
            return true;
        }
    }
    return false;
}
 
Example 6
private static boolean hasColumn(SQLStatement statement) {
    for (SQLTableElement tableElement : ((SQLCreateTableStatement) statement).getTableElementList()) {
        SQLName sqlName = null;
        if (tableElement instanceof SQLColumnDefinition) {
            sqlName = ((SQLColumnDefinition) tableElement).getName();
        }

        if (sqlName != null) {
            String simpleName = sqlName.getSimpleName();
            simpleName = StringUtil.removeBackQuote(simpleName);
            if (tableElement instanceof SQLColumnDefinition && "_slot".equalsIgnoreCase(simpleName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 7
Source Project: baymax   Source File: SqlVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(MySqlDeleteStatement x) {
    setAliasMap();

    setMode(x, Mode.Delete);

    accept(x.getFrom());
    accept(x.getUsing());
    x.getTableSource().accept(this);

    if (x.getTableSource() instanceof SQLExprTableSource) {
        SQLName tableName = (SQLName) ((SQLExprTableSource) x.getTableSource()).getExpr();
        String ident = tableName.toString();
        setCurrentTable(x, ident);
        // 和父类只有这行不同
        TableStat stat = this.getTableStat(ident,ident);
        stat.incrementDeleteCount();
    }

    accept(x.getWhere());

    accept(x.getOrderBy());
    accept(x.getLimit());

    return false;
}
 
Example 8
Source Project: Zebra   Source File: ShardColumnValueUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static void parseValueList(Set<Object> evalSet, List<Object> params, List<SQLExpr> columns,
      List<SQLInsertStatement.ValuesClause> valuesList, String column) {
	SQLInsertStatement.ValuesClause values = valuesList.get(0);
	for (int i = 0; i < columns.size(); i++) {
		SQLName columnObj = (SQLName) columns.get(i);
		if (evalColumn(columnObj.getSimpleName(), column)) {
			SQLExpr sqlExpr = values.getValues().get(i);
			if (sqlExpr instanceof SQLVariantRefExpr) {
				SQLVariantRefExpr ref = (SQLVariantRefExpr) sqlExpr;
				evalSet.add(params.get(ref.getIndex()));
			} else if (sqlExpr instanceof SQLValuableExpr) {
				evalSet.add(((SQLValuableExpr) sqlExpr).getValue());
			}
			break;
		}
	}
}
 
Example 9
Source Project: elasticsearch-sql   Source File: ElasticSqlExprParser.java    License: Apache License 2.0 6 votes vote down vote up
public SQLName nameRest(SQLName name) {
    if (lexer.token() == Token.VARIANT && "@".equals(lexer.stringVal())) {
        lexer.nextToken();
        MySqlUserName userName = new MySqlUserName();
        userName.setUserName(((SQLIdentifierExpr) name).getName());

        if (lexer.token() == Token.LITERAL_CHARS) {
            userName.setHost("'" + lexer.stringVal() + "'");
        } else {
            userName.setHost(lexer.stringVal());
        }
        lexer.nextToken();

        if (lexer.token() == Token.IDENTIFIED) {
            lexer.nextToken();
            accept(Token.BY);
            userName.setIdentifiedBy(lexer.stringVal());
            lexer.nextToken();
        }

        return userName;
    }
    return super.nameRest(name);
}
 
Example 10
public boolean visit(MySqlCreateTableStatement x) {
    SQLName sqlName=  x.getName();
    if(sqlName!=null)
    {
        String table = sqlName.toString();
        if(table.startsWith("`"))
        {
            table=table.substring(1,table.length()-1);
        }
        setCurrentTable(table);
    }
    return false;
}
 
Example 11
public boolean visit(MySqlInsertStatement x) {
    SQLName sqlName=  x.getTableName();
    if(sqlName!=null)
    {
        String table = sqlName.toString();
        if(table.startsWith("`"))
        {
            table=table.substring(1,table.length()-1);
        }
        setCurrentTable(sqlName.toString());
    }
    return false;
}
 
Example 12
public boolean visit(SQLUpdateStatement x) {
    setAliasMap();

    setMode(x, Mode.Update);

    SQLName identName = x.getTableName();
    if (identName != null) {
        String ident = identName.toString();
        String alias = x.getTableSource().getAlias();
        setCurrentTable(ident);

        TableStat stat = getTableStat(ident);
        stat.incrementUpdateCount();

        Map<String, String> aliasMap = getAliasMap();
        
        aliasMap.put(ident, ident);
        if(alias != null) {
        	aliasMap.put(alias, ident);
        }
    } else {
        x.getTableSource().accept(this);
    }

    accept(x.getItems());
    accept(x.getWhere());

    return false;
}
 
Example 13
Source Project: dble   Source File: ShowColumns.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void response(ServerConnection c, String stmt) {
    try {
        Pattern pattern = ShowColumns.PATTERN;
        Matcher ma = pattern.matcher(stmt);
        // always match
        if (ma.matches()) {
            int start = ma.start(6);
            int end = ma.end(6);
            String sub = stmt.substring(0, start);
            String sub2 = stmt.substring(end, stmt.length());
            stmt = sub + " from " + sub2;
        }

        SQLStatement statement = RouteStrategyFactory.getRouteStrategy().parserSQL(stmt);
        MySqlShowColumnsStatement showColumnsStatement = (MySqlShowColumnsStatement) statement;
        String table = StringUtil.removeBackQuote(showColumnsStatement.getTable().getSimpleName());
        SQLName database = showColumnsStatement.getDatabase();
        String schema = database == null ? c.getSchema() : StringUtil.removeBackQuote(database.getSimpleName());
        if (schema == null) {
            c.writeErrMessage("3D000", "No database selected", ErrorCode.ER_NO_DB_ERROR);
            return;
        }
        String sql = stmt;
        if (showColumnsStatement.getDatabase() != null) {
            showColumnsStatement.setDatabase(null);
            sql = showColumnsStatement.toString();
        }
        if (DbleServer.getInstance().getSystemVariables().isLowerCaseTableNames()) {
            schema = schema.toLowerCase();
            table = table.toLowerCase();
        }
        SchemaInfo schemaInfo = new SchemaInfo(schema, table);
        c.routeSystemInfoAndExecuteSQL(sql, schemaInfo, ServerParse.SHOW);
    } catch (Exception e) {
        c.writeErrMessage(ErrorCode.ER_PARSE_ERROR, e.toString());
    }
}
 
Example 14
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean visit(MySqlInsertStatement x) {
    SQLName sqlName = x.getTableName();
    if (sqlName != null) {
        currentTable = sqlName.toString();
    }
    return false;
}
 
Example 15
Source Project: dble   Source File: DruidAlterTableParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * the function is check if the columns contains the import column
 * true -- yes the sql did not to exec
 * false -- safe the sql can be exec
 */
private boolean columnInfluenceCheck(List<SQLName> columnList, SchemaConfig schema, String table) {
    for (SQLName name : columnList) {
        if (this.influenceKeyColumn(name, schema, table)) {
            return true;
        }
    }
    return false;
}
 
Example 16
Source Project: baymax   Source File: SqlVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(SQLUpdateStatement x) {
    setAliasMap();

    setMode(x, Mode.Update);

    SQLName identName = x.getTableName();
    if (identName != null) {
        String ident = identName.toString();
        //
        String alias = x.getTableSource().getAlias();
        setCurrentTable(ident);

        TableStat stat = getTableStat(ident);
        stat.incrementUpdateCount();

        Map<String, String> aliasMap = getAliasMap();
        
        aliasMap.put(ident, ident);
        //
        if(alias != null) {
        	aliasMap.put(alias, ident);
        }
    } else {
        x.getTableSource().accept(this);
    }

    accept(x.getItems());
    accept(x.getWhere());

    return false;
}
 
Example 17
Source Project: Zebra   Source File: MySQLSelectASTVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(SQLSelectGroupByClause x) {
	result.getMergeContext().increGroupByCount();
	List<String> groupByColumns = new ArrayList<String>();
	List<SQLExpr> items = x.getItems();

	for (SQLExpr expr : items) {
		groupByColumns.add(((SQLName) expr).getSimpleName());
	}

	result.getMergeContext().setGroupByColumns(groupByColumns);
	return true;
}
 
Example 18
Source Project: Zebra   Source File: AbstractMySQLASTVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(SQLExprTableSource x) {
	SQLName table = (SQLName) x.getExpr();
	String simpleName = table.getSimpleName();
	String tableName = simpleName.startsWith("`") ? parseTableName(simpleName) : simpleName;

	result.getRouterContext().getTableSet().add(tableName);

	return true;
}
 
Example 19
Source Project: elasticsearch-sql   Source File: ElasticSqlExprParser.java    License: Apache License 2.0 5 votes vote down vote up
public SQLName userName() {
    SQLName name = this.name();
    if (lexer.token() == Token.LPAREN && name.hashCode64() == FnvHash.Constants.CURRENT_USER) {
        lexer.nextToken();
        accept(Token.RPAREN);
        return name;
    }

    return (SQLName) userNameRest(name);
}
 
Example 20
Source Project: dble   Source File: DruidAlterTableParser.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt, ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain)
        throws SQLException {
    SQLAlterTableStatement alterTable = (SQLAlterTableStatement) stmt;
    String schemaName = schema == null ? null : schema.getName();
    SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(sc.getUser(), schemaName, alterTable.getTableSource());
    boolean support = false;
    String msg = "The DDL is not supported, sql:";
    for (SQLAlterTableItem alterItem : alterTable.getItems()) {
        if (alterItem instanceof SQLAlterTableAddColumn ||
                alterItem instanceof SQLAlterTableDropKey ||
                alterItem instanceof SQLAlterTableDropPrimaryKey) {
            support = true;
        } else if (alterItem instanceof SQLAlterTableAddIndex ||
                alterItem instanceof SQLAlterTableDropIndex) {
            support = true;
            rrs.setOnline(true);
        } else if (alterItem instanceof SQLAlterTableAddConstraint) {
            SQLConstraint constraint = ((SQLAlterTableAddConstraint) alterItem).getConstraint();
            if (constraint instanceof MySqlPrimaryKey) {
                support = true;
            }
        } else if (alterItem instanceof MySqlAlterTableChangeColumn ||
                alterItem instanceof MySqlAlterTableModifyColumn ||
                alterItem instanceof SQLAlterTableDropColumnItem) {
            List<SQLName> columnList = new ArrayList<>();
            if (alterItem instanceof MySqlAlterTableChangeColumn) {
                columnList.add(((MySqlAlterTableChangeColumn) alterItem).getColumnName());
            } else if (alterItem instanceof MySqlAlterTableModifyColumn) {
                columnList.add(((MySqlAlterTableModifyColumn) alterItem).getNewColumnDefinition().getName());
            } else if (alterItem instanceof SQLAlterTableDropColumnItem) {
                columnList = ((SQLAlterTableDropColumnItem) alterItem).getColumns();
            }
            support = !this.columnInfluenceCheck(columnList, schemaInfo.getSchemaConfig(), schemaInfo.getTable());
            if (!support) {
                msg = "The columns may be sharding keys or ER keys, are not allowed to alter sql:";
            }
        }
    }
    if (!support) {
        msg = msg + stmt;
        throw new SQLNonTransientException(msg);
    }
    String statement = RouterUtil.removeSchema(rrs.getStatement(), schemaInfo.getSchema());
    rrs.setStatement(statement);
    String noShardingNode = RouterUtil.isNoShardingDDL(schemaInfo.getSchemaConfig(), schemaInfo.getTable());
    if (noShardingNode != null) {
        RouterUtil.routeToSingleDDLNode(schemaInfo, rrs, noShardingNode);
        return schemaInfo.getSchemaConfig();
    }
    RouterUtil.routeToDDLNode(schemaInfo, rrs);
    return schemaInfo.getSchemaConfig();
}
 
Example 21
Source Project: baymax   Source File: MySqlSelectParser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 解析groupby
 * @param result
 * @param plan
 * @param mysqlSelectQuery
 */
protected void parseGroupBy(ParseResult result, ExecutePlan plan, MySqlSelectQueryBlock mysqlSelectQuery){
    if(mysqlSelectQuery.getGroupBy() == null) {
        return;
    }
    List<SQLExpr> groupByItems = mysqlSelectQuery.getGroupBy().getItems();
    if (groupByItems == null || groupByItems.size() == 0){
        return;
    }
    List<SQLSelectItem> selectList      = mysqlSelectQuery.getSelectList();
    List<String> groupbyColumns  = new ArrayList<String>(groupByItems.size());
    for(SQLExpr item : groupByItems){
        String name = null;
        if (item instanceof MySqlSelectGroupByExpr){
            name = StringUtil.removeDot(((MySqlSelectGroupByExpr) item).getExpr().toString());
        }else if (item instanceof SQLIdentifierExpr){
            name = item.toString();
        }else if (item instanceof SQLName){
            name = ((SQLName) item).getSimpleName();
        }else {
            throw new BayMaxException("group by 不支持的表达式:" + item.toString());
        }
        if (result.getAliaColumns() != null){
            // 有别名,说明在select list中使用了别名
            String alias = result.getAliaColumns().get(name);
            if (alias != null){
                // select user_id as uid ....order by user_id
                // 要把oderby的user_id转换为uid,以便结果集合并,这个替换是等价的
                // 因为合并的时候需要根据orderby的字段,取值,比较
                groupbyColumns.add(alias);
                continue;
            }
        }
        if (!result.isHasAllColumnExpr()){
            // select列表中没有orderby的字段 添加,用于后面做合并
            SQLIdentifierExpr exp = new SQLIdentifierExpr(name);
            // item
            SQLSelectItem addItem = new SQLSelectItem();
            addItem.setExpr(exp);
            exp.setParent(item);
            selectList.add(addItem);
        }
        groupbyColumns.add(name);
    }
    plan.setGroupbyColumns(groupbyColumns);
}
 
Example 22
Source Project: Zebra   Source File: MySQLSelectASTVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean visit(MySqlSelectQueryBlock x) {
	result.getMergeContext().increQueryCount();
	Map<String, SQLObjectImpl> selectItemMap = result.getMergeContext().getSelectItemMap();
	Map<String, String> columnNameAliasMapping = result.getMergeContext().getColumnNameAliasMapping();

	for (SQLSelectItem column : x.getSelectList()) {
		String name = null;
		if (column.getExpr() instanceof SQLAggregateExpr) {
			SQLAggregateExpr expr = (SQLAggregateExpr) column.getExpr();
			SQLExpr argument = expr.getArguments().get(0);
			if (argument instanceof SQLAllColumnExpr) {
				name = expr.getMethodName() + "(*)";
			} else if (argument instanceof SQLIntegerExpr) {
				name = expr.getMethodName() + "(1)";
			} else {
				name = expr.getMethodName() + "(" + argument.toString() + ")";
				if (column.getAlias() != null) {
					columnNameAliasMapping.put(name, column.getAlias());
				}
			}

			result.getMergeContext().setAggregate(true);
		} else if (column.getExpr() instanceof SQLIdentifierExpr || column.getExpr() instanceof SQLPropertyExpr) {
			name = ((SQLName) column.getExpr()).getSimpleName();

			if (column.getAlias() != null) {
				SQLName identifier = (SQLName) column.getExpr();
				columnNameAliasMapping.put(identifier.getSimpleName(), column.getAlias());
			}
		} else {
			// ignore SQLAllColumnExpr,SQLMethodInvokeExpr and etc.
		}

		selectItemMap.put(column.getAlias() == null ? name : column.getAlias(), column);
	}

	if (x.getDistionOption() == 2) {
		result.getMergeContext().setDistinct(true);
	}

	return true;
}
 
Example 23
Source Project: Zebra   Source File: OrderByDataMerger.java    License: Apache License 2.0 4 votes vote down vote up
public int compareOrderByEle(RowData o1, RowData o2, MergeContext mergeContext) {
	SQLOrderBy orderBy = mergeContext.getOrderBy();
	List<SQLSelectOrderByItem> items = orderBy.getItems();
	try {
		for (SQLSelectOrderByItem orderByEle : items) {
			SQLName identifier = (SQLName) orderByEle
			      .getExpr();
			String columnLabel = mergeContext.getColumnNameAliasMapping().get(identifier.getSimpleName());
			if (columnLabel == null) {
				columnLabel = identifier.getSimpleName();
			}

			Object value1 = o1.get(columnLabel).getValue();
			Class<?> type1 = o1.get(columnLabel).getType();
			Object value2 = o2.get(columnLabel).getValue();
			Class<?> type2 = o2.get(columnLabel).getType();

			if (!type1.equals(type2)) {
				throw new SQLException("Invalid data");
			}

			if (!Comparable.class.isAssignableFrom(type1)) {
				throw new SQLException("Can not orderBy column : " + identifier + " which isn't comparable.");
			}

			@SuppressWarnings({ "unchecked", "rawtypes" })
			int compareRes = ((Comparable) value1).compareTo((Comparable) value2);

			if (orderByEle.getType() == null || ((SQLOrderingSpecification) orderByEle.getType()).name().equals("ASC")) {
				if (compareRes != 0) {
					return compareRes;
				}
			} else {
				if (compareRes != 0) {
					return compareRes < 0 ? 1 : -1;
				}
			}
		}

		return 0;

	} catch (SQLException e) {
		throw new RuntimeException(e);
	}
}
 
Example 24
Source Project: elasticsearch-sql   Source File: ElasticSqlSelectParser.java    License: Apache License 2.0 4 votes vote down vote up
protected MySqlUpdateStatement parseUpdateStatment() {
    MySqlUpdateStatement update = new MySqlUpdateStatement();

    lexer.nextToken();

    if (lexer.identifierEquals(FnvHash.Constants.LOW_PRIORITY)) {
        lexer.nextToken();
        update.setLowPriority(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.IGNORE)) {
        lexer.nextToken();
        update.setIgnore(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.COMMIT_ON_SUCCESS)) {
        lexer.nextToken();
        update.setCommitOnSuccess(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.ROLLBACK_ON_FAIL)) {
        lexer.nextToken();
        update.setRollBackOnFail(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.QUEUE_ON_PK)) {
        lexer.nextToken();
        update.setQueryOnPk(true);
    }

    if (lexer.identifierEquals(FnvHash.Constants.TARGET_AFFECT_ROW)) {
        lexer.nextToken();
        SQLExpr targetAffectRow = this.exprParser.expr();
        update.setTargetAffectRow(targetAffectRow);
    }

    if (lexer.identifierEquals(FnvHash.Constants.FORCE)) {
        lexer.nextToken();

        if (lexer.token() == Token.ALL) {
            lexer.nextToken();
            acceptIdentifier("PARTITIONS");
            update.setForceAllPartitions(true);
        } else if (lexer.identifierEquals(FnvHash.Constants.PARTITIONS)){
            lexer.nextToken();
            update.setForceAllPartitions(true);
        } else if (lexer.token() == Token.PARTITION) {
            lexer.nextToken();
            SQLName partition = this.exprParser.name();
            update.setForcePartition(partition);
        } else {
            throw new ParserException("TODO. " + lexer.info());
        }
    }

    while (lexer.token() == Token.HINT) {
        this.exprParser.parseHints(update.getHints());
    }

    SQLSelectParser selectParser = this.exprParser.createSelectParser();
    SQLTableSource updateTableSource = selectParser.parseTableSource();
    update.setTableSource(updateTableSource);

    accept(Token.SET);

    for (;;) {
        SQLUpdateSetItem item = this.exprParser.parseUpdateSetItem();
        update.addItem(item);

        if (lexer.token() != Token.COMMA) {
            break;
        }

        lexer.nextToken();
    }

    if (lexer.token() == (Token.WHERE)) {
        lexer.nextToken();
        update.setWhere(this.exprParser.expr());
    }

    update.setOrderBy(this.exprParser.parseOrderBy());
    update.setLimit(this.exprParser.parseLimit());

    return update;
}
 
Example 25
Source Project: elasticsearch-sql   Source File: ElasticSqlExprParser.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MySqlPrimaryKey parsePrimaryKey() {
    accept(Token.PRIMARY);
    accept(Token.KEY);

    MySqlPrimaryKey primaryKey = new MySqlPrimaryKey();

    if (lexer.identifierEquals(FnvHash.Constants.USING)) {
        lexer.nextToken();
        primaryKey.setIndexType(lexer.stringVal());
        lexer.nextToken();
    }

    if (lexer.token() != Token.LPAREN) {
        SQLName name = this.name();
        primaryKey.setName(name);
    }

    accept(Token.LPAREN);
    for (;;) {
        SQLExpr expr;
        if (lexer.token() == Token.LITERAL_ALIAS) {
            expr = this.name();
        } else {
            expr = this.expr();
        }
        primaryKey.addColumn(expr);
        if (!(lexer.token() == (Token.COMMA))) {
            break;
        } else {
            lexer.nextToken();
        }
    }
    accept(Token.RPAREN);

    if (lexer.identifierEquals(FnvHash.Constants.USING)) {
        lexer.nextToken();
        primaryKey.setIndexType(lexer.stringVal());
        lexer.nextToken();
    }

    return primaryKey;
}
 
Example 26
Source Project: elasticsearch-sql   Source File: ElasticSqlExprParser.java    License: Apache License 2.0 4 votes vote down vote up
public SQLPartition parsePartition() {
    accept(Token.PARTITION);

    SQLPartition partitionDef = new SQLPartition();

    partitionDef.setName(this.name());

    SQLPartitionValue values = this.parsePartitionValues();
    if (values != null) {
        partitionDef.setValues(values);
    }

    for (;;) {
        boolean storage = false;
        if (lexer.identifierEquals(FnvHash.Constants.DATA)) {
            lexer.nextToken();
            acceptIdentifier("DIRECTORY");
            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }
            partitionDef.setDataDirectory(this.expr());
        } else if (lexer.token() == Token.TABLESPACE) {
            lexer.nextToken();
            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }
            SQLName tableSpace = this.name();
            partitionDef.setTablespace(tableSpace);
        } else if (lexer.token() == Token.INDEX) {
            lexer.nextToken();
            acceptIdentifier("DIRECTORY");
            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }
            partitionDef.setIndexDirectory(this.expr());
        } else if (lexer.identifierEquals(FnvHash.Constants.MAX_ROWS)) {
            lexer.nextToken();
            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }
            SQLExpr maxRows = this.primary();
            partitionDef.setMaxRows(maxRows);
        } else if (lexer.identifierEquals(FnvHash.Constants.MIN_ROWS)) {
            lexer.nextToken();
            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }
            SQLExpr minRows = this.primary();
            partitionDef.setMaxRows(minRows);
        } else if (lexer.identifierEquals(FnvHash.Constants.ENGINE) || //
                (storage = (lexer.token() == Token.STORAGE || lexer.identifierEquals(FnvHash.Constants.STORAGE)))) {
            if (storage) {
                lexer.nextToken();
            }
            acceptIdentifier("ENGINE");

            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }

            SQLName engine = this.name();
            partitionDef.setEngine(engine);
        } else if (lexer.token() == Token.COMMENT) {
            lexer.nextToken();
            if (lexer.token() == Token.EQ) {
                lexer.nextToken();
            }
            SQLExpr comment = this.primary();
            partitionDef.setComment(comment);
        } else {
            break;
        }
    }

    if (lexer.token() == Token.LPAREN) {
        lexer.nextToken();

        for (;;) {
            acceptIdentifier("SUBPARTITION");

            SQLName subPartitionName = this.name();
            SQLSubPartition subPartition = new SQLSubPartition();
            subPartition.setName(subPartitionName);

            partitionDef.addSubPartition(subPartition);

            if (lexer.token() == Token.COMMA) {
                lexer.nextToken();
                continue;
            }
            break;
        }

        accept(Token.RPAREN);
    }
    return partitionDef;
}