/** * Validate that the ordering of the returned Exceptions is correct * using traditional while loop */ @Test public void test12() { SQLSyntaxErrorException ex = new SQLSyntaxErrorException("Exception 1", t1); SQLSyntaxErrorException ex1 = new SQLSyntaxErrorException("Exception 2"); SQLSyntaxErrorException ex2 = new SQLSyntaxErrorException("Exception 3", t2); ex.setNextException(ex1); ex.setNextException(ex2); int num = 0; SQLException sqe = ex; while (sqe != null) { assertTrue(msgs[num++].equals(sqe.getMessage())); Throwable c = sqe.getCause(); while (c != null) { assertTrue(msgs[num++].equals(c.getMessage())); c = c.getCause(); } sqe = sqe.getNextException(); } }
public RouteResultset routeSystemInfo(SchemaConfig schema, int sqlType, String stmt, RouteResultset rrs) throws SQLSyntaxErrorException { switch(sqlType){ case ServerParse.SHOW:// if origSQL is like show tables return analyseShowSQL(schema, rrs, stmt); case ServerParse.SELECT://if origSQL is like select @@ if(stmt.contains("@@")){ return analyseDoubleAtSgin(schema, rrs, stmt); } break; case ServerParse.DESCRIBE:// if origSQL is meta SQL, such as describe table int ind = stmt.indexOf(' '); stmt = stmt.trim(); return analyseDescrSQL(schema, rrs, stmt, ind + 1); } return null; }
/** * tableRule tag: * <tableRule name="sharding-by-month"> * <rule> * <columns>create_date</columns> * <algorithm>partbymonth</algorithm> * </rule> * </tableRule> * * @param root * @throws SQLSyntaxErrorException */ private void loadTableRules(Element root) throws SQLSyntaxErrorException { NodeList list = root.getElementsByTagName("tableRule"); for (int i = 0, n = list.getLength(); i < n; ++i) { Node node = list.item(i); if (node instanceof Element) { Element e = (Element) node; String name = e.getAttribute("name"); if (StringUtil.isEmpty(name)) { throw new ConfigException("name is null or empty"); } if (tableRules.containsKey(name)) { throw new ConfigException("table rule " + name + " duplicated!"); } NodeList ruleNodes = e.getElementsByTagName("rule"); int length = ruleNodes.getLength(); if (length > 1) { throw new ConfigException("only one rule can defined :" + name); } //rule has only one element now. Maybe it will not contains one rule in feature //RuleConfig:rule->function RuleConfig rule = loadRule((Element) ruleNodes.item(0)); tableRules.put(name, new TableRuleConfig(name, rule)); } } }
private RuleConfig loadRule(Element element) throws SQLSyntaxErrorException { Element columnsEle = ConfigUtil.loadElement(element, "columns"); String column = columnsEle.getTextContent(); if (StringUtil.isEmpty(column)) { throw new ConfigException("no rule column is found"); } String[] columns = SplitUtil.split(column, ',', true); if (columns.length > 1) { throw new ConfigException("table rule coulmns has multi values:" + columnsEle.getTextContent()); } Element algorithmEle = ConfigUtil.loadElement(element, "algorithm"); String algorithmName = algorithmEle.getTextContent(); if (StringUtil.isEmpty(algorithmName)) { throw new ConfigException("algorithm is null or empty"); } AbstractPartitionAlgorithm algorithm = functions.get(algorithmName); if (algorithm == null) { throw new ConfigException("can't find function of name :" + algorithmName); } return new RuleConfig(column.toUpperCase(), algorithmName, algorithm); }
@Override public SQLStatement parserSQL(String originSql) throws SQLSyntaxErrorException { SQLStatementParser parser = new MySqlStatementParser(originSql); /** * thrown SQL SyntaxError if parser error */ try { List<SQLStatement> list = parser.parseStatementList(); if (list.size() > 1) { throw new SQLSyntaxErrorException("MultiQueries is not supported,use single query instead "); } return list.get(0); } catch (Exception t) { LOGGER.info("routeNormalSqlWithAST", t); if (t.getMessage() != null) { throw new SQLSyntaxErrorException(t.getMessage()); } else { throw new SQLSyntaxErrorException(t); } } }
@Test public void hasIpv6_falseWhenKnownSQLState() throws SQLException { SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException( "Unknown column 'zipkin_annotations.endpoint_ipv6' in 'field list'", "42S22", 1054); DataSource dataSource = mock(DataSource.class); // cheats to lower mock count: this exception is really thrown during execution of the query when(dataSource.getConnection()).thenThrow( new DataAccessException(sqlException.getMessage(), sqlException)); Boolean result = MySQLStorage.builder() .executor(Runnable::run) .datasource(dataSource) .build().hasIpv6.get(); assertThat(result).isFalse(); }
/** * This returns false instead of failing when the SQLState code doesn't imply the column is * missing. This is to prevent zipkin from crashing due to scenarios we haven't thought up, yet. * The root error goes into the log in this case. */ @Test public void hasIpv6_falseWhenUnknownSQLState() throws SQLException { SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException( "java.sql.SQLSyntaxErrorException: Table 'zipkin.zipkin_annotations' doesn't exist", "42S02", 1146); DataSource dataSource = mock(DataSource.class); // cheats to lower mock count: this exception is really thrown during execution of the query when(dataSource.getConnection()).thenThrow( new DataAccessException(sqlException.getMessage(), sqlException)); Boolean result = MySQLStorage.builder() .executor(Runnable::run) .datasource(dataSource) .build().hasIpv6.get(); assertThat(result).isFalse(); }
@Test public void hasDependencies_missing() throws SQLException { SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException( "SQL [select count(*) from `zipkin_dependencies`]; Table 'zipkin.zipkin_dependencies' doesn't exist\n" + " Query is : select count(*) from `zipkin_dependencies`", "42S02", 1146); DataSource dataSource = mock(DataSource.class); // cheats to lower mock count: this exception is really thrown during execution of the query when(dataSource.getConnection()).thenThrow( new DataAccessException(sqlException.getMessage(), sqlException)); Boolean result = MySQLStorage.builder() .executor(Runnable::run) .datasource(dataSource) .build().hasPreAggregatedDependencies.get(); assertThat(result).isFalse(); }
public void execute(String sql, int type) { if (!TimoServer.getInstance().isOnline()) { writeErrMessage(ErrorCode.ER_ACCESS_DENIED_ERROR, "Timo-server is offline"); return; } Database database = checkDB(); if (database == null) { return; } Outlets out = null; try { out = Router.route(database, sql, this.getCharset(), type); } catch (SQLSyntaxErrorException e) { String msg = e.getMessage(); writeErrMessage(ErrorCode.ER_PARSE_ERROR, msg == null ? e.getClass().getSimpleName() : msg); return; } chooseSession(out, type); session.execute(out, type); }
/** * @return index of expected token, start from 0 * @throws SQLSyntaxErrorException if no token is matched */ protected int matchIdentifier(String... expectTextUppercase) throws SQLSyntaxErrorException { if (expectTextUppercase == null || expectTextUppercase.length <= 0) throw new IllegalArgumentException("at least one expect token"); if (lexer.token() != MySQLToken.IDENTIFIER) { throw err("expect an id"); } String id = lexer.stringValueUppercase(); for (int i = 0; i < expectTextUppercase.length; ++i) { if (id == null ? expectTextUppercase[i] == null : id.equals(expectTextUppercase[i])) { lexer.nextToken(); return i; } } throw err("expect " + expectTextUppercase); }
/** * @param quoteMode if false: first <code>0x</code> has been skipped; if true: first * <code>x'</code> has been skipped */ protected void scanHexaDecimal(boolean quoteMode) throws SQLSyntaxErrorException { offsetCache = curIndex; for (; CharTypes.isHex(ch); scanChar()); sizeCache = curIndex - offsetCache; // if (sizeCache <= 0) { // throw err("expect at least one hexdigit"); // } if (quoteMode) { if (ch != '\'') { throw err("invalid char for hex: " + ch); } scanChar(); } else if (CharTypes.isIdentifierChar(ch)) { scanIdentifierFromNumber(offsetCache - 2, sizeCache + 2); return; } token = MySQLToken.LITERAL_HEX; }
/** * first <code>@@</code> is included */ protected void scanSystemVariable() throws SQLSyntaxErrorException { if (ch != '@' || sql[curIndex + 1] != '@') throw err("first char must be @@"); offsetCache = curIndex + 2; sizeCache = 0; scanChar(2); if (ch == '`') { for (++sizeCache;; ++sizeCache) { if (scanChar() == '`') { ++sizeCache; if (scanChar() != '`') { break; } } } } else { for (; CharTypes.isIdentifierChar(ch); ++sizeCache) { scanChar(); } } updateStringValue(sql, offsetCache, sizeCache); token = MySQLToken.SYS_VAR; }
/** * @return null if there is no hint */ private List<IndexHint> hintList() throws SQLSyntaxErrorException { IndexHint hint = hint(); if (hint == null) return null; List<IndexHint> list; IndexHint hint2 = hint(); if (hint2 == null) { list = new ArrayList<IndexHint>(1); list.add(hint); return list; } list = new LinkedList<IndexHint>(); list.add(hint); list.add(hint2); for (; (hint2 = hint()) != null; list.add(hint2)) ; return list; }
/** * @return argument itself if there is no union */ protected DMLQueryStatement buildUnionSelect(DMLSelectStatement select) throws SQLSyntaxErrorException { if (lexer.token() != KW_UNION) { return select; } DMLSelectUnionStatement union = new DMLSelectUnionStatement(select); for (; lexer.token() == KW_UNION;) { lexer.nextToken(); boolean isAll = false; switch (lexer.token()) { case KW_ALL: isAll = true; case KW_DISTINCT: lexer.nextToken(); break; default: break; } select = selectPrimary(); union.addSelect(select, isAll); } union.setOrderBy(orderBy()).setLimit(limit()); return union; }
@Test public void testInsertSQLWithAutoIncrement() throws SQLSyntaxErrorException { Identifier columnAutoIncrementColumn = new Identifier(null, "id"); String sql = null; SQLStatement ast = null; DMLInsertStatement parsInf = null; sql = "insert into table1(name1,name2,id) values ('1','2',10) "; ast = SQLParserDelegate.parse(sql); parsInf = (DMLInsertStatement) (ast); enrichAutoIncrementColumn(columnAutoIncrementColumn, parsInf); StringBuilder sb = new StringBuilder(); OutputVisitor visitor = new OutputVisitor(sb, false); parsInf.accept(visitor); System.out.println(sb.toString()); Assert.assertEquals("table1".toUpperCase(), parsInf.getTable().getIdTextUpUnescape()); Assert.assertNotNull(parsInf.getColumnNameList()); }
private String getStringValue() throws SQLSyntaxErrorException { String name; switch (lexer.token()) { case IDENTIFIER: name = Identifier.unescapeName(lexer.stringValue()); lexer.nextToken(); return name; case LITERAL_CHARS: name = lexer.stringValue(); name = LiteralString.getUnescapedString(name.substring(1, name.length() - 1)); lexer.nextToken(); return name; default: throw err("unexpected token: " + lexer.token()); } }
public MySQLLexer(char[] sql) throws SQLSyntaxErrorException{ if ((this.sbuf = sbufRef.get()) == null) { this.sbuf = new char[1024]; sbufRef.set(this.sbuf); } if (CharTypes.isWhitespace(sql[sql.length - 1])) { this.sql = sql; } else { this.sql = new char[sql.length + 1]; System.arraycopy(sql, 0, this.sql, 0, sql.length); } this.eofIndex = this.sql.length - 1; this.sql[this.eofIndex] = MySQLLexer.EOI; scanChar(); nextToken(); }
/** * first <code>'('</code> has been consumed. At least one element. Consume * last ')' after invocation <br/> * <code>'(' expr (',' expr)* ')'</code> */ private List<Expression> expressionList(List<Expression> exprList) throws SQLSyntaxErrorException { for (;;) { Expression expr = expression(); exprList.add(expr); switch (lexer.token()) { case PUNC_COMMA: lexer.nextToken(); break; case PUNC_RIGHT_PAREN: lexer.nextToken(); return exprList; default: throw err("unexpected token: " + lexer.token()); } } }
protected List<RowExpression> rowList() throws SQLSyntaxErrorException { List<RowExpression> valuesList; List<Expression> tempRowValue = rowValue(); if (lexer.token() == PUNC_COMMA) { valuesList = new LinkedList<RowExpression>(); valuesList.add(new RowExpression(tempRowValue)); for (; lexer.token() == PUNC_COMMA;) { lexer.nextToken(); tempRowValue = rowValue(); valuesList.add(new RowExpression(tempRowValue)); } } else { valuesList = new ArrayList<RowExpression>(1); valuesList.add(new RowExpression(tempRowValue)); } return valuesList; }
private Expression anyAllExpression() throws SQLSyntaxErrorException { QueryExpression subquery = null; switch (lexer.token()) { case KW_ALL: lexer.nextToken(); match(PUNC_LEFT_PAREN); subquery = subQuery(); match(PUNC_RIGHT_PAREN); return new SubqueryAllExpression(subquery).setCacheEvalRst(cacheEvalRst); default: int matchIndex = equalsIdentifier("SOME", "ANY"); if (matchIndex < 0) { return bitOrExpression(null, null); } String consumed = lexer.stringValue(); String consumedUp = lexer.stringValueUppercase(); if (lexer.nextToken() == PUNC_LEFT_PAREN) { lexer.nextToken(); subquery = subQuery(); match(PUNC_RIGHT_PAREN); return new SubqueryAnyExpression(subquery).setCacheEvalRst(cacheEvalRst); } return bitOrExpression(consumed, consumedUp); } }
/** * <code>higherExpr ( ('+'|'-') higherExpr)+</code> */ private Expression arithmeticTermOperatorExpression(String consumed, String consumedUp) throws SQLSyntaxErrorException { Expression temp; for (Expression expr = arithmeticFactorOperatorExpression(consumed, consumedUp);;) { switch (lexer.token()) { case OP_PLUS: lexer.nextToken(); temp = arithmeticFactorOperatorExpression(null, null); expr = new ArithmeticAddExpression(expr, temp).setCacheEvalRst(cacheEvalRst); break; case OP_MINUS: lexer.nextToken(); temp = arithmeticFactorOperatorExpression(null, null); expr = new ArithmeticSubtractExpression(expr, temp) .setCacheEvalRst(cacheEvalRst); break; default: return expr; } } }
/** * <code>higherExpr ('^' higherExpr)+</code> */ private Expression bitXORExpression(String consumed, String consumedUp) throws SQLSyntaxErrorException { Expression temp; for (Expression expr = unaryOpExpression(consumed, consumedUp);;) { switch (lexer.token()) { case OP_CARET: lexer.nextToken(); temp = unaryOpExpression(null, null); expr = new BitXORExpression(expr, temp).setCacheEvalRst(cacheEvalRst); break; default: return expr; } } }
/** * <code>higherExpr ( ('+'|'-') higherExpr)+</code> */ private Expression arithmeticTermOperatorExpression(String consumed, String consumedUp) throws SQLSyntaxErrorException { Expression temp; for (Expression expr = arithmeticFactorOperatorExpression(consumed, consumedUp);;) { switch (lexer.token()) { case OP_PLUS: lexer.nextToken(); temp = arithmeticFactorOperatorExpression(null, null); expr = new ArithmeticAddExpression(expr, temp).setCacheEvalRst(cacheEvalRst); break; case OP_MINUS: lexer.nextToken(); temp = arithmeticFactorOperatorExpression(null, null); expr = new ArithmeticSubtractExpression(expr, temp).setCacheEvalRst(cacheEvalRst); break; default: return expr; } } }
/** * @return never empty. upper-case if id format. <code>"alias1" |"`al`ias1`" | "'alias1'" | "_latin1'alias1'"</code> */ protected String as() throws SQLSyntaxErrorException { if (lexer.token() == KW_AS) { lexer.nextToken(); } StringBuilder alias = new StringBuilder(); boolean id = false; if (lexer.token() == IDENTIFIER) { alias.append(lexer.stringValueUppercase()); id = true; lexer.nextToken(); } if (lexer.token() == LITERAL_CHARS) { if (!id || id && alias.charAt(0) == '_') { alias.append(lexer.stringValue()); lexer.nextToken(); } } return alias.length() > 0 ? alias.toString() : null; }
public MySQLLexer(char[] sql) throws SQLSyntaxErrorException { if ((this.sbuf = sbufRef.get()) == null) { this.sbuf = new char[1024]; sbufRef.set(this.sbuf); } if (CharTypes.isWhitespace(sql[sql.length - 1])) { this.sql = sql; } else { this.sql = new char[sql.length + 1]; System.arraycopy(sql, 0, this.sql, 0, sql.length); } this.eofIndex = this.sql.length - 1; this.sql[this.eofIndex] = MySQLLexer.EOI; scanChar(); nextToken(); }
/** * <code>higherPRJExpr ( ('AND'|'&&') higherPRJExpr )*</code> * * @throws SQLSyntaxErrorException */ private Expression logicalAndExpression() throws SQLSyntaxErrorException { LogicalAndExpression and = null; for (Expression expr = logicalNotExpression();;) { switch (lexer.token()) { case OP_LOGICAL_AND: case KW_AND: lexer.nextToken(); if (and == null) { and = new LogicalAndExpression(); and.setCacheEvalRst(cacheEvalRst); and.appendOperand(expr); expr = and; } Expression newExpr = logicalNotExpression(); and.appendOperand(newExpr); break; default: return expr; } } }
public void testSavepint() throws SQLSyntaxErrorException { String sql = " savepoint 123e123e"; MySQLMTSParser parser = new MySQLMTSParser(new MySQLLexer(sql)); MTSSavepointStatement savepoint = parser.savepoint(); String output = output2MySQL(savepoint, sql); Assert.assertEquals("SAVEPOINT 123e123e", output); Assert.assertEquals("123e123e", savepoint.getSavepoint().getIdText()); sql = " savepoint SAVEPOINT"; parser = new MySQLMTSParser(new MySQLLexer(sql)); savepoint = parser.savepoint(); output = output2MySQL(savepoint, sql); Assert.assertEquals("SAVEPOINT SAVEPOINT", output); Assert.assertEquals("SAVEPOINT", savepoint.getSavepoint().getIdText()); sql = " savepoInt `select`"; parser = new MySQLMTSParser(new MySQLLexer(sql)); savepoint = parser.savepoint(); output = output2MySQL(savepoint, sql); Assert.assertEquals("SAVEPOINT `select`", output); Assert.assertEquals("`select`", savepoint.getSavepoint().getIdText()); }
/** * reload schema * * @return * @throws SQLSyntaxErrorException */ public SQLStatement reload() throws SQLSyntaxErrorException { lexer.nextToken(); switch (lexer.token()) { // case EOF: // return new // MTSRollbackStatement(MTSRollbackStatement.CompleteType.UN_DEF); case KW_SCHEMA: lexer.nextToken(); match(EOF); return new ReloadSchema(); default: throw err("unrecognized complete type: " + lexer.token()); } }
private List<Pair<Expression, String>> selectExprList() throws SQLSyntaxErrorException { Expression expr = exprParser.expression(); String alias = as(); List<Pair<Expression, String>> list; if (lexer.token() == PUNC_COMMA) { list = new LinkedList<Pair<Expression, String>>(); list.add(new Pair<Expression, String>(expr, alias)); } else { list = new ArrayList<Pair<Expression, String>>(1); list.add(new Pair<Expression, String>(expr, alias)); return list; } for (; lexer.token() == PUNC_COMMA; list.add(new Pair<Expression, String>(expr, alias))) { lexer.nextToken(); expr = exprParser.expression(); alias = as(); } return list; }
public DMLDeleteStatement(boolean lowPriority, boolean quick, boolean ignore, List<Identifier> tableNameList, TableReferences tableRefs, Expression whereCondition) throws SQLSyntaxErrorException{ this.lowPriority = lowPriority; this.quick = quick; this.ignore = ignore; if (tableNameList == null || tableNameList.isEmpty()) { throw new IllegalArgumentException("argument 'tableNameList' is empty"); } else if (tableNameList instanceof ArrayList) { this.tableNames = tableNameList; } else { this.tableNames = new ArrayList<Identifier>(tableNameList); } if (tableRefs == null) { throw new IllegalArgumentException("argument 'tableRefs' is null"); } this.tableRefs = tableRefs; this.whereCondition = whereCondition; this.orderBy = null; this.limit = null; }
private TableReference tableFactor() throws SQLSyntaxErrorException { String alias = null; switch (lexer.token()) { case PUNC_LEFT_PAREN: lexer.nextToken(); Object ref = trsOrQuery(); match(PUNC_RIGHT_PAREN); if (ref instanceof QueryExpression) { alias = as(); return new SubqueryFactor((QueryExpression) ref, alias); } return (TableReferences) ref; case IDENTIFIER: Identifier table = identifier(); alias = as(); List<IndexHint> hintList = hintList(); return new TableRefFactor(table, alias, hintList); default: throw err("unexpected token for tableFactor: " + lexer.token()); } }
/** * <code>higherExpr ( ('<<'|'>>') higherExpr)+</code> */ private Expression bitShiftExpression(String consumed, String consumedUp) throws SQLSyntaxErrorException { Expression temp; for (Expression expr = arithmeticTermOperatorExpression(consumed, consumedUp);;) { switch (lexer.token()) { case OP_LEFT_SHIFT: lexer.nextToken(); temp = arithmeticTermOperatorExpression(null, null); expr = new BitShiftExpression(false, expr, temp).setCacheEvalRst(cacheEvalRst); break; case OP_RIGHT_SHIFT: lexer.nextToken(); temp = arithmeticTermOperatorExpression(null, null); expr = new BitShiftExpression(true, expr, temp).setCacheEvalRst(cacheEvalRst); break; default: return expr; } } }