diff --git a/README b/README index 8fce5e2d1b..6a7fc3c292 100644 --- a/README +++ b/README @@ -1,6 +1,10 @@ Introduction --- -* git clone https://github.com/AlibabaTech/druid.git +* git clone https://github.com/alibaba/druid.git * cd druid && mvn install * have fun. +Doucumentation +--- +中文 https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98 +English https://github.com/alibaba/druid/wiki/FAQ diff --git a/pom.xml b/pom.xml index d4bee6fefb..8385cae505 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.alibaba druid - 0.2.12-SNAPSHOT + 0.2.16-SNAPSHOT jar druid @@ -131,6 +131,7 @@ + true public UTF-8 UTF-8 diff --git a/src/main/java/com/alibaba/druid/VERSION.java b/src/main/java/com/alibaba/druid/VERSION.java index 4f63632830..c45969dfdb 100644 --- a/src/main/java/com/alibaba/druid/VERSION.java +++ b/src/main/java/com/alibaba/druid/VERSION.java @@ -19,7 +19,7 @@ public final class VERSION { public final static int MajorVersion = 0; public final static int MinorVersion = 2; - public final static int RevisionVersion = 11; + public final static int RevisionVersion = 16; public static String getVersionNumber() { return VERSION.MajorVersion + "." + VERSION.MinorVersion + "." + VERSION.RevisionVersion; diff --git a/src/main/java/com/alibaba/druid/filter/config/ConfigFilter.java b/src/main/java/com/alibaba/druid/filter/config/ConfigFilter.java index 9fa5e095a7..58760be896 100644 --- a/src/main/java/com/alibaba/druid/filter/config/ConfigFilter.java +++ b/src/main/java/com/alibaba/druid/filter/config/ConfigFilter.java @@ -279,8 +279,8 @@ public class ConfigFilter extends FilterAdapter { } } - @SuppressWarnings("resource") - private InputStream getFileAsStream(String filePath) throws FileNotFoundException { + @SuppressWarnings("resource") + private InputStream getFileAsStream(String filePath) throws FileNotFoundException { InputStream inStream = null; File file = new File(filePath); if (file.exists()) { diff --git a/src/main/java/com/alibaba/druid/pool/DruidDataSource.java b/src/main/java/com/alibaba/druid/pool/DruidDataSource.java index 4cda1552a8..eff24fb1c9 100644 --- a/src/main/java/com/alibaba/druid/pool/DruidDataSource.java +++ b/src/main/java/com/alibaba/druid/pool/DruidDataSource.java @@ -77,6 +77,7 @@ import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.druid.util.IOUtils; import com.alibaba.druid.util.JMXUtils; import com.alibaba.druid.util.JdbcUtils; +import com.alibaba.druid.wall.WallFilter; /** * @author ljw @@ -584,12 +585,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat } oracleValidationQueryCheck(); - } else if (JdbcUtils.MYSQL.equals(this.dbType)) { - if (!this.isTestWhileIdle()) { - if (LOG.isWarnEnabled()) { - LOG.warn("Your dbType is mysql, recommend set testWhileIdle is true"); - } - } } else if (JdbcUtils.DB2.equals(dbType)) { db2ValidationQueryCheck(); } @@ -875,7 +870,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat } } this.discardConnection(holder.getConnection()); - pooledConnection.disable(); + pooledConnection.disable(t); } throw sqlEx; @@ -1440,8 +1435,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat ref.add(new StringRefAddr("instanceKey", instanceKey)); ref.add(new StringRefAddr("url", this.getUrl())); ref.add(new StringRefAddr("username", this.getUsername())); - ref.add(new StringRefAddr("password",this.getPassword())); - //TODO ADD OTHER PROPERTIES + ref.add(new StringRefAddr("password", this.getPassword())); + // TODO ADD OTHER PROPERTIES return ref; } @@ -1946,6 +1941,17 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat return this.getDataSourceStat().getSqlStatMap(); } + public Map getWallStatMap() { + for (Filter filter : this.filters) { + if (filter instanceof WallFilter) { + WallFilter wallFilter = (WallFilter) filter; + return wallFilter.getProvider().getStatsMap(); + } + } + + return null; + } + public Lock getLock() { return lock; } diff --git a/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java b/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java index 4557d28468..d4d8bed89e 100644 --- a/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java +++ b/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java @@ -53,24 +53,28 @@ import com.alibaba.druid.support.logging.LogFactory; */ public class DruidPooledConnection extends PoolableWrapper implements javax.sql.PooledConnection, Connection { - private final static Log LOG = LogFactory.getLog(DruidPooledConnection.class); + private final static Log LOG = LogFactory.getLog(DruidPooledConnection.class); + + public static final int MAX_RECORD_SQL_COUNT = 10; protected Connection conn; protected volatile DruidConnectionHolder holder; protected TransactionInfo transactionInfo; private final boolean dupCloseLogEnable; - private volatile boolean traceEnable = false; - private boolean disable = false; - private boolean closed = false; + private volatile boolean traceEnable = false; + private boolean disable = false; + private boolean closed = false; private final Thread ownerThread; private long connectedTimeNano; - private volatile boolean running = false; + private volatile boolean running = false; - private volatile boolean abandoned = false; + private volatile boolean abandoned = false; private StackTraceElement[] connectStackTrace; + private Throwable disableError = null; + public DruidPooledConnection(DruidConnectionHolder holder){ super(holder.getConnection()); @@ -148,7 +152,7 @@ public class DruidPooledConnection extends PoolableWrapper implements javax.sql. if (rawStatement.getConnection().isClosed()) { return; } - + LOG.error("clear parameter error", ex); } } @@ -179,10 +183,15 @@ public class DruidPooledConnection extends PoolableWrapper implements javax.sql. } public void disable() { + disable(null); + } + + public void disable(Throwable error) { this.traceEnable = false; this.holder = null; this.transactionInfo = null; this.disable = true; + this.disableError = error; } public boolean isDisable() { @@ -679,7 +688,10 @@ public class DruidPooledConnection extends PoolableWrapper implements javax.sql. } if (transactionInfo != null) { - transactionInfo.getSqlList().add(sql); + List sqlList = transactionInfo.getSqlList(); + if (sqlList.size() < MAX_RECORD_SQL_COUNT) { + sqlList.add(sql); + } } } @@ -1012,8 +1024,16 @@ public class DruidPooledConnection extends PoolableWrapper implements javax.sql. } public void checkState() throws SQLException { - if (holder == null || closed || disable) { - throw new SQLException("connection is closed"); + if (holder == null) { + throw new SQLException("connection holder is null"); + } + + if (closed) { + throw new SQLException("connection closed"); + } + + if (disable) { + throw new SQLException("connection disabled", disableError); } } diff --git a/src/main/java/com/alibaba/druid/sql/SQLUtils.java b/src/main/java/com/alibaba/druid/sql/SQLUtils.java index 10a36ef8dd..664118193e 100644 --- a/src/main/java/com/alibaba/druid/sql/SQLUtils.java +++ b/src/main/java/com/alibaba/druid/sql/SQLUtils.java @@ -31,7 +31,6 @@ import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerOutputVisitor; import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor; import com.alibaba.druid.sql.parser.ParserException; import com.alibaba.druid.sql.parser.SQLExprParser; -import com.alibaba.druid.sql.parser.SQLParseException; import com.alibaba.druid.sql.parser.SQLParserUtils; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.parser.Token; @@ -150,9 +149,6 @@ public class SQLUtils { List statementList = toStatementList(sql, dbType); return toSQLString(statementList, dbType, parameters); - } catch (SQLParseException ex) { - LOG.warn("format error", ex); - return sql; } catch (ParserException ex) { LOG.warn("format error", ex); return sql; diff --git a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBinaryOperator.java b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBinaryOperator.java index b371006492..294f3ff4a3 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBinaryOperator.java +++ b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLBinaryOperator.java @@ -38,7 +38,6 @@ public enum SQLBinaryOperator { BitwiseAnd("&", 90), BitwiseOr("|", 100), - InvertBits("~", 100), GreaterThan(">", 110), GreaterThanOrEqual(">=", 110), @@ -71,12 +70,9 @@ public enum SQLBinaryOperator { BooleanOr("OR", 160), Assignment(":=", 169), + PostgresStyleTypeCast("::", 20), ; - - - - public static int getPriority(SQLBinaryOperator operator) { return 0; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLIdentifierExpr.java b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLIdentifierExpr.java index 4ce5c14321..e8cb662198 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLIdentifierExpr.java +++ b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLIdentifierExpr.java @@ -25,15 +25,16 @@ public class SQLIdentifierExpr extends SQLExprImpl implements SQLName { private String name; + private transient String lowerName; + public SQLIdentifierExpr(){ } public SQLIdentifierExpr(String name){ - this.name = name; } - + public String getSimleName() { return name; } @@ -44,6 +45,18 @@ public class SQLIdentifierExpr extends SQLExprImpl implements SQLName { public void setName(String name) { this.name = name; + this.lowerName = null; + } + + public String getLowerName() { + if (lowerName == null && name != null) { + lowerName = name.toLowerCase(); + } + return lowerName; + } + + public void setLowerName(String lowerName) { + this.lowerName = lowerName; } public void output(StringBuffer buf) { diff --git a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLPropertyExpr.java b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLPropertyExpr.java index 5220ff9cef..69b0ad7fa3 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/expr/SQLPropertyExpr.java +++ b/src/main/java/com/alibaba/druid/sql/ast/expr/SQLPropertyExpr.java @@ -28,7 +28,9 @@ public class SQLPropertyExpr extends SQLExprImpl implements SQLName { private String name; public SQLPropertyExpr(SQLExpr owner, String name){ - + if (owner != null) { + owner.setParent(this); + } this.owner = owner; this.name = name; } @@ -46,6 +48,9 @@ public class SQLPropertyExpr extends SQLExprImpl implements SQLName { } public void setOwner(SQLExpr owner) { + if (owner != null) { + owner.setParent(this); + } this.owner = owner; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableAlterColumn.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableAlterColumn.java new file mode 100644 index 0000000000..a2c2de7ab9 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableAlterColumn.java @@ -0,0 +1,44 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.druid.sql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLObjectImpl; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class SQLAlterTableAlterColumn extends SQLObjectImpl implements SQLAlterTableItem { + + private static final long serialVersionUID = 1L; + + private SQLColumnDefinition column; + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, column); + } + visitor.endVisit(this); + } + + public SQLColumnDefinition getColumn() { + return column; + } + + public void setColumn(SQLColumnDefinition column) { + this.column = column; + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDisableKeys.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDisableKeys.java new file mode 100644 index 0000000000..d526e09368 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDisableKeys.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLObjectImpl; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class SQLAlterTableDisableKeys extends SQLObjectImpl implements SQLAlterTableItem { + + private static final long serialVersionUID = 1L; + + @Override + protected void accept0(SQLASTVisitor visitor) { + visitor.visit(this); + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropForeinKey.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropForeinKey.java new file mode 100644 index 0000000000..cc2603d069 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropForeinKey.java @@ -0,0 +1,44 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLName; +import com.alibaba.druid.sql.ast.SQLObjectImpl; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class SQLAlterTableDropForeinKey extends SQLObjectImpl implements SQLAlterTableItem { + + private static final long serialVersionUID = 1L; + + private SQLName indexName; + + public SQLName getIndexName() { + return indexName; + } + + public void setIndexName(SQLName indexName) { + this.indexName = indexName; + } + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, indexName); + } + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropPrimaryKey.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropPrimaryKey.java new file mode 100644 index 0000000000..3c5617c17a --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableDropPrimaryKey.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLObjectImpl; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class SQLAlterTableDropPrimaryKey extends SQLObjectImpl implements SQLAlterTableItem { + + private static final long serialVersionUID = 1L; + + @Override + protected void accept0(SQLASTVisitor visitor) { + visitor.visit(this); + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableEnableKeys.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableEnableKeys.java new file mode 100644 index 0000000000..af73924f05 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableEnableKeys.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLObjectImpl; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class SQLAlterTableEnableKeys extends SQLObjectImpl implements SQLAlterTableItem { + + private static final long serialVersionUID = 1L; + + @Override + protected void accept0(SQLASTVisitor visitor) { + visitor.visit(this); + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableStatement.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableStatement.java index 0361be89d6..eb159a7b8c 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableStatement.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableStatement.java @@ -20,6 +20,7 @@ import java.util.List; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLStatementImpl; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; public class SQLAlterTableStatement extends SQLStatementImpl implements SQLDDLStatement { @@ -54,4 +55,13 @@ public class SQLAlterTableStatement extends SQLStatementImpl implements SQLDDLSt public void setName(SQLName name) { this.setTableSource(new SQLExprTableSource(name)); } + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, getTableSource()); + acceptChild(visitor, getItems()); + } + visitor.endVisit(this); + } } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCheck.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCheck.java new file mode 100644 index 0000000000..72af8193eb --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCheck.java @@ -0,0 +1,45 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class SQLCheck extends SQLConstaintImpl implements SQLTableElement { + + private static final long serialVersionUID = 1L; + + private SQLExpr expr; + + public SQLExpr getExpr() { + return expr; + } + + public void setExpr(SQLExpr expr) { + this.expr = expr; + } + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, this.getName()); + acceptChild(visitor, this.getExpr()); + } + visitor.endVisit(this); + } + + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateViewStatement.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateViewStatement.java index 6e1c20beb9..b363021e90 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateViewStatement.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateViewStatement.java @@ -26,6 +26,7 @@ import com.alibaba.druid.sql.visitor.SQLASTVisitor; public class SQLCreateViewStatement extends SQLStatementImpl implements SQLDDLStatement { private static final long serialVersionUID = 1L; + private boolean orReplace = false; protected SQLName name; protected SQLSelect subQuery; @@ -37,6 +38,14 @@ public class SQLCreateViewStatement extends SQLStatementImpl implements SQLDDLSt } + public boolean isOrReplace() { + return orReplace; + } + + public void setOrReplace(boolean orReplace) { + this.orReplace = orReplace; + } + public SQLName getName() { return name; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDeleteStatement.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDeleteStatement.java index efb3607131..330f524444 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDeleteStatement.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDeleteStatement.java @@ -44,6 +44,9 @@ public class SQLDeleteStatement extends SQLStatementImpl { } public void setTableSource(SQLTableSource tableSource) { + if (tableSource != null) { + tableSource.setParent(this); + } this.tableSource = tableSource; } @@ -64,6 +67,9 @@ public class SQLDeleteStatement extends SQLStatementImpl { } public void setWhere(SQLExpr where) { + if (where != null) { + where.setParent(this); + } this.where = where; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyConstraint.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyConstraint.java index cc85d568e5..a1147a2d81 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyConstraint.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyConstraint.java @@ -19,7 +19,7 @@ import java.util.List; import com.alibaba.druid.sql.ast.SQLName; -public interface SQLForeignKeyConstraint extends SQLConstaint { +public interface SQLForeignKeyConstraint extends SQLConstaint, SQLTableElement { List getReferencingColumns(); diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyImpl.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyImpl.java new file mode 100644 index 0000000000..73db9f4b5d --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLForeignKeyImpl.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.ast.statement; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.druid.sql.ast.SQLName; + +public abstract class SQLForeignKeyImpl extends SQLConstaintImpl implements SQLForeignKeyConstraint { + + private static final long serialVersionUID = 1L; + private SQLName referencedTableName; + private List referencingColumns = new ArrayList(); + private List referencedColumns = new ArrayList(); + + @Override + public List getReferencingColumns() { + return referencingColumns; + } + + @Override + public SQLName getReferencedTableName() { + return referencedTableName; + } + + @Override + public void setReferencedTableName(SQLName value) { + this.referencedTableName = value; + } + + @Override + public List getReferencedColumns() { + return referencedColumns; + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLInsertInto.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLInsertInto.java index 9acb59dfaf..6396ae3985 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLInsertInto.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLInsertInto.java @@ -49,6 +49,9 @@ public abstract class SQLInsertInto extends SQLObjectImpl { } public void setTableSource(SQLExprTableSource tableSource) { + if (tableSource != null) { + tableSource.setParent(this); + } this.tableSource = tableSource; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLJoinTableSource.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLJoinTableSource.java index 0668977fcf..1af33c8274 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLJoinTableSource.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLJoinTableSource.java @@ -15,17 +15,21 @@ */ package com.alibaba.druid.sql.ast.statement; +import java.util.ArrayList; +import java.util.List; + import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.visitor.SQLASTVisitor; public class SQLJoinTableSource extends SQLTableSourceImpl { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - protected SQLTableSource left; - protected JoinType joinType; - protected SQLTableSource right; - protected SQLExpr condition; + protected SQLTableSource left; + protected JoinType joinType; + protected SQLTableSource right; + protected SQLExpr condition; + protected final List using = new ArrayList(); public SQLJoinTableSource(String alias){ super(alias); @@ -40,6 +44,7 @@ public class SQLJoinTableSource extends SQLTableSourceImpl { acceptChild(visitor, this.left); acceptChild(visitor, this.right); acceptChild(visitor, this.condition); + acceptChild(visitor, this.using); } visitor.endVisit(this); @@ -58,6 +63,9 @@ public class SQLJoinTableSource extends SQLTableSourceImpl { } public void setLeft(SQLTableSource left) { + if (left != null) { + left.setParent(this); + } this.left = left; } @@ -66,6 +74,9 @@ public class SQLJoinTableSource extends SQLTableSourceImpl { } public void setRight(SQLTableSource right) { + if (right != null) { + right.setParent(this); + } this.right = right; } @@ -74,9 +85,16 @@ public class SQLJoinTableSource extends SQLTableSourceImpl { } public void setCondition(SQLExpr condition) { + if (condition != null) { + condition.setParent(this); + } this.condition = condition; } + public List getUsing() { + return this.using; + } + public void output(StringBuffer buf) { this.left.output(buf); buf.append(' '); @@ -91,15 +109,13 @@ public class SQLJoinTableSource extends SQLTableSourceImpl { } public static enum JoinType { - COMMA(","), // + COMMA(","), // JOIN("JOIN"), // - INNER_JOIN("INNER JOIN"), // - CROSS_JOIN("CROSS JOIN"), // - NATURAL_JOIN("NATURAL JOIN"), // - NATURAL_INNER_JOIN("NATURAL INNER JOIN"), // - LEFT_OUTER_JOIN("LEFT JOIN"), - RIGHT_OUTER_JOIN("RIGHT JOIN"), - FULL_OUTER_JOIN("FULL JOIN"), + INNER_JOIN("INNER JOIN"), // + CROSS_JOIN("CROSS JOIN"), // + NATURAL_JOIN("NATURAL JOIN"), // + NATURAL_INNER_JOIN("NATURAL INNER JOIN"), // + LEFT_OUTER_JOIN("LEFT JOIN"), RIGHT_OUTER_JOIN("RIGHT JOIN"), FULL_OUTER_JOIN("FULL JOIN"), STRAIGHT_JOIN("STRAIGHT_JOIN"); public final String name; @@ -107,6 +123,7 @@ public class SQLJoinTableSource extends SQLTableSourceImpl { JoinType(String name){ this.name = name; } + public static String toString(JoinType joinType) { return joinType.name; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectItem.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectItem.java index 68b60494ec..5d78228a68 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectItem.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectItem.java @@ -35,9 +35,12 @@ public class SQLSelectItem extends SQLObjectImpl { } public SQLSelectItem(SQLExpr expr, String alias){ - this.expr = expr; this.alias = alias; + + if (expr != null) { + expr.setParent(this); + } } public SQLExpr getExpr() { @@ -46,6 +49,9 @@ public class SQLSelectItem extends SQLObjectImpl { public void setExpr(SQLExpr expr) { this.expr = expr; + if (expr != null) { + expr.setParent(this); + } } public String getAlias() { diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java index b2cb7b96bf..30abaf4596 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java @@ -43,10 +43,13 @@ public class SQLSelectQueryBlock extends SQLSelectQuery { } public void setInto(SQLExpr into) { - this.into = new SQLExprTableSource(into); + this.setInto(new SQLExprTableSource(into)); } public void setInto(SQLExprTableSource into) { + if (into != null) { + into.setParent(this); + } this.into = into; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLTruncateStatement.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLTruncateStatement.java index 3a70032ac2..2ba1b69b61 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLTruncateStatement.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLTruncateStatement.java @@ -36,7 +36,9 @@ public class SQLTruncateStatement extends SQLStatementImpl { } public void addTableSource(SQLName name) { - this.tableSources.add(new SQLExprTableSource(name)); + SQLExprTableSource tableSource = new SQLExprTableSource(name); + tableSource.setParent(this); + this.tableSources.add(tableSource); } @Override diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUpdateStatement.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUpdateStatement.java index ae582b381a..8590529c23 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUpdateStatement.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUpdateStatement.java @@ -45,6 +45,9 @@ public class SQLUpdateStatement extends SQLStatementImpl { } public void setTableSource(SQLTableSource tableSource) { + if (tableSource != null) { + tableSource.setParent(this); + } this.tableSource = tableSource; } @@ -61,6 +64,9 @@ public class SQLUpdateStatement extends SQLStatementImpl { } public void setWhere(SQLExpr where) { + if (where != null) { + where.setParent(this); + } this.where = where; } diff --git a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLWithSubqueryClause.java b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLWithSubqueryClause.java index afc34684ad..b198529845 100644 --- a/src/main/java/com/alibaba/druid/sql/ast/statement/SQLWithSubqueryClause.java +++ b/src/main/java/com/alibaba/druid/sql/ast/statement/SQLWithSubqueryClause.java @@ -55,7 +55,7 @@ public class SQLWithSubqueryClause extends SQLObjectImpl { private static final long serialVersionUID = 1L; protected SQLIdentifierExpr name; protected final List columns = new ArrayList(); - protected SQLSelectQuery subQuery; + protected SQLSelect subQuery; @Override protected void accept0(SQLASTVisitor visitor) { @@ -75,11 +75,11 @@ public class SQLWithSubqueryClause extends SQLObjectImpl { this.name = name; } - public SQLSelectQuery getSubQuery() { + public SQLSelect getSubQuery() { return subQuery; } - public void setSubQuery(SQLSelectQuery subQuery) { + public void setSubQuery(SQLSelect subQuery) { this.subQuery = subQuery; } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlForeignKey.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlForeignKey.java new file mode 100644 index 0000000000..1250d1b158 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlForeignKey.java @@ -0,0 +1,45 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.mysql.ast; + +import com.alibaba.druid.sql.ast.statement.SQLForeignKeyConstraint; +import com.alibaba.druid.sql.ast.statement.SQLForeignKeyImpl; +import com.alibaba.druid.sql.ast.statement.SQLTableElement; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class MySqlForeignKey extends SQLForeignKeyImpl implements SQLForeignKeyConstraint, SQLTableElement { + + private static final long serialVersionUID = 1L; + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor instanceof MySqlASTVisitor) { + accept0((MySqlASTVisitor) visitor); + } + } + + protected void accept0(MySqlASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, this.getName()); + acceptChild(visitor, this.getReferencedTableName()); + acceptChild(visitor, this.getReferencingColumns()); + acceptChild(visitor, this.getReferencedColumns()); + } + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlUnique.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlUnique.java new file mode 100644 index 0000000000..cb80911516 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlUnique.java @@ -0,0 +1,35 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.mysql.ast; + +import com.alibaba.druid.sql.ast.statement.SQLPrimaryKey; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; + +@SuppressWarnings("serial") +public class MySqlUnique extends MySqlKey implements SQLPrimaryKey { + + public MySqlUnique(){ + + } + + protected void accept0(MySqlASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, this.getName()); + acceptChild(visitor, this.getColumns()); + } + visitor.endVisit(this); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableChangeColumn.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableChangeColumn.java index 3947ce73da..55fafc03f4 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableChangeColumn.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableChangeColumn.java @@ -40,7 +40,7 @@ public class MySqlAlterTableChangeColumn extends MySqlObjectImpl implements SQLA if (visitor.visit(this)) { acceptChild(visitor, columnName); acceptChild(visitor, newColumnDefinition); - + acceptChild(visitor, firstColumn); acceptChild(visitor, afterColumn); } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableDiscardTablespace.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableDiscardTablespace.java new file mode 100644 index 0000000000..f8c5d2dc6e --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableDiscardTablespace.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.mysql.ast.statement; + +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddIndex; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableItem; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlObject; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class MySqlAlterTableDiscardTablespace extends SQLAlterTableAddIndex implements SQLAlterTableItem, MySqlObject { + + private static final long serialVersionUID = 1L; + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor instanceof MySqlASTVisitor) { + accept0((MySqlASTVisitor) visitor); + } else { + throw new IllegalArgumentException("not support visitor type : " + visitor.getClass().getName()); + } + } + + public void accept0(MySqlASTVisitor visitor) { + visitor.visit(this); + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableImportTablespace.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableImportTablespace.java new file mode 100644 index 0000000000..6eaa054983 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableImportTablespace.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.mysql.ast.statement; + +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddIndex; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableItem; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlObject; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; +import com.alibaba.druid.sql.visitor.SQLASTVisitor; + +public class MySqlAlterTableImportTablespace extends SQLAlterTableAddIndex implements SQLAlterTableItem, MySqlObject { + + private static final long serialVersionUID = 1L; + + @Override + protected void accept0(SQLASTVisitor visitor) { + if (visitor instanceof MySqlASTVisitor) { + accept0((MySqlASTVisitor) visitor); + } else { + throw new IllegalArgumentException("not support visitor type : " + visitor.getClass().getName()); + } + } + + public void accept0(MySqlASTVisitor visitor) { + visitor.visit(this); + visitor.endVisit(this); + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableModifyColumn.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableModifyColumn.java new file mode 100644 index 0000000000..25044436e7 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableModifyColumn.java @@ -0,0 +1,78 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.mysql.ast.statement; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableItem; +import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlObjectImpl; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; + +public class MySqlAlterTableModifyColumn extends MySqlObjectImpl implements SQLAlterTableItem { + + private static final long serialVersionUID = 1L; + + + private SQLColumnDefinition newColumnDefinition; + + private boolean first; + + private SQLExpr firstColumn; + private SQLExpr afterColumn; + + @Override + public void accept0(MySqlASTVisitor visitor) { + if (visitor.visit(this)) { + acceptChild(visitor, newColumnDefinition); + + acceptChild(visitor, firstColumn); + acceptChild(visitor, afterColumn); + } + } + + public SQLExpr getFirstColumn() { + return firstColumn; + } + + public void setFirstColumn(SQLExpr firstColumn) { + this.firstColumn = firstColumn; + } + + public SQLExpr getAfterColumn() { + return afterColumn; + } + + public void setAfterColumn(SQLExpr afterColumn) { + this.afterColumn = afterColumn; + } + + public SQLColumnDefinition getNewColumnDefinition() { + return newColumnDefinition; + } + + public void setNewColumnDefinition(SQLColumnDefinition newColumnDefinition) { + this.newColumnDefinition = newColumnDefinition; + } + + public boolean isFirst() { + return first; + } + + public void setFirst(boolean first) { + this.first = first; + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableOption.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableOption.java index f5e50a037d..4ab8be82ec 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableOption.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableOption.java @@ -24,9 +24,9 @@ public class MySqlAlterTableOption extends MySqlObjectImpl implements SQLAlterTa private static final long serialVersionUID = 1L; private String name; - private String value; + private Object value; - public MySqlAlterTableOption(String name, String value){ + public MySqlAlterTableOption(String name, Object value){ this.name = name; this.value = value; } @@ -48,11 +48,11 @@ public class MySqlAlterTableOption extends MySqlObjectImpl implements SQLAlterTa this.name = name; } - public String getValue() { + public Object getValue() { return value; } - public void setValue(String value) { + public void setValue(Object value) { this.value = value; } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowAuthorsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowAuthorsStatement.java index 376304e5fc..7b0fdaa673 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowAuthorsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowAuthorsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowAuthorsStatement extends MySqlStatementImpl { +public class MySqlShowAuthorsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinLogEventsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinLogEventsStatement.java index 8f2dc2699d..5080bef506 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinLogEventsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinLogEventsStatement.java @@ -19,7 +19,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock.Limit; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowBinLogEventsStatement extends MySqlStatementImpl { +public class MySqlShowBinLogEventsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinaryLogsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinaryLogsStatement.java index 16c44c1765..f18b3479e0 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinaryLogsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowBinaryLogsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowBinaryLogsStatement extends MySqlStatementImpl { +public class MySqlShowBinaryLogsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCharacterSetStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCharacterSetStatement.java index 9010892e58..32137ca4c1 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCharacterSetStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCharacterSetStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCharacterSetStatement extends MySqlStatementImpl { +public class MySqlShowCharacterSetStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCollationStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCollationStatement.java index 961c53b02c..c6d56c8833 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCollationStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCollationStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCollationStatement extends MySqlStatementImpl { +public class MySqlShowCollationStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowColumnsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowColumnsStatement.java index d765617ec1..3fc96fa099 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowColumnsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowColumnsStatement.java @@ -21,7 +21,7 @@ import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowColumnsStatement extends MySqlStatementImpl { +public class MySqlShowColumnsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowContributorsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowContributorsStatement.java index 8023dac9b2..7163b9415f 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowContributorsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowContributorsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowContributorsStatement extends MySqlStatementImpl { +public class MySqlShowContributorsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateDatabaseStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateDatabaseStatement.java index fd67aaf519..0b79f7facf 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateDatabaseStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateDatabaseStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateDatabaseStatement extends MySqlStatementImpl { +public class MySqlShowCreateDatabaseStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateEventStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateEventStatement.java index 34ec26ec6e..a2445e28d7 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateEventStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateEventStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateEventStatement extends MySqlStatementImpl { +public class MySqlShowCreateEventStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateFunctionStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateFunctionStatement.java index 291989ed43..9442970ddf 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateFunctionStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateFunctionStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateFunctionStatement extends MySqlStatementImpl { +public class MySqlShowCreateFunctionStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateProcedureStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateProcedureStatement.java index 14c3026801..9b80c7b3fd 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateProcedureStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateProcedureStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateProcedureStatement extends MySqlStatementImpl { +public class MySqlShowCreateProcedureStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTableStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTableStatement.java index 3055dd6033..a0c8b4d097 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTableStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTableStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateTableStatement extends MySqlStatementImpl { +public class MySqlShowCreateTableStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTriggerStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTriggerStatement.java index ac5460fd23..2e9611c8cb 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTriggerStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateTriggerStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateTriggerStatement extends MySqlStatementImpl { +public class MySqlShowCreateTriggerStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateViewStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateViewStatement.java index 40f5c4dd91..5596f08ab0 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateViewStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowCreateViewStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowCreateViewStatement extends MySqlStatementImpl { +public class MySqlShowCreateViewStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowDatabasesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowDatabasesStatement.java index 96491082ec..a48e64e8af 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowDatabasesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowDatabasesStatement.java @@ -19,7 +19,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowDatabasesStatement extends MySqlStatementImpl { +public class MySqlShowDatabasesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEngineStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEngineStatement.java index 378c8131ad..b4cef94d1a 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEngineStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEngineStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowEngineStatement extends MySqlStatementImpl { +public class MySqlShowEngineStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEnginesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEnginesStatement.java index 386efc01c4..37cfd208a8 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEnginesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEnginesStatement.java @@ -17,7 +17,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowEnginesStatement extends MySqlStatementImpl { +public class MySqlShowEnginesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; private boolean storage = false; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowErrorsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowErrorsStatement.java index 0ba9db8a1e..5ffa444e8f 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowErrorsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowErrorsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock.Limit; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowErrorsStatement extends MySqlStatementImpl { +public class MySqlShowErrorsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEventsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEventsStatement.java index 1b067482be..3656d7bdde 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEventsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowEventsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowEventsStatement extends MySqlStatementImpl { +public class MySqlShowEventsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionCodeStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionCodeStatement.java index a1a7e8b2c2..68e12e900a 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionCodeStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionCodeStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowFunctionCodeStatement extends MySqlStatementImpl { +public class MySqlShowFunctionCodeStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionStatusStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionStatusStatement.java index 12378b3c2b..53edb1910b 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionStatusStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionStatusStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowFunctionStatusStatement extends MySqlStatementImpl { +public class MySqlShowFunctionStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowGrantsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowGrantsStatement.java index 768f9a522b..30754e44c1 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowGrantsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowGrantsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowGrantsStatement extends MySqlStatementImpl { +public class MySqlShowGrantsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowIndexesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowIndexesStatement.java index 5eff5a0a35..b2e5e99371 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowIndexesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowIndexesStatement.java @@ -20,7 +20,7 @@ import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowIndexesStatement extends MySqlStatementImpl { +public class MySqlShowIndexesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowKeysStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowKeysStatement.java index aabdbf7f50..63af10c844 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowKeysStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowKeysStatement.java @@ -20,7 +20,7 @@ import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowKeysStatement extends MySqlStatementImpl { +public class MySqlShowKeysStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterLogsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterLogsStatement.java index 7477f926b1..5e5ee43361 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterLogsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterLogsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowMasterLogsStatement extends MySqlStatementImpl { +public class MySqlShowMasterLogsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterStatusStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterStatusStatement.java index b1389ababd..a99b49e88f 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterStatusStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterStatusStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowMasterStatusStatement extends MySqlStatementImpl { +public class MySqlShowMasterStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowOpenTablesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowOpenTablesStatement.java index 3637e27b4d..e2c1629773 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowOpenTablesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowOpenTablesStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowOpenTablesStatement extends MySqlStatementImpl { +public class MySqlShowOpenTablesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPluginsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPluginsStatement.java index 3dd093b413..19415b19a1 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPluginsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPluginsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowPluginsStatement extends MySqlStatementImpl { +public class MySqlShowPluginsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPrivilegesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPrivilegesStatement.java index ad172b1c98..08f4b6f0d1 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPrivilegesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowPrivilegesStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowPrivilegesStatement extends MySqlStatementImpl { +public class MySqlShowPrivilegesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureCodeStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureCodeStatement.java index c827f6ee0a..8df39c6d7b 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureCodeStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureCodeStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowProcedureCodeStatement extends MySqlStatementImpl { +public class MySqlShowProcedureCodeStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureStatusStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureStatusStatement.java index 6ad9403429..3ae6fce5a1 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureStatusStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcedureStatusStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowProcedureStatusStatement extends MySqlStatementImpl { +public class MySqlShowProcedureStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcessListStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcessListStatement.java index 6a2bb5af8f..e2a3da1607 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcessListStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProcessListStatement.java @@ -17,7 +17,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowProcessListStatement extends MySqlStatementImpl { +public class MySqlShowProcessListStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfileStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfileStatement.java index eb9023457b..fdbdf1151b 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfileStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfileStatement.java @@ -22,7 +22,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock.Limit; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowProfileStatement extends MySqlStatementImpl { +public class MySqlShowProfileStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfilesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfilesStatement.java index 822e7fb324..7b2174f1dc 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfilesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowProfilesStatement.java @@ -17,7 +17,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowProfilesStatement extends MySqlStatementImpl { +public class MySqlShowProfilesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowRelayLogEventsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowRelayLogEventsStatement.java index a36e058655..5aa49da5f9 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowRelayLogEventsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowRelayLogEventsStatement.java @@ -19,7 +19,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock.Limit; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowRelayLogEventsStatement extends MySqlStatementImpl { +public class MySqlShowRelayLogEventsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveHostsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveHostsStatement.java index d5539fe704..8ebce36046 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveHostsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveHostsStatement.java @@ -17,7 +17,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowSlaveHostsStatement extends MySqlStatementImpl { +public class MySqlShowSlaveHostsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveStatusStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveStatusStatement.java index 239d763bfe..3d0065082e 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveStatusStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowSlaveStatusStatement.java @@ -17,7 +17,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowSlaveStatusStatement extends MySqlStatementImpl { +public class MySqlShowSlaveStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatement.java new file mode 100644 index 0000000000..b4227d9086 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatement.java @@ -0,0 +1,21 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.mysql.ast.statement; + + +public interface MySqlShowStatement { + +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatusStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatusStatement.java index 38328172e7..028f2f814e 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatusStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowStatusStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowStatusStatement extends MySqlStatementImpl { +public class MySqlShowStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTableStatusStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTableStatusStatement.java index e420148831..58f750fe9a 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTableStatusStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTableStatusStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowTableStatusStatement extends MySqlStatementImpl { +public class MySqlShowTableStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTablesStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTablesStatement.java index 43aa955026..ed917d31e0 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTablesStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTablesStatement.java @@ -19,7 +19,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowTablesStatement extends MySqlStatementImpl { +public class MySqlShowTablesStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTriggersStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTriggersStatement.java index 0217f27022..edfba267df 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTriggersStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowTriggersStatement.java @@ -19,7 +19,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowTriggersStatement extends MySqlStatementImpl { +public class MySqlShowTriggersStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowVariantsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowVariantsStatement.java index 6afdec2cd0..eb781472af 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowVariantsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowVariantsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowVariantsStatement extends MySqlStatementImpl { +public class MySqlShowVariantsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowWarningsStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowWarningsStatement.java index 34b82409d7..5cde0ee01a 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowWarningsStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowWarningsStatement.java @@ -18,7 +18,7 @@ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock.Limit; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; -public class MySqlShowWarningsStatement extends MySqlStatementImpl { +public class MySqlShowWarningsStatement extends MySqlStatementImpl implements MySqlShowStatement { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlCreateTableParser.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlCreateTableParser.java index 461baf6788..8a065445fb 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlCreateTableParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlCreateTableParser.java @@ -16,10 +16,12 @@ package com.alibaba.druid.sql.dialect.mysql.parser; import com.alibaba.druid.sql.ast.SQLName; +import com.alibaba.druid.sql.ast.statement.SQLCheck; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLSelect; import com.alibaba.druid.sql.ast.statement.SQLTableConstaint; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForeignKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlKey; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlPartitionByKey; @@ -43,6 +45,10 @@ public class MySqlCreateTableParser extends SQLCreateTableParser { return parseCrateTable(true); } + public MySqlExprParser getExprParser() { + return (MySqlExprParser) exprParser; + } + public MySqlCreateTableStatement parseCrateTable(boolean acceptCreate) { if (acceptCreate) { accept(Token.CREATE); @@ -73,7 +79,10 @@ public class MySqlCreateTableParser extends SQLCreateTableParser { if (lexer.token() == Token.IDENTIFIER) { SQLColumnDefinition column = this.exprParser.parseColumn(); stmt.getTableElementList().add(column); - } else if (lexer.token() == (Token.CONSTRAINT)) { + } else if (lexer.token() == Token.CONSTRAINT // + || lexer.token() == Token.PRIMARY // + || lexer.token() == Token.UNIQUE + ) { stmt.getTableElementList().add(parseConstraint()); } else if (lexer.token() == (Token.INDEX)) { lexer.nextToken(); @@ -108,6 +117,32 @@ public class MySqlCreateTableParser extends SQLCreateTableParser { stmt.getTableElementList().add(parseConstraint()); } else if (lexer.token() == (Token.PRIMARY)) { stmt.getTableElementList().add(parseConstraint()); + } else if (lexer.token() == (Token.FOREIGN)) { + lexer.nextToken(); + accept(Token.KEY); + + MySqlForeignKey fk = new MySqlForeignKey(); + + accept(Token.LPAREN); + this.exprParser.names(fk.getReferencingColumns()); + accept(Token.RPAREN); + + accept(Token.REFERENCES); + + fk.setReferencedTableName(this.exprParser.name()); + + accept(Token.LPAREN); + this.exprParser.names(fk.getReferencedColumns()); + accept(Token.RPAREN); + + stmt.getTableElementList().add(fk); + } else if (lexer.token() == Token.CHECK) { + lexer.nextToken(); + SQLCheck check = new SQLCheck(); + accept(Token.LPAREN); + check.setExpr(this.exprParser.expr()); + accept(Token.RPAREN); + stmt.getTableElementList().add(check); } if (!(lexer.token() == (Token.COMMA))) { @@ -165,6 +200,26 @@ public class MySqlCreateTableParser extends SQLCreateTableParser { } } + if (lexer.token() == Token.DEFAULT) { + lexer.nextToken(); + if (identifierEquals("CHARACTER")) { + lexer.nextToken(); + accept(Token.SET); + if (lexer.token() == Token.EQ) { + lexer.nextToken(); + } + stmt.getTableOptions().put("CHARACTER SET", lexer.stringVal()); + lexer.nextToken(); + } else if (identifierEquals("CHARSET")) { + lexer.nextToken(); + if (lexer.token() == Token.EQ) { + lexer.nextToken(); + } + stmt.getTableOptions().put("CHARSET", lexer.stringVal()); + lexer.nextToken(); + } + } + break; } @@ -215,7 +270,7 @@ public class MySqlCreateTableParser extends SQLCreateTableParser { } } accept(Token.RPAREN); - + if (name != null) { key.setName(name); } @@ -227,6 +282,10 @@ public class MySqlCreateTableParser extends SQLCreateTableParser { return (SQLTableConstaint) this.exprParser.parsePrimaryKey(); } + if (lexer.token() == (Token.UNIQUE)) { + return (SQLTableConstaint) this.getExprParser().parseUnique(); + } + throw new ParserException("TODO"); } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlExprParser.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlExprParser.java index 0b3d672990..f04194e9c9 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlExprParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlExprParser.java @@ -31,6 +31,7 @@ import com.alibaba.druid.sql.ast.statement.SQLAssignItem; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLPrimaryKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlPrimaryKey; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUnique; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBinaryExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlCharExpr; @@ -56,7 +57,7 @@ public class MySqlExprParser extends SQLExprParser { super(lexer); } - public MySqlExprParser(String sql) { + public MySqlExprParser(String sql){ this(new MySqlLexer(sql)); this.lexer.nextToken(); } @@ -70,7 +71,7 @@ public class MySqlExprParser extends SQLExprParser { return new SQLBinaryOpExpr(expr, SQLBinaryOperator.RegExp, rightExp); } - + if (identifierEquals("RLIKE")) { lexer.nextToken(); SQLExpr rightExp = equality(); @@ -105,7 +106,7 @@ public class MySqlExprParser extends SQLExprParser { return new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotRegExp, rightExp); } - + if (identifierEquals("RLIKE")) { lexer.nextToken(); SQLExpr rightExp = primary(); @@ -120,14 +121,14 @@ public class MySqlExprParser extends SQLExprParser { public SQLExpr primary() { final Token tok = lexer.token(); - + if (identifierEquals("outfile")) { lexer.nextToken(); SQLExpr file = primary(); SQLExpr expr = new MySqlOutFileExpr(file); - + return primaryRest(expr); - + } switch (tok) { @@ -154,7 +155,7 @@ public class MySqlExprParser extends SQLExprParser { } else if (varRefExpr.getName().equals("@@") && lexer.token() == Token.LITERAL_CHARS) { varRefExpr.setName("@@'" + lexer.stringVal() + "'"); lexer.nextToken(); - } + } return primaryRest(varRefExpr); case VALUES: lexer.nextToken(); @@ -164,8 +165,15 @@ public class MySqlExprParser extends SQLExprParser { return this.methodRest(new SQLIdentifierExpr("VALUES"), true); case BINARY: lexer.nextToken(); - SQLUnaryExpr binaryExpr = new SQLUnaryExpr(SQLUnaryOperator.BINARY, expr()); - return primaryRest(binaryExpr); + if (lexer.token() == Token.COMMA || lexer.token() == Token.SEMI || lexer.token() == Token.EOF) { + return new SQLIdentifierExpr("BINARY"); + } else { + SQLUnaryExpr binaryExpr = new SQLUnaryExpr(SQLUnaryOperator.BINARY, expr()); + return primaryRest(binaryExpr); + } + case GROUP: + lexer.nextToken(); + return primaryRest(new SQLIdentifierExpr(lexer.stringVal())); default: return super.primary(); } @@ -318,12 +326,12 @@ public class MySqlExprParser extends SQLExprParser { } else if (lexer.token() == Token.FROM) { lexer.nextToken(); SQLExpr from = expr(); - methodInvokeExpr.putAttribute("FROM", from); + methodInvokeExpr.getParameters().add(from); if (lexer.token() == Token.FOR) { lexer.nextToken(); SQLExpr forExpr = expr(); - methodInvokeExpr.putAttribute("FOR", forExpr); + methodInvokeExpr.getParameters().add(forExpr); } break; } else if (lexer.token() == Token.RPAREN) { @@ -399,6 +407,10 @@ public class MySqlExprParser extends SQLExprParser { } else { matchAgainstExpr.setSearchModifier(SearchModifier.IN_NATURAL_LANGUAGE_MODE); } + } else if (identifierEquals("BOOLEAN")) { + lexer.nextToken(); + acceptIdentifier("MODE"); + matchAgainstExpr.setSearchModifier(SearchModifier.IN_BOOLEAN_MODE); } else { throw new ParserException("TODO"); } @@ -436,16 +448,16 @@ public class MySqlExprParser extends SQLExprParser { return primaryRest(expr); } } - + if (lexer.token() == Token.VARIANT && "@".equals(lexer.stringVal())) { lexer.nextToken(); MySqlUserName userName = new MySqlUserName(); if (expr instanceof SQLCharExpr) { - userName.setUserName(((SQLCharExpr)expr).toString()); + userName.setUserName(((SQLCharExpr) expr).toString()); } else { - userName.setUserName(((SQLIdentifierExpr)expr).getName()); + userName.setUserName(((SQLIdentifierExpr) expr).getName()); } - + if (lexer.token() == Token.LITERAL_CHARS) { userName.setHost("'" + lexer.stringVal() + "'"); } else { @@ -493,7 +505,7 @@ public class MySqlExprParser extends SQLExprParser { return intervalExpr; } } - + public SQLColumnDefinition parseColumn() { MySqlSQLColumnDefinition column = new MySqlSQLColumnDefinition(); column.setName(name()); @@ -510,7 +522,7 @@ public class MySqlExprParser extends SQLExprParser { } return parseColumnRest(column); } - + if (identifierEquals("PARTITION")) { throw new ParserException("syntax error " + lexer.token() + " " + lexer.stringVal()); } @@ -518,7 +530,7 @@ public class MySqlExprParser extends SQLExprParser { return column; } - + public SQLExpr orRest(SQLExpr expr) { for (;;) { @@ -539,44 +551,57 @@ public class MySqlExprParser extends SQLExprParser { return expr; } - + public SQLAssignItem parseAssignItem() { SQLAssignItem item = new SQLAssignItem(); - + SQLExpr var = primary(); - + + String ident = null; if (var instanceof SQLIdentifierExpr) { - String ident = ((SQLIdentifierExpr) var).getName(); - + ident = ((SQLIdentifierExpr) var).getName(); + if ("GLOBAL".equalsIgnoreCase(ident)) { ident = lexer.stringVal(); lexer.nextToken(); var = new SQLVariantRefExpr(ident, true); } else if ("SESSION".equalsIgnoreCase(ident)) { - ident = lexer.stringVal(); - lexer.nextToken(); - var = new SQLVariantRefExpr(ident, false); + ident = lexer.stringVal(); + lexer.nextToken(); + var = new SQLVariantRefExpr(ident, false); } else { var = new SQLVariantRefExpr(ident); } } - item.setTarget(var); - if (lexer.token() == Token.COLONEQ) { - lexer.nextToken(); - } else { - accept(Token.EQ); - } - item.setValue(expr()); + if ("NAMES".equalsIgnoreCase(ident)) { + // skip + } else if ("CHARACTER".equalsIgnoreCase(ident)) { + var = new SQLIdentifierExpr("CHARACTER SET"); + accept(Token.SET); + if (lexer.token() == Token.EQ) { + lexer.nextToken(); + } + } else { + if (lexer.token() == Token.COLONEQ) { + lexer.nextToken(); + } else { + accept(Token.EQ); + } + } + + item.setValue(this.expr()); + + item.setTarget(var); return item; } - + public SQLName nameRest(SQLName name) { if (lexer.token() == Token.VARIANT && "@".equals(lexer.stringVal())) { lexer.nextToken(); MySqlUserName userName = new MySqlUserName(); - userName.setUserName(((SQLIdentifierExpr)name).getName()); - + userName.setUserName(((SQLIdentifierExpr) name).getName()); + if (lexer.token() == Token.LITERAL_CHARS) { userName.setHost("'" + lexer.stringVal() + "'"); } else { @@ -587,7 +612,7 @@ public class MySqlExprParser extends SQLExprParser { } return super.nameRest(name); } - + public Limit parseLimit() { if (lexer.token() == Token.LIMIT) { lexer.nextToken(); @@ -638,4 +663,29 @@ public class MySqlExprParser extends SQLExprParser { return primaryKey; } + + public MySqlUnique parseUnique() { + accept(Token.UNIQUE); + + MySqlUnique primaryKey = new MySqlUnique(); + + if (identifierEquals("USING")) { + lexer.nextToken(); + primaryKey.setIndexType(lexer.stringVal()); + lexer.nextToken(); + } + + accept(Token.LPAREN); + for (;;) { + primaryKey.getColumns().add(this.expr()); + if (!(lexer.token() == (Token.COMMA))) { + break; + } else { + lexer.nextToken(); + } + } + accept(Token.RPAREN); + + return primaryKey; + } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlLexer.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlLexer.java index 0b70649d41..a295bc1a84 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlLexer.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlLexer.java @@ -27,7 +27,6 @@ import com.alibaba.druid.sql.parser.Keywords; import com.alibaba.druid.sql.parser.Lexer; import com.alibaba.druid.sql.parser.NotAllowCommentException; import com.alibaba.druid.sql.parser.ParserException; -import com.alibaba.druid.sql.parser.SQLParseException; import com.alibaba.druid.sql.parser.Token; public class MySqlLexer extends Lexer { @@ -64,7 +63,7 @@ public class MySqlLexer extends Lexer { public void scanVariable() { if (ch != '@' && ch != ':' && ch != '#' && ch != '$') { - throw new SQLParseException("illegal variable"); + throw new ParserException("illegal variable"); } mark = pos; @@ -87,7 +86,7 @@ public class MySqlLexer extends Lexer { ch = charAt(++pos); break; } else if (ch == EOI) { - throw new SQLParseException("illegal identifier"); + throw new ParserException("illegal identifier"); } bufPos++; @@ -110,7 +109,7 @@ public class MySqlLexer extends Lexer { ch = charAt(++pos); break; } else if (ch == EOI) { - throw new SQLParseException("illegal identifier"); + throw new ParserException("illegal identifier"); } bufPos++; @@ -156,7 +155,7 @@ public class MySqlLexer extends Lexer { ch = charAt(++pos); break; } else if (ch == EOI) { - throw new SQLParseException("illegal identifier"); + throw new ParserException("illegal identifier"); } bufPos++; @@ -176,7 +175,7 @@ public class MySqlLexer extends Lexer { final boolean firstFlag = isFirstIdentifierChar(first); if (!firstFlag) { - throw new SQLParseException("illegal identifier"); + throw new ParserException("illegal identifier"); } mark = pos; @@ -204,12 +203,12 @@ public class MySqlLexer extends Lexer { } } } - + protected final void scanString() { { boolean hasSpecial = false; int startIndex = pos + 1; - int endIndex = -1; //text.indexOf('\'', startIndex); + int endIndex = -1; // text.indexOf('\'', startIndex); for (int i = startIndex; i < text.length(); ++i) { final char ch = text.charAt(i); if (ch == '\\') { @@ -220,13 +219,13 @@ public class MySqlLexer extends Lexer { break; } } - + if (endIndex == -1) { throw new ParserException("unclosed str"); } String stringVal = subString(startIndex, endIndex - startIndex); -// hasSpecial = stringVal.indexOf('\\') != -1; + // hasSpecial = stringVal.indexOf('\\') != -1; if (!hasSpecial) { this.stringVal = stringVal; @@ -329,6 +328,8 @@ public class MySqlLexer extends Lexer { } public void scanComment() { + Token lastToken = this.token; + if (ch != '/' && ch != '-') { throw new IllegalStateException(); } @@ -356,6 +357,10 @@ public class MySqlLexer extends Lexer { } for (;;) { + if (ch == EOI) { + this.token = Token.ERROR; + return; + } if (ch == '*' && charAt(pos + 1) == '/') { bufPos += 2; scanChar(); @@ -375,8 +380,14 @@ public class MySqlLexer extends Lexer { token = Token.MULTI_LINE_COMMENT; } - if (token != Token.HINT && !isAllowComment()) { - throw new NotAllowCommentException(); + if (token != Token.HINT) { + if (commentHandler != null && commentHandler.handle(lastToken, stringVal)) { + return; + } + + if (!isAllowComment()) { + throw new NotAllowCommentException(); + } } return; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlSelectParser.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlSelectParser.java index bb39281bd1..10d1f4c99e 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlSelectParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlSelectParser.java @@ -17,6 +17,7 @@ package com.alibaba.druid.sql.dialect.mysql.parser; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLSetQuantifier; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLLiteralExpr; import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause; import com.alibaba.druid.sql.ast.statement.SQLSelectQuery; @@ -44,7 +45,7 @@ public class MySqlSelectParser extends SQLSelectParser { super(exprParser); } - public MySqlSelectParser(String sql) { + public MySqlSelectParser(String sql){ this(new MySqlExprParser(sql)); } @@ -64,9 +65,14 @@ public class MySqlSelectParser extends SQLSelectParser { if (lexer.token() == Token.SELECT) { lexer.nextToken(); + if (lexer.token() == Token.HINT) { this.exprParser.parseHints(queryBlock.getHints()); } + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } if (lexer.token() == (Token.DISTINCT)) { queryBlock.setDistionOption(SQLSetQuantifier.DISTINCT); @@ -260,7 +266,7 @@ public class MySqlSelectParser extends SQLSelectParser { return tableSource; } - if (identifierEquals("USE")) { + if (lexer.token() == Token.USE) { lexer.nextToken(); MySqlUseIndexHint hint = new MySqlUseIndexHint(); parseIndexHint(hint); @@ -273,7 +279,7 @@ public class MySqlSelectParser extends SQLSelectParser { parseIndexHint(hint); tableSource.getHints().add(hint); } - + if (identifierEquals("FORCE")) { lexer.nextToken(); MySqlForceIndexHint hint = new MySqlForceIndexHint(); @@ -290,10 +296,10 @@ public class MySqlSelectParser extends SQLSelectParser { } else { accept(Token.KEY); } - + if (lexer.token() == Token.FOR) { lexer.nextToken(); - + if (lexer.token() == Token.JOIN) { lexer.nextToken(); hint.setOption(MySqlIndexHint.Option.JOIN); @@ -307,9 +313,14 @@ public class MySqlSelectParser extends SQLSelectParser { hint.setOption(MySqlIndexHint.Option.GROUP_BY); } } - + accept(Token.LPAREN); - this.exprParser.names(hint.getIndexList()); + if (lexer.token() == Token.PRIMARY) { + lexer.nextToken(); + hint.getIndexList().add(new SQLIdentifierExpr("PRIMARY")); + } else { + this.exprParser.names(hint.getIndexList()); + } accept(Token.RPAREN); } @@ -326,6 +337,6 @@ public class MySqlSelectParser extends SQLSelectParser { } public Limit parseLimit() { - return ((MySqlExprParser)this.exprParser) .parseLimit(); + return ((MySqlExprParser) this.exprParser).parseLimit(); } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlStatementParser.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlStatementParser.java index 1a0b0991b4..29fddfbff3 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlStatementParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlStatementParser.java @@ -30,8 +30,13 @@ import com.alibaba.druid.sql.ast.expr.SQLLiteralExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAlterColumn; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDisableKeys; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropColumnItem; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropForeinKey; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropIndex; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableEnableKeys; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLCreateDatabaseStatement; import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; @@ -53,6 +58,9 @@ import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddIndex import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddUnique; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableChangeColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableCharacter; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableDiscardTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableImportTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableModifyColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableOption; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlBinlogStatement; @@ -130,42 +138,42 @@ import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUnlockTablesStatem import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateStatement; import com.alibaba.druid.sql.parser.Lexer; import com.alibaba.druid.sql.parser.ParserException; -import com.alibaba.druid.sql.parser.SQLParseException; import com.alibaba.druid.sql.parser.SQLSelectParser; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.parser.Token; public class MySqlStatementParser extends SQLStatementParser { - private static final String COLLATE2 = "COLLATE"; - private static final String CASCADE = "CASCADE"; - private static final String RESTRICT = "RESTRICT"; - private static final String CHAIN = "CHAIN"; - private static final String ENGINES = "ENGINES"; - private static final String ENGINE = "ENGINE"; - private static final String BINLOG = "BINLOG"; - private static final String EVENTS = "EVENTS"; - private static final String CHARACTER = "CHARACTER"; - private static final String SESSION = "SESSION"; - private static final String GLOBAL = "GLOBAL"; - private static final String VARIABLES = "VARIABLES"; - private static final String ERRORS = "ERRORS"; - private static final String STATUS = "STATUS"; - private static final String IGNORE = "IGNORE"; - private static final String RESET = "RESET"; - private static final String DESCRIBE = "DESCRIBE"; - private static final String DESC = "DESC"; - private static final String WRITE = "WRITE"; - private static final String READ = "READ"; - private static final String LOCAL = "LOCAL"; - private static final String TABLES = "TABLES"; - private static final String TEMPORARY = "TEMPORARY"; - private static final String USER = "USER"; - private static final String SPATIAL = "SPATIAL"; - private static final String FULLTEXT = "FULLTEXT"; - private static final String REPLACE = "REPLACE"; - private static final String DELAYED = "DELAYED"; - private static final String LOW_PRIORITY = "LOW_PRIORITY"; + private static final String AUTO_INCREMENT = "AUTO_INCREMENT"; + private static final String COLLATE2 = "COLLATE"; + private static final String CASCADE = "CASCADE"; + private static final String RESTRICT = "RESTRICT"; + private static final String CHAIN = "CHAIN"; + private static final String ENGINES = "ENGINES"; + private static final String ENGINE = "ENGINE"; + private static final String BINLOG = "BINLOG"; + private static final String EVENTS = "EVENTS"; + private static final String CHARACTER = "CHARACTER"; + private static final String SESSION = "SESSION"; + private static final String GLOBAL = "GLOBAL"; + private static final String VARIABLES = "VARIABLES"; + private static final String ERRORS = "ERRORS"; + private static final String STATUS = "STATUS"; + private static final String IGNORE = "IGNORE"; + private static final String RESET = "RESET"; + private static final String DESCRIBE = "DESCRIBE"; + private static final String DESC = "DESC"; + private static final String WRITE = "WRITE"; + private static final String READ = "READ"; + private static final String LOCAL = "LOCAL"; + private static final String TABLES = "TABLES"; + private static final String TEMPORARY = "TEMPORARY"; + private static final String USER = "USER"; + private static final String SPATIAL = "SPATIAL"; + private static final String FULLTEXT = "FULLTEXT"; + private static final String REPLACE = "REPLACE"; + private static final String DELAYED = "DELAYED"; + private static final String LOW_PRIORITY = "LOW_PRIORITY"; public MySqlStatementParser(String sql){ super(new MySqlExprParser(sql)); @@ -181,7 +189,8 @@ public class MySqlStatementParser extends SQLStatementParser { } public SQLSelectStatement parseSelect() { - return new SQLSelectStatement(new MySqlSelectParser(this.exprParser).select()); + MySqlSelectParser selectParser = new MySqlSelectParser(this.exprParser); + return new SQLSelectStatement(selectParser.select()); } public SQLUpdateStatement parseUpdateStatement() { @@ -228,6 +237,10 @@ public class MySqlStatementParser extends SQLStatementParser { if (lexer.token() == Token.DELETE) { lexer.nextToken(); + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } + if (identifierEquals(LOW_PRIORITY)) { deleteStatement.setLowPriority(true); lexer.nextToken(); @@ -283,11 +296,24 @@ public class MySqlStatementParser extends SQLStatementParser { } public SQLStatement parseCreate() { + char markChar = lexer.current(); + int markBp = lexer.bp(); + accept(Token.CREATE); + boolean replace = false; + if (lexer.token() == Token.OR) { + lexer.nextToken(); + acceptIdentifier("REPLACE"); + replace = true; + } + List hints = this.exprParser.parseHints(); if (lexer.token() == Token.TABLE || identifierEquals(TEMPORARY)) { + if (replace) { + lexer.reset(markBp, markChar, Token.CREATE); + } MySqlCreateTableParser parser = new MySqlCreateTableParser(this.exprParser); MySqlCreateTableStatement stmt = parser.parseCrateTable(false); stmt.setHints(hints); @@ -295,18 +321,35 @@ public class MySqlStatementParser extends SQLStatementParser { } if (lexer.token() == Token.DATABASE) { + if (replace) { + lexer.reset(markBp, markChar, Token.CREATE); + } return parseCreateDatabase(); } if (lexer.token() == Token.UNIQUE || lexer.token() == Token.INDEX || identifierEquals(FULLTEXT) || identifierEquals(SPATIAL)) { + if (replace) { + lexer.reset(markBp, markChar, Token.CREATE); + } return parseCreateIndex(); } if (identifierEquals(USER)) { + if (replace) { + lexer.reset(markBp, markChar, Token.CREATE); + } return parseCreateUser(); } + if (lexer.token() == Token.VIEW) { + if (replace) { + lexer.reset(markBp, markChar, Token.CREATE); + } + + return parseCreateView(); + } + throw new ParserException("TODO " + lexer.token()); } @@ -596,20 +639,23 @@ public class MySqlStatementParser extends SQLStatementParser { public SQLStatement parseShow() { acceptIdentifier("SHOW"); + boolean full = false; if (lexer.token() == Token.FULL) { lexer.nextToken(); + } - if (identifierEquals("PROCESSLIST")) { - lexer.nextToken(); - MySqlShowProcessListStatement stmt = new MySqlShowProcessListStatement(); - stmt.setFull(true); - return stmt; - } + if (identifierEquals("PROCESSLIST")) { + lexer.nextToken(); + MySqlShowProcessListStatement stmt = new MySqlShowProcessListStatement(); + stmt.setFull(full); + return stmt; + } - acceptIdentifier("COLUMNS"); + if (identifierEquals("COLUMNS")) { + lexer.nextToken(); MySqlShowColumnsStatement stmt = parseShowColumns(); - stmt.setFull(true); + stmt.setFull(full); return stmt; } @@ -626,6 +672,7 @@ public class MySqlStatementParser extends SQLStatementParser { lexer.nextToken(); MySqlShowTablesStatement stmt = parseShowTabless(); + stmt.setFull(full); return stmt; } @@ -1489,7 +1536,7 @@ public class MySqlStatementParser extends SQLStatementParser { if (lexer.token() == Token.VALUES || identifierEquals("VALUE")) { lexer.nextToken(); - + parseValueClause(stmt.getValuesList(), 0); } else if (lexer.token() == Token.SELECT) { SQLQueryExpr queryExpr = (SQLQueryExpr) this.exprParser.expr(); @@ -1821,7 +1868,7 @@ public class MySqlStatementParser extends SQLStatementParser { private void parseValueClause(List valueClauseList, int columnSize) { for (;;) { if (lexer.token() != Token.LPAREN) { - throw new SQLParseException("syntax error, expect ')'"); + throw new ParserException("syntax error, expect ')'"); } lexer.nextTokenValue(); @@ -1866,7 +1913,7 @@ public class MySqlStatementParser extends SQLStatementParser { } } } - + SQLInsertStatement.ValuesClause values = new SQLInsertStatement.ValuesClause(valueExprList); valueClauseList.add(values); } else { @@ -1875,7 +1922,7 @@ public class MySqlStatementParser extends SQLStatementParser { } if (lexer.token() != Token.RPAREN) { - throw new SQLParseException("syntax error"); + throw new ParserException("syntax error"); } lexer.nextTokenComma(); @@ -2197,7 +2244,20 @@ public class MySqlStatementParser extends SQLStatementParser { } else if (lexer.token() == Token.KEY) { throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); } else if (lexer.token() == Token.CONSTRAINT) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + lexer.nextToken(); + SQLName constraintName = this.exprParser.name(); + + if (lexer.token() == Token.PRIMARY) { + SQLPrimaryKey primaryKey = ((MySqlExprParser) this.exprParser).parsePrimaryKey(); + + primaryKey.setName(constraintName); + + SQLAlterTableAddPrimaryKey item = new SQLAlterTableAddPrimaryKey(); + item.setPrimaryKey(primaryKey); + stmt.getItems().add(item); + } else { + throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + } } else if (identifierEquals(FULLTEXT)) { throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); } else if (identifierEquals(SPATIAL)) { @@ -2212,8 +2272,17 @@ public class MySqlStatementParser extends SQLStatementParser { } stmt.getItems().add(item); } - } else if (identifierEquals("ALTER")) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + } else if (lexer.token() == Token.ALTER) { + lexer.nextToken(); + if (identifierEquals("COLUMN")) { + lexer.nextToken(); + } + + SQLAlterTableAlterColumn alterColumn = new SQLAlterTableAlterColumn(); + SQLColumnDefinition columnDef = this.exprParser.parseColumn(); + alterColumn.setColumn(columnDef); + + stmt.getItems().add(alterColumn); } else if (identifierEquals("CHANGE")) { lexer.nextToken(); if (identifierEquals("COLUMN")) { @@ -2235,7 +2304,24 @@ public class MySqlStatementParser extends SQLStatementParser { } stmt.getItems().add(item); } else if (identifierEquals("MODIFY")) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + lexer.nextToken(); + if (identifierEquals("COLUMN")) { + lexer.nextToken(); + } + MySqlAlterTableModifyColumn item = new MySqlAlterTableModifyColumn(); + item.setNewColumnDefinition(this.exprParser.parseColumn()); + if (identifierEquals("AFTER")) { + lexer.nextToken(); + item.setAfterColumn(this.exprParser.name()); + } else if (identifierEquals("FIRST")) { + lexer.nextToken(); + if (lexer.token() == Token.IDENTIFIER) { + item.setFirstColumn(this.exprParser.name()); + } else { + item.setFirst(true); + } + } + stmt.getItems().add(item); } else if (lexer.token() == Token.DROP) { lexer.nextToken(); if (lexer.token() == Token.INDEX) { @@ -2244,6 +2330,18 @@ public class MySqlStatementParser extends SQLStatementParser { SQLAlterTableDropIndex item = new SQLAlterTableDropIndex(); item.setIndexName(indexName); stmt.getItems().add(item); + } else if (lexer.token() == Token.FOREIGN) { + lexer.nextToken(); + accept(Token.KEY); + SQLName indexName = this.exprParser.name(); + SQLAlterTableDropForeinKey item = new SQLAlterTableDropForeinKey(); + item.setIndexName(indexName); + stmt.getItems().add(item); + } else if (lexer.token() == Token.PRIMARY) { + lexer.nextToken(); + accept(Token.KEY); + SQLAlterTableDropPrimaryKey item = new SQLAlterTableDropPrimaryKey(); + stmt.getItems().add(item); } else { if (identifierEquals("COLUMN")) { lexer.nextToken(); @@ -2253,9 +2351,15 @@ public class MySqlStatementParser extends SQLStatementParser { stmt.getItems().add(item); } } else if (identifierEquals("DISABLE")) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + lexer.nextToken(); + acceptIdentifier("KEYS"); + SQLAlterTableDisableKeys item = new SQLAlterTableDisableKeys(); + stmt.getItems().add(item); } else if (identifierEquals("ENABLE")) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + lexer.nextToken(); + acceptIdentifier("KEYS"); + SQLAlterTableEnableKeys item = new SQLAlterTableEnableKeys(); + stmt.getItems().add(item); } else if (identifierEquals("RENAME")) { lexer.nextToken(); MySqlRenameTableStatement renameStmt = new MySqlRenameTableStatement(); @@ -2272,9 +2376,15 @@ public class MySqlStatementParser extends SQLStatementParser { } else if (lexer.token() == Token.DEFAULT) { throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); } else if (identifierEquals("DISCARD")) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + lexer.nextToken(); + acceptIdentifier("TABLESPACE"); + MySqlAlterTableDiscardTablespace item = new MySqlAlterTableDiscardTablespace(); + stmt.getItems().add(item); } else if (identifierEquals("IMPORT")) { - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); + lexer.nextToken(); + acceptIdentifier("TABLESPACE"); + MySqlAlterTableImportTablespace item = new MySqlAlterTableImportTablespace(); + stmt.getItems().add(item); } else if (identifierEquals("FORCE")) { throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal()); } else if (identifierEquals("TRUNCATE")) { @@ -2303,6 +2413,11 @@ public class MySqlStatementParser extends SQLStatementParser { accept(Token.EQ); stmt.getItems().add(new MySqlAlterTableOption(ENGINE, lexer.stringVal())); lexer.nextToken(); + } else if (identifierEquals(AUTO_INCREMENT)) { + lexer.nextToken(); + accept(Token.EQ); + stmt.getItems().add(new MySqlAlterTableOption(AUTO_INCREMENT, lexer.integerValue())); + lexer.nextToken(); } else if (identifierEquals(COLLATE2)) { lexer.nextToken(); accept(Token.EQ); diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitor.java index 3036e3e181..edb597fb17 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitor.java @@ -16,9 +16,11 @@ package com.alibaba.druid.sql.dialect.mysql.visitor; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForceIndexHint; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForeignKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlIgnoreIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlPrimaryKey; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUnique; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUseIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBinaryExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; @@ -34,6 +36,9 @@ import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddIndex import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddUnique; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableChangeColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableCharacter; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableDiscardTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableImportTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableModifyColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableOption; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlBinlogStatement; @@ -136,6 +141,10 @@ public interface MySqlASTVisitor extends SQLASTVisitor { void endVisit(MySqlPrimaryKey x); + boolean visit(MySqlUnique x); + + void endVisit(MySqlUnique x); + void endVisit(MySqlIntervalExpr x); boolean visit(MySqlIntervalExpr x); @@ -451,68 +460,84 @@ public interface MySqlASTVisitor extends SQLASTVisitor { boolean visit(MySqlRenameTableStatement.Item x); void endVisit(MySqlRenameTableStatement.Item x); - + boolean visit(MySqlRenameTableStatement x); - + void endVisit(MySqlRenameTableStatement x); - + boolean visit(MySqlDropViewStatement x); - + void endVisit(MySqlDropViewStatement x); - + boolean visit(MySqlUnionQuery x); - + void endVisit(MySqlUnionQuery x); - + boolean visit(MySqlUseIndexHint x); - + void endVisit(MySqlUseIndexHint x); - + boolean visit(MySqlIgnoreIndexHint x); - + void endVisit(MySqlIgnoreIndexHint x); - + boolean visit(MySqlLockTableStatement x); - + void endVisit(MySqlLockTableStatement x); - + boolean visit(MySqlUnlockTablesStatement x); - + void endVisit(MySqlUnlockTablesStatement x); - + boolean visit(MySqlForceIndexHint x); - + void endVisit(MySqlForceIndexHint x); - + boolean visit(MySqlAlterTableChangeColumn x); - + void endVisit(MySqlAlterTableChangeColumn x); - + boolean visit(MySqlAlterTableCharacter x); - + void endVisit(MySqlAlterTableCharacter x); - + boolean visit(MySqlAlterTableAddIndex x); - + void endVisit(MySqlAlterTableAddIndex x); - + boolean visit(MySqlAlterTableOption x); - + void endVisit(MySqlAlterTableOption x); - + boolean visit(MySqlCreateTableStatement x); - + void endVisit(MySqlCreateTableStatement x); - + boolean visit(MySqlHelpStatement x); - + void endVisit(MySqlHelpStatement x); - + boolean visit(MySqlCharExpr x); - + void endVisit(MySqlCharExpr x); - + boolean visit(MySqlAlterTableAddUnique x); - + void endVisit(MySqlAlterTableAddUnique x); -} + + boolean visit(MySqlForeignKey x); + + void endVisit(MySqlForeignKey x); + + boolean visit(MySqlAlterTableModifyColumn x); + + void endVisit(MySqlAlterTableModifyColumn x); + + boolean visit(MySqlAlterTableDiscardTablespace x); + + void endVisit(MySqlAlterTableDiscardTablespace x); + + boolean visit(MySqlAlterTableImportTablespace x); + + void endVisit(MySqlAlterTableImportTablespace x); +} // diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitorAdapter.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitorAdapter.java index 62f2af8633..1c98aade48 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitorAdapter.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlASTVisitorAdapter.java @@ -16,9 +16,11 @@ package com.alibaba.druid.sql.dialect.mysql.visitor; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForceIndexHint; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForeignKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlIgnoreIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlPrimaryKey; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUnique; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUseIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBinaryExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; @@ -34,6 +36,9 @@ import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddIndex import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddUnique; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableChangeColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableCharacter; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableDiscardTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableImportTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableModifyColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableOption; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlBinlogStatement; @@ -1138,4 +1143,54 @@ public class MySqlASTVisitorAdapter extends SQLASTVisitorAdapter implements public void endVisit(MySqlAlterTableAddUnique x) { } -} + + @Override + public boolean visit(MySqlUnique x) { + return true; + } + + @Override + public void endVisit(MySqlUnique x) { + + } + + @Override + public boolean visit(MySqlForeignKey x) { + return true; + } + + @Override + public void endVisit(MySqlForeignKey x) { + + } + + @Override + public boolean visit(MySqlAlterTableModifyColumn x) { + return true; + } + + @Override + public void endVisit(MySqlAlterTableModifyColumn x) { + + } + + @Override + public boolean visit(MySqlAlterTableDiscardTablespace x) { + return true; + } + + @Override + public void endVisit(MySqlAlterTableDiscardTablespace x) { + + } + + @Override + public boolean visit(MySqlAlterTableImportTablespace x) { + return true; + } + + @Override + public void endVisit(MySqlAlterTableImportTablespace x) { + + } +} // diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlEvalVisitorImpl.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlEvalVisitorImpl.java index 78f3dacbfc..d479e2a50d 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlEvalVisitorImpl.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlEvalVisitorImpl.java @@ -16,30 +16,36 @@ package com.alibaba.druid.sql.dialect.mysql.visitor; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import com.alibaba.druid.sql.ast.expr.SQLBetweenExpr; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLCharExpr; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; +import com.alibaba.druid.sql.ast.expr.SQLUnaryExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; import com.alibaba.druid.sql.visitor.SQLEvalVisitor; import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.sql.visitor.functions.Function; public class MySqlEvalVisitorImpl extends MySqlASTVisitorAdapter implements SQLEvalVisitor { - private List parameters = new ArrayList(); + private Map functions = new HashMap(); + private List parameters = new ArrayList(); - private int variantIndex = -1; + private int variantIndex = -1; - private boolean markVariantIndex = true; + private boolean markVariantIndex = true; public MySqlEvalVisitorImpl(){ this(new ArrayList(1)); @@ -77,6 +83,10 @@ public class MySqlEvalVisitorImpl extends MySqlASTVisitorAdapter implements SQLE return SQLEvalVisitorUtils.visit(this, x); } + public boolean visit(SQLUnaryExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + public boolean visit(SQLIntegerExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @@ -129,4 +139,17 @@ public class MySqlEvalVisitorImpl extends MySqlASTVisitorAdapter implements SQLE this.markVariantIndex = markVariantIndex; } + @Override + public Function getFunction(String funcName) { + return functions.get(funcName); + } + + @Override + public void registerFunction(String funcName, Function function) { + functions.put(funcName, function); + } + + public boolean visit(SQLIdentifierExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java index 5afba62eb8..fd70b69674 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java @@ -15,6 +15,7 @@ */ package com.alibaba.druid.sql.dialect.mysql.visitor; +import java.util.List; import java.util.Map; import com.alibaba.druid.sql.ast.SQLCommentHint; @@ -26,6 +27,7 @@ import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.SQLAlterTableItem; +import com.alibaba.druid.sql.ast.statement.SQLAssignItem; import com.alibaba.druid.sql.ast.statement.SQLCharactorDataType; import com.alibaba.druid.sql.ast.statement.SQLColumnConstraint; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; @@ -33,9 +35,11 @@ import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForceIndexHint; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForeignKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlIgnoreIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlPrimaryKey; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUnique; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUseIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBinaryExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; @@ -51,6 +55,9 @@ import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddIndex import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddUnique; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableChangeColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableCharacter; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableDiscardTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableImportTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableModifyColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableOption; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlBinlogStatement; @@ -342,7 +349,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV printAndAccept(x.getArguments(), ", "); print(")"); } - + if (x.getCharSetName() != null) { print(" CHARACTER SET "); print(x.getCharSetName()); @@ -483,7 +490,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV public boolean visit(MySqlPrimaryKey x) { if (x.getName() != null) { print("CONSTRAINT "); - x.accept(this); + x.getName().accept(this); print(' '); } @@ -521,6 +528,17 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV } public boolean visit(SQLVariantRefExpr x) { + { + List parameters = this.getParameters(); + int index = x.getIndex(); + + if (parameters != null && index >= 0 && index < parameters.size()) { + Object param = parameters.get(index); + printParameter(param); + return false; + } + } + if (x.isGlobal()) { print("@@global."); } else { @@ -2576,6 +2594,28 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV @Override public void endVisit(MySqlAlterTableChangeColumn x) { + } + + @Override + public boolean visit(MySqlAlterTableModifyColumn x) { + print("MODIFY COLUMN "); + x.getNewColumnDefinition().accept(this); + if (x.getFirstColumn() != null) { + print(" FIRST "); + x.getFirstColumn().accept(this); + } else if (x.getAfterColumn() != null) { + print(" AFTER "); + x.getAfterColumn().accept(this); + } else if (x.isFirst()) { + print(" FIRST"); + } + + return false; + } + + @Override + public void endVisit(MySqlAlterTableModifyColumn x) { + } @Override @@ -2660,7 +2700,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV public boolean visit(MySqlAlterTableOption x) { print(x.getName()); print(" = "); - print(x.getValue()); + print(x.getValue().toString()); return false; } @@ -2696,4 +2736,91 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV public void endVisit(MySqlCharExpr x) { } -} + + @Override + public boolean visit(MySqlUnique x) { + if (x.getName() != null) { + print("CONSTRAINT "); + x.getName().accept(this); + print(' '); + } + + print("UNIQUE"); + + if (x.getIndexType() != null) { + print(" USING "); + print(x.getIndexType()); + } + + print(" ("); + printAndAccept(x.getColumns(), ", "); + print(")"); + + return false; + } + + @Override + public void endVisit(MySqlUnique x) { + + } + + @Override + public boolean visit(MySqlForeignKey x) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void endVisit(MySqlForeignKey x) { + if (x.getName() != null) { + print("CONSTRAINT "); + x.getName().accept(this); + print(' '); + } + + print("FOREIGN KEY "); + + print(" ("); + printAndAccept(x.getReferencedColumns(), ", "); + print(")"); + + print(" REFERENCES "); + x.getReferencedTableName().accept(this); + + print(" ("); + printAndAccept(x.getReferencedColumns(), ", "); + print(")"); + } + + @Override + public boolean visit(MySqlAlterTableDiscardTablespace x) { + print("DISCARD TABLESPACE"); + return false; + } + + @Override + public void endVisit(MySqlAlterTableDiscardTablespace x) { + + } + + @Override + public boolean visit(MySqlAlterTableImportTablespace x) { + print("IMPORT TABLESPACE"); + return false; + } + + @Override + public void endVisit(MySqlAlterTableImportTablespace x) { + + } + + @Override + public boolean visit(SQLAssignItem x) { + x.getTarget().accept(this); + if (!"NAMES".equalsIgnoreCase(x.getTarget().toString())) { + print(" = "); + } + x.getValue().accept(this); + return false; + } +} // diff --git a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlSchemaStatVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlSchemaStatVisitor.java index 305d8cded4..1d7a71db66 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlSchemaStatVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/mysql/visitor/MySqlSchemaStatVisitor.java @@ -19,6 +19,9 @@ import java.util.Map; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddColumn; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableItem; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; @@ -27,9 +30,11 @@ import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.ast.statement.SQLUnionQuery; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForceIndexHint; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForeignKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlIgnoreIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlKey; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlPrimaryKey; +import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUnique; import com.alibaba.druid.sql.dialect.mysql.ast.MySqlUseIndexHint; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBinaryExpr; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; @@ -45,6 +50,9 @@ import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddIndex import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableAddUnique; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableChangeColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableCharacter; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableDiscardTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableImportTablespace; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableModifyColumn; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableOption; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlBinlogStatement; @@ -138,7 +146,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS return true; } - + @Override public String getDbType() { return JdbcUtils.MYSQL; @@ -245,8 +253,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public boolean visit(MySqlKey x) { - - return true; + return false; } @Override @@ -425,7 +432,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public boolean visit(MySqlShowTablesStatement x) { - return true; + return false; } @Override @@ -435,7 +442,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public boolean visit(MySqlShowDatabasesStatement x) { - return true; + return false; } @Override @@ -659,15 +666,15 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS public void endVisit(MySqlShowCollationStatement x) { } - + @Override public boolean visit(MySqlShowBinLogEventsStatement x) { return false; } - + @Override public void endVisit(MySqlShowBinLogEventsStatement x) { - + } @Override @@ -677,27 +684,27 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCharacterSetStatement x) { - + } - + @Override public boolean visit(MySqlShowContributorsStatement x) { return false; } - + @Override public void endVisit(MySqlShowContributorsStatement x) { - + } - + @Override public boolean visit(MySqlShowCreateDatabaseStatement x) { return false; } - + @Override public void endVisit(MySqlShowCreateDatabaseStatement x) { - + } @Override @@ -707,7 +714,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCreateEventStatement x) { - + } @Override @@ -717,7 +724,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCreateFunctionStatement x) { - + } @Override @@ -727,7 +734,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCreateProcedureStatement x) { - + } @Override @@ -737,7 +744,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCreateTableStatement x) { - + } @Override @@ -747,7 +754,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCreateTriggerStatement x) { - + } @Override @@ -757,7 +764,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowCreateViewStatement x) { - + } @Override @@ -767,17 +774,17 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowEngineStatement x) { - + } - + @Override public boolean visit(MySqlShowEnginesStatement x) { return false; } - + @Override public void endVisit(MySqlShowEnginesStatement x) { - + } @Override @@ -787,7 +794,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowErrorsStatement x) { - + } @Override @@ -797,7 +804,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowEventsStatement x) { - + } @Override @@ -807,7 +814,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowFunctionCodeStatement x) { - + } @Override @@ -817,7 +824,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowFunctionStatusStatement x) { - + } @Override @@ -827,7 +834,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowGrantsStatement x) { - + } @Override @@ -837,7 +844,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlUserName x) { - + } @Override @@ -847,7 +854,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowIndexesStatement x) { - + } @Override @@ -857,7 +864,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowKeysStatement x) { - + } @Override @@ -867,7 +874,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowMasterStatusStatement x) { - + } @Override @@ -877,7 +884,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowOpenTablesStatement x) { - + } @Override @@ -887,7 +894,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowPluginsStatement x) { - + } @Override @@ -897,7 +904,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowPrivilegesStatement x) { - + } @Override @@ -907,7 +914,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowProcedureCodeStatement x) { - + } @Override @@ -917,7 +924,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowProcedureStatusStatement x) { - + } @Override @@ -927,7 +934,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowProcessListStatement x) { - + } @Override @@ -937,7 +944,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowProfileStatement x) { - + } @Override @@ -947,7 +954,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowProfilesStatement x) { - + } @Override @@ -957,7 +964,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowRelayLogEventsStatement x) { - + } @Override @@ -967,7 +974,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowSlaveHostsStatement x) { - + } @Override @@ -977,7 +984,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowSlaveStatusStatement x) { - + } @Override @@ -987,7 +994,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowTableStatusStatement x) { - + } @Override @@ -997,7 +1004,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowTriggersStatement x) { - + } @Override @@ -1007,37 +1014,48 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlShowVariantsStatement x) { - + } @Override public boolean visit(MySqlAlterTableStatement x) { + String tableName = x.getName().toString(); + TableStat stat = getTableStat(tableName); + stat.incrementAlterCount(); + + setCurrentTable(x, tableName); + + for (SQLAlterTableItem item : x.getItems()) { + item.setParent(x); + item.accept(this); + } + return false; } @Override public void endVisit(MySqlAlterTableStatement x) { - + } @Override public boolean visit(MySqlAlterTableAddColumn x) { - return false; + return visit((SQLAlterTableAddColumn) x); } @Override public void endVisit(MySqlAlterTableAddColumn x) { - + } - + @Override public boolean visit(MySqlCreateIndexStatement x) { return false; } - + @Override public void endVisit(MySqlCreateIndexStatement x) { - + } @Override @@ -1047,7 +1065,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlRenameTableStatement.Item x) { - + } @Override @@ -1057,17 +1075,18 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlRenameTableStatement x) { - + } @Override public boolean visit(MySqlDropViewStatement x) { + setMode(x, Mode.Drop); return true; } @Override public void endVisit(MySqlDropViewStatement x) { - + } @Override @@ -1077,7 +1096,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlUnionQuery x) { - + } @Override @@ -1087,7 +1106,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlUseIndexHint x) { - + } @Override @@ -1097,7 +1116,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlIgnoreIndexHint x) { - + } @Override @@ -1107,7 +1126,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlLockTableStatement x) { - + } @Override @@ -1117,7 +1136,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlUnlockTablesStatement x) { - + } @Override @@ -1127,17 +1146,37 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlForceIndexHint x) { - + } @Override public boolean visit(MySqlAlterTableChangeColumn x) { + SQLAlterTableStatement stmt = (SQLAlterTableStatement) x.getParent(); + String table = stmt.getName().toString(); + + String columnName = x.getColumnName().toString(); + addColumn(table, columnName); return false; } @Override public void endVisit(MySqlAlterTableChangeColumn x) { - + + } + + @Override + public boolean visit(MySqlAlterTableModifyColumn x) { + SQLAlterTableStatement stmt = (SQLAlterTableStatement) x.getParent(); + String table = stmt.getName().toString(); + + String columnName = x.getNewColumnDefinition().getName().toString(); + addColumn(table, columnName); + return false; + } + + @Override + public void endVisit(MySqlAlterTableModifyColumn x) { + } @Override @@ -1147,7 +1186,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlAlterTableCharacter x) { - + } @Override @@ -1157,7 +1196,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlAlterTableAddIndex x) { - + } @Override @@ -1167,7 +1206,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlAlterTableOption x) { - + } @Override @@ -1177,7 +1216,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlCreateTableStatement x) { - + } @Override @@ -1187,7 +1226,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlHelpStatement x) { - + } @Override @@ -1197,7 +1236,7 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlCharExpr x) { - + } @Override @@ -1207,6 +1246,47 @@ public class MySqlSchemaStatVisitor extends SchemaStatVisitor implements MySqlAS @Override public void endVisit(MySqlAlterTableAddUnique x) { - + } + + @Override + public boolean visit(MySqlUnique x) { + return false; + } + + @Override + public void endVisit(MySqlUnique x) { + + } + + @Override + public boolean visit(MySqlForeignKey x) { + return false; + } + + @Override + public void endVisit(MySqlForeignKey x) { + + } + + @Override + public boolean visit(MySqlAlterTableDiscardTablespace x) { + return false; + } + + @Override + public void endVisit(MySqlAlterTableDiscardTablespace x) { + + } + + @Override + public boolean visit(MySqlAlterTableImportTablespace x) { + return false; + } + + @Override + public void endVisit(MySqlAlterTableImportTablespace x) { + + } + } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectJoin.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectJoin.java index b9bb88557b..3397593543 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectJoin.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectJoin.java @@ -15,9 +15,6 @@ */ package com.alibaba.druid.sql.dialect.oracle.ast.stmt; -import java.util.ArrayList; -import java.util.List; - import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; import com.alibaba.druid.sql.dialect.oracle.ast.clause.FlashbackQueryClause; @@ -28,7 +25,6 @@ public class OracleSelectJoin extends SQLJoinTableSource implements OracleSelect private static final long serialVersionUID = 1L; - private final List using = new ArrayList(); protected OracleSelectPivotBase pivot; protected FlashbackQueryClause flashback; @@ -73,10 +69,6 @@ public class OracleSelectJoin extends SQLJoinTableSource implements OracleSelect visitor.endVisit(this); } - public List getUsing() { - return this.using; - } - public void output(StringBuffer buf) { this.left.output(buf); buf.append(JoinType.toString(this.joinType)); diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleExprParser.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleExprParser.java index 08d42327dd..d2e36b9644 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleExprParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleExprParser.java @@ -80,20 +80,59 @@ public class OracleExprParser extends SQLExprParser { + + + + + + + + public boolean allowStringAdditive = false; /** * @formatter:off */ - private static final String[] _aggregateFunctions = { // - "AVG", "CORR", "COVAR_POP", "COVAR_SAMP", "COUNT", // - "CUME_DIST", "DENSE_RANK", "FIRST", "FIRST_VALUE", // - "LAG", "LAST", "LAST_VALUE", "LEAD", "MAX", "MIN", // - "NTILE", "PERCENT_RANK", "PERCENTILE_CONT", "PERCENTILE_DISC", "RANK", // - "RATIO_TO_REPORT", "REGR_SLOPE", "REGR_INTERCEPT", "REGR_COUNT", "REGR_R2", // - "REGR_AVGX", "REGR_AVGY", "REGR_SXX", "REGR_SYY", "REGR_SXY", // - "ROW_NUMBER", "STDDEV", "STDDEV_POP", "STDDEV_SAMP", "SUM", // - "VAR_POP", "VAR_SAMP", "VARIANCE" // + private static final String[] AGGREGATE_FUNCTIONS = { + "AVG", // + "CORR", // + "COVAR_POP", // + "COVAR_SAMP", // + "COUNT", // + "CUME_DIST", // + "DENSE_RANK", // + "FIRST", // + "FIRST_VALUE", // + "LAG", // + "LAST", // + "LAST_VALUE", // + "LEAD", // + "MAX", // + "MIN", // + "NTILE", // + "PERCENT_RANK", // + "PERCENTILE_CONT", // + "PERCENTILE_DISC", // + "RANK", // + "RATIO_TO_REPORT", // + "REGR_SLOPE", // + "REGR_INTERCEPT", // + "REGR_COUNT", // + "REGR_R2", // + "REGR_AVGX", // + "REGR_AVGY", // + "REGR_SXX", // + "REGR_SYY", // + "REGR_SXY", // + "ROW_NUMBER", // + "STDDEV", // + "STDDEV_POP", // + "STDDEV_SAMP", // + "SUM", // + "VAR_POP", // + "VAR_SAMP", // + "VARIANCE", // + "WM_CONCAT" }; public OracleExprParser(Lexer lexer){ @@ -229,8 +268,8 @@ public class OracleExprParser extends SQLExprParser { } public boolean isAggreateFunction(String word) { - for (int i = 0; i < _aggregateFunctions.length; ++i) { - if (_aggregateFunctions[i].compareToIgnoreCase(word) == 0) { + for (int i = 0; i < AGGREGATE_FUNCTIONS.length; ++i) { + if (AGGREGATE_FUNCTIONS[i].compareToIgnoreCase(word) == 0) { return true; } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleLexer.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleLexer.java index efd7611eb2..830272c9a8 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleLexer.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleLexer.java @@ -16,6 +16,7 @@ package com.alibaba.druid.sql.dialect.oracle.parser; import static com.alibaba.druid.sql.parser.CharTypes.isIdentifierChar; +import static com.alibaba.druid.sql.parser.LayoutCharacters.EOI; import java.util.HashMap; import java.util.Map; @@ -23,11 +24,9 @@ import java.util.Map; import com.alibaba.druid.sql.parser.Keywords; import com.alibaba.druid.sql.parser.Lexer; import com.alibaba.druid.sql.parser.NotAllowCommentException; -import com.alibaba.druid.sql.parser.SQLParseException; +import com.alibaba.druid.sql.parser.ParserException; import com.alibaba.druid.sql.parser.Token; -import static com.alibaba.druid.sql.parser.LayoutCharacters.EOI; - public class OracleLexer extends Lexer { public final static Keywords DEFAULT_ORACLE_KEYWORDS; @@ -104,7 +103,7 @@ public class OracleLexer extends Lexer { } if (ch != ':' && ch != '#' && ch != '$') { - throw new SQLParseException("illegal variable"); + throw new ParserException("illegal variable"); } mark = pos; @@ -136,13 +135,13 @@ public class OracleLexer extends Lexer { if (quoteFlag) { if (ch != '"') { - throw new SQLParseException("syntax error"); + throw new ParserException("syntax error"); } ++pos; bufPos++; } else if (mybatisFlag) { if (ch != '}') { - throw new SQLParseException("syntax error"); + throw new ParserException("syntax error"); } ++pos; bufPos++; diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java index a866b9da39..644ea15a13 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleSelectParser.java @@ -67,7 +67,6 @@ import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleSelectTableSource; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleSelectUnPivot; import com.alibaba.druid.sql.parser.ParserException; import com.alibaba.druid.sql.parser.SQLExprParser; -import com.alibaba.druid.sql.parser.SQLParseException; import com.alibaba.druid.sql.parser.SQLSelectParser; import com.alibaba.druid.sql.parser.Token; @@ -174,7 +173,7 @@ public class OracleSelectParser extends SQLSelectParser { accept(Token.AS); accept(Token.LPAREN); - entry.setSubQuery(query()); + entry.setSubQuery(select()); accept(Token.RPAREN); if (identifierEquals("SEARCH")) { @@ -182,7 +181,7 @@ public class OracleSelectParser extends SQLSelectParser { SearchClause searchClause = new SearchClause(); if (lexer.token() != Token.IDENTIFIER) { - throw new SQLParseException("syntax erorr : " + lexer.token()); + throw new ParserException("syntax erorr : " + lexer.token()); } searchClause.setType(SearchClause.Type.valueOf(lexer.stringVal())); @@ -245,6 +244,10 @@ public class OracleSelectParser extends SQLSelectParser { OracleSelectQueryBlock queryBlock = new OracleSelectQueryBlock(); if (lexer.token() == Token.SELECT) { lexer.nextToken(); + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } parseHints(queryBlock); @@ -823,7 +826,7 @@ public class OracleSelectParser extends SQLSelectParser { SQLBinaryOpExpr binaryExpr = (SQLBinaryOpExpr) exprParser.expr(); if (binaryExpr.getOperator() != SQLBinaryOperator.BooleanAnd) { - throw new SQLParseException("syntax error : " + binaryExpr.getOperator()); + throw new ParserException("syntax error : " + binaryExpr.getOperator()); } clause.setBegin(binaryExpr.getLeft()); @@ -831,7 +834,7 @@ public class OracleSelectParser extends SQLSelectParser { tableReference.setFlashback(clause); } else { - throw new SQLParseException("TODO"); + throw new ParserException("TODO"); } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleStatementParser.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleStatementParser.java index 84d52d4b47..f367cb814c 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleStatementParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/parser/OracleStatementParser.java @@ -1462,6 +1462,10 @@ public class OracleStatementParser extends SQLStatementParser { if (lexer.token() == Token.DELETE) { lexer.nextToken(); + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } parseHints(deleteStatement.getHints()); diff --git a/src/main/java/com/alibaba/druid/sql/dialect/oracle/visitor/OracleEvalVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/oracle/visitor/OracleEvalVisitor.java index a7f62b49b5..d1e03a5208 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/oracle/visitor/OracleEvalVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/oracle/visitor/OracleEvalVisitor.java @@ -16,28 +16,34 @@ package com.alibaba.druid.sql.dialect.oracle.visitor; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLCharExpr; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; +import com.alibaba.druid.sql.ast.expr.SQLUnaryExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.visitor.SQLEvalVisitor; import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.sql.visitor.functions.Function; public class OracleEvalVisitor extends OracleASTVisitorAdapter implements SQLEvalVisitor { - private List parameters = new ArrayList(); + private Map functions = new HashMap(); + private List parameters = new ArrayList(); - private int variantIndex = -1; + private int variantIndex = -1; - private boolean markVariantIndex = true; + private boolean markVariantIndex = true; public OracleEvalVisitor(){ this(new ArrayList(1)); @@ -75,6 +81,10 @@ public class OracleEvalVisitor extends OracleASTVisitorAdapter implements SQLEva return SQLEvalVisitorUtils.visit(this, x); } + public boolean visit(SQLUnaryExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + public boolean visit(SQLIntegerExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @@ -116,4 +126,17 @@ public class OracleEvalVisitor extends OracleASTVisitorAdapter implements SQLEva this.markVariantIndex = markVariantIndex; } + @Override + public Function getFunction(String funcName) { + return functions.get(funcName); + } + + @Override + public void registerFunction(String funcName, Function function) { + functions.put(funcName, function); + } + + public boolean visit(SQLIdentifierExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java index f07a3b9eec..1cd0dde67e 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java @@ -66,6 +66,11 @@ public class PGInsertStatement extends SQLInsertStatement implements PGSQLStatem public List getValuesList() { return valuesList; } + + public void addValueCause(ValuesClause valueClause) { + valueClause.setParent(this); + valuesList.add(valueClause); + } protected void accept0(SQLASTVisitor visitor) { accept0((PGASTVisitor) visitor); diff --git a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGExprParser.java b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGExprParser.java index 5a50b36e6f..0cb3c1266c 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGExprParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGExprParser.java @@ -15,6 +15,9 @@ */ package com.alibaba.druid.sql.dialect.postgresql.parser; +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; +import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator; import com.alibaba.druid.sql.dialect.postgresql.ast.PGOrderBy; import com.alibaba.druid.sql.parser.Lexer; import com.alibaba.druid.sql.parser.SQLExprParser; @@ -30,6 +33,18 @@ public class PGExprParser extends SQLExprParser { public PGExprParser(Lexer lexer){ super(lexer); } + + public boolean isAggreateFunction(String word) { + String[] aggregateFunctions = { "AVG", "COUNT", "MAX", "MIN", "STDDEV", "SUM", "ROW_NUMBER" }; + + for (int i = 0; i < aggregateFunctions.length; ++i) { + if (aggregateFunctions[i].compareToIgnoreCase(word) == 0) { + return true; + } + } + + return false; + } @Override public PGOrderBy parseOrderBy() { @@ -56,4 +71,16 @@ public class PGExprParser extends SQLExprParser { return null; } + + public SQLExpr primaryRest(SQLExpr expr) { + if (lexer.token() == Token.COLONCOLON) { + lexer.nextToken(); + SQLExpr typeExpr = this.expr(); + SQLBinaryOpExpr castExpr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.PostgresStyleTypeCast, typeExpr); + + return primaryRest(castExpr); + } + + return super.primaryRest(expr); + } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSQLStatementParser.java b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSQLStatementParser.java index e8cb151bc2..30750644ab 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSQLStatementParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSQLStatementParser.java @@ -110,9 +110,10 @@ public class PGSQLStatementParser extends SQLStatementParser { for (;;) { accept(Token.LPAREN); - SQLInsertStatement.ValuesClause values = new SQLInsertStatement.ValuesClause(); - this.exprParser.exprList(values.getValues()); - stmt.getValuesList().add(values); + SQLInsertStatement.ValuesClause valuesCaluse = new SQLInsertStatement.ValuesClause(); + this.exprParser.exprList(valuesCaluse.getValues()); + stmt.addValueCause(valuesCaluse); + accept(Token.RPAREN); if (lexer.token() == Token.COMMA) { lexer.nextToken(); diff --git a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSelectParser.java b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSelectParser.java index 743122bcb3..8ce42e0cb7 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSelectParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/parser/PGSelectParser.java @@ -52,6 +52,10 @@ public class PGSelectParser extends SQLSelectParser { if (lexer.token() == Token.SELECT) { lexer.nextToken(); + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } if (lexer.token() == Token.DISTINCT) { queryBlock.setDistionOption(SQLSetQuantifier.DISTINCT); diff --git a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGEvalVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGEvalVisitor.java index 6e590d4b84..1efd330256 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGEvalVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGEvalVisitor.java @@ -16,28 +16,34 @@ package com.alibaba.druid.sql.dialect.postgresql.visitor; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLCharExpr; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; +import com.alibaba.druid.sql.ast.expr.SQLUnaryExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.visitor.SQLEvalVisitor; import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.sql.visitor.functions.Function; public class PGEvalVisitor extends PGASTVisitorAdapter implements SQLEvalVisitor { - private List parameters = new ArrayList(); + private Map functions = new HashMap(); + private List parameters = new ArrayList(); - private int variantIndex = -1; + private int variantIndex = -1; - private boolean markVariantIndex = true; + private boolean markVariantIndex = true; public PGEvalVisitor(){ this(new ArrayList(1)); @@ -75,6 +81,10 @@ public class PGEvalVisitor extends PGASTVisitorAdapter implements SQLEvalVisitor return SQLEvalVisitorUtils.visit(this, x); } + public boolean visit(SQLUnaryExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + public boolean visit(SQLIntegerExpr x) { return SQLEvalVisitorUtils.visit(this, x); } @@ -116,4 +126,17 @@ public class PGEvalVisitor extends PGASTVisitorAdapter implements SQLEvalVisitor this.markVariantIndex = markVariantIndex; } + @Override + public Function getFunction(String funcName) { + return functions.get(funcName); + } + + @Override + public void registerFunction(String funcName, Function function) { + functions.put(funcName, function); + } + + public boolean visit(SQLIdentifierExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGExportParameterVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGExportParameterVisitor.java new file mode 100644 index 0000000000..c7b719223c --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/postgresql/visitor/PGExportParameterVisitor.java @@ -0,0 +1,87 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.postgresql.visitor; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.druid.sql.ast.SQLOrderBy; +import com.alibaba.druid.sql.ast.expr.SQLBetweenExpr; +import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; +import com.alibaba.druid.sql.ast.expr.SQLInListExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause; +import com.alibaba.druid.sql.ast.statement.SQLSelectItem; +import com.alibaba.druid.sql.visitor.ExportParameterVisitor; +import com.alibaba.druid.sql.visitor.ExportParameterVisitorUtils; + +public class PGExportParameterVisitor extends PGASTVisitorAdapter implements ExportParameterVisitor { + + private final List parameters; + + public PGExportParameterVisitor() { + this(new ArrayList()); + } + + public PGExportParameterVisitor(List parameters){ + this.parameters = parameters; + } + + public List getParameters() { + return parameters; + } + + @Override + public boolean visit(SQLSelectItem x) { + return false; + } + + @Override + public boolean visit(SQLOrderBy x) { + return false; + } + + @Override + public boolean visit(SQLSelectGroupByClause x) { + return false; + } + + @Override + public boolean visit(SQLMethodInvokeExpr x) { + ExportParameterVisitorUtils.exportParamterAndAccept(this.parameters, x.getParameters()); + + return true; + } + + @Override + public boolean visit(SQLInListExpr x) { + ExportParameterVisitorUtils.exportParamterAndAccept(this.parameters, x.getTargetList()); + + return true; + } + + @Override + public boolean visit(SQLBetweenExpr x) { + ExportParameterVisitorUtils.exportParameter(this.parameters, x); + return true; + } + + public boolean visit(SQLBinaryOpExpr x) { + ExportParameterVisitorUtils.exportParameter(this.parameters, x); + return true; + } + +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerExprParser.java b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerExprParser.java index d9c661d3e5..e9d8cc3838 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerExprParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerExprParser.java @@ -47,6 +47,10 @@ public class SQLServerExprParser extends SQLExprParser { return super.primary(); } + + public SQLServerSelectParser createSelectParser() { + return new SQLServerSelectParser(this); + } public SQLExpr primaryRest(SQLExpr expr) { if (lexer.token() == Token.DOTDOT) { @@ -125,6 +129,11 @@ public class SQLServerExprParser extends SQLExprParser { accept(Token.RPAREN); } + if (lexer.token() == Token.PERCENT) { + lexer.nextToken(); + top.setPercent(true); + } + return top; } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerLexer.java b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerLexer.java index 676440b361..d1b5e5f9a0 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerLexer.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerLexer.java @@ -39,6 +39,7 @@ public class SQLServerLexer extends Lexer { map.put("TOP", Token.TOP); map.put("USE", Token.USE); map.put("WITH", Token.WITH); + map.put("PERCENT", Token.PERCENT); DEFAULT_SQL_SERVER_KEYWORDS = new Keywords(map); } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerSelectParser.java b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerSelectParser.java index 9cedc21efd..5db2dd4994 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerSelectParser.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/parser/SQLServerSelectParser.java @@ -66,6 +66,10 @@ public class SQLServerSelectParser extends SQLSelectParser { if (lexer.token() == Token.SELECT) { lexer.nextToken(); + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } if (lexer.token() == Token.DISTINCT) { queryBlock.setDistionOption(SQLSetQuantifier.DISTINCT); @@ -76,9 +80,7 @@ public class SQLServerSelectParser extends SQLSelectParser { } if (lexer.token() == Token.TOP) { - SQLServerTop top = new SQLServerTop(); - lexer.nextToken(); - top.setExpr(createExprParser().primary()); + SQLServerTop top = this.createExprParser().parseTop(); queryBlock.setTop(top); } @@ -101,7 +103,7 @@ public class SQLServerSelectParser extends SQLSelectParser { return queryRest(queryBlock); } - protected SQLExprParser createExprParser() { + protected SQLServerExprParser createExprParser() { return new SQLServerExprParser(lexer); } } diff --git a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerEvalVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerEvalVisitor.java new file mode 100644 index 0000000000..d24e664b2c --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerEvalVisitor.java @@ -0,0 +1,142 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.dialect.sqlserver.visitor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; +import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; +import com.alibaba.druid.sql.ast.expr.SQLCharExpr; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; +import com.alibaba.druid.sql.ast.expr.SQLInListExpr; +import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.ast.expr.SQLNullExpr; +import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; +import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; +import com.alibaba.druid.sql.ast.expr.SQLUnaryExpr; +import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.sql.visitor.functions.Function; + +public class SQLServerEvalVisitor extends SQLServerASTVisitorAdapter implements SQLEvalVisitor { + + private Map functions = new HashMap(); + private List parameters = new ArrayList(); + + private int variantIndex = -1; + + private boolean markVariantIndex = true; + + public SQLServerEvalVisitor(){ + this(new ArrayList(1)); + } + + public SQLServerEvalVisitor(List parameters){ + this.parameters = parameters; + } + + public List getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + + public boolean visit(SQLCharExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + public int incrementAndGetVariantIndex() { + return ++variantIndex; + } + + public int getVariantIndex() { + return variantIndex; + } + + public boolean visit(SQLVariantRefExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + public boolean visit(SQLBinaryOpExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + public boolean visit(SQLUnaryExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + public boolean visit(SQLIntegerExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + public boolean visit(SQLNumberExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + @Override + public boolean visit(SQLCaseExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + @Override + public boolean visit(SQLInListExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + @Override + public boolean visit(SQLNullExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + @Override + public boolean visit(SQLMethodInvokeExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + @Override + public boolean visit(SQLQueryExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } + + public boolean isMarkVariantIndex() { + return markVariantIndex; + } + + public void setMarkVariantIndex(boolean markVariantIndex) { + this.markVariantIndex = markVariantIndex; + } + + @Override + public Function getFunction(String funcName) { + return functions.get(funcName); + } + + @Override + public void registerFunction(String funcName, Function function) { + functions.put(funcName, function); + } + + public boolean visit(SQLIdentifierExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerOutputVisitor.java b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerOutputVisitor.java index 1b81b38ff6..8f49ef7198 100644 --- a/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerOutputVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerOutputVisitor.java @@ -96,6 +96,10 @@ public class SQLServerOutputVisitor extends SQLASTOutputVisitor implements SQLSe print(")"); } + if (x.isPercent()) { + print(" PERCENT"); + } + return false; } diff --git a/src/main/java/com/alibaba/druid/sql/parser/EOFParserException.java b/src/main/java/com/alibaba/druid/sql/parser/EOFParserException.java new file mode 100644 index 0000000000..c280d7c26f --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/parser/EOFParserException.java @@ -0,0 +1,24 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.parser; + +@SuppressWarnings("serial") +public class EOFParserException extends ParserException { + + public EOFParserException(){ + super("EOF"); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/parser/Keywords.java b/src/main/java/com/alibaba/druid/sql/parser/Keywords.java index ab8d2a0f1e..fda68bb56c 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/Keywords.java +++ b/src/main/java/com/alibaba/druid/sql/parser/Keywords.java @@ -81,7 +81,6 @@ public class Keywords { map.put("LIKE", Token.LIKE); map.put("LOCK", Token.LOCK); map.put("MINUS", Token.MINUS); - map.put("NEW", Token.NEW); map.put("NOT", Token.NOT); map.put("NULL", Token.NULL); @@ -114,6 +113,7 @@ public class Keywords { map.put("OVER", Token.OVER); map.put("TO", Token.TO); + map.put("USE", Token.USE); DEFAULT_KEYWORDS = new Keywords(map); } diff --git a/src/main/java/com/alibaba/druid/sql/parser/Lexer.java b/src/main/java/com/alibaba/druid/sql/parser/Lexer.java index 06a2ad4674..1283bf9528 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/Lexer.java +++ b/src/main/java/com/alibaba/druid/sql/parser/Lexer.java @@ -19,6 +19,7 @@ import static com.alibaba.druid.sql.parser.CharTypes.isFirstIdentifierChar; import static com.alibaba.druid.sql.parser.CharTypes.isIdentifierChar; import static com.alibaba.druid.sql.parser.CharTypes.isWhitespace; import static com.alibaba.druid.sql.parser.LayoutCharacters.EOI; +import static com.alibaba.druid.sql.parser.Token.COLONCOLON; import static com.alibaba.druid.sql.parser.Token.COLONEQ; import static com.alibaba.druid.sql.parser.Token.COMMA; import static com.alibaba.druid.sql.parser.Token.EOF; @@ -41,36 +42,46 @@ import java.util.Arrays; */ public class Lexer { - protected final String text; - protected int pos; - protected int mark; + protected final String text; + protected int pos; + protected int mark; - protected char ch; + protected char ch; - protected char[] buf; - protected int bufPos; + protected char[] buf; + protected int bufPos; - protected Token token; + protected Token token; - protected Keywords keywods = Keywords.DEFAULT_KEYWORDS; + protected Keywords keywods = Keywords.DEFAULT_KEYWORDS; - protected String stringVal; + protected String stringVal; - protected boolean skipComment = true; + protected boolean skipComment = true; - private SavePoint savePoint = null; + private SavePoint savePoint = null; /* * anti sql injection */ - private boolean allowComment = true; + private boolean allowComment = true; - private int varIndex = -1; + private int varIndex = -1; + + protected CommentHandler commentHandler; public Lexer(String input){ this(input, true); } + public CommentHandler getCommentHandler() { + return commentHandler; + } + + public void setCommentHandler(CommentHandler commentHandler) { + this.commentHandler = commentHandler; + } + public final char charAt(int index) { if (index >= text.length()) { return EOI; @@ -78,7 +89,7 @@ public class Lexer { return text.charAt(index); } - + public final String addSymbol() { return subString(mark, bufPos); } @@ -86,7 +97,7 @@ public class Lexer { public final String subString(int offset, int count) { return text.substring(offset, offset + count); } - + protected void initBuff(int size) { if (buf == null) { if (size < 32) { @@ -94,7 +105,7 @@ public class Lexer { } else { buf = new char[size + 32]; } - } else if(buf.length < size) { + } else if (buf.length < size) { buf = Arrays.copyOf(buf, size); } } @@ -116,6 +127,7 @@ public class Lexer { } private static class SavePoint { + int bp; int sp; int np; @@ -187,32 +199,32 @@ public class Lexer { public String info() { return this.token + " " + this.stringVal(); } - + public final void nextTokenComma() { if (ch == ' ') { scanChar(); } - + if (ch == ',') { scanChar(); token = COMMA; return; } - + if (ch == ')') { scanChar(); token = RPAREN; return; } - + nextToken(); } - + public final void nextTokenLParen() { if (ch == ' ') { scanChar(); } - + if (ch == '(') { scanChar(); token = LPAREN; @@ -220,38 +232,38 @@ public class Lexer { } nextToken(); } - + public final void nextTokenValue() { if (ch == ' ') { scanChar(); } - + if (ch == '\'') { bufPos = 0; scanString(); return; } - + if (ch >= '0' && ch <= '9') { bufPos = 0; scanNumber(); return; } - + if (ch == '?') { scanChar(); token = Token.QUES; return; } - + if (isFirstIdentifierChar(ch) && ch != 'N') { scanIdentifier(); return; } - + nextToken(); } - + public final void nextToken() { bufPos = 0; @@ -334,6 +346,9 @@ public class Lexer { if (ch == '=') { scanChar(); token = COLONEQ; + } else if (ch == ':') { + scanChar(); + token = COLONCOLON; } else { if (isDigit(ch)) { unscan(); @@ -384,7 +399,7 @@ public class Lexer { token = Token.SEMI; return; case '`': - throw new SQLParseException("TODO"); // TODO + throw new ParserException("TODO"); // TODO case '@': scanVariable(); return; @@ -552,7 +567,7 @@ public class Lexer { token = Token.TILDE; break; default: - throw new SQLParseException("TODO"); + throw new ParserException("TODO"); } } @@ -636,7 +651,7 @@ public class Lexer { public void scanVariable() { if (ch != '@' && ch != ':' && ch != '#' && ch != '$') { - throw new SQLParseException("illegal variable"); + throw new ParserException("illegal variable"); } mark = pos; @@ -667,7 +682,7 @@ public class Lexer { if (mybatisFlag) { if (ch != '}') { - throw new SQLParseException("syntax error"); + throw new ParserException("syntax error"); } ++pos; bufPos++; @@ -749,7 +764,7 @@ public class Lexer { final boolean firstFlag = isFirstIdentifierChar(first); if (!firstFlag) { - throw new SQLParseException("illegal identifier"); + throw new ParserException("illegal identifier"); } mark = pos; @@ -762,7 +777,6 @@ public class Lexer { break; } - bufPos++; continue; } @@ -1004,4 +1018,9 @@ public class Lexer { public BigDecimal decimalValue() { return new BigDecimal(text.toCharArray(), mark, bufPos); } + + public static interface CommentHandler { + + boolean handle(Token lastToken, String comment); + } } diff --git a/src/main/java/com/alibaba/druid/sql/parser/NotAllowCommentException.java b/src/main/java/com/alibaba/druid/sql/parser/NotAllowCommentException.java index 1dbe8d3f83..21ec93ba69 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/NotAllowCommentException.java +++ b/src/main/java/com/alibaba/druid/sql/parser/NotAllowCommentException.java @@ -20,7 +20,7 @@ public class NotAllowCommentException extends ParserException { private static final long serialVersionUID = 1L; public NotAllowCommentException(){ - super(); + this("comment not allow"); } public NotAllowCommentException(String message, Throwable e){ diff --git a/src/main/java/com/alibaba/druid/sql/parser/SQLExprParser.java b/src/main/java/com/alibaba/druid/sql/parser/SQLExprParser.java index 87cfc8a251..565e9ddd21 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/SQLExprParser.java +++ b/src/main/java/com/alibaba/druid/sql/parser/SQLExprParser.java @@ -126,7 +126,7 @@ public class SQLExprParser extends SQLParser { } public final SQLExpr multiplicative() { - SQLExpr expr = primary(); + SQLExpr expr = bitXor(); return multiplicativeRest(expr); } @@ -335,8 +335,12 @@ public class SQLExprParser extends SQLParser { sqlExpr = new SQLIdentifierExpr('-' + lexer.stringVal()); lexer.nextToken(); break; + case QUES: + sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Negative, new SQLVariantRefExpr("?")); + lexer.nextToken(); + break; default: - throw new ParserException("TODO"); + throw new ParserException("TODO : " + lexer.token()); } break; case PLUS: @@ -453,8 +457,10 @@ public class SQLExprParser extends SQLParser { sqlExpr = new SQLIdentifierExpr('"' + lexer.stringVal() + '"'); lexer.nextToken(); break; + case EOF: + throw new EOFParserException(); default: - throw new ParserException("ERROR. token : " + tok + " " + lexer.stringVal()); + throw new ParserException("ERROR. token : " + tok + ", pos : " + lexer.pos()); } return primaryRest(sqlExpr); @@ -702,12 +708,12 @@ public class SQLExprParser extends SQLParser { exprList(aggregateExpr.getArguments()); accept(Token.RPAREN); - + if (lexer.token() == Token.OVER) { lexer.nextToken(); SQLOver over = new SQLOver(); accept(Token.LPAREN); - + if (identifierEquals("PARTITION")) { lexer.nextToken(); accept(Token.BY); @@ -721,13 +727,12 @@ public class SQLExprParser extends SQLParser { } } - over.setOrderBy(parseOrderBy()); - + // if (over.getOrderBy() != null) { // //TODO window // } - + accept(Token.RPAREN); aggregateExpr.setOver(over); @@ -798,17 +803,12 @@ public class SQLExprParser extends SQLParser { SQLExpr rightExp = bitAnd(); expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.BitwiseOr, rightExp); expr = bitAndRest(expr); - } else if (lexer.token() == Token.TILDE) { - lexer.nextToken(); - SQLExpr rightExp = bitAnd(); - expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.InvertBits, rightExp); - expr = bitAndRest(expr); } return expr; } public final SQLExpr equality() { - SQLExpr expr = shift(); + SQLExpr expr = bitOr(); return equalityRest(expr); } @@ -816,14 +816,17 @@ public class SQLExprParser extends SQLParser { SQLExpr rightExp; if (lexer.token() == Token.EQ) { lexer.nextToken(); - rightExp = shift(); - + try { + rightExp = bitOr(); + } catch (EOFParserException e) { + throw new ParserException("EOF, " + expr + "=", e); + } rightExp = equalityRest(rightExp); expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Equality, rightExp); } else if (lexer.token() == Token.BANGEQ) { lexer.nextToken(); - rightExp = shift(); + rightExp = bitOr(); rightExp = equalityRest(rightExp); @@ -1134,16 +1137,16 @@ public class SQLExprParser extends SQLParser { SQLName typeExpr = name(); String typeName = typeExpr.toString(); - + if (isCharType(typeName)) { SQLCharactorDataType charType = new SQLCharactorDataType(typeName); - + if (lexer.token() == Token.LPAREN) { lexer.nextToken(); charType.getArguments().add(this.expr()); accept(Token.RPAREN); } - + return parseCharTypeRest(charType); } @@ -1206,8 +1209,8 @@ public class SQLExprParser extends SQLParser { if (lexer.token() == token) { lexer.nextToken(); } else { - throw new SQLParseException("syntax error, expect " + token + ", actual " + lexer.token() + " " - + lexer.stringVal()); + throw new ParserException("syntax error, expect " + token + ", actual " + lexer.token() + " " + + lexer.stringVal()); } } @@ -1238,19 +1241,19 @@ public class SQLExprParser extends SQLParser { column.setDefaultExpr(new SQLNullExpr()); return parseColumnRest(column); } - + if (lexer.token == Token.PRIMARY) { lexer.nextToken(); accept(Token.KEY); column.getConstaints().add(new SQLColumnPrimaryKey()); - return parseColumnRest(column); + return parseColumnRest(column); } - + if (lexer.token == Token.UNION) { lexer.nextToken(); accept(Token.KEY); column.getConstaints().add(new SQLColumnPrimaryKey()); - return parseColumnRest(column); + return parseColumnRest(column); } return column; diff --git a/src/main/java/com/alibaba/druid/sql/parser/SQLParseException.java b/src/main/java/com/alibaba/druid/sql/parser/SQLParseException.java index c1d6037344..655e0c5db8 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/SQLParseException.java +++ b/src/main/java/com/alibaba/druid/sql/parser/SQLParseException.java @@ -20,6 +20,7 @@ import com.alibaba.druid.DruidRuntimeException; /** * @author wenshao */ +@Deprecated public class SQLParseException extends DruidRuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/alibaba/druid/sql/parser/SQLParser.java b/src/main/java/com/alibaba/druid/sql/parser/SQLParser.java index b63c5544c3..b725a2d636 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/SQLParser.java +++ b/src/main/java/com/alibaba/druid/sql/parser/SQLParser.java @@ -41,11 +41,11 @@ public class SQLParser { lexer.nextToken(); } else { setErrorEndPos(lexer.pos()); - throw new SQLParseException("syntax error, expect " + text + ", actual " + lexer.token()); + throw new ParserException("syntax error, expect " + text + ", actual " + lexer.token()); } } - protected String as() { + protected String as() { String alias = null; if (lexer.token() == Token.AS) { @@ -54,36 +54,38 @@ public class SQLParser { if (lexer.token() == Token.LITERAL_ALIAS) { alias = '"' + lexer.stringVal() + '"'; lexer.nextToken(); - return alias; - } - - if (lexer.token() == Token.IDENTIFIER) { + } else if (lexer.token() == Token.IDENTIFIER) { alias = lexer.stringVal(); lexer.nextToken(); - return alias; - } - - if (lexer.token() == Token.LITERAL_CHARS) { + } else if (lexer.token() == Token.LITERAL_CHARS) { alias = "'" + lexer.stringVal() + "'"; lexer.nextToken(); - return alias; + } else { + switch (lexer.token()) { + case KEY: + case INDEX: + case CASE: + alias = lexer.token().name(); + lexer.nextToken(); + return alias; + case QUES: + alias = "?"; + lexer.nextToken(); + default: + break; + } } - if (lexer.token() == Token.KEY || lexer.token() == Token.CASE) { - alias = lexer.token.name(); - lexer.nextToken(); - return alias; - } - - switch (lexer.token()) { - case KEY: - alias = lexer.token().name(); + if (alias != null) { + while (lexer.token() == Token.DOT) { lexer.nextToken(); - return alias; - default: - break; + alias += ('.' + lexer.token().name()); + lexer.nextToken(); + } + + return alias; } - + if (lexer.token() == Token.LPAREN) { return null; } @@ -122,14 +124,14 @@ public class SQLParser { lexer.nextToken(); } else { setErrorEndPos(lexer.pos()); - throw new SQLParseException("syntax error, expect " + token + ", actual " + lexer.token() + " " - + lexer.stringVal()); + throw new ParserException("syntax error, expect " + token + ", actual " + lexer.token() + " " + + lexer.stringVal() + ", pos " + this.lexer.pos()); } } public void match(Token token) { if (lexer.token() != token) { - throw new SQLParseException("syntax error, expect " + token + ", actual " + lexer.token() + " " + throw new ParserException("syntax error, expect " + token + ", actual " + lexer.token() + " " + lexer.stringVal()); } } diff --git a/src/main/java/com/alibaba/druid/sql/parser/SQLSelectParser.java b/src/main/java/com/alibaba/druid/sql/parser/SQLSelectParser.java index 74c633377b..7487e8b2b7 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/SQLSelectParser.java +++ b/src/main/java/com/alibaba/druid/sql/parser/SQLSelectParser.java @@ -141,6 +141,10 @@ public class SQLSelectParser extends SQLParser { } accept(Token.SELECT); + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } SQLSelectQueryBlock queryBlock = new SQLSelectQueryBlock(); @@ -169,14 +173,14 @@ public class SQLSelectParser extends SQLParser { protected void withSubquery(SQLSelect select) { if (lexer.token() == Token.WITH) { lexer.nextToken(); - + SQLWithSubqueryClause withQueryClause = new SQLWithSubqueryClause(); - + if (lexer.token == Token.RECURSIVE || identifierEquals("RECURSIVE")) { lexer.nextToken(); withQueryClause.setRecursive(true); } - + for (;;) { SQLWithSubqueryClause.Entry entry = new SQLWithSubqueryClause.Entry(); entry.setName((SQLIdentifierExpr) this.exprParser.name()); @@ -189,7 +193,7 @@ public class SQLSelectParser extends SQLParser { accept(Token.AS); accept(Token.LPAREN); - entry.setSubQuery(query()); + entry.setSubQuery(select()); accept(Token.RPAREN); withQueryClause.getEntries().add(entry); @@ -252,7 +256,7 @@ public class SQLSelectParser extends SQLParser { if (lexer.token() == Token.IDENTIFIER) { expr = new SQLIdentifierExpr(lexer.stringVal()); lexer.nextTokenComma(); - + if (lexer.token() != Token.COMMA) { expr = this.exprParser.primaryRest(expr); expr = this.exprParser.exprRest(expr); @@ -261,13 +265,13 @@ public class SQLSelectParser extends SQLParser { expr = expr(); } final String alias = as(); - + final SQLSelectItem selectItem = new SQLSelectItem(expr, alias); selectList.add(selectItem); if (lexer.token() != Token.COMMA) { break; } - + lexer.nextToken(); } } @@ -386,6 +390,15 @@ public class SQLSelectParser extends SQLParser { if (lexer.token() == Token.ON) { lexer.nextToken(); join.setCondition(expr()); + } else if (identifierEquals("USING")) { + lexer.nextToken(); + if (lexer.token() == Token.LPAREN) { + lexer.nextToken(); + this.exprParser.exprList(join.getUsing()); + accept(Token.RPAREN); + } else { + join.getUsing().add(this.expr()); + } } return parseTableSourceRest(join); @@ -407,7 +420,7 @@ public class SQLSelectParser extends SQLParser { lexer.nextToken(); } else { setErrorEndPos(lexer.pos()); - throw new SQLParseException("syntax error, expect " + ident + ", actual " + lexer.token()); + throw new ParserException("syntax error, expect " + ident + ", actual " + lexer.token()); } } diff --git a/src/main/java/com/alibaba/druid/sql/parser/SQLStatementParser.java b/src/main/java/com/alibaba/druid/sql/parser/SQLStatementParser.java index f3d2fe5f9a..10756dfede 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/SQLStatementParser.java +++ b/src/main/java/com/alibaba/druid/sql/parser/SQLStatementParser.java @@ -223,7 +223,7 @@ public class SQLStatementParser extends SQLParser { continue; } - throw new ParserException("TODO " + lexer.token() + " " + lexer.stringVal() + ", pos " + lexer.pos()); + throw new ParserException("syntax error, " + lexer.token() + " " + lexer.stringVal() + ", pos " + lexer.pos()); } } @@ -509,6 +509,8 @@ public class SQLStatementParser extends SQLParser { } else if (identifierEquals("PUBLIC") || identifierEquals("SHARE")) { lexer.reset(markBp, markChar, Token.CREATE); return parseCreateDbLink(); + } else if (token == Token.VIEW) { + return parseCreateView(); } throw new ParserException("TODO " + lexer.token()); @@ -615,6 +617,10 @@ public class SQLStatementParser extends SQLParser { if (lexer.token() == (Token.FROM)) { lexer.nextToken(); } + + if (lexer.token() == Token.COMMENT) { + lexer.nextToken(); + } SQLName tableName = exprParser.name(); @@ -639,7 +645,15 @@ public class SQLStatementParser extends SQLParser { public SQLCreateViewStatement parseCreateView() { SQLCreateViewStatement createView = new SQLCreateViewStatement(); - this.accept(Token.CREATE); + if (lexer.token() == Token.CREATE) { + lexer.nextToken(); + } + + if (lexer.token() == Token.OR) { + lexer.nextToken(); + acceptIdentifier("REPLACE"); + createView.setOrReplace(true); + } this.accept(Token.VIEW); diff --git a/src/main/java/com/alibaba/druid/sql/parser/Token.java b/src/main/java/com/alibaba/druid/sql/parser/Token.java index 0b300197d2..2410cf69ee 100644 --- a/src/main/java/com/alibaba/druid/sql/parser/Token.java +++ b/src/main/java/com/alibaba/druid/sql/parser/Token.java @@ -207,6 +207,7 @@ public enum Token { TILDE("~"), QUES("?"), COLON(":"), + COLONCOLON(":"), COLONEQ(":="), EQEQ("=="), LTEQ("<="), diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java index f1fc43ce06..d82c9c3a89 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java @@ -67,11 +67,17 @@ import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.NotNullConstraint; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddColumn; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAlterColumn; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDisableKeys; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropColumnItem; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropForeinKey; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropIndex; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableEnableKeys; import com.alibaba.druid.sql.ast.statement.SQLAssignItem; import com.alibaba.druid.sql.ast.statement.SQLCallStatement; import com.alibaba.druid.sql.ast.statement.SQLCharactorDataType; +import com.alibaba.druid.sql.ast.statement.SQLCheck; import com.alibaba.druid.sql.ast.statement.SQLColumnConstraint; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLColumnPrimaryKey; @@ -700,56 +706,59 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { } Object param = parameters.get(index); + printParameter(param); + return false; + } + public void printParameter(Object param) { if (param == null) { print("NULL"); - return false; + return; } if (param instanceof Number // || param instanceof Boolean) { print(param.toString()); - return false; + return; } if (param instanceof String) { SQLCharExpr charExpr = new SQLCharExpr((String) param); visit(charExpr); - return false; + return; } if (param instanceof Date) { print((Date) param); - return false; + return; } if (param instanceof InputStream) { print("'"); - return false; + return; } if (param instanceof Reader) { print("'"); - return false; + return; } if (param instanceof Blob) { print("'"); - return false; + return; } if (param instanceof NClob) { print("'"); - return false; + return; } if (param instanceof Clob) { print("'"); - return false; + return; } print("'" + param.getClass().getName() + "'"); - return false; } public boolean visit(SQLDropTableStatement x) { @@ -1065,6 +1074,17 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { x.getCondition().accept(this); decrementIndent(); } + + if (x.getUsing().size() > 0) { + print(" USING ("); + printAndAccept(x.getUsing(), ", "); + print(")"); + } + + if (x.getAlias() != null) { + print(" AS "); + print(x.getAlias()); + } decrementIndent(); @@ -1350,4 +1370,49 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter { return false; } + + @Override + public boolean visit(SQLAlterTableAlterColumn x) { + print("ALTER COLUMN "); + x.getColumn().accept(this); + return false; + } + + @Override + public boolean visit(SQLCheck x) { + if (x.getName() != null) { + print("CONSTRAINT "); + x.getName().accept(this); + print(' '); + } + print("CHECK ("); + x.getExpr().accept(this); + print(')'); + return false; + } + + @Override + public boolean visit(SQLAlterTableDropForeinKey x) { + print("DROP FOREIGN KEY "); + x.getIndexName().accept(this); + return false; + } + + @Override + public boolean visit(SQLAlterTableDropPrimaryKey x) { + print("DROP PRIMARY KEY"); + return false; + } + + @Override + public boolean visit(SQLAlterTableEnableKeys x) { + print("ENABLE KEYS"); + return false; + } + + @Override + public boolean visit(SQLAlterTableDisableKeys x) { + print("DISABLE KEYS"); + return false; + } } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitor.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitor.java index 2f00b9d368..f1cefe8b41 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitor.java @@ -55,11 +55,18 @@ import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.NotNullConstraint; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddColumn; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAlterColumn; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDisableKeys; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropColumnItem; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropForeinKey; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropIndex; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableEnableKeys; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; import com.alibaba.druid.sql.ast.statement.SQLAssignItem; import com.alibaba.druid.sql.ast.statement.SQLCallStatement; import com.alibaba.druid.sql.ast.statement.SQLCharactorDataType; +import com.alibaba.druid.sql.ast.statement.SQLCheck; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLColumnPrimaryKey; import com.alibaba.druid.sql.ast.statement.SQLColumnUniqueIndex; @@ -251,7 +258,7 @@ public interface SQLASTVisitor { boolean visit(SQLDataType x); void endVisit(SQLDataType x); - + boolean visit(SQLCharactorDataType x); void endVisit(SQLCharactorDataType x); @@ -363,13 +370,13 @@ public interface SQLASTVisitor { boolean visit(SQLAlterTableDropColumnItem x); void endVisit(SQLAlterTableDropColumnItem x); - + boolean visit(SQLAlterTableDropIndex x); - + void endVisit(SQLAlterTableDropIndex x); - + boolean visit(SQLAlterTableAddPrimaryKey x); - + void endVisit(SQLAlterTableAddPrimaryKey x); boolean visit(SQLDropIndexStatement x); @@ -399,24 +406,52 @@ public interface SQLASTVisitor { void endVisit(SQLCreateDatabaseStatement x); boolean visit(SQLCreateDatabaseStatement x); - + void endVisit(SQLOver x); - + boolean visit(SQLOver x); - + void endVisit(SQLColumnPrimaryKey x); - + boolean visit(SQLColumnPrimaryKey x); - + void endVisit(SQLColumnUniqueIndex x); - + boolean visit(SQLColumnUniqueIndex x); - + void endVisit(SQLWithSubqueryClause x); - + boolean visit(SQLWithSubqueryClause x); - + void endVisit(SQLWithSubqueryClause.Entry x); - + boolean visit(SQLWithSubqueryClause.Entry x); + + void endVisit(SQLAlterTableAlterColumn x); + + boolean visit(SQLAlterTableAlterColumn x); + + boolean visit(SQLCheck x); + + void endVisit(SQLCheck x); + + boolean visit(SQLAlterTableDropForeinKey x); + + void endVisit(SQLAlterTableDropForeinKey x); + + boolean visit(SQLAlterTableDropPrimaryKey x); + + void endVisit(SQLAlterTableDropPrimaryKey x); + + boolean visit(SQLAlterTableDisableKeys x); + + void endVisit(SQLAlterTableDisableKeys x); + + boolean visit(SQLAlterTableEnableKeys x); + + void endVisit(SQLAlterTableEnableKeys x); + + boolean visit(SQLAlterTableStatement x); + + void endVisit(SQLAlterTableStatement x); } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitorAdapter.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitorAdapter.java index dcdfe83975..afe0b2ad3b 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitorAdapter.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLASTVisitorAdapter.java @@ -55,11 +55,18 @@ import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.NotNullConstraint; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddColumn; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableAlterColumn; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDisableKeys; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropColumnItem; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropForeinKey; import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropIndex; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropPrimaryKey; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableEnableKeys; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; import com.alibaba.druid.sql.ast.statement.SQLAssignItem; import com.alibaba.druid.sql.ast.statement.SQLCallStatement; import com.alibaba.druid.sql.ast.statement.SQLCharactorDataType; +import com.alibaba.druid.sql.ast.statement.SQLCheck; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLColumnPrimaryKey; import com.alibaba.druid.sql.ast.statement.SQLColumnUniqueIndex; @@ -765,4 +772,74 @@ public class SQLASTVisitorAdapter implements SQLASTVisitor { public void endVisit(SQLCharactorDataType x) { } + + @Override + public void endVisit(SQLAlterTableAlterColumn x) { + + } + + @Override + public boolean visit(SQLAlterTableAlterColumn x) { + return true; + } + + @Override + public boolean visit(SQLCheck x) { + return true; + } + + @Override + public void endVisit(SQLCheck x) { + + } + + @Override + public boolean visit(SQLAlterTableDropForeinKey x) { + return true; + } + + @Override + public void endVisit(SQLAlterTableDropForeinKey x) { + + } + + @Override + public boolean visit(SQLAlterTableDropPrimaryKey x) { + return true; + } + + @Override + public void endVisit(SQLAlterTableDropPrimaryKey x) { + + } + + @Override + public boolean visit(SQLAlterTableDisableKeys x) { + return true; + } + + @Override + public void endVisit(SQLAlterTableDisableKeys x) { + + } + + @Override + public boolean visit(SQLAlterTableEnableKeys x) { + return true; + } + + @Override + public void endVisit(SQLAlterTableEnableKeys x) { + + } + + @Override + public boolean visit(SQLAlterTableStatement x) { + return true; + } + + @Override + public void endVisit(SQLAlterTableStatement x) { + + } } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitor.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitor.java index 68b042b97e..5c3d44d5b7 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitor.java @@ -17,17 +17,25 @@ package com.alibaba.druid.sql.visitor; import java.util.List; +import com.alibaba.druid.sql.visitor.functions.Function; + public interface SQLEvalVisitor extends SQLASTVisitor { - public static final String EVAL_VALUE = "eval.value"; + public static final String EVAL_VALUE = "eval.value"; + public static final String EVAL_EXPR = "eval.expr"; + public static final Object EVAL_ERROR = new Object(); + + Function getFunction(String funcName); + + void registerFunction(String funcName, Function function); List getParameters(); - + void setParameters(List parameters); int incrementAndGetVariantIndex(); - + boolean isMarkVariantIndex(); - + void setMarkVariantIndex(boolean markVariantIndex); } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorImpl.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorImpl.java index 576dbb1063..2ec6156c09 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorImpl.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorImpl.java @@ -16,11 +16,14 @@ package com.alibaba.druid.sql.visitor; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLCharExpr; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; @@ -28,14 +31,17 @@ import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; +import com.alibaba.druid.sql.visitor.functions.Function; public class SQLEvalVisitorImpl extends SQLASTVisitorAdapter implements SQLEvalVisitor { - private List parameters = new ArrayList(); + private List parameters = new ArrayList(); - private int variantIndex = -1; + private Map functions = new HashMap(); - private boolean markVariantIndex = true; + private int variantIndex = -1; + + private boolean markVariantIndex = true; public SQLEvalVisitorImpl(){ this(new ArrayList(1)); @@ -114,4 +120,17 @@ public class SQLEvalVisitorImpl extends SQLASTVisitorAdapter implements SQLEvalV this.markVariantIndex = markVariantIndex; } + @Override + public Function getFunction(String funcName) { + return functions.get(funcName); + } + + @Override + public void registerFunction(String funcName, Function function) { + functions.put(funcName, function); + } + + public boolean visit(SQLIdentifierExpr x) { + return SQLEvalVisitorUtils.visit(this, x); + } } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorUtils.java b/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorUtils.java index af79de83f7..0479024ef4 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorUtils.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SQLEvalVisitorUtils.java @@ -15,6 +15,7 @@ */ package com.alibaba.druid.sql.visitor; +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_EXPR; import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; import java.math.BigDecimal; @@ -24,6 +25,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; @@ -34,6 +36,7 @@ import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLObject; import com.alibaba.druid.sql.ast.expr.SQLBetweenExpr; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; +import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLCharExpr; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; @@ -42,6 +45,8 @@ import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumericLiteralExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; +import com.alibaba.druid.sql.ast.expr.SQLUnaryExpr; +import com.alibaba.druid.sql.ast.expr.SQLUnaryOperator; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLSelectItem; @@ -49,10 +54,42 @@ import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlEvalVisitorImpl; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleEvalVisitor; import com.alibaba.druid.sql.dialect.postgresql.visitor.PGEvalVisitor; +import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerEvalVisitor; +import com.alibaba.druid.sql.visitor.functions.Ascii; +import com.alibaba.druid.sql.visitor.functions.Bin; +import com.alibaba.druid.sql.visitor.functions.BitLength; +import com.alibaba.druid.sql.visitor.functions.Char; +import com.alibaba.druid.sql.visitor.functions.Concat; +import com.alibaba.druid.sql.visitor.functions.Elt; +import com.alibaba.druid.sql.visitor.functions.Function; +import com.alibaba.druid.sql.visitor.functions.Hex; +import com.alibaba.druid.sql.visitor.functions.Insert; +import com.alibaba.druid.sql.visitor.functions.Instr; +import com.alibaba.druid.sql.visitor.functions.Lcase; +import com.alibaba.druid.sql.visitor.functions.Left; +import com.alibaba.druid.sql.visitor.functions.Length; +import com.alibaba.druid.sql.visitor.functions.Locate; +import com.alibaba.druid.sql.visitor.functions.Lpad; +import com.alibaba.druid.sql.visitor.functions.Ltrim; +import com.alibaba.druid.sql.visitor.functions.Now; +import com.alibaba.druid.sql.visitor.functions.Reverse; +import com.alibaba.druid.sql.visitor.functions.Right; +import com.alibaba.druid.sql.visitor.functions.Substring; +import com.alibaba.druid.sql.visitor.functions.Trim; +import com.alibaba.druid.sql.visitor.functions.Ucase; +import com.alibaba.druid.sql.visitor.functions.Unhex; import com.alibaba.druid.util.JdbcUtils; +import com.alibaba.druid.wall.spi.WallVisitorUtils; +import com.alibaba.druid.wall.spi.WallVisitorUtils.WallConditionContext; public class SQLEvalVisitorUtils { + private static Map functions = new HashMap(); + + static { + registerBaseFunctions(); + } + public static Object evalExpr(String dbType, String expr, Object... parameters) { SQLExpr sqlExpr = SQLUtils.toSQLExpr(expr, dbType); return eval(dbType, sqlExpr, parameters); @@ -111,206 +148,60 @@ public class SQLEvalVisitorUtils { return new PGEvalVisitor(); } + if (JdbcUtils.SQL_SERVER.equals(dbType)) { + return new SQLServerEvalVisitor(); + } + return new SQLEvalVisitorImpl(); } + static void registerBaseFunctions() { + functions.put("now", Now.instance); + functions.put("concat", Concat.instance); + functions.put("concat_ws", Concat.instance); + functions.put("ascii", Ascii.instance); + functions.put("bin", Bin.instance); + functions.put("bit_length", BitLength.instance); + functions.put("insert", Insert.instance); + functions.put("instr", Instr.instance); + functions.put("char", Char.instance); + functions.put("elt", Elt.instance); + functions.put("left", Left.instance); + functions.put("locate", Locate.instance); + functions.put("lpad", Lpad.instance); + functions.put("ltrim", Ltrim.instance); + functions.put("mid", Substring.instance); + functions.put("substring", Substring.instance); + functions.put("right", Right.instance); + functions.put("reverse", Reverse.instance); + functions.put("len", Length.instance); + functions.put("length", Length.instance); + functions.put("char_length", Length.instance); + functions.put("character_length", Length.instance); + functions.put("trim", Trim.instance); + functions.put("ucase", Ucase.instance); + functions.put("upper", Ucase.instance); + functions.put("ucase", Lcase.instance); + functions.put("lower", Lcase.instance); + functions.put("hex", Hex.instance); + functions.put("unhex", Unhex.instance); + } + public static boolean visit(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { - if ("concat".equalsIgnoreCase(x.getMethodName())) { - StringBuilder buf = new StringBuilder(); + String methodName = x.getMethodName().toLowerCase(); - for (SQLExpr item : x.getParameters()) { - item.accept(visitor); + Function function = functions.get(methodName); - Object itemValue = item.getAttributes().get(EVAL_VALUE); - if (itemValue == null) { - continue; - } - buf.append(itemValue.toString()); + if (function != null) { + Object result = function.eval(visitor, x); + + if (result != SQLEvalVisitor.EVAL_ERROR) { + x.getAttributes().put(EVAL_VALUE, result); } + return false; + } - x.getAttributes().put(EVAL_VALUE, buf.toString()); - } else if ("now".equalsIgnoreCase(x.getMethodName())) { - x.getAttributes().put(EVAL_VALUE, new Date()); - } else if ("ascii".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() == 0) { - return false; - } - SQLExpr param = x.getParameters().get(0); - param.accept(visitor); - - Object paramValue = param.getAttributes().get(EVAL_VALUE); - if (paramValue == null) { - return false; - } - - String strValue = paramValue.toString(); - if (strValue.length() == 0) { - return false; - } - - int ascii = strValue.charAt(0); - x.getAttributes().put(EVAL_VALUE, ascii); - } else if ("instr".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 2) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - SQLExpr param1 = x.getParameters().get(1); - param0.accept(visitor); - param1.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - Object param1Value = param1.getAttributes().get(EVAL_VALUE); - if (param0Value == null || param1Value == null) { - return false; - } - - String strValue0 = param0Value.toString(); - String strValue1 = param1Value.toString(); - - int result = strValue0.indexOf(strValue1) + 1; - - x.putAttribute(EVAL_VALUE, result); - } else if ("left".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 2) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - SQLExpr param1 = x.getParameters().get(1); - param0.accept(visitor); - param1.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - Object param1Value = param1.getAttributes().get(EVAL_VALUE); - if (param0Value == null || param1Value == null) { - return false; - } - - String strValue = param0Value.toString(); - int intValue = castToInteger(param1Value); - - String result = strValue.substring(0, intValue); - - x.putAttribute(EVAL_VALUE, result); - } else if ("right".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 2) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - SQLExpr param1 = x.getParameters().get(1); - param0.accept(visitor); - param1.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - Object param1Value = param1.getAttributes().get(EVAL_VALUE); - if (param0Value == null || param1Value == null) { - return false; - } - - String strValue = param0Value.toString(); - int intValue = castToInteger(param1Value); - - String result = strValue.substring(strValue.length() - intValue, strValue.length()); - - x.putAttribute(EVAL_VALUE, result); - } else if ("reverse".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 1) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - param0.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - if (param0Value == null) { - return false; - } - - String strValue = param0Value.toString(); - - StringBuilder buf = new StringBuilder(); - for (int i = strValue.length() - 1; i >= 0; --i) { - buf.append(strValue.charAt(i)); - } - String result = buf.toString(); - - x.putAttribute(EVAL_VALUE, result); - } else if ("trim".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 1) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - param0.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - if (param0Value == null) { - return false; - } - - String strValue = param0Value.toString(); - String result = strValue.trim(); - - x.putAttribute(EVAL_VALUE, result); - } else if ("length".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 1) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - param0.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - if (param0Value == null) { - return false; - } - - String strValue = param0Value.toString(); - - int result = strValue.length(); - - x.putAttribute(EVAL_VALUE, result); - } else if ("ucase".equalsIgnoreCase(x.getMethodName()) || "upper".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 1) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - param0.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - if (param0Value == null) { - return false; - } - - String strValue = param0Value.toString(); - - String result = strValue.toUpperCase(); - - x.putAttribute(EVAL_VALUE, result); - } else if ("lcase".equalsIgnoreCase(x.getMethodName()) || "lower".equalsIgnoreCase(x.getMethodName())) { - if (x.getParameters().size() != 1) { - return false; - } - - SQLExpr param0 = x.getParameters().get(0); - param0.accept(visitor); - - Object param0Value = param0.getAttributes().get(EVAL_VALUE); - if (param0Value == null) { - return false; - } - - String strValue = param0Value.toString(); - - String result = strValue.toLowerCase(); - - x.putAttribute(EVAL_VALUE, result); - - } else if ("mod".equalsIgnoreCase(x.getMethodName())) { + if ("mod".equals(methodName)) { if (x.getParameters().size() != 2) { return false; } @@ -332,7 +223,7 @@ public class SQLEvalVisitorUtils { int result = intValue0 % intValue1; x.putAttribute(EVAL_VALUE, result); - } else if ("abs".equalsIgnoreCase(x.getMethodName())) { + } else if ("abs".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -355,7 +246,7 @@ public class SQLEvalVisitorUtils { } x.putAttribute(EVAL_VALUE, result); - } else if ("acos".equalsIgnoreCase(x.getMethodName())) { + } else if ("acos".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -376,7 +267,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("asin".equalsIgnoreCase(x.getMethodName())) { + } else if ("asin".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -397,7 +288,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("atan".equalsIgnoreCase(x.getMethodName())) { + } else if ("atan".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -418,7 +309,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("atan2".equalsIgnoreCase(x.getMethodName())) { + } else if ("atan2".equals(methodName)) { if (x.getParameters().size() != 2) { return false; } @@ -443,7 +334,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("ceil".equalsIgnoreCase(x.getMethodName()) || "ceiling".equalsIgnoreCase(x.getMethodName())) { + } else if ("ceil".equals(methodName) || "ceiling".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -464,7 +355,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("cos".equalsIgnoreCase(x.getMethodName())) { + } else if ("cos".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -485,7 +376,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("sin".equalsIgnoreCase(x.getMethodName())) { + } else if ("sin".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -506,7 +397,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("log".equalsIgnoreCase(x.getMethodName())) { + } else if ("log".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -527,7 +418,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("log10".equalsIgnoreCase(x.getMethodName())) { + } else if ("log10".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -548,7 +439,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("tan".equalsIgnoreCase(x.getMethodName())) { + } else if ("tan".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -569,7 +460,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("sqrt".equalsIgnoreCase(x.getMethodName())) { + } else if ("sqrt".equals(methodName)) { if (x.getParameters().size() != 1) { return false; } @@ -590,7 +481,7 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("power".equalsIgnoreCase(x.getMethodName())) { + } else if ("power".equals(methodName)) { if (x.getParameters().size() != 2) { return false; } @@ -615,10 +506,18 @@ public class SQLEvalVisitorUtils { } else { x.putAttribute(EVAL_VALUE, result); } - } else if ("pi".equalsIgnoreCase(x.getMethodName())) { + } else if ("pi".equals(methodName)) { x.putAttribute(EVAL_VALUE, Math.PI); - } else if ("rand".equalsIgnoreCase(x.getMethodName())) { + } else if ("rand".equals(methodName)) { x.putAttribute(EVAL_VALUE, Math.random()); + } else if ("chr".equals(methodName) && x.getParameters().size() == 1) { + SQLExpr first = x.getParameters().get(0); + Object firstResult = getValue(first); + if (firstResult instanceof Number) { + int intValue = ((Number) firstResult).intValue(); + char ch = (char) intValue; + x.putAttribute(EVAL_VALUE, Character.toString(ch)); + } } return false; } @@ -740,6 +639,11 @@ public class SQLEvalVisitorUtils { } public static boolean visit(SQLEvalVisitor visitor, SQLQueryExpr x) { + if (WallVisitorUtils.isSimpleCountTableSource(((SQLQueryExpr) x).getSubQuery())) { + x.putAttribute(EVAL_VALUE, 1); + return false; + } + if (x.getSubQuery().getQuery() instanceof SQLSelectQueryBlock) { SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) x.getSubQuery().getQuery(); @@ -778,93 +682,184 @@ public class SQLEvalVisitorUtils { return false; } + public static boolean visit(SQLEvalVisitor visitor, SQLUnaryExpr x) { + final WallConditionContext wallConditionContext = WallVisitorUtils.getWallConditionContext(); + if (x.getOperator() == SQLUnaryOperator.Compl && wallConditionContext != null) { + wallConditionContext.setBitwise(true); + } + + return false; + } + public static boolean visit(SQLEvalVisitor visitor, SQLBinaryOpExpr x) { SQLExpr left = x.getLeft(); SQLExpr right = x.getRight(); + // final WallConditionContext old = wallConditionContextLocal.get(); + left.accept(visitor); - if (!left.getAttributes().containsKey(EVAL_VALUE)) { + right.accept(visitor); + + final WallConditionContext wallConditionContext = WallVisitorUtils.getWallConditionContext(); + if (x.getOperator() == SQLBinaryOperator.BooleanOr) { + if (wallConditionContext != null) { + if (left.getAttribute(EVAL_VALUE) == Boolean.TRUE || right.getAttribute(EVAL_VALUE) == Boolean.TRUE) { + wallConditionContext.setPartAlwayTrue(true); + } + } + } else if (x.getOperator() == SQLBinaryOperator.BooleanXor) { + if (wallConditionContext != null) { + wallConditionContext.setXor(true); + } + } else if (x.getOperator() == SQLBinaryOperator.BitwiseAnd // + || x.getOperator() == SQLBinaryOperator.BitwiseNot // + || x.getOperator() == SQLBinaryOperator.BitwiseOr // + || x.getOperator() == SQLBinaryOperator.BitwiseXor) { + if (wallConditionContext != null) { + wallConditionContext.setBitwise(true); + } + } + + Object leftValue = left.getAttribute(EVAL_VALUE); + Object rightValue = right.getAttributes().get(EVAL_VALUE); + + if (x.getOperator() == SQLBinaryOperator.Like) { + if (isAlwayTrueLikePattern(x.getRight())) { + x.putAttribute(EVAL_VALUE, Boolean.TRUE); + return false; + } + } + + if (x.getOperator() == SQLBinaryOperator.NotLike) { + if (isAlwayTrueLikePattern(x)) { + x.putAttribute(EVAL_VALUE, Boolean.FALSE); + return false; + } + } + + boolean leftHasValue = left.getAttributes().containsKey(EVAL_VALUE); + boolean rightHasValue = right.getAttributes().containsKey(EVAL_VALUE); + + if ((!leftHasValue) && !rightHasValue) { + SQLExpr leftEvalExpr = (SQLExpr) left.getAttribute(EVAL_EXPR); + SQLExpr rightEvalExpr = (SQLExpr) right.getAttribute(EVAL_EXPR); + + if (leftEvalExpr != null && leftEvalExpr.equals(rightEvalExpr)) { + switch (x.getOperator()) { + case Like: + case Equality: + case GreaterThanOrEqual: + case LessThanOrEqual: + case NotLessThan: + case NotGreaterThan: + x.putAttribute(EVAL_VALUE, Boolean.TRUE); + return false; + case NotEqual: + case NotLike: + case GreaterThan: + case LessThan: + x.putAttribute(EVAL_VALUE, Boolean.FALSE); + return false; + default: + break; + } + } + } + + if (!leftHasValue) { return false; } - right.accept(visitor); - if (!right.getAttributes().containsKey(EVAL_VALUE)) { + if (!rightHasValue) { return false; } + if (wallConditionContext != null) { + wallConditionContext.setConstArithmetic(true); + } + Object value = null; switch (x.getOperator()) { case Add: - value = add(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = add(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case Subtract: - value = sub(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = sub(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case Multiply: - value = multi(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = multi(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case Divide: - value = div(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = div(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case GreaterThan: - value = gt(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = gt(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case GreaterThanOrEqual: - value = gteq(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = gteq(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case LessThan: - value = lt(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = lt(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case LessThanOrEqual: - value = lteq(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = lteq(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case Is: case Equality: - value = eq(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = eq(leftValue, rightValue); + x.putAttribute(EVAL_VALUE, value); + break; + case NotEqual: + value = !eq(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case IsNot: - value = !eq(left.getAttribute(EVAL_VALUE), right.getAttributes().get(EVAL_VALUE)); + value = !eq(leftValue, rightValue); x.putAttribute(EVAL_VALUE, value); break; case RegExp: case RLike: { - String pattern = castToString(right.getAttributes().get(EVAL_VALUE)); + String pattern = castToString(rightValue); String input = castToString(left.getAttributes().get(EVAL_VALUE)); boolean matchResult = Pattern.matches(pattern, input); x.putAttribute(EVAL_VALUE, matchResult); - } break; + } case NotRegExp: case NotRLike: { - String pattern = castToString(right.getAttributes().get(EVAL_VALUE)); + String pattern = castToString(rightValue); String input = castToString(left.getAttributes().get(EVAL_VALUE)); boolean matchResult = !Pattern.matches(pattern, input); x.putAttribute(EVAL_VALUE, matchResult); + break; } - break; case Like: { - String pattern = castToString(right.getAttributes().get(EVAL_VALUE)); + String pattern = castToString(rightValue); String input = castToString(left.getAttributes().get(EVAL_VALUE)); boolean matchResult = like(input, pattern); x.putAttribute(EVAL_VALUE, matchResult); - } break; + } case NotLike: { - String pattern = castToString(right.getAttributes().get(EVAL_VALUE)); + String pattern = castToString(rightValue); String input = castToString(left.getAttributes().get(EVAL_VALUE)); boolean matchResult = !like(input, pattern); x.putAttribute(EVAL_VALUE, matchResult); - } break; + } + case Concat: { + String result = leftValue.toString() + rightValue.toString(); + x.putAttribute(EVAL_VALUE, result); + break; + } default: break; } @@ -872,6 +867,22 @@ public class SQLEvalVisitorUtils { return false; } + private static boolean isAlwayTrueLikePattern(SQLExpr x) { + if (x instanceof SQLCharExpr) { + String text = ((SQLCharExpr) x).getText(); + + if (text.length() >= 0) { + for (char ch : text.toCharArray()) { + if (ch != '%') { + return false; + } + } + return true; + } + } + return false; + } + public static boolean visit(SQLEvalVisitor visitor, SQLNumericLiteralExpr x) { x.getAttributes().put(EVAL_VALUE, x.getNumber()); return false; @@ -1519,4 +1530,8 @@ public class SQLEvalVisitorUtils { return Pattern.matches(regexpr, input); } + public static boolean visit(SQLEvalVisitor visitor, SQLIdentifierExpr x) { + x.putAttribute(EVAL_EXPR, x); + return false; + } } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/SchemaStatVisitor.java b/src/main/java/com/alibaba/druid/sql/visitor/SchemaStatVisitor.java index 0c77bcb481..27b1c75426 100644 --- a/src/main/java/com/alibaba/druid/sql/visitor/SchemaStatVisitor.java +++ b/src/main/java/com/alibaba/druid/sql/visitor/SchemaStatVisitor.java @@ -39,11 +39,13 @@ import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.statement.SQLAlterTableAddColumn; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableDropForeinKey; import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; import com.alibaba.druid.sql.ast.statement.SQLCallStatement; import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition; import com.alibaba.druid.sql.ast.statement.SQLCommentStatement; import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement; import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; @@ -60,6 +62,7 @@ import com.alibaba.druid.sql.ast.statement.SQLSubqueryTableSource; import com.alibaba.druid.sql.ast.statement.SQLTableElement; import com.alibaba.druid.sql.ast.statement.SQLTruncateStatement; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; +import com.alibaba.druid.sql.ast.statement.SQLUseStatement; import com.alibaba.druid.stat.TableStat; import com.alibaba.druid.stat.TableStat.Column; import com.alibaba.druid.stat.TableStat.Condition; @@ -153,11 +156,11 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter { if (flag0) { ident = ident.replaceAll("\"", ""); } - + if (flag1) { ident = ident.replaceAll("`", ""); } - + if (flag2) { ident = ident.replaceAll(" ", ""); } @@ -560,6 +563,10 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter { } public boolean visit(SQLSelectQueryBlock x) { + if (x.getFrom() == null) { + return false; + } + setMode(x, Mode.Select); if (x.getFrom() instanceof SQLSubqueryTableSource) { @@ -622,7 +629,12 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter { } public boolean visit(SQLJoinTableSource x) { - return true; + x.getLeft().accept(this); + x.getRight().accept(this); + if (x.getCondition() != null) { + x.getCondition().accept(this); + } + return false; } public boolean visit(SQLPropertyExpr x) { @@ -807,6 +819,9 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter { case Merge: stat.incrementMergeCount(); break; + case Drop: + stat.incrementDropCount(); + break; default: break; } @@ -870,14 +885,21 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter { public boolean visit(SQLUpdateStatement x) { setAliasMap(); - String ident = x.getTableName().toString(); - setCurrentTable(ident); + setMode(x, Mode.Update); - TableStat stat = getTableStat(ident); - stat.incrementUpdateCount(); + SQLName identName = x.getTableName(); + if (identName != null) { + String ident = identName.toString(); + setCurrentTable(ident); - Map aliasMap = getAliasMap(); - aliasMap.put(ident, ident); + TableStat stat = getTableStat(ident); + stat.incrementUpdateCount(); + + Map aliasMap = getAliasMap(); + aliasMap.put(ident, ident); + } else { + x.getTableSource().accept(this); + } accept(x.getItems()); accept(x.getWhere()); @@ -1004,9 +1026,24 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter { public void endVisit(SQLAlterTableAddColumn x) { } - + @Override public boolean visit(SQLRollbackStatement x) { return false; } + + public boolean visit(SQLCreateViewStatement x) { + x.getSubQuery().accept(this); + return false; + } + + @Override + public boolean visit(SQLAlterTableDropForeinKey x) { + return false; + } + + @Override + public boolean visit(SQLUseStatement x) { + return false; + } } diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Ascii.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Ascii.java new file mode 100644 index 0000000000..5423220687 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Ascii.java @@ -0,0 +1,48 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Ascii implements Function { + + public final static Ascii instance = new Ascii(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() == 0) { + return SQLEvalVisitor.EVAL_ERROR; + } + SQLExpr param = x.getParameters().get(0); + param.accept(visitor); + + Object paramValue = param.getAttributes().get(EVAL_VALUE); + if (paramValue == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = paramValue.toString(); + if (strValue.length() == 0) { + return SQLEvalVisitor.EVAL_ERROR; + } + + int ascii = strValue.charAt(0); + return ascii; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Bin.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Bin.java new file mode 100644 index 0000000000..2de0d0f45c --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Bin.java @@ -0,0 +1,48 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Bin implements Function { + + public final static Bin instance = new Bin(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + if (param0Value instanceof Number) { + long longValue = ((Number) param0Value).longValue(); + String result = Long.toString(longValue, 2); + return result; + } + return SQLEvalVisitor.EVAL_ERROR; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/BitLength.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/BitLength.java new file mode 100644 index 0000000000..28f254a21d --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/BitLength.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class BitLength implements Function { + + public final static BitLength instance = new BitLength(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + if (param0Value instanceof String) { + return ((String) param0Value).getBytes().length * 8; + } + return SQLEvalVisitor.EVAL_ERROR; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Char.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Char.java new file mode 100644 index 0000000000..27f9146982 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Char.java @@ -0,0 +1,54 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import java.math.BigDecimal; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Char implements Function { + + public final static Char instance = new Char(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() == 0) { + return SQLEvalVisitor.EVAL_ERROR; + } + + StringBuffer buf = new StringBuffer(x.getParameters().size()); + for (SQLExpr param : x.getParameters()) { + param.accept(visitor); + + Object paramValue = param.getAttributes().get(EVAL_VALUE); + + if (paramValue instanceof Number) { + int charCode = ((Number) paramValue).intValue(); + buf.append((char) charCode); + } else if (paramValue instanceof String) { + int charCode = new BigDecimal((String)paramValue).intValue(); + buf.append((char) charCode); + } else { + return SQLEvalVisitor.EVAL_ERROR; + } + } + + return buf.toString(); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Concat.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Concat.java new file mode 100644 index 0000000000..57aa04f7e7 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Concat.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Concat implements Function { + + public final static Concat instance = new Concat(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + StringBuilder buf = new StringBuilder(); + + for (SQLExpr item : x.getParameters()) { + item.accept(visitor); + + Object itemValue = item.getAttributes().get(EVAL_VALUE); + if (itemValue == null) { + continue; + } + buf.append(itemValue.toString()); + } + + return buf.toString(); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Elt.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Elt.java new file mode 100644 index 0000000000..3a354f497f --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Elt.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Elt implements Function { + + public final static Elt instance = new Elt(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() <= 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + int param0IntValue; + if (!(param0Value instanceof Number)) { + return SQLEvalVisitor.EVAL_ERROR; + } + param0IntValue = ((Number) param0Value).intValue(); + + if (param0IntValue >= x.getParameters().size()) { + return null; + } + + SQLExpr item = x.getParameters().get(param0IntValue); + item.accept(visitor); + + Object itemValue = item.getAttributes().get(EVAL_VALUE); + return itemValue; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Function.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Function.java new file mode 100644 index 0000000000..001ddf2edc --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Function.java @@ -0,0 +1,24 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public interface Function { + Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x); +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Hex.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Hex.java new file mode 100644 index 0000000000..4a2bfa9985 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Hex.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.parser.ParserException; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; +import com.alibaba.druid.util.HexBin; + +public class Hex implements Function { + + public final static Hex instance = new Hex(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + throw new ParserException("argument's != 1, " + x.getParameters().size()); + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + if (param0Value instanceof String) { + byte[] bytes = ((String) param0Value).getBytes(); + String result = HexBin.encode(bytes); + return result; + } + + if (param0Value instanceof Number) { + long value = ((Number) param0Value).longValue(); + String result = Long.toHexString(value).toUpperCase(); + return result; + } + + return SQLEvalVisitor.EVAL_ERROR; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Insert.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Insert.java new file mode 100644 index 0000000000..c2e9321bb7 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Insert.java @@ -0,0 +1,83 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Insert implements Function { + + public final static Insert instance = new Insert(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 4) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + SQLExpr param1 = x.getParameters().get(1); + SQLExpr param2 = x.getParameters().get(2); + SQLExpr param3 = x.getParameters().get(3); + param0.accept(visitor); + param1.accept(visitor); + param2.accept(visitor); + param3.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + Object param2Value = param2.getAttributes().get(EVAL_VALUE); + Object param3Value = param3.getAttributes().get(EVAL_VALUE); + + if (!(param0Value instanceof String)) { + return SQLEvalVisitor.EVAL_ERROR; + } + if (!(param1Value instanceof Number)) { + return SQLEvalVisitor.EVAL_ERROR; + } + if (!(param2Value instanceof Number)) { + return SQLEvalVisitor.EVAL_ERROR; + } + if (!(param3Value instanceof String)) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String str = (String) param0Value; + int pos = ((Number) param1Value).intValue(); + int len = ((Number) param2Value).intValue(); + String newstr = (String) param3Value; + + if (pos <= 0) { + return str; + } + + if (pos == 1) { + if (len > str.length()) { + return newstr; + } + return newstr + str.substring(len); + } + + String first = str.substring(0, pos - 1); + if (pos + len - 1 > str.length()) { + return first + newstr; + } + + return first + newstr + str.substring(pos + len - 1); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Instr.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Instr.java new file mode 100644 index 0000000000..45a58f5cc2 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Instr.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public class Instr implements Function { + public final static Instr instance = new Instr(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 2) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + SQLExpr param1 = x.getParameters().get(1); + param0.accept(visitor); + param1.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + if (param0Value == null || param1Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue0 = param0Value.toString(); + String strValue1 = param1Value.toString(); + + int result = strValue0.indexOf(strValue1) + 1; + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Lcase.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Lcase.java new file mode 100644 index 0000000000..71256e3ad6 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Lcase.java @@ -0,0 +1,47 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public class Lcase implements Function { + public final static Lcase instance = new Lcase(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + + String result = strValue.toLowerCase(); + + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Left.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Left.java new file mode 100644 index 0000000000..5f117ddcf2 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Left.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; + +public class Left implements Function { + + public final static Left instance = new Left(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 2) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + SQLExpr param1 = x.getParameters().get(1); + param0.accept(visitor); + param1.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + if (param0Value == null || param1Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + int intValue = SQLEvalVisitorUtils.castToInteger(param1Value); + + String result = strValue.substring(0, intValue); + + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Length.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Length.java new file mode 100644 index 0000000000..5def41c8c2 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Length.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public class Length implements Function { + public final static Length instance = new Length(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + + int result = strValue.length(); + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Locate.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Locate.java new file mode 100644 index 0000000000..605a1eb184 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Locate.java @@ -0,0 +1,68 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import java.util.List; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Locate implements Function { + + public final static Locate instance = new Locate(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + List params = x.getParameters(); + int paramSize = params.size(); + if (paramSize != 2 && paramSize != 3) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = params.get(0); + SQLExpr param1 = params.get(1); + SQLExpr param2 = null; + + param0.accept(visitor); + param1.accept(visitor); + if (paramSize == 3) { + param2 = params.get(2); + param2.accept(visitor); + } + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + if (param0Value == null || param1Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue0 = param0Value.toString(); + String strValue1 = param1Value.toString(); + + if (paramSize == 2) { + int result = strValue1.indexOf(strValue0) + 1; + return result; + } + + Object param2Value = param2.getAttributes().get(EVAL_VALUE); + int start = ((Number) param2Value).intValue(); + + int result = strValue1.indexOf(strValue0, start + 1) + 1; + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Lpad.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Lpad.java new file mode 100644 index 0000000000..d0e8d1372b --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Lpad.java @@ -0,0 +1,67 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import java.util.List; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Lpad implements Function { + + public final static Lpad instance = new Lpad(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + List params = x.getParameters(); + int paramSize = params.size(); + if (paramSize != 3) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = params.get(0); + SQLExpr param1 = params.get(1); + SQLExpr param2 = params.get(2); + + param0.accept(visitor); + param1.accept(visitor); + param2.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + Object param2Value = param2.getAttributes().get(EVAL_VALUE); + if (param0Value == null || param1Value == null || param2Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue0 = param0Value.toString(); + int len = ((Number) param1Value).intValue(); + String strValue1 = param2Value.toString(); + + String result = strValue0; + if (result.length() > len) { + return result.substring(0, len); + } + + while (result.length() < len) { + result = strValue1 + result; + } + + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Ltrim.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Ltrim.java new file mode 100644 index 0000000000..40502441fa --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Ltrim.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Ltrim implements Function { + + public final static Ltrim instance = new Ltrim(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + + int index = -1; + for (int i = 0; i < strValue.length(); ++i) { + if (!Character.isWhitespace(strValue.charAt(i))) { + index = i; + break; + } + } + + if (index <= 0) { + return strValue; + } else { + return strValue.substring(index); + } + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Now.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Now.java new file mode 100644 index 0000000000..8df567540e --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Now.java @@ -0,0 +1,30 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import java.util.Date; + +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public class Now implements Function { + public final static Now instance = new Now(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + return new Date(); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Reverse.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Reverse.java new file mode 100644 index 0000000000..e72db58cb6 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Reverse.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public class Reverse implements Function { + public final static Reverse instance = new Reverse(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + + StringBuilder buf = new StringBuilder(); + for (int i = strValue.length() - 1; i >= 0; --i) { + buf.append(strValue.charAt(i)); + } + String result = buf.toString(); + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Right.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Right.java new file mode 100644 index 0000000000..718d554d3f --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Right.java @@ -0,0 +1,51 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; + + +public class Right implements Function { + public final static Right instance = new Right(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 2) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + SQLExpr param1 = x.getParameters().get(1); + param0.accept(visitor); + param1.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + if (param0Value == null || param1Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + int intValue = SQLEvalVisitorUtils.castToInteger(param1Value); + + String result = strValue.substring(strValue.length() - intValue, strValue.length()); + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Substring.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Substring.java new file mode 100644 index 0000000000..4ade056894 --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Substring.java @@ -0,0 +1,80 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import java.util.List; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Substring implements Function { + + public final static Substring instance = new Substring(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + List params = x.getParameters(); + int paramSize = params.size(); + if (paramSize != 2 && paramSize != 3) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = params.get(0); + SQLExpr param1 = params.get(1); + param0.accept(visitor); + param1.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + Object param1Value = param1.getAttributes().get(EVAL_VALUE); + if (param0Value == null || param1Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String str = param0Value.toString(); + int index = ((Number) param1Value).intValue(); + + if (paramSize == 2) { + + if (index < 0) { + int lastIndex = str.length() + index ; + return str.substring(lastIndex); + } + + return str.substring(index - 1); + } + + SQLExpr param2 = params.get(2); + param2.accept(visitor); + Object param2Value = param2.getAttributes().get(EVAL_VALUE); + if (param2Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + int len = ((Number) param2Value).intValue(); + + String result; + if (index < 0) { + int lastIndex = str.length() + index ; + result = str.substring(lastIndex); + } else { + result = str.substring(index - 1); + } + + return result.substring(0, len); + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Trim.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Trim.java new file mode 100644 index 0000000000..1bf16ba88f --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Trim.java @@ -0,0 +1,45 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + +public class Trim implements Function { + + public final static Trim instance = new Trim(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + String result = strValue.trim(); + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Ucase.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Ucase.java new file mode 100644 index 0000000000..48b18d6eca --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Ucase.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; + + +public class Ucase implements Function { + public final static Ucase instance = new Ucase(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + String strValue = param0Value.toString(); + + String result = strValue.toUpperCase(); + return result; + } +} diff --git a/src/main/java/com/alibaba/druid/sql/visitor/functions/Unhex.java b/src/main/java/com/alibaba/druid/sql/visitor/functions/Unhex.java new file mode 100644 index 0000000000..1b634108de --- /dev/null +++ b/src/main/java/com/alibaba/druid/sql/visitor/functions/Unhex.java @@ -0,0 +1,75 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.sql.visitor.functions; + +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_EXPR; +import static com.alibaba.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE; + +import java.io.UnsupportedEncodingException; + +import com.alibaba.druid.sql.ast.SQLExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.visitor.SQLEvalVisitor; +import com.alibaba.druid.util.HexBin; + +public class Unhex implements Function { + + public final static Unhex instance = new Unhex(); + + public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { + if (x.getParameters().size() != 1) { + return SQLEvalVisitor.EVAL_ERROR; + } + + SQLExpr param0 = x.getParameters().get(0); + + if (param0 instanceof SQLMethodInvokeExpr) { + SQLMethodInvokeExpr paramMethodExpr = (SQLMethodInvokeExpr) param0; + if (paramMethodExpr.getMethodName().equalsIgnoreCase("hex")) { + SQLExpr subParamExpr = paramMethodExpr.getParameters().get(0); + subParamExpr.accept(visitor); + + Object param0Value = subParamExpr.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + x.putAttribute(EVAL_EXPR, subParamExpr); + return SQLEvalVisitor.EVAL_ERROR; + } + + return param0Value; + } + } + + param0.accept(visitor); + + Object param0Value = param0.getAttributes().get(EVAL_VALUE); + if (param0Value == null) { + return SQLEvalVisitor.EVAL_ERROR; + } + + if (param0Value instanceof String) { + byte[] bytes = HexBin.decode((String) param0Value); + String result; + try { + result = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e.getMessage(), e); + } + return result; + } + + return SQLEvalVisitor.EVAL_ERROR; + } +} diff --git a/src/main/java/com/alibaba/druid/stat/DruidStatManagerFacade.java b/src/main/java/com/alibaba/druid/stat/DruidStatManagerFacade.java index 671cd68690..11dc85cd5c 100644 --- a/src/main/java/com/alibaba/druid/stat/DruidStatManagerFacade.java +++ b/src/main/java/com/alibaba/druid/stat/DruidStatManagerFacade.java @@ -21,6 +21,7 @@ import java.sql.DriverManager; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -135,17 +136,17 @@ public final class DruidStatManagerFacade { public List> getSqlStatDataList(Integer dataSourceId) { Set dataSources = getDruidDataSourceInstances(); - + if (dataSourceId == null) { List> sqlList = new ArrayList>(); - + for (Object datasource : dataSources) { sqlList.addAll(getSqlStatDataList(datasource)); } - + return sqlList; } - + for (Object datasource : dataSources) { if (dataSourceId != null && dataSourceId.intValue() != System.identityHashCode(datasource)) { continue; @@ -157,6 +158,62 @@ public final class DruidStatManagerFacade { return new ArrayList>(); } + @SuppressWarnings("unchecked") + public Map getWallStatMap(Integer dataSourceId) { + Set dataSources = getDruidDataSourceInstances(); + + if (dataSourceId == null) { + Map map = new HashMap(); + + for (Object datasource : dataSources) { + Map wallStat = DruidDataSourceUtils.getWallStatMap(datasource); + map = mergWallStat(map, wallStat); + } + + return map; + } + + for (Object datasource : dataSources) { + if (dataSourceId != null && dataSourceId.intValue() != System.identityHashCode(datasource)) { + continue; + } + + return DruidDataSourceUtils.getWallStatMap(datasource); + } + + return new HashMap(); + // + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + static Map mergWallStat(Map mapA, Map mapB) { + if (mapA.size() == 0) { + return mapB; + } + + if (mapB.size() == 0) { + return mapA; + } + + for (Object item : mapB.entrySet()) { + Map.Entry entry = (Map.Entry) item; + String key = (String) entry.getKey(); + Object valueB = entry.getValue(); + Object valueA = mapA.get(key); + + if (valueA == null) { + mapA.put(key, valueB); + } else { + if (valueA instanceof Map && valueB instanceof Map) { + Object newValue = mergWallStat((Map)valueA, (Map)valueB); + mapA.put(key, newValue); + } + } + } + + return null; + } + public List> getSqlStatDataList(Object datasource) { List> result = new ArrayList>(); Map sqlStatMap = DruidDataSourceUtils.getSqlStatMap(datasource); diff --git a/src/main/java/com/alibaba/druid/stat/DruidStatService.java b/src/main/java/com/alibaba/druid/stat/DruidStatService.java index 1b510e0804..2ba4e17196 100644 --- a/src/main/java/com/alibaba/druid/stat/DruidStatService.java +++ b/src/main/java/com/alibaba/druid/stat/DruidStatService.java @@ -256,6 +256,17 @@ public final class DruidStatService implements DruidStatServiceMBean { List> sortedArray = comparatorOrderBy(array, parameters); return sortedArray; } + + public Map getWallStatMap(Map parameters) { + Integer dataSourceId = null; + + String dataSourceIdParam = parameters.get("dataSourceId"); + if (dataSourceIdParam != null && dataSourceIdParam.length() > 0) { + dataSourceId = Integer.parseInt(dataSourceIdParam); + } + + return statManagerFacade.getWallStatMap(dataSourceId); + } private String getSqlStat(Integer id) { Map map = statManagerFacade.getSqlStatData(id); @@ -299,7 +310,7 @@ public final class DruidStatService implements DruidStatServiceMBean { return returnJSONResult(RESULT_CODE_SUCCESS, result); } - private String returnJSONResult(int resultCode, Object content) { + public static String returnJSONResult(int resultCode, Object content) { Map dataMap = new LinkedHashMap(); dataMap.put("ResultCode", resultCode); dataMap.put("Content", content); diff --git a/src/main/java/com/alibaba/druid/stat/TableStat.java b/src/main/java/com/alibaba/druid/stat/TableStat.java index 1eab9866ee..f52d0f06ef 100644 --- a/src/main/java/com/alibaba/druid/stat/TableStat.java +++ b/src/main/java/com/alibaba/druid/stat/TableStat.java @@ -445,7 +445,14 @@ public class TableStat { } public static enum Mode { - Insert(1), Update(2), Delete(4), Select(8), Merge(16), Truncate(32); + Insert(1), // + Update(2), // + Delete(4), // + Select(8), // + Merge(16), // + Truncate(32), // + Alter(64), // + Drop(128); public final int mark; diff --git a/src/main/java/com/alibaba/druid/support/console/DruidStat.java b/src/main/java/com/alibaba/druid/support/console/DruidStat.java index 8bf4375617..5718366ee7 100644 --- a/src/main/java/com/alibaba/druid/support/console/DruidStat.java +++ b/src/main/java/com/alibaba/druid/support/console/DruidStat.java @@ -15,10 +15,10 @@ */ package com.alibaba.druid.support.console; -import java.io.PrintStream; -import java.util.ArrayList; import java.io.File; import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; diff --git a/src/main/java/com/alibaba/druid/support/http/StatViewServlet.java b/src/main/java/com/alibaba/druid/support/http/StatViewServlet.java index 69b0a490ed..cd503d48da 100644 --- a/src/main/java/com/alibaba/druid/support/http/StatViewServlet.java +++ b/src/main/java/com/alibaba/druid/support/http/StatViewServlet.java @@ -17,8 +17,15 @@ package com.alibaba.druid.support.http; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import javax.management.MBeanServerConnection; +import javax.management.ObjectName; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -40,31 +47,43 @@ import com.alibaba.druid.util.StringUtils; */ public class StatViewServlet extends HttpServlet { - private final static Log LOG = LogFactory.getLog(StatViewServlet.class); + private final static Log LOG = LogFactory.getLog(StatViewServlet.class); - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public static final String PARAM_NAME_RESET_ENABLE = "resetEnable"; - public static final String PARAM_NAME_ALLOW = "allow"; - public static final String PARAM_NAME_DENY = "deny"; + public static final String PARAM_NAME_RESET_ENABLE = "resetEnable"; + public static final String PARAM_NAME_ALLOW = "allow"; + public static final String PARAM_NAME_DENY = "deny"; - public static final String PARAM_NAME_USERNAME = "loginUsername"; - public static final String PARAM_NAME_PASSWORD = "loginPassword"; + public static final String PARAM_NAME_USERNAME = "loginUsername"; + public static final String PARAM_NAME_PASSWORD = "loginPassword"; - public static final String SESSION_USER_KEY = "druid-user"; + public static final String PARAM_NAME_JMX_URL = "jmxUrl"; + public static final String PARAM_NAME_JMX_USERNAME = "jmxUsername"; + public static final String PARAM_NAME_JMX_PASSWORD = "jmxPassword"; - private final static String RESOURCE_PATH = "support/http/resources"; - private final static String TEMPLATE_PAGE_RESOURCE_PATH = RESOURCE_PATH + "/template.html"; + public static final String SESSION_USER_KEY = "druid-user"; - private DruidStatService statService = DruidStatService.getInstance(); + private final static String RESOURCE_PATH = "support/http/resources"; + private final static String TEMPLATE_PAGE_RESOURCE_PATH = RESOURCE_PATH + "/template.html"; - public String templatePage; + private DruidStatService statService = DruidStatService.getInstance(); - private List allowList = new ArrayList(); - private List denyList = new ArrayList(); + public String templatePage; - private String username = null; - private String password = null; + private List allowList = new ArrayList(); + private List denyList = new ArrayList(); + + private String username = null; + private String password = null; + + /** web.xml中配置的jmx的连接地址 */ + private String jmxUrl = null; + /** web.xml中配置的jmx的用户名 */ + private String jmxUsername = null; + /** web.xml中配置的jmx的密码 */ + private String jmxPassword = null; + private MBeanServerConnection conn = null; public void init() throws ServletException { initAuthEnv(); @@ -127,6 +146,120 @@ public class StatViewServlet extends HttpServlet { String msg = "initParameter config error, deny : " + getInitParameter(PARAM_NAME_DENY); LOG.error(msg, e); } + + // 获取jmx的连接配置信息 + String param = readInitParam(PARAM_NAME_JMX_URL); + if (param != null) { + jmxUrl = param; + jmxUsername = readInitParam(PARAM_NAME_JMX_USERNAME); + jmxPassword = readInitParam(PARAM_NAME_JMX_PASSWORD); + try { + initJmxConn(); + } catch (IOException e) { + LOG.error("init jmx connection error", e); + } + } + + } + + /** + * 读取servlet中的配置参数. + * + * @param key 配置参数名 + * @return 配置参数值,如果不存在当前配置参数,或者为配置参数长度为0,将返回null + */ + private String readInitParam(String key) { + String value = null; + try { + String param = getInitParameter(key); + if (param != null) { + param = param.trim(); + if (param.length() > 0) { + value = param; + } + } + } catch (Exception e) { + String msg = "initParameter config [" + key + "] error"; + LOG.warn(msg, e); + } + return value; + } + + /** + * 初始化jmx连接 + * + * @throws IOException + */ + private void initJmxConn() throws IOException { + if (jmxUrl != null) { + JMXServiceURL url = new JMXServiceURL(jmxUrl); + Map env = null; + if (jmxUsername != null) { + env = new HashMap(); + String[] credentials = new String[] { jmxUsername, jmxPassword }; + env.put(JMXConnector.CREDENTIALS, credentials); + } + JMXConnector jmxc = JMXConnectorFactory.connect(url, env); + conn = jmxc.getMBeanServerConnection(); + } + } + + /** + * 根据指定的url来获取jmx服务返回的内容. + * + * @param connetion jmx连接 + * @param url url内容 + * @return the jmx返回的内容 + * @throws Exception the exception + */ + private String getJmxResult(MBeanServerConnection connetion, String url) throws Exception { + ObjectName name = new ObjectName(DruidStatService.MBEAN_NAME); + + String result = (String) conn.invoke(name, "service", new String[] { url }, + new String[] { String.class.getName() }); + return result; + } + + /** + * 程序首先判断是否存在jmx连接地址,如果不存在,则直接调用本地的duird服务; 如果存在,则调用远程jmx服务。在进行jmx通信,首先判断一下jmx连接是否已经建立成功,如果已经 + * 建立成功,则直接进行通信,如果之前没有成功建立,则会尝试重新建立一遍。. + * + * @param url 要连接的服务地址 + * @return 调用服务后返回的json字符串 + */ + private String genServiceResponse(String url) { + String resp = null; + if (jmxUrl == null) { + resp = statService.service(url); + } else { + if (conn == null) {// 连接在初始化时创建失败 + try {// 尝试重新连接 + initJmxConn(); + } catch (IOException e) { + LOG.error("init jmx connection error", e); + resp = DruidStatService.returnJSONResult(DruidStatService.RESULT_CODE_ERROR, + "init jmx connection error" + e.getMessage()); + } + if (conn != null) {// 连接成功 + try { + resp = getJmxResult(conn, url); + } catch (Exception e) { + LOG.error("get jmx data error", e); + resp = DruidStatService.returnJSONResult(DruidStatService.RESULT_CODE_ERROR, "get data error:" + + e.getMessage()); + } + } + } else {// 连接成功 + try { + resp = getJmxResult(conn, url); + } catch (Exception e) { + LOG.error("get jmx data error", e); + resp = DruidStatService.returnJSONResult(DruidStatService.RESULT_CODE_ERROR, + "get data error" + e.getMessage()); + } + } + } + return resp; } private void initAuthEnv() { @@ -242,7 +375,7 @@ public class StatViewServlet extends HttpServlet { if (request.getQueryString() != null && request.getQueryString().length() > 0) { fullUrl += "?" + request.getQueryString(); } - response.getWriter().print(statService.service(fullUrl)); + response.getWriter().print(genServiceResponse(fullUrl)); return; } @@ -257,7 +390,7 @@ public class StatViewServlet extends HttpServlet { if (bytes != null) { response.getOutputStream().write(bytes); } - + return; } diff --git a/src/main/java/com/alibaba/druid/util/DruidDataSourceUtils.java b/src/main/java/com/alibaba/druid/util/DruidDataSourceUtils.java index fd9a5cceba..b0b27fc6a0 100644 --- a/src/main/java/com/alibaba/druid/util/DruidDataSourceUtils.java +++ b/src/main/java/com/alibaba/druid/util/DruidDataSourceUtils.java @@ -167,6 +167,22 @@ public class DruidDataSourceUtils { } } + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static Map getWallStatMap(Object druidDatasource) { + if (druidDatasource.getClass() == DruidDataSource.class) { + return ((DruidDataSource) druidDatasource).getWallStatMap(); + } + + try { + Method method = druidDatasource.getClass().getMethod("getWallStatMap"); + Object obj = method.invoke(druidDatasource); + return (Map) obj; + } catch (Exception e) { + LOG.error("getWallStatMap error", e); + return null; + } + } + @SuppressWarnings("unchecked") public static List> getPoolingConnectionInfo(Object druidDatasource) { if (druidDatasource.getClass() == DruidDataSource.class) { diff --git a/src/main/java/com/alibaba/druid/util/JdbcUtils.java b/src/main/java/com/alibaba/druid/util/JdbcUtils.java index 8aa458ae1d..e8c9ecbea7 100644 --- a/src/main/java/com/alibaba/druid/util/JdbcUtils.java +++ b/src/main/java/com/alibaba/druid/util/JdbcUtils.java @@ -47,11 +47,9 @@ import com.alibaba.druid.support.logging.LogFactory; */ public final class JdbcUtils implements JdbcConstants { - + private final static Log LOG = LogFactory.getLog(JdbcUtils.class); - private final static Log LOG = LogFactory.getLog(JdbcUtils.class); - - private static final Properties driverUrlMapping = new Properties(); + private static final Properties driverUrlMapping = new Properties(); static { try { @@ -213,13 +211,21 @@ public final class JdbcUtils implements JdbcConstants { } else { out.print(String.valueOf(objec)); } + } else if (type == Types.NULL) { + out.print("null"); } else { Object objec = rs.getObject(columnIndex); if (rs.wasNull()) { out.print("null"); } else { - out.print(String.valueOf(objec)); + if (objec instanceof byte[]) { + byte[] bytes = (byte[]) objec; + String text = HexBin.encode(bytes); + out.print(text); + } else { + out.print(String.valueOf(objec)); + } } } } @@ -462,7 +468,7 @@ public final class JdbcUtils implements JdbcConstants { return null; } } - + public static Driver createDriver(String driverClassName) throws SQLException { return createDriver(null, driverClassName); } @@ -479,7 +485,7 @@ public final class JdbcUtils implements JdbcConstants { throw new SQLException(e.getMessage(), e); } } - + try { return (Driver) Class.forName(driverClassName).newInstance(); } catch (IllegalAccessException e) { diff --git a/src/main/java/com/alibaba/druid/wall/Violation.java b/src/main/java/com/alibaba/druid/wall/Violation.java index ba82ab4407..07cd139589 100644 --- a/src/main/java/com/alibaba/druid/wall/Violation.java +++ b/src/main/java/com/alibaba/druid/wall/Violation.java @@ -16,6 +16,7 @@ package com.alibaba.druid.wall; public interface Violation { + String getMessage(); String toString(); } diff --git a/src/main/java/com/alibaba/druid/wall/WallConfig.java b/src/main/java/com/alibaba/druid/wall/WallConfig.java index 3cfb2f23b1..de1b72d383 100644 --- a/src/main/java/com/alibaba/druid/wall/WallConfig.java +++ b/src/main/java/com/alibaba/druid/wall/WallConfig.java @@ -17,8 +17,8 @@ package com.alibaba.druid.wall; import static com.alibaba.druid.wall.spi.WallVisitorUtils.loadResource; -import java.util.HashSet; import java.util.Set; +import java.util.concurrent.ConcurrentSkipListSet; import com.alibaba.druid.wall.spi.WallVisitorUtils; @@ -33,25 +33,37 @@ public class WallConfig implements WallConfigMBean { private boolean selectWhereAlwayTrueCheck = true; private boolean selectHavingAlwayTrueCheck = true; private boolean selectUnionCheck = true; + private boolean createTableAllow = true; + private boolean dropTableAllow = true; + private boolean alterTableAllow = true; private boolean selectAllColumnAllow = true; private boolean deleteAllow = true; private boolean deleteWhereAlwayTrueCheck = true; + private boolean deleteWhereNoneCheck = false; private boolean updateAllow = true; private boolean updateWhereAlayTrueCheck = true; + private boolean updateWhereNoneCheck = false; private boolean insertAllow = true; private boolean mergeAllow = true; + private boolean minusAllow = false; + private boolean intersectAllow = false; + private boolean replaceAllow = true; + private boolean setAllow = true; private boolean multiStatementAllow = false; - private boolean truncateAllow = false; + private boolean truncateAllow = true; private boolean commentAllow = false; + private boolean strictSyntaxCheck = true; + private boolean constArithmeticAllow = true; - private boolean describeAllow = false; + private boolean describeAllow = true; + private boolean showAllow = true; private boolean schemaCheck = true; private boolean tableCheck = true; @@ -63,13 +75,18 @@ public class WallConfig implements WallConfigMBean { private boolean doPrivilegedAllow = false; - protected final Set permitFunctions = new HashSet(); - protected final Set permitTables = new HashSet(); - protected final Set permitSchemas = new HashSet(); - protected final Set permitVariants = new HashSet(); - protected final Set permitObjects = new HashSet(); + protected final Set denyFunctions = new ConcurrentSkipListSet(); + protected final Set denyTables = new ConcurrentSkipListSet(); + protected final Set denySchemas = new ConcurrentSkipListSet(); + protected final Set denyVariants = new ConcurrentSkipListSet(); + protected final Set denyObjects = new ConcurrentSkipListSet(); - protected final Set readOnlyTables = new HashSet(); + protected final Set permitFunctions = new ConcurrentSkipListSet(); + protected final Set permitTables = new ConcurrentSkipListSet(); + protected final Set permitSchemas = new ConcurrentSkipListSet(); + protected final Set permitVariants = new ConcurrentSkipListSet(); + + protected final Set readOnlyTables = new ConcurrentSkipListSet(); private String dir; @@ -81,10 +98,45 @@ public class WallConfig implements WallConfigMBean { private boolean wrapAllow = true; private boolean metadataAllow = true; + private boolean conditionOpXorAllow = false; + private boolean conditionOpBitwseAllow = true; + public WallConfig(){ } + public boolean isIntersectAllow() { + return intersectAllow; + } + + public void setIntersectAllow(boolean intersectAllow) { + this.intersectAllow = intersectAllow; + } + + public boolean isMinusAllow() { + return minusAllow; + } + + public void setMinusAllow(boolean minusAllow) { + this.minusAllow = minusAllow; + } + + public boolean isConditionOpXorAllow() { + return conditionOpXorAllow; + } + + public void setConditionOpXorAllow(boolean conditionOpXorAllow) { + this.conditionOpXorAllow = conditionOpXorAllow; + } + + public boolean isConditionOpBitwseAllow() { + return conditionOpBitwseAllow; + } + + public void setConditionOpBitwseAllow(boolean conditionOpBitwseAllow) { + this.conditionOpBitwseAllow = conditionOpBitwseAllow; + } + public String getTenantTablePattern() { return tenantTablePattern; } @@ -159,12 +211,17 @@ public class WallConfig implements WallConfigMBean { dir = dir.substring(0, dir.length() - 1); } - loadResource(this.permitVariants, dir + "/permit-variant.txt"); - loadResource(this.permitSchemas, dir + "/permit-schema.txt"); + loadResource(this.denyVariants, dir + "/deny-variant.txt"); + loadResource(this.denySchemas, dir + "/deny-schema.txt"); + loadResource(this.denyFunctions, dir + "/deny-function.txt"); + loadResource(this.denyTables, dir + "/deny-table.txt"); + loadResource(this.denyObjects, dir + "/deny-object.txt"); + loadResource(this.readOnlyTables, dir + "/readonly-table.txt"); + loadResource(this.permitFunctions, dir + "/permit-function.txt"); loadResource(this.permitTables, dir + "/permit-table.txt"); - loadResource(this.permitObjects, dir + "/permit-object.txt"); - loadResource(this.readOnlyTables, dir + "/readonly-table.txt"); + loadResource(this.permitSchemas, dir + "/permit-schema.txt"); + loadResource(this.permitVariants, dir + "/permit-variant.txt"); } public boolean isNoneBaseStatementAllow() { @@ -195,6 +252,14 @@ public class WallConfig implements WallConfigMBean { this.describeAllow = describeAllow; } + public boolean isShowAllow() { + return showAllow; + } + + public void setShowAllow(boolean showAllow) { + this.showAllow = showAllow; + } + public boolean isTruncateAllow() { return truncateAllow; } @@ -227,6 +292,30 @@ public class WallConfig implements WallConfigMBean { this.selectIntoOutfileAllow = selectIntoOutfileAllow; } + public boolean isCreateTableAllow() { + return createTableAllow; + } + + public void setCreateTableAllow(boolean createTableAllow) { + this.createTableAllow = createTableAllow; + } + + public boolean isDropTableAllow() { + return dropTableAllow; + } + + public void setDropTableAllow(boolean dropTableAllow) { + this.dropTableAllow = dropTableAllow; + } + + public boolean isAlterTableAllow() { + return alterTableAllow; + } + + public void setAlterTableAllow(boolean alterTableAllow) { + this.alterTableAllow = alterTableAllow; + } + public boolean isSelectUnionCheck() { return selectUnionCheck; } @@ -267,6 +356,14 @@ public class WallConfig implements WallConfigMBean { this.deleteWhereAlwayTrueCheck = deleteWhereAlwayTrueCheck; } + public boolean isDeleteWhereNoneCheck() { + return deleteWhereNoneCheck; + } + + public void setDeleteWhereNoneCheck(boolean deleteWhereNoneCheck) { + this.deleteWhereNoneCheck = deleteWhereNoneCheck; + } + public boolean isUpdateAllow() { return updateAllow; } @@ -283,6 +380,14 @@ public class WallConfig implements WallConfigMBean { this.updateWhereAlayTrueCheck = updateWhereAlayTrueCheck; } + public boolean isUpdateWhereNoneCheck() { + return updateWhereNoneCheck; + } + + public void setUpdateWhereNoneCheck(boolean updateWhereNoneCheck) { + this.updateWhereNoneCheck = updateWhereNoneCheck; + } + public boolean isInsertAllow() { return insertAllow; } @@ -291,6 +396,22 @@ public class WallConfig implements WallConfigMBean { this.insertAllow = insertAllow; } + public boolean isReplaceAllow() { + return replaceAllow; + } + + public void setReplaceAllow(boolean replaceAllow) { + this.replaceAllow = replaceAllow; + } + + public boolean isSetAllow() { + return setAllow; + } + + public void setSetAllow(boolean value) { + this.setAllow = value; + } + public boolean isMergeAllow() { return mergeAllow; } @@ -357,6 +478,54 @@ public class WallConfig implements WallConfigMBean { this.commentAllow = commentAllow; } + public boolean isStrictSyntaxCheck() { + return strictSyntaxCheck; + } + + public void setStrictSyntaxCheck(boolean strictSyntaxCheck) { + this.strictSyntaxCheck = strictSyntaxCheck; + } + + public boolean isConstArithmeticAllow() { + return constArithmeticAllow; + } + + public void setConstArithmeticAllow(boolean constArithmeticAllow) { + this.constArithmeticAllow = constArithmeticAllow; + } + + public Set getDenyFunctions() { + return denyFunctions; + } + + public Set getDenyTables() { + return denyTables; + } + + public Set getDenySchemas() { + return denySchemas; + } + + public Set getDenyVariants() { + return denyVariants; + } + + public Set getDenyObjects() { + return denyObjects; + } + + public Set getReadOnlyTables() { + return readOnlyTables; + } + + public void addReadOnlyTable(String tableName) { + this.readOnlyTables.add(tableName); + } + + public boolean isReadOnly(String tableName) { + return this.readOnlyTables.contains(tableName); + } + public Set getPermitFunctions() { return permitFunctions; } @@ -373,14 +542,6 @@ public class WallConfig implements WallConfigMBean { return permitVariants; } - public Set getPermitObjects() { - return permitObjects; - } - - public Set getReadOnlyTables() { - return readOnlyTables; - } - public boolean isMustParameterized() { return mustParameterized; } @@ -389,31 +550,31 @@ public class WallConfig implements WallConfigMBean { this.mustParameterized = mustParameterized; } - public boolean isPermitObjects(String name) { + public boolean isDenyObjects(String name) { if (!objectCheck) { return false; } name = WallVisitorUtils.form(name); - return permitObjects.contains(name); + return denyObjects.contains(name); } - public boolean isPermitSchema(String name) { + public boolean isDenySchema(String name) { if (!schemaCheck) { return false; } name = WallVisitorUtils.form(name); - return this.permitSchemas.contains(name); + return this.denySchemas.contains(name); } - public boolean isPermitFunction(String name) { + public boolean isDenyFunction(String name) { if (!functionCheck) { return false; } name = WallVisitorUtils.form(name); - return this.permitFunctions.contains(name); + return this.denyFunctions.contains(name); } public boolean isCallAllow() { diff --git a/src/main/java/com/alibaba/druid/wall/WallConfigMBean.java b/src/main/java/com/alibaba/druid/wall/WallConfigMBean.java index 317f59ea18..108eee17ac 100644 --- a/src/main/java/com/alibaba/druid/wall/WallConfigMBean.java +++ b/src/main/java/com/alibaba/druid/wall/WallConfigMBean.java @@ -113,22 +113,22 @@ public interface WallConfigMBean { void setCommentAllow(boolean commentAllow); - Set getPermitFunctions(); + Set getDenyFunctions(); - Set getPermitTables(); + Set getDenyTables(); - Set getPermitSchemas(); + Set getDenySchemas(); - Set getPermitVariants(); + Set getDenyVariants(); - Set getPermitObjects(); + Set getDenyObjects(); Set getReadOnlyTables(); - boolean isPermitObjects(String name); + boolean isDenyObjects(String name); - boolean isPermitSchema(String name); + boolean isDenySchema(String name); - boolean isPermitFunction(String name); + boolean isDenyFunction(String name); } diff --git a/src/main/java/com/alibaba/druid/wall/WallContext.java b/src/main/java/com/alibaba/druid/wall/WallContext.java new file mode 100644 index 0000000000..d0cf3e3910 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallContext.java @@ -0,0 +1,116 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall; + +import java.util.HashMap; +import java.util.Map; + +public class WallContext { + + private final static ThreadLocal contextLocal = new ThreadLocal(); + + private WallSqlStat sqlState; + private Map tableStats; + private Map functionStats; + private final String dbType; + + public WallContext(String dbType){ + this.dbType = dbType; + } + + public void incrementFunctionInvoke(String tableName) { + if (functionStats == null) { + functionStats = new HashMap(); + } + + String lowerCaseName = tableName.toLowerCase(); + + WallSqlFunctionStat stat = functionStats.get(lowerCaseName); + if (stat == null) { + if (functionStats.size() > 100) { + return; + } + + stat = new WallSqlFunctionStat(); + functionStats.put(tableName, stat); + } + + stat.incrementInvokeCount(); + } + + public WallSqlTableStat getTableStat(String tableName) { + if (tableStats == null) { + tableStats = new HashMap(2); + } + + String lowerCaseName = tableName.toLowerCase(); + + WallSqlTableStat stat = tableStats.get(lowerCaseName); + if (stat == null) { + if (tableStats.size() > 100) { + return null; + } + + stat = new WallSqlTableStat(); + tableStats.put(tableName, stat); + } + return stat; + } + + public static WallContext createIfNotExists(String dbType) { + WallContext context = contextLocal.get(); + if (context == null) { + context = new WallContext(dbType); + contextLocal.set(context); + } + return context; + } + + public static WallContext create(String dbType) { + WallContext context = new WallContext(dbType); + contextLocal.set(context); + return context; + } + + public static WallContext current() { + return contextLocal.get(); + } + + public static void clearContext() { + contextLocal.remove(); + } + + public WallSqlStat getSqlState() { + return sqlState; + } + + public void setSqlState(WallSqlStat sqlState) { + this.sqlState = sqlState; + } + + public Map getTableStats() { + return tableStats; + } + + public Map getFunctionStats() { + return functionStats; + } + + public String getDbType() { + return dbType; + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/WallDenyStat.java b/src/main/java/com/alibaba/druid/wall/WallDenyStat.java new file mode 100644 index 0000000000..e8c7c0822b --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallDenyStat.java @@ -0,0 +1,61 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall; + +import java.util.Date; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +public class WallDenyStat { + + private volatile long denyCount; + + private volatile long lastDenyTimeMillis; + + private volatile long resetCount; + + final static AtomicLongFieldUpdater denyCountUpdater = AtomicLongFieldUpdater.newUpdater(WallDenyStat.class, + "denyCount"); + + final static AtomicLongFieldUpdater resetCountUpdater = AtomicLongFieldUpdater.newUpdater(WallDenyStat.class, + "resetCount"); + + public long incrementAndGetDenyCount() { + lastDenyTimeMillis = System.currentTimeMillis(); + return denyCountUpdater.incrementAndGet(this); + } + + public long getDenyCount() { + return denyCount; + } + + public Date getLastDenyTime() { + if (lastDenyTimeMillis <= 0) { + return null; + } + return new Date(lastDenyTimeMillis); + } + + public void reset() { + lastDenyTimeMillis = 0; + denyCount = 0; + resetCountUpdater.incrementAndGet(this); + } + + public long getResetCount() { + return this.resetCount; + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/WallFilter.java b/src/main/java/com/alibaba/druid/wall/WallFilter.java index 105fe339a0..dd87bc00d6 100644 --- a/src/main/java/com/alibaba/druid/wall/WallFilter.java +++ b/src/main/java/com/alibaba/druid/wall/WallFilter.java @@ -21,7 +21,6 @@ import java.sql.Wrapper; import java.util.Collections; import java.util.List; import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; import com.alibaba.druid.DruidRuntimeException; import com.alibaba.druid.filter.FilterAdapter; @@ -37,7 +36,8 @@ import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.druid.util.JdbcUtils; import com.alibaba.druid.wall.spi.MySqlWallProvider; import com.alibaba.druid.wall.spi.OracleWallProvider; -import com.alibaba.druid.wall.spi.SQLServerProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; import com.alibaba.druid.wall.violation.SyntaxErrorViolation; public class WallFilter extends FilterAdapter implements WallFilterMBean { @@ -55,9 +55,6 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { private volatile boolean logViolation = false; private volatile boolean throwException = true; - // stats - private final AtomicLong violationCount = new AtomicLong(); - @Override public void init(DataSourceProxy dataSource) { if (this.dbType == null || this.dbType.trim().length() == 0) { @@ -86,10 +83,16 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { provider = new OracleWallProvider(config); } else if (JdbcUtils.SQL_SERVER.equals(dbType) || JdbcUtils.JTDS.equals(dbType)) { if (config == null) { - config = new WallConfig(SQLServerProvider.DEFAULT_CONFIG_DIR); + config = new WallConfig(SQLServerWallProvider.DEFAULT_CONFIG_DIR); } - provider = new SQLServerProvider(config); + provider = new SQLServerWallProvider(config); + } else if (JdbcUtils.POSTGRESQL.equals(dbType)) { + if (config == null) { + config = new WallConfig(PGWallProvider.DEFAULT_CONFIG_DIR); + } + + provider = new PGWallProvider(config); } else { throw new IllegalStateException("dbType not support : " + dbType + ", url " + dataSource.getUrl()); } @@ -159,139 +162,254 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { @Override public void statement_addBatch(FilterChain chain, StatementProxy statement, String sql) throws SQLException { - sql = check(sql); - chain.statement_addBatch(statement, sql); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + chain.statement_addBatch(statement, sql); + } finally { + WallContext.clearContext(); + } } @Override public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql) throws SQLException { - sql = check(sql); - return chain.connection_prepareStatement(connection, sql); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareStatement(connection, sql); + } finally { + WallContext.clearContext(); + } } @Override public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql, int autoGeneratedKeys) throws SQLException { - sql = check(sql); - return chain.connection_prepareStatement(connection, sql, autoGeneratedKeys); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareStatement(connection, sql, autoGeneratedKeys); + } finally { + WallContext.clearContext(); + } } @Override public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - sql = check(sql); - return chain.connection_prepareStatement(connection, sql, resultSetType, resultSetConcurrency); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareStatement(connection, sql, resultSetType, resultSetConcurrency); + } finally { + WallContext.clearContext(); + } } @Override public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - sql = check(sql); - return chain.connection_prepareStatement(connection, sql, resultSetType, resultSetConcurrency, - resultSetHoldability); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareStatement(connection, sql, resultSetType, resultSetConcurrency, + resultSetHoldability); + } finally { + WallContext.clearContext(); + } } @Override public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql, int[] columnIndexes) throws SQLException { - sql = check(sql); - return chain.connection_prepareStatement(connection, sql, columnIndexes); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareStatement(connection, sql, columnIndexes); + } finally { + WallContext.clearContext(); + } } @Override public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql, String[] columnNames) throws SQLException { - sql = check(sql); - return chain.connection_prepareStatement(connection, sql, columnNames); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareStatement(connection, sql, columnNames); + } finally { + WallContext.clearContext(); + } } @Override public CallableStatementProxy connection_prepareCall(FilterChain chain, ConnectionProxy connection, String sql) throws SQLException { - sql = check(sql); - return chain.connection_prepareCall(connection, sql); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareCall(connection, sql); + } finally { + WallContext.clearContext(); + } } @Override public CallableStatementProxy connection_prepareCall(FilterChain chain, ConnectionProxy connection, String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - sql = check(sql); - return chain.connection_prepareCall(connection, sql, resultSetType, resultSetConcurrency); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareCall(connection, sql, resultSetType, resultSetConcurrency); + } finally { + WallContext.clearContext(); + } } @Override public CallableStatementProxy connection_prepareCall(FilterChain chain, ConnectionProxy connection, String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - sql = check(sql); - return chain.connection_prepareCall(connection, sql, resultSetType, resultSetConcurrency, resultSetHoldability); + String dbType = connection.getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.connection_prepareCall(connection, sql, resultSetType, resultSetConcurrency, + resultSetHoldability); + } finally { + WallContext.clearContext(); + } } // ////////////// @Override public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql) throws SQLException { - sql = check(sql); - return chain.statement_execute(statement, sql); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_execute(statement, sql); + } finally { + WallContext.clearContext(); + } } @Override public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, int autoGeneratedKeys) throws SQLException { - sql = check(sql); - return chain.statement_execute(statement, sql, autoGeneratedKeys); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_execute(statement, sql, autoGeneratedKeys); + } finally { + WallContext.clearContext(); + } } @Override public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, int columnIndexes[]) throws SQLException { - sql = check(sql); - return chain.statement_execute(statement, sql, columnIndexes); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_execute(statement, sql, columnIndexes); + } finally { + WallContext.clearContext(); + } } @Override public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, String columnNames[]) throws SQLException { - sql = check(sql); - return chain.statement_execute(statement, sql, columnNames); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_execute(statement, sql, columnNames); + } finally { + WallContext.clearContext(); + } } @Override public ResultSetProxy statement_executeQuery(FilterChain chain, StatementProxy statement, String sql) throws SQLException { - sql = check(sql); - return chain.statement_executeQuery(statement, sql); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_executeQuery(statement, sql); + } finally { + WallContext.clearContext(); + } } @Override public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql) throws SQLException { - sql = check(sql); - return chain.statement_executeUpdate(statement, sql); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_executeUpdate(statement, sql); + } finally { + WallContext.clearContext(); + } } @Override public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, int autoGeneratedKeys) throws SQLException { - sql = check(sql); - return chain.statement_executeUpdate(statement, sql, autoGeneratedKeys); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_executeUpdate(statement, sql, autoGeneratedKeys); + } finally { + WallContext.clearContext(); + } } @Override public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, int columnIndexes[]) throws SQLException { - sql = check(sql); - return chain.statement_executeUpdate(statement, sql, columnIndexes); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_executeUpdate(statement, sql, columnIndexes); + } finally { + WallContext.clearContext(); + } } @Override public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, String columnNames[]) throws SQLException { - sql = check(sql); - return chain.statement_executeUpdate(statement, sql, columnNames); + String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType(); + WallContext.createIfNotExists(dbType); + try { + sql = check(sql); + return chain.statement_executeUpdate(statement, sql, columnNames); + } finally { + WallContext.clearContext(); + } } public String check(String sql) throws SQLException { @@ -299,18 +417,18 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { List violations = checkResult.getViolations(); if (violations.size() > 0) { - violationCount.incrementAndGet(); - + Violation firstViolation = violations.get(0); if (isLogViolation()) { - LOG.error("sql injection violation : " + sql); + LOG.error("sql injection violation, " + firstViolation.getMessage() + " : " + sql); } if (throwException) { if (violations.get(0) instanceof SyntaxErrorViolation) { SyntaxErrorViolation violation = (SyntaxErrorViolation) violations.get(0); - throw new SQLException("sql injection violation : " + sql, violation.getException()); + throw new SQLException("sql injection violation, " + firstViolation.getMessage() + " : " + sql, + violation.getException()); } else { - throw new SQLException("sql injection violation : " + sql); + throw new SQLException("sql injection violation, " + firstViolation.getMessage() + " : " + sql); } } } @@ -337,7 +455,6 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { } if (!this.provider.getConfig().isWrapAllow()) { - violationCount.incrementAndGet(); return null; } @@ -351,11 +468,10 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { } if (!this.provider.getConfig().isMetadataAllow()) { - violationCount.incrementAndGet(); if (isLogViolation()) { LOG.error("not support method : Connection.getMetdataData"); } - + if (throwException) { throw new WallSQLException("not support method : Connection.getMetdataData"); } else { @@ -367,6 +483,18 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean { } public long getViolationCount() { - return this.violationCount.get(); + return this.provider.getViolationCount(); + } + + public void resetViolationCount() { + this.provider.reset(); + } + + public void clearWhiteList() { + this.provider.clearCache(); + } + + public boolean checkValid(String sql) { + return provider.checkValid(sql); } } diff --git a/src/main/java/com/alibaba/druid/wall/WallFilterMBean.java b/src/main/java/com/alibaba/druid/wall/WallFilterMBean.java index 297c12f336..bd2f51450c 100644 --- a/src/main/java/com/alibaba/druid/wall/WallFilterMBean.java +++ b/src/main/java/com/alibaba/druid/wall/WallFilterMBean.java @@ -39,4 +39,10 @@ public interface WallFilterMBean { String check(String sql) throws SQLException; long getViolationCount(); + + void resetViolationCount(); + + void clearWhiteList(); + + boolean checkValid(String sql); } diff --git a/src/main/java/com/alibaba/druid/wall/WallFunctionStat.java b/src/main/java/com/alibaba/druid/wall/WallFunctionStat.java new file mode 100644 index 0000000000..4f24a8953f --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallFunctionStat.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall; + +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +public class WallFunctionStat { + + private volatile long invokeCount; + final static AtomicLongFieldUpdater invokeCountUpdater = AtomicLongFieldUpdater.newUpdater(WallFunctionStat.class, + "invokeCount"); + + public long getInvokeCount() { + return invokeCount; + } + + public void incrementInvokeCount() { + this.invokeCount++; + } + + public void addSqlFunctionStat(WallSqlFunctionStat sqlFunctionStat) { + this.invokeCount += sqlFunctionStat.getInvokeCount(); + } + + public String toString() { + return "{\"invokeCount\":" + invokeCount + "}"; + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/WallProvider.java b/src/main/java/com/alibaba/druid/wall/WallProvider.java index 92a15f36b6..aedbe294f9 100644 --- a/src/main/java/com/alibaba/druid/wall/WallProvider.java +++ b/src/main/java/com/alibaba/druid/wall/WallProvider.java @@ -16,53 +16,167 @@ package com.alibaba.druid.wall; import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.parser.Lexer; +import com.alibaba.druid.sql.parser.NotAllowCommentException; import com.alibaba.druid.sql.parser.ParserException; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.parser.Token; import com.alibaba.druid.sql.visitor.ExportParameterVisitor; import com.alibaba.druid.util.LRUCache; +import com.alibaba.druid.wall.spi.WallVisitorUtils; import com.alibaba.druid.wall.violation.IllegalSQLObjectViolation; import com.alibaba.druid.wall.violation.SyntaxErrorViolation; public abstract class WallProvider { - // Dummy value to associate with an Object in the backing Map - private static final Object PRESENT = new Object(); + private LRUCache whiteList; - private LinkedHashMap whiteList; + private int MAX_SQL_LENGTH = 2048; // 1k - private int whileListMaxSize = 1024; + private int whiteSqlMaxSize = 10000; // 1k - private int whiteSqlMaxLength = 1024; // 1k + private LRUCache blackList; - protected final WallConfig config; + private int blackSqlMaxSize = 1000; // 1k - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + protected final WallConfig config; - private static final ThreadLocal privileged = new ThreadLocal(); + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + + private static final ThreadLocal privileged = new ThreadLocal(); + + private final ConcurrentMap functionStats = new ConcurrentHashMap(); + private final ConcurrentMap tableStats = new ConcurrentHashMap(); + + public final WallDenyStat commentDeniedStat = new WallDenyStat(); + + protected String dbType = null; + protected final AtomicLong checkCount = new AtomicLong(); + protected final AtomicLong hardCheckCount = new AtomicLong(); + protected final AtomicLong whiteListHitCount = new AtomicLong(); + protected final AtomicLong blackListHitCount = new AtomicLong(); + protected final AtomicLong syntaxErrrorCount = new AtomicLong(); + protected final AtomicLong violationCount = new AtomicLong(); public WallProvider(WallConfig config){ this.config = config; } + public WallProvider(WallConfig config, String dbType){ + this.config = config; + this.dbType = dbType; + } + + public void reset() { + this.checkCount.set(0); + this.hardCheckCount.set(0); + this.violationCount.set(0); + this.whiteListHitCount.set(0); + this.blackListHitCount.set(0); + this.clearWhiteList(); + this.clearBlackList(); + this.functionStats.clear(); + this.tableStats.clear(); + } + + public ConcurrentMap getTableStats() { + return this.tableStats; + } + + public ConcurrentMap getFunctionStats() { + return this.functionStats; + } + + public WallTableStat getTableStat(String tableName) { + String lowerCaseName = tableName.toLowerCase(); + return getTableStatWithLowerName(lowerCaseName); + } + + public WallTableStat getTableStatWithLowerName(String lowerCaseName) { + WallTableStat stat = tableStats.get(lowerCaseName); + if (stat == null) { + if (tableStats.size() > 10000) { + return null; + } + + tableStats.putIfAbsent(lowerCaseName, new WallTableStat()); + stat = tableStats.get(lowerCaseName); + } + return stat; + } + + public WallFunctionStat getFunctionStat(String functionName) { + String lowerCaseName = functionName.toLowerCase(); + return getFunctionStatWithLowerName(lowerCaseName); + } + + public WallFunctionStat getFunctionStatWithLowerName(String lowerCaseName) { + WallFunctionStat stat = functionStats.get(lowerCaseName); + if (stat == null) { + if (functionStats.size() > 10000) { + return null; + } + + functionStats.putIfAbsent(lowerCaseName, new WallFunctionStat()); + stat = functionStats.get(lowerCaseName); + } + return stat; + } + public WallConfig getConfig() { return config; } - public void addWhiteSql(String sql) { + public WallSqlStat addWhiteSql(String sql, Map tableStats, + Map functionStats, boolean syntaxError) { lock.writeLock().lock(); try { if (whiteList == null) { - whiteList = new LRUCache(whileListMaxSize); + whiteList = new LRUCache(whiteSqlMaxSize); } - whiteList.put(sql, PRESENT); + WallSqlStat wallStat = whiteList.get(sql); + if (wallStat == null) { + wallStat = new WallSqlStat(tableStats, functionStats, syntaxError); + whiteList.put(sql, wallStat); + } + + return wallStat; + } finally { + lock.writeLock().unlock(); + } + } + + public WallSqlStat addBlackSql(String sql, Map tableStats, + Map functionStats, List violations, + boolean syntaxError) { + lock.writeLock().lock(); + try { + if (blackList == null) { + blackList = new LRUCache(blackSqlMaxSize); + } + + WallSqlStat wallStat = blackList.get(sql); + if (wallStat == null) { + wallStat = new WallSqlStat(tableStats, functionStats, violations, syntaxError); + blackList.put(sql, wallStat); + } + + return wallStat; } finally { lock.writeLock().unlock(); } @@ -79,10 +193,28 @@ public abstract class WallProvider { lock.readLock().unlock(); } - return hashSet; + return Collections. unmodifiableSet(hashSet); + } + + public Set getBlackList() { + Set hashSet = new HashSet(); + lock.readLock().lock(); + try { + if (blackList != null) { + hashSet.addAll(blackList.keySet()); + } + } finally { + lock.readLock().unlock(); + } + + return Collections. unmodifiableSet(hashSet); } public void clearCache() { + clearWhiteList(); + } + + public void clearWhiteList() { lock.writeLock().lock(); try { if (whiteList != null) { @@ -92,20 +224,48 @@ public abstract class WallProvider { lock.writeLock().unlock(); } } + + public void clearBlackList() { + lock.writeLock().lock(); + try { + if (blackList != null) { + blackList = null; + } + } finally { + lock.writeLock().unlock(); + } + } - public boolean whiteContains(String sql) { + public WallSqlStat getWhiteSql(String sql) { lock.readLock().lock(); try { if (whiteList == null) { - return false; + return null; } - return whiteList.get(sql) != null; + return whiteList.get(sql); } finally { lock.readLock().unlock(); } } + public WallSqlStat getBlackSql(String sql) { + lock.readLock().lock(); + try { + if (blackList == null) { + return null; + } + + return blackList.get(sql); + } finally { + lock.readLock().unlock(); + } + } + + public boolean whiteContains(String sql) { + return getWhiteSql(sql) != null; + } + public abstract SQLStatementParser createParser(String sql); public abstract WallVisitor createWallVisitor(); @@ -113,10 +273,104 @@ public abstract class WallProvider { public abstract ExportParameterVisitor createExportParameterVisitor(); public boolean checkValid(String sql) { - return check(sql).getViolations().isEmpty(); + WallContext originalContext = WallContext.current(); + + try { + WallContext.create(dbType); + WallCheckResult result = checkInternal(sql); + return result.getViolations().isEmpty(); + } finally { + + if (originalContext == null) { + WallContext.clearContext(); + } + } + } + + public void incrementCommentDeniedCount() { + this.commentDeniedStat.incrementAndGetDenyCount(); + } + + public boolean checkDenyFunction(String functionName) { + if (functionName == null) { + return true; + } + + functionName = functionName.toLowerCase(); + + if (getConfig().getDenyFunctions().contains(functionName)) { + return false; + } + + return true; + } + + public boolean checkDenySchema(String schemaName) { + if (schemaName == null) { + return true; + } + + schemaName = schemaName.toLowerCase(); + if (getConfig().getDenySchemas().contains(schemaName)) { + return false; + } + + return true; + } + + public boolean checkDenyTable(String tableName) { + if (tableName == null) { + return true; + } + + tableName = WallVisitorUtils.form(tableName); + if (getConfig().getDenyTables().contains(tableName)) { + return false; + } + + return true; + } + + public boolean checkReadOnlyTable(String tableName) { + if (tableName == null) { + return true; + } + + tableName = WallVisitorUtils.form(tableName); + if (getConfig().isReadOnly(tableName)) { + return false; + } + + return true; + } + + public WallDenyStat getCommentDenyStat() { + return this.commentDeniedStat; } public WallCheckResult check(String sql) { + WallContext originalContext = WallContext.current(); + + try { + WallContext.create(dbType); + return checkInternal(sql); + } finally { + if (originalContext == null) { + WallContext.clearContext(); + } + } + } + + public WallCheckResult checkInternal(String sql) { + checkCount.incrementAndGet(); + + WallContext context = WallContext.current(); + + if (context != null && !this.dbType.equals(context.getDbType())) { + WallContext.clearContext(); + } + + WallContext.createIfNotExists(this.dbType); WallCheckResult result = new WallCheckResult(); if (config.isDoPrivilegedAllow() && ispPivileged()) { @@ -124,65 +378,138 @@ public abstract class WallProvider { } // first step, check whiteList - boolean isWhite = whiteContains(sql); - if (isWhite) { - return result; + { + WallSqlStat sqlStat = getWhiteSql(sql); + if (sqlStat != null) { + whiteListHitCount.incrementAndGet(); + sqlStat.incrementAndGetExecuteCount(); + + if (sqlStat.isSyntaxError()) { + syntaxErrrorCount.incrementAndGet(); + } + + recordStats(sqlStat.getTableStats(), sqlStat.getFunctionStats()); + return result; + } } + // check black list + { + WallSqlStat sqlStat = getBlackSql(sql); + if (sqlStat != null) { + blackListHitCount.incrementAndGet(); + violationCount.incrementAndGet(); - SQLStatementParser parser = createParser(sql); + if (sqlStat.isSyntaxError()) { + syntaxErrrorCount.incrementAndGet(); + } - if (!config.isCommentAllow()) { - parser.getLexer().setAllowComment(false); // permit comment - } + sqlStat.incrementAndGetExecuteCount(); + recordStats(sqlStat.getTableStats(), sqlStat.getFunctionStats()); + List blackViolations = sqlStat.getViolations(); - try { - parser.parseStatementList(result.getStatementList()); - } catch (Exception e) { - result.getViolations().add(new SyntaxErrorViolation(e, sql)); - return result; - } - - if (parser.getLexer().token() != Token.EOF) { - result.getViolations().add(new IllegalSQLObjectViolation(sql)); - return result; - } - - if (result.getStatementList().size() == 0) { - return result; - } - - if (result.getStatementList().size() > 1 && !config.isMultiStatementAllow()) { - result.getViolations().add(new IllegalSQLObjectViolation(sql)); - return result; - } - - SQLStatement stmt = result.getStatementList().get(0); - - WallVisitor visitor = createWallVisitor(); - - try { - stmt.accept(visitor); - } catch (ParserException e) { - result.getViolations().add(new IllegalSQLObjectViolation(sql)); - return result; - } - - if (visitor.getViolations().size() == 0) { - if (sql.length() < whiteSqlMaxLength) { - this.addWhiteSql(sql); + result.getViolations().addAll(blackViolations); + return result; } } - result.getViolations().addAll(visitor.getViolations()); + hardCheckCount.incrementAndGet(); + boolean syntaxError = false; + try { + SQLStatementParser parser = createParser(sql); + parser.getLexer().setCommentHandler(WallCommentHandler.instance); + + if (!config.isCommentAllow()) { + parser.getLexer().setAllowComment(false); // deny comment + } + + parser.parseStatementList(result.getStatementList()); + + final Token lastToken = parser.getLexer().token(); + if (lastToken != Token.EOF) { + result.getViolations().add(new IllegalSQLObjectViolation("not terminal sql, token " + lastToken, sql)); + } + } catch (NotAllowCommentException e) { + result.getViolations().add(new SyntaxErrorViolation(e, sql)); + incrementCommentDeniedCount(); + } catch (ParserException e) { + syntaxErrrorCount.incrementAndGet(); + syntaxError = true; + if (config.isStrictSyntaxCheck()) { + result.getViolations().add(new SyntaxErrorViolation(e, sql)); + } + } catch (Exception e) { + result.getViolations().add(new SyntaxErrorViolation(e, sql)); + } + + if (result.getViolations().size() == 0 && result.getStatementList().size() > 1 + && !config.isMultiStatementAllow()) { + result.getViolations().add(new IllegalSQLObjectViolation("multi-statement not allow", sql)); + } + + WallVisitor visitor = createWallVisitor(); + + if (result.getStatementList().size() > 0) { + SQLStatement stmt = result.getStatementList().get(0); + try { + stmt.accept(visitor); + } catch (ParserException e) { + result.getViolations().add(new SyntaxErrorViolation(e, sql)); + } + } + + if (visitor.getViolations().size() > 0) { + result.getViolations().addAll(visitor.getViolations()); + } + + if (result.getViolations().size() > 0) { + violationCount.incrementAndGet(); + + if (sql.length() < MAX_SQL_LENGTH) { + addBlackSql(sql, context.getTableStats(), context.getFunctionStats(), result.getViolations(), + syntaxError); + } + } else { + if (sql.length() < MAX_SQL_LENGTH) { + addWhiteSql(sql, context.getTableStats(), context.getFunctionStats(), syntaxError); + } + } + + if (context != null) { + recordStats(context.getTableStats(), context.getFunctionStats()); + } + return result; } - + + void recordStats(Map tableStats, Map functionStats) { + if (tableStats != null) { + for (Map.Entry entry : tableStats.entrySet()) { + String tableName = entry.getKey(); + WallSqlTableStat sqlTableStat = entry.getValue(); + WallTableStat tableStat = getTableStat(tableName); + if (tableStat != null) { + tableStat.addSqlTableStat(sqlTableStat); + } + } + } + if (functionStats != null) { + for (Map.Entry entry : functionStats.entrySet()) { + String tableName = entry.getKey(); + WallSqlFunctionStat sqlTableStat = entry.getValue(); + WallFunctionStat functionStat = getFunctionStatWithLowerName(tableName); + if (functionStat != null) { + functionStat.addSqlFunctionStat(sqlTableStat); + } + } + } + } + public static boolean ispPivileged() { Boolean value = privileged.get(); if (value == null) { return false; } - + return value.booleanValue(); } @@ -204,4 +531,91 @@ public abstract class WallProvider { public static Object getTenantValue() { return tenantValueLocal.get(); } + + public long getWhiteListHitCount() { + return whiteListHitCount.get(); + } + + public long getBlackListHitCount() { + return blackListHitCount.get(); + } + + public long getSyntaxErrorCount() { + return syntaxErrrorCount.get(); + } + + public long getCheckCount() { + return checkCount.get(); + } + + public long getViolationCount() { + return violationCount.get(); + } + + public long getHardCheckCount() { + return hardCheckCount.get(); + } + + public static class WallCommentHandler implements Lexer.CommentHandler { + + public final static WallCommentHandler instance = new WallCommentHandler(); + + @Override + public boolean handle(Token lastToken, String comment) { + if (lastToken == null) { + return false; + } + + switch (lastToken) { + case SELECT: + case INSERT: + case DELETE: + case UPDATE: + case TRUNCATE: + case SET: + case CREATE: + case ALTER: + case DROP: + return true; + default: + break; + } + + return false; + } + } + + public Map getStatsMap() { + Map info = new LinkedHashMap(); + + info.put("checkCount", this.getCheckCount()); + info.put("violationCount", this.getViolationCount()); + info.put("blackListHitCount", this.getBlackListHitCount()); + info.put("blackListSize", this.getBlackList().size()); + info.put("whiteListHitCount", this.getWhiteListHitCount()); + info.put("whiteListSize", this.getWhiteList().size()); + info.put("syntaxErrrorCount", this.getSyntaxErrorCount()); + + { + List> tables = new ArrayList>(); + for (Map.Entry entry : this.tableStats.entrySet()) { + Map stat = new LinkedHashMap(); + stat.put("name", entry.getKey()); + entry.getValue().toMap(stat); + tables.add(stat); + } + info.put("tables", tables); + } + { + List> functions = new ArrayList>(); + for (Map.Entry entry : this.functionStats.entrySet()) { + Map stat = new HashMap(); + stat.put("name", entry.getValue()); + stat.put("invokeCount", entry.getValue().getInvokeCount()); + functions.add(stat); + } + info.put("functions", functions); + } + return info; + } } diff --git a/src/main/java/com/alibaba/druid/wall/WallSqlFunctionStat.java b/src/main/java/com/alibaba/druid/wall/WallSqlFunctionStat.java new file mode 100644 index 0000000000..02754a0ac0 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallSqlFunctionStat.java @@ -0,0 +1,30 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall; + +public class WallSqlFunctionStat { + + private int invokeCount; + + public int getInvokeCount() { + return invokeCount; + } + + public void incrementInvokeCount() { + this.invokeCount++; + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/WallSqlStat.java b/src/main/java/com/alibaba/druid/wall/WallSqlStat.java new file mode 100644 index 0000000000..d431f360f0 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallSqlStat.java @@ -0,0 +1,74 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +public class WallSqlStat { + + private volatile long executeCount; + + final static AtomicLongFieldUpdater executeCountUpdater = AtomicLongFieldUpdater.newUpdater(WallSqlStat.class, + "executeCount"); + private final Map tableStats; + + private final List violations; + + private final Map functionStats; + + private final boolean syntaxError; + + public WallSqlStat(Map tableStats, Map functionStats, + boolean syntaxError){ + this(tableStats, functionStats, Collections. emptyList(), syntaxError); + } + + public WallSqlStat(Map tableStats, Map functionStats, + List violations, boolean syntaxError){ + this.violations = violations; + this.tableStats = tableStats; + this.functionStats = functionStats; + this.syntaxError = syntaxError; + } + + public long incrementAndGetExecuteCount() { + return executeCountUpdater.incrementAndGet(this); + } + + public long getExecuteCount() { + return executeCount; + } + + public Map getTableStats() { + return tableStats; + } + + public Map getFunctionStats() { + return functionStats; + } + + public List getViolations() { + return violations; + } + + public boolean isSyntaxError() { + return syntaxError; + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/WallSqlTableStat.java b/src/main/java/com/alibaba/druid/wall/WallSqlTableStat.java new file mode 100644 index 0000000000..36e8ce1112 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallSqlTableStat.java @@ -0,0 +1,102 @@ +package com.alibaba.druid.wall; + +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class WallSqlTableStat { + + private int selectCount; + private int selectIntoCount; + private int insertCount; + private int updateCount; + private int deleteCount; + private int truncateCount; + private int createCount; + private int alterCount; + private int dropCount; + + public int getSelectCount() { + return selectCount; + } + + public void incrementSelectCount() { + this.selectCount++; + } + + public int getSelectIntoCount() { + return selectIntoCount; + } + + public void incrementSelectIntoCount() { + this.selectIntoCount++; + } + + public int getInsertCount() { + return insertCount; + } + + public void incrementInsertCount() { + this.insertCount++; + } + + public int getUpdateCount() { + return updateCount; + } + + public void incrementUpdateCount() { + this.updateCount++; + } + + public int getDeleteCount() { + return deleteCount; + } + + public void incrementDeleteCount() { + this.deleteCount++; + } + + public int getTruncateCount() { + return truncateCount; + } + + public void incrementTruncateCount() { + this.truncateCount++; + } + + public int getCreateCount() { + return createCount; + } + + public void incrementCreateCount() { + this.createCount++; + } + + public int getAlterCount() { + return alterCount; + } + + public void incrementAlterCount() { + this.alterCount++; + } + + public int getDropCount() { + return dropCount; + } + + public void incrementDropCount() { + this.dropCount++; + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/WallTableStat.java b/src/main/java/com/alibaba/druid/wall/WallTableStat.java new file mode 100644 index 0000000000..5eafe5eac7 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/WallTableStat.java @@ -0,0 +1,191 @@ +package com.alibaba.druid.wall; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +import com.alibaba.druid.support.json.JSONUtils; + +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class WallTableStat { + + private volatile long selectCount; + private volatile long selectIntoCount; + private volatile long insertCount; + private volatile long updateCount; + private volatile long deleteCount; + private volatile long truncateCount; + private volatile long createCount; + private volatile long alterCount; + private volatile long dropCount; + + final static AtomicLongFieldUpdater selectCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "selectCount"); + final static AtomicLongFieldUpdater selectIntoCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "selectIntoCount"); + final static AtomicLongFieldUpdater insertCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "insertCount"); + final static AtomicLongFieldUpdater updateCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "updateCount"); + final static AtomicLongFieldUpdater deleteCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "deleteCount"); + final static AtomicLongFieldUpdater truncateCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "truncateCount"); + final static AtomicLongFieldUpdater createCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "createCount"); + final static AtomicLongFieldUpdater alterCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "alterCount"); + final static AtomicLongFieldUpdater dropCountUpdater = AtomicLongFieldUpdater.newUpdater(WallTableStat.class, + "dropCount"); + + public WallTableStat(){ + + } + + public long getSelectCount() { + return selectCount; + } + + public long getSelectIntoCount() { + return selectIntoCount; + } + + public long getInsertCount() { + return insertCount; + } + + public long getUpdateCount() { + return updateCount; + } + + public long getDeleteCount() { + return deleteCount; + } + + public long getTruncateCount() { + return truncateCount; + } + + public long getCreateCount() { + return createCount; + } + + public long getAlterCount() { + return alterCount; + } + + public long getDropCount() { + return dropCount; + } + + public void addSqlTableStat(WallSqlTableStat stat) { + { + long val = stat.getSelectCount(); + if (val > 0) { + selectCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getSelectIntoCount(); + if (val > 0) { + selectIntoCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getInsertCount(); + if (val > 0) { + insertCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getUpdateCount(); + if (val > 0) { + updateCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getDeleteCount(); + if (val > 0) { + deleteCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getAlterCount(); + if (val > 0) { + alterCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getTruncateCount(); + if (val > 0) { + truncateCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getCreateCount(); + if (val > 0) { + createCountUpdater.addAndGet(this, val); + } + } + { + long val = stat.getDropCount(); + if (val > 0) { + dropCountUpdater.addAndGet(this, val); + } + } + } + + public String toString() { + + Map map = toMap(); + + return JSONUtils.toJSONString(map); + } + + public Map toMap() { + Map map = new LinkedHashMap(); + return toMap(map); + } + + public Map toMap(Map map) { + if (selectCount > 0) { + map.put("selectCount", selectCount); + } + if (deleteCount > 0) { + map.put("deleteCount", deleteCount); + } + if (insertCount > 0) { + map.put("insertCount", insertCount); + } + if (updateCount > 0) { + map.put("updateCount", updateCount); + } + if (alterCount > 0) { + map.put("alterCount", alterCount); + } + if (dropCount > 0) { + map.put("dropCount", dropCount); + } + if (createCount > 0) { + map.put("createCount", createCount); + } + if (truncateCount > 0) { + map.put("truncateCount", truncateCount); + } + return map; + } +} diff --git a/src/main/java/com/alibaba/druid/wall/WallUtils.java b/src/main/java/com/alibaba/druid/wall/WallUtils.java index 8cb6fe560c..f4f8d5e8d3 100644 --- a/src/main/java/com/alibaba/druid/wall/WallUtils.java +++ b/src/main/java/com/alibaba/druid/wall/WallUtils.java @@ -17,10 +17,20 @@ package com.alibaba.druid.wall; import com.alibaba.druid.wall.spi.MySqlWallProvider; import com.alibaba.druid.wall.spi.OracleWallProvider; -import com.alibaba.druid.wall.spi.SQLServerProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; public class WallUtils { + public static boolean isValidatePostgres(String sql) { + PGWallProvider provider = new PGWallProvider(); + return provider.checkValid(sql); + } + public static boolean isValidatePostgres(String sql, WallConfig config) { + PGWallProvider provider = new PGWallProvider(config); + return provider.checkValid(sql); + } + public static boolean isValidateMySql(String sql) { MySqlWallProvider provider = new MySqlWallProvider(); return provider.checkValid(sql); @@ -42,12 +52,12 @@ public class WallUtils { } public static boolean isValidateSqlServer(String sql) { - SQLServerProvider provider = new SQLServerProvider(); + SQLServerWallProvider provider = new SQLServerWallProvider(); return provider.checkValid(sql); } public static boolean isValidateSqlServer(String sql, WallConfig config) { - SQLServerProvider provider = new SQLServerProvider(config); + SQLServerWallProvider provider = new SQLServerWallProvider(config); return provider.checkValid(sql); } } diff --git a/src/main/java/com/alibaba/druid/wall/WallVisitor.java b/src/main/java/com/alibaba/druid/wall/WallVisitor.java index f1fccfeb24..34c852ed62 100644 --- a/src/main/java/com/alibaba/druid/wall/WallVisitor.java +++ b/src/main/java/com/alibaba/druid/wall/WallVisitor.java @@ -30,7 +30,7 @@ public interface WallVisitor extends SQLASTVisitor { void addViolation(Violation violation); - boolean isPermitTable(String name); + boolean isDenyTable(String name); String toSQL(SQLObject obj); } diff --git a/src/main/java/com/alibaba/druid/wall/spi/MySqlWallProvider.java b/src/main/java/com/alibaba/druid/wall/spi/MySqlWallProvider.java index 8d29f6b93d..2f863bbedc 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/MySqlWallProvider.java +++ b/src/main/java/com/alibaba/druid/wall/spi/MySqlWallProvider.java @@ -19,6 +19,7 @@ import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlExportParameterVisitor; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.visitor.ExportParameterVisitor; +import com.alibaba.druid.util.JdbcConstants; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallProvider; import com.alibaba.druid.wall.WallVisitor; @@ -32,7 +33,7 @@ public class MySqlWallProvider extends WallProvider { } public MySqlWallProvider(WallConfig config){ - super(config); + super(config, JdbcConstants.MYSQL); } @Override diff --git a/src/main/java/com/alibaba/druid/wall/spi/MySqlWallVisitor.java b/src/main/java/com/alibaba/druid/wall/spi/MySqlWallVisitor.java index 8a50af9d04..e3acf710f6 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/MySqlWallVisitor.java +++ b/src/main/java/com/alibaba/druid/wall/spi/MySqlWallVisitor.java @@ -21,27 +21,31 @@ import java.util.List; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLObject; -import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNumericLiteralExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; -import com.alibaba.druid.sql.ast.statement.SQLCallStatement; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLAssignItem; +import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; +import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause; import com.alibaba.druid.sql.ast.statement.SQLSelectItem; import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; -import com.alibaba.druid.sql.ast.statement.SQLTruncateStatement; +import com.alibaba.druid.sql.ast.statement.SQLSetStatement; import com.alibaba.druid.sql.ast.statement.SQLUnionQuery; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlOutFileExpr; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterTableStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement; -import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDescribeStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDropTableStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectGroupBy; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock; @@ -83,11 +87,6 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi return violations; } - public boolean visit(SQLPropertyExpr x) { - WallVisitorUtils.check(this, x); - return true; - } - public boolean visit(SQLInListExpr x) { WallVisitorUtils.check(this, x); return true; @@ -160,7 +159,7 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi @Override public boolean visit(SQLSelectStatement x) { if (!config.isSelelctAllow()) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + this.getViolations().add(new IllegalSQLObjectViolation("select not allow", this.toSQL(x))); return false; } @@ -172,20 +171,70 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi if (x.getRowCount() instanceof SQLNumericLiteralExpr) { int rowCount = ((SQLNumericLiteralExpr) x.getRowCount()).getNumber().intValue(); if (rowCount == 0) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + this.getViolations().add(new IllegalSQLObjectViolation("limit row 0", this.toSQL(x))); } } return true; } + public boolean visit(SQLPropertyExpr x) { + if (x.getOwner() instanceof SQLVariantRefExpr) { + SQLVariantRefExpr varExpr = (SQLVariantRefExpr) x.getOwner(); + SQLObject parent = x.getParent(); + String varName = varExpr.getName(); + if (varName.equalsIgnoreCase("@@session") || varName.equalsIgnoreCase("@@global")) { + if (!(parent instanceof SQLSelectItem) && !(parent instanceof SQLAssignItem)) { + violations.add(new IllegalSQLObjectViolation("variable in condition not allow", toSQL(x))); + return false; + } + + if (!checkVar(x.getParent(), x.getName())) { + violations.add(new IllegalSQLObjectViolation("variable not allow : " + x.getName(), toSQL(x))); + } + return false; + } + } + + WallVisitorUtils.check(this, x); + return true; + } + + public boolean checkVar(SQLObject parent, String varName) { + if (varName == null) { + return false; + } + + if (varName.equals("?")) { + return true; + } + + if (!config.isVariantCheck()) { + return true; + } + + if (varName.startsWith("@@")) { + if (!(parent instanceof SQLSelectItem) && !(parent instanceof SQLAssignItem)) { + return false; + } + + varName = varName.substring(2); + } + + if (config.getPermitVariants().contains(varName)) { + return true; + } + + return false; + } + public boolean visit(SQLVariantRefExpr x) { String varName = x.getName(); if (varName == null) { return false; } - if (config.isVariantCheck() && varName.startsWith("@@")) { - violations.add(new IllegalSQLObjectViolation(toSQL(x))); + if (!checkVar(x.getParent(), x.getName())) { + violations.add(new IllegalSQLObjectViolation("variable not allow : " + x.getName(), toSQL(x))); } return false; @@ -211,7 +260,7 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi @Override public boolean visit(MySqlOutFileExpr x) { if (!config.isSelectIntoOutfileAllow()) { - violations.add(new IllegalSQLObjectViolation(toSQL(x))); + violations.add(new IllegalSQLObjectViolation("into out file not allow", toSQL(x))); } return true; @@ -223,7 +272,7 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi return true; } - + @Override public boolean visit(MySqlUnionQuery x) { WallVisitorUtils.checkUnion(this, x); @@ -237,44 +286,16 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi } @Override - public boolean isPermitTable(String name) { + public boolean isDenyTable(String name) { if (!config.isTableCheck()) { return false; } - name = WallVisitorUtils.form(name); - return config.getPermitTables().contains(name); + return !this.provider.checkDenyTable(name); } public void preVisit(SQLObject x) { - if (!(x instanceof SQLStatement)) { - return; - } - - if (config.isNoneBaseStatementAllow()) { - return; - } - - boolean allow = false; - if (x instanceof SQLInsertStatement) { - allow = true; - } else if (x instanceof SQLSelectStatement) { - allow = true; - } else if (x instanceof SQLDeleteStatement) { - allow = true; - } else if (x instanceof SQLUpdateStatement) { - allow = true; - } else if (x instanceof SQLCallStatement) { - allow = true; - } else if (x instanceof SQLTruncateStatement) { - allow = config.isTruncateAllow(); - } else if (x instanceof MySqlDescribeStatement) { - allow = config.isDescribeAllow(); - } - - if (!allow) { - violations.add(new IllegalSQLObjectViolation(toSQL(x))); - } + WallVisitorUtils.preVisitCheck(this, x); } @Override @@ -282,4 +303,43 @@ public class MySqlWallVisitor extends MySqlASTVisitorAdapter implements WallVisi WallVisitorUtils.check(this, x); return true; } + + @Override + public boolean visit(SQLCreateTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(MySqlCreateTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + public boolean visit(SQLAlterTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(MySqlAlterTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + public boolean visit(SQLDropTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(MySqlDropTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLSetStatement x) { + return false; + } } diff --git a/src/main/java/com/alibaba/druid/wall/spi/OracleWallProvider.java b/src/main/java/com/alibaba/druid/wall/spi/OracleWallProvider.java index 78c9c3291a..a4ff337de3 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/OracleWallProvider.java +++ b/src/main/java/com/alibaba/druid/wall/spi/OracleWallProvider.java @@ -19,6 +19,7 @@ import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleExportParameterVisitor; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.visitor.ExportParameterVisitor; +import com.alibaba.druid.util.JdbcConstants; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallProvider; import com.alibaba.druid.wall.WallVisitor; @@ -32,7 +33,7 @@ public class OracleWallProvider extends WallProvider { } public OracleWallProvider(WallConfig config){ - super(config); + super(config, JdbcConstants.ORACLE); } @Override diff --git a/src/main/java/com/alibaba/druid/wall/spi/OracleWallVisitor.java b/src/main/java/com/alibaba/druid/wall/spi/OracleWallVisitor.java index 86de9d461d..2aeab53636 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/OracleWallVisitor.java +++ b/src/main/java/com/alibaba/druid/wall/spi/OracleWallVisitor.java @@ -21,26 +21,28 @@ import java.util.List; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLObject; -import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; -import com.alibaba.druid.sql.ast.statement.SQLCallStatement; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; +import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause; import com.alibaba.druid.sql.ast.statement.SQLSelectItem; import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; -import com.alibaba.druid.sql.ast.statement.SQLTruncateStatement; +import com.alibaba.druid.sql.ast.statement.SQLSetStatement; import com.alibaba.druid.sql.ast.statement.SQLUnionQuery; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleAlterTableStatement; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleCreateTableStatement; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleDeleteStatement; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleInsertStatement; -import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMergeStatement; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMultiInsertStatement; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMultiInsertStatement.InsertIntoClause; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleSelectQueryBlock; @@ -75,7 +77,7 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi public void addViolation(Violation violation) { this.violations.add(violation); } - + public List getViolations() { return violations; } @@ -83,8 +85,8 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi public boolean visit(SQLIdentifierExpr x) { String name = x.getName(); name = WallVisitorUtils.form(name); - if (config.isVariantCheck() && config.getPermitVariants().contains(name)) { - getViolations().add(new IllegalSQLObjectViolation(toSQL(x))); + if (config.isVariantCheck() && config.getDenyVariants().contains(name)) { + getViolations().add(new IllegalSQLObjectViolation("variable not allow : " + name, toSQL(x))); } return true; } @@ -112,8 +114,7 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi } public boolean visit(OracleSelectTableReference x) { - WallVisitorUtils.check(this, x); - return true; + return WallVisitorUtils.check(this, x); } public boolean visit(SQLExprTableSource x) { @@ -158,7 +159,7 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi } @Override - public boolean isPermitTable(String name) { + public boolean isDenyTable(String name) { if (!config.isTableCheck()) { return false; } @@ -167,46 +168,17 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi if (name.startsWith("v$") || name.startsWith("v_$")) { return true; } - return config.getPermitTables().contains(name); + return !this.provider.checkDenyTable(name); } public void preVisit(SQLObject x) { - if (!(x instanceof SQLStatement)) { - return; - } - - if (config.isNoneBaseStatementAllow()) { - return; - } - - boolean allow = false; - if (x instanceof SQLInsertStatement) { - allow = true; - } else if (x instanceof SQLSelectStatement) { - allow = true; - } else if (x instanceof SQLDeleteStatement) { - allow = true; - } else if (x instanceof SQLUpdateStatement) { - allow = true; - } else if (x instanceof OracleMultiInsertStatement) { - allow = true; - } else if (x instanceof OracleMergeStatement) { - allow = true; - } else if (x instanceof SQLCallStatement) { - allow = true; - } else if (x instanceof SQLTruncateStatement) { - allow = config.isTruncateAllow(); - } - - if (!allow) { - violations.add(new IllegalSQLObjectViolation(toSQL(x))); - } + WallVisitorUtils.preVisitCheck(this, x); } @Override public boolean visit(SQLSelectStatement x) { if (!config.isSelelctAllow()) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + this.getViolations().add(new IllegalSQLObjectViolation("select not allow", this.toSQL(x))); return false; } @@ -235,7 +207,7 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi @Override public boolean visit(OracleMultiInsertStatement x) { if (!config.isInsertAllow()) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + this.getViolations().add(new IllegalSQLObjectViolation("insert not allow", this.toSQL(x))); return false; } @@ -264,10 +236,45 @@ public class OracleWallVisitor extends OracleASTVisitorAdapter implements WallVi return true; } - + @Override public boolean visit(SQLSelectItem x) { WallVisitorUtils.check(this, x); return true; } + + @Override + public boolean visit(SQLCreateTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(OracleCreateTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLAlterTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(OracleAlterTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLDropTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLSetStatement x) { + return false; + } } diff --git a/src/main/java/com/alibaba/druid/wall/spi/PGWallProvider.java b/src/main/java/com/alibaba/druid/wall/spi/PGWallProvider.java new file mode 100644 index 0000000000..62c91f1dc7 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/spi/PGWallProvider.java @@ -0,0 +1,55 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall.spi; + +import com.alibaba.druid.sql.dialect.postgresql.parser.PGSQLStatementParser; +import com.alibaba.druid.sql.dialect.postgresql.visitor.PGExportParameterVisitor; +import com.alibaba.druid.sql.parser.SQLStatementParser; +import com.alibaba.druid.sql.visitor.ExportParameterVisitor; +import com.alibaba.druid.util.JdbcConstants; +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallVisitor; + + +public class PGWallProvider extends WallProvider { + + public final static String DEFAULT_CONFIG_DIR = "META-INF/druid/wall/postgres"; + + public PGWallProvider(){ + this(new WallConfig(DEFAULT_CONFIG_DIR)); + } + + public PGWallProvider(WallConfig config){ + super(config, JdbcConstants.POSTGRESQL); + } + + @Override + public SQLStatementParser createParser(String sql) { + return new PGSQLStatementParser(sql); + } + + @Override + public WallVisitor createWallVisitor() { + return new PGWallVisitor(this); + } + + @Override + public ExportParameterVisitor createExportParameterVisitor() { + return new PGExportParameterVisitor(); + } + +} diff --git a/src/main/java/com/alibaba/druid/wall/spi/PGWallVisitor.java b/src/main/java/com/alibaba/druid/wall/spi/PGWallVisitor.java new file mode 100644 index 0000000000..2a94ac9e27 --- /dev/null +++ b/src/main/java/com/alibaba/druid/wall/spi/PGWallVisitor.java @@ -0,0 +1,229 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.wall.spi; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLName; +import com.alibaba.druid.sql.ast.SQLObject; +import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; +import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; +import com.alibaba.druid.sql.ast.expr.SQLInListExpr; +import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; +import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; +import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; +import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; +import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause; +import com.alibaba.druid.sql.ast.statement.SQLSelectItem; +import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; +import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; +import com.alibaba.druid.sql.ast.statement.SQLSetStatement; +import com.alibaba.druid.sql.ast.statement.SQLUnionQuery; +import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleSelectTableReference; +import com.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGSelectQueryBlock; +import com.alibaba.druid.sql.dialect.postgresql.visitor.PGASTVisitorAdapter; +import com.alibaba.druid.wall.Violation; +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallVisitor; +import com.alibaba.druid.wall.violation.IllegalSQLObjectViolation; + +public class PGWallVisitor extends PGASTVisitorAdapter implements WallVisitor { + + private final WallConfig config; + private final WallProvider provider; + private final List violations = new ArrayList(); + + public PGWallVisitor(WallProvider provider){ + this.config = provider.getConfig(); + this.provider = provider; + } + + public WallProvider getProvider() { + return provider; + } + + public WallConfig getConfig() { + return config; + } + + public void addViolation(Violation violation) { + this.violations.add(violation); + } + + public List getViolations() { + return violations; + } + + public boolean visit(SQLIdentifierExpr x) { + String name = x.getName(); + name = WallVisitorUtils.form(name); + if (config.isVariantCheck() && config.getDenyVariants().contains(name)) { + getViolations().add(new IllegalSQLObjectViolation("variable not allow : " + name, toSQL(x))); + } + return true; + } + + public boolean visit(SQLPropertyExpr x) { + WallVisitorUtils.check(this, x); + return true; + } + + public boolean visit(SQLInListExpr x) { + WallVisitorUtils.check(this, x); + return true; + } + + public boolean visit(SQLBinaryOpExpr x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLMethodInvokeExpr x) { + WallVisitorUtils.checkFunction(this, x); + + return true; + } + + public boolean visit(OracleSelectTableReference x) { + return WallVisitorUtils.check(this, x); + } + + public boolean visit(SQLExprTableSource x) { + WallVisitorUtils.check(this, x); + + if (x.getExpr() instanceof SQLName) { + return false; + } + + return true; + } + + public boolean visit(SQLSelectGroupByClause x) { + WallVisitorUtils.checkHaving(this, x.getHaving()); + return true; + } + + @Override + public boolean visit(SQLSelectQueryBlock x) { + WallVisitorUtils.checkSelelct(this, x); + + return true; + } + + @Override + public boolean visit(PGSelectQueryBlock x) { + WallVisitorUtils.checkSelelct(this, x); + + return true; + } + + @Override + public boolean visit(SQLUnionQuery x) { + WallVisitorUtils.checkUnion(this, x); + + return true; + } + + @Override + public String toSQL(SQLObject obj) { + return SQLUtils.toOracleString(obj); + } + + @Override + public boolean isDenyTable(String name) { + if (!config.isTableCheck()) { + return false; + } + + name = WallVisitorUtils.form(name); + if (name.startsWith("v$") || name.startsWith("v_$")) { + return true; + } + return !this.provider.checkDenyTable(name); + } + + public void preVisit(SQLObject x) { + WallVisitorUtils.preVisitCheck(this, x); + } + + @Override + public boolean visit(SQLSelectStatement x) { + if (!config.isSelelctAllow()) { + this.getViolations().add(new IllegalSQLObjectViolation("selelct not allow", this.toSQL(x))); + return false; + } + + return true; + } + + @Override + public boolean visit(SQLInsertStatement x) { + WallVisitorUtils.checkInsert(this, x); + + return true; + } + + @Override + public boolean visit(SQLDeleteStatement x) { + WallVisitorUtils.checkDelete(this, x); + return true; + } + + @Override + public boolean visit(SQLUpdateStatement x) { + WallVisitorUtils.checkUpdate(this, x); + + return true; + } + + @Override + public boolean visit(SQLSelectItem x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLCreateTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLAlterTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLDropTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLSetStatement x) { + return false; + } +} diff --git a/src/main/java/com/alibaba/druid/wall/spi/SQLServerProvider.java b/src/main/java/com/alibaba/druid/wall/spi/SQLServerWallProvider.java similarity index 85% rename from src/main/java/com/alibaba/druid/wall/spi/SQLServerProvider.java rename to src/main/java/com/alibaba/druid/wall/spi/SQLServerWallProvider.java index f9e2f57013..b636103280 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/SQLServerProvider.java +++ b/src/main/java/com/alibaba/druid/wall/spi/SQLServerWallProvider.java @@ -19,6 +19,7 @@ import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser; import com.alibaba.druid.sql.dialect.sqlserver.visitor.MSSQLServerExportParameterVisitor; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.visitor.ExportParameterVisitor; +import com.alibaba.druid.util.JdbcConstants; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallProvider; import com.alibaba.druid.wall.WallVisitor; @@ -30,19 +31,19 @@ import com.alibaba.druid.wall.WallVisitor; * @version 1.0, 2012-3-17 * @see */ -public class SQLServerProvider extends WallProvider { +public class SQLServerWallProvider extends WallProvider { public final static String DEFAULT_CONFIG_DIR = "META-INF/druid/wall/sqlserver"; /** * @param config */ - public SQLServerProvider(){ + public SQLServerWallProvider(){ this(new WallConfig(DEFAULT_CONFIG_DIR)); } - public SQLServerProvider(WallConfig config){ - super(config); + public SQLServerWallProvider(WallConfig config){ + super(config, JdbcConstants.SQL_SERVER); } @Override diff --git a/src/main/java/com/alibaba/druid/wall/spi/SQLServerWallVisitor.java b/src/main/java/com/alibaba/druid/wall/spi/SQLServerWallVisitor.java index 09fa50ee08..99e64b4ef5 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/SQLServerWallVisitor.java +++ b/src/main/java/com/alibaba/druid/wall/spi/SQLServerWallVisitor.java @@ -21,22 +21,23 @@ import java.util.List; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLObject; -import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; -import com.alibaba.druid.sql.ast.statement.SQLCallStatement; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; +import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause; import com.alibaba.druid.sql.ast.statement.SQLSelectItem; import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; -import com.alibaba.druid.sql.ast.statement.SQLTruncateStatement; +import com.alibaba.druid.sql.ast.statement.SQLSetStatement; import com.alibaba.druid.sql.ast.statement.SQLUnionQuery; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerSelectQueryBlock; @@ -73,20 +74,19 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements public void addViolation(Violation violation) { this.violations.add(violation); } - + @Override public List getViolations() { return violations; } @Override - public boolean isPermitTable(String name) { + public boolean isDenyTable(String name) { if (!config.isTableCheck()) { return false; } - name = WallVisitorUtils.form(name); - return config.getPermitTables().contains(name); + return !this.provider.checkDenyTable(name); } @Override @@ -97,8 +97,8 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements public boolean visit(SQLIdentifierExpr x) { String name = x.getName(); name = WallVisitorUtils.form(name); - if (config.isVariantCheck() && config.getPermitVariants().contains(name)) { - getViolations().add(new IllegalSQLObjectViolation(toSQL(x))); + if (config.isVariantCheck() && config.getDenyVariants().contains(name)) { + getViolations().add(new IllegalSQLObjectViolation("variable not allow : " + name, toSQL(x))); } return true; } @@ -139,7 +139,7 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements WallVisitorUtils.checkHaving(this, x.getHaving()); return true; } - + @Override public boolean visit(SQLServerSelectQueryBlock x) { WallVisitorUtils.checkSelelct(this, x); @@ -162,38 +162,13 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements } public void preVisit(SQLObject x) { - if (!(x instanceof SQLStatement)) { - return; - } - - if (config.isNoneBaseStatementAllow()) { - return; - } - - boolean allow = false; - if (x instanceof SQLInsertStatement) { - allow = true; - } else if (x instanceof SQLSelectStatement) { - allow = true; - } else if (x instanceof SQLDeleteStatement) { - allow = true; - } else if (x instanceof SQLUpdateStatement) { - allow = true; - } else if (x instanceof SQLCallStatement) { - allow = true; - } else if (x instanceof SQLTruncateStatement) { - allow = config.isTruncateAllow(); - } - - if (!allow) { - violations.add(new IllegalSQLObjectViolation(toSQL(x))); - } + WallVisitorUtils.preVisitCheck(this, x); } @Override public boolean visit(SQLSelectStatement x) { if (!config.isSelelctAllow()) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + this.getViolations().add(new IllegalSQLObjectViolation("selelct not allow", this.toSQL(x))); return false; } @@ -202,11 +177,7 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements @Override public boolean visit(SQLInsertStatement x) { - if (!config.isInsertAllow()) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); - return false; - } - + WallVisitorUtils.checkInsert(this, x); return true; } @@ -230,7 +201,7 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements } if (config.isVariantCheck() && varName.startsWith("@@")) { - violations.add(new IllegalSQLObjectViolation(toSQL(x))); + violations.add(new IllegalSQLObjectViolation("global variable not allow", toSQL(x))); } return false; @@ -238,29 +209,52 @@ public class SQLServerWallVisitor extends SQLServerASTVisitorAdapter implements @Override public boolean visit(SQLServerObjectReferenceExpr x) { - if (x.getSchema() != null && config.isPermitSchema(x.getSchema())) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + if (x.getSchema() != null && !provider.checkDenySchema(x.getSchema())) { + this.getViolations().add(new IllegalSQLObjectViolation("schema not allow : " + x.getSchema(), this.toSQL(x))); } - if (x.getDatabase() != null && config.isPermitSchema(x.getDatabase())) { - this.getViolations().add(new IllegalSQLObjectViolation(this.toSQL(x))); + if (x.getDatabase() != null && !provider.checkDenySchema(x.getDatabase())) { + this.getViolations().add(new IllegalSQLObjectViolation("schema not allow : " + x.getDatabase(), + this.toSQL(x))); } return true; } - + @Override public boolean visit(SQLServerInsertStatement x) { - this.visit((SQLInsertStatement) x); - return false; + return this.visit((SQLInsertStatement) x); } @Override public void endVisit(SQLServerInsertStatement x) { - this.endVisit((SQLInsertStatement) x); + this.endVisit((SQLInsertStatement) x); } - + @Override public boolean visit(SQLSelectItem x) { WallVisitorUtils.check(this, x); return true; } + + @Override + public boolean visit(SQLCreateTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLAlterTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLDropTableStatement x) { + WallVisitorUtils.check(this, x); + return true; + } + + @Override + public boolean visit(SQLSetStatement x) { + return false; + } } diff --git a/src/main/java/com/alibaba/druid/wall/spi/WallVisitorUtils.java b/src/main/java/com/alibaba/druid/wall/spi/WallVisitorUtils.java index 830baf67a6..4905e47773 100644 --- a/src/main/java/com/alibaba/druid/wall/spi/WallVisitorUtils.java +++ b/src/main/java/com/alibaba/druid/wall/spi/WallVisitorUtils.java @@ -19,9 +19,9 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.math.BigDecimal; import java.net.URL; import java.util.ArrayList; +import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Set; @@ -29,6 +29,7 @@ import java.util.Set; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLObject; +import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr; import com.alibaba.druid.sql.ast.expr.SQLAllColumnExpr; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; @@ -40,30 +41,50 @@ import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNCharExpr; import com.alibaba.druid.sql.ast.expr.SQLNotExpr; -import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; import com.alibaba.druid.sql.ast.expr.SQLNumericLiteralExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLQueryExpr; +import com.alibaba.druid.sql.ast.statement.SQLAlterTableStatement; +import com.alibaba.druid.sql.ast.statement.SQLCallStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; +import com.alibaba.druid.sql.ast.statement.SQLDropTableStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertInto; +import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; import com.alibaba.druid.sql.ast.statement.SQLSelect; import com.alibaba.druid.sql.ast.statement.SQLSelectItem; import com.alibaba.druid.sql.ast.statement.SQLSelectQuery; import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock; +import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; +import com.alibaba.druid.sql.ast.statement.SQLSetStatement; import com.alibaba.druid.sql.ast.statement.SQLSubqueryTableSource; import com.alibaba.druid.sql.ast.statement.SQLTableSource; +import com.alibaba.druid.sql.ast.statement.SQLTruncateStatement; +import com.alibaba.druid.sql.ast.statement.SQLUnionOperator; import com.alibaba.druid.sql.ast.statement.SQLUnionQuery; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDescribeStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlReplaceStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSetCharSetStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSetNamesStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlShowStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateStatement; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMergeStatement; +import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMultiInsertStatement; import com.alibaba.druid.sql.visitor.ExportParameterVisitor; +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.druid.util.JdbcUtils; import com.alibaba.druid.util.ServletPathMatcher; +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallContext; import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallSqlTableStat; import com.alibaba.druid.wall.WallVisitor; import com.alibaba.druid.wall.violation.IllegalSQLObjectViolation; @@ -79,6 +100,44 @@ public class WallVisitorUtils { } + public static void check(WallVisitor visitor, SQLCreateTableStatement x) { + String tableName = ((SQLName) x.getName()).getSimleName(); + WallContext context = WallContext.current(); + if (context != null) { + WallSqlTableStat tableStat = context.getTableStat(tableName); + if (tableStat != null) { + tableStat.incrementCreateCount(); + } + } + } + + public static void check(WallVisitor visitor, SQLAlterTableStatement x) { + String tableName = ((SQLName) x.getName()).getSimleName(); + WallContext context = WallContext.current(); + if (context != null) { + WallSqlTableStat tableStat = context.getTableStat(tableName); + if (tableStat != null) { + tableStat.incrementAlterCount(); + } + } + } + + public static void check(WallVisitor visitor, SQLDropTableStatement x) { + for (SQLTableSource item : x.getTableSources()) { + if (item instanceof SQLExprTableSource) { + SQLExpr expr = ((SQLExprTableSource) item).getExpr(); + String tableName = ((SQLName) expr).getSimleName(); + WallContext context = WallContext.current(); + if (context != null) { + WallSqlTableStat tableStat = context.getTableStat(tableName); + if (tableStat != null) { + tableStat.incrementDropCount(); + } + } + } + } + } + public static void check(WallVisitor visitor, SQLSelectItem x) { if (visitor.getConfig().isSelectAllColumnAllow()) { return; @@ -88,9 +147,9 @@ public class WallVisitorUtils { && x.getParent() instanceof SQLSelectQueryBlock) { SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) x.getParent(); SQLTableSource from = queryBlock.getFrom(); - + if (from instanceof SQLExprTableSource) { - addViolation(visitor, x); + addViolation(visitor, "'SELECT *' not allow", x); } } } @@ -103,7 +162,7 @@ public class WallVisitorUtils { checkReadOnly(visitor, x.getTableSource()); if (!visitor.getConfig().isInsertAllow()) { - addViolation(visitor, x); + addViolation(visitor, "insert not allow", x); } } @@ -117,12 +176,12 @@ public class WallVisitorUtils { } if (!visitor.getConfig().isSelectIntoAllow() && x.getInto() != null) { - addViolation(visitor, x); + addViolation(visitor, "select into not allow", x); return; } - if (!visitor.getConfig().isSelectWhereAlwayTrueCheck()) { - return; + if (x.getFrom() != null) { + x.getFrom().setParent(x); } SQLExpr where = x.getWhere(); @@ -131,19 +190,22 @@ public class WallVisitorUtils { x.getWhere().setParent(x); checkCondition(visitor, x.getWhere()); - if (Boolean.TRUE == getValue(where)) { + if (Boolean.TRUE == getConditionValue(visitor, where, visitor.getConfig().isSelectWhereAlwayTrueCheck())) { + boolean isSimpleConstExpr = false; if (where instanceof SQLBinaryOpExpr) { SQLBinaryOpExpr binaryOpExpr = (SQLBinaryOpExpr) where; if (binaryOpExpr.getOperator() == SQLBinaryOperator.Equality || binaryOpExpr.getOperator() == SQLBinaryOperator.NotEqual) { if (binaryOpExpr.getLeft() instanceof SQLIntegerExpr && binaryOpExpr.getRight() instanceof SQLIntegerExpr) { - return; + isSimpleConstExpr = true; } } } - addViolation(visitor, x); + if (!isSimpleConstExpr) { + addViolation(visitor, "select alway true condition not allow", x); + } } } @@ -155,33 +217,30 @@ public class WallVisitorUtils { return; } - if (!visitor.getConfig().isSelectHavingAlwayTrueCheck()) { - return; - } - - if (Boolean.TRUE == getValue(x)) { - addViolation(visitor, x); + if (Boolean.TRUE == getConditionValue(visitor, x, visitor.getConfig().isSelectHavingAlwayTrueCheck())) { + addViolation(visitor, "having alway true condition not allow", x); } } public static void checkDelete(WallVisitor visitor, SQLDeleteStatement x) { checkReadOnly(visitor, x.getExprTableSource()); - if (!visitor.getConfig().isDeleteAllow()) { - addViolation(visitor, x); + WallConfig config = visitor.getConfig(); + if (!config.isDeleteAllow()) { + addViolation(visitor, "delete not allow", x); return; } - if (!visitor.getConfig().isDeleteWhereAlwayTrueCheck()) { + if (x.getWhere() == null && config.isDeleteWhereNoneCheck()) { + addViolation(visitor, "delete none condition not allow", x); return; } - if (x.getWhere() == null || Boolean.TRUE == getValue(x.getWhere())) { - addViolation(visitor, x); + if (Boolean.TRUE == getConditionValue(visitor, x.getWhere(), config.isDeleteWhereAlwayTrueCheck())) { + addViolation(visitor, "delete alway true condition not allow", x); return; } - x.getWhere().setParent(x); checkCondition(visitor, x.getWhere()); checkConditionForMultiTenant(visitor, x.getWhere(), x); } @@ -196,7 +255,7 @@ public class WallVisitorUtils { x.accept(exportParameterVisitor); if (exportParameterVisitor.getParameters().size() > 0) { - addViolation(visitor, x); + addViolation(visitor, "sql must parameterized", x); return; } } @@ -345,11 +404,9 @@ public class WallVisitorUtils { tableName = ((SQLName) tableNameExpr).getSimleName(); } - if (tableName != null) { - tableName = form(tableName); - if (visitor.getConfig().getReadOnlyTables().contains(tableName)) { - addViolation(visitor, tableSource); - } + boolean readOnlyValid = visitor.getProvider().checkReadOnlyTable(tableName); + if (!readOnlyValid) { + addViolation(visitor, "table readonly : " + tableName, tableSource); } } else if (tableSource instanceof SQLJoinTableSource) { SQLJoinTableSource join = (SQLJoinTableSource) tableSource; @@ -362,26 +419,39 @@ public class WallVisitorUtils { public static void checkUpdate(WallVisitor visitor, SQLUpdateStatement x) { checkReadOnly(visitor, x.getTableSource()); - if (!visitor.getConfig().isUpdateAllow()) { - addViolation(visitor, x); + WallConfig config = visitor.getConfig(); + if (!config.isUpdateAllow()) { + addViolation(visitor, "update not allow", x); return; } - if (!visitor.getConfig().isUpdateWhereAlayTrueCheck()) { - return; + if (x.getWhere() == null && config.isUpdateWhereNoneCheck()) { + if (x instanceof MySqlUpdateStatement) { + MySqlUpdateStatement mysqlUpdate = (MySqlUpdateStatement) x; + if (mysqlUpdate.getLimit() == null) { + addViolation(visitor, "update none condition not allow", x); + return; + } + } else { + addViolation(visitor, "update none condition not allow", x); + return; + } } - if (x.getWhere() == null || Boolean.TRUE == getValue(x.getWhere())) { - addViolation(visitor, x); - return; + if (config.isUpdateWhereAlayTrueCheck()) { + if (Boolean.TRUE == getConditionValue(visitor, x.getWhere(), true)) { + addViolation(visitor, "update alway true condition not allow", x); + return; + } } - x.getWhere().setParent(x); + if (x.getWhere() != null) { + x.getWhere().setParent(x); + } checkCondition(visitor, x.getWhere()); checkConditionForMultiTenant(visitor, x.getWhere(), x); } - @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object getValue(SQLBinaryOpExpr x) { x.getLeft().setParent(x); x.getRight().setParent(x); @@ -431,6 +501,10 @@ public class WallVisitorUtils { for (int i = groupList.size() - 1; i >= 0; --i) { Object result = getValue(groupList.get(i)); if (Boolean.TRUE == result) { + final WallConditionContext wallContext = WallVisitorUtils.getWallConditionContext(); + if (wallContext != null) { + wallContext.setPartAlwayTrue(true); + } return true; } @@ -454,135 +528,127 @@ public class WallVisitorUtils { return false; } + if (leftResult == Boolean.TRUE) { + if (!isFirst(x.getLeft())) { + final WallConditionContext current = wallConditionContextLocal.get(); + if (current != null) { + current.setPartAlwayTrue(true); + } + } + } else if (rightResult == Boolean.TRUE) { + final WallConditionContext current = wallConditionContextLocal.get(); + if (current != null) { + current.setPartAlwayTrue(true); + } + } + if (Boolean.TRUE == leftResult && Boolean.TRUE == rightResult) { return true; } } - if (x.getOperator() == SQLBinaryOperator.Like) { - if (x.getRight() instanceof SQLCharExpr) { - String text = ((SQLCharExpr) x.getRight()).getText(); - - if (text.length() >= 0) { - for (char ch : text.toCharArray()) { - if (ch != '%') { - return null; - } - } - - return true; - } - - } + String dbType = null; + WallContext wallContext = WallContext.current(); + if (wallContext != null) { + dbType = wallContext.getDbType(); } - if (leftResult == null || rightResult == null) { - return null; - } - - if (x.getOperator() == SQLBinaryOperator.Equality) { - if (x.getLeft() instanceof SQLNullExpr && x.getRight() instanceof SQLNullExpr) { - return true; - } - - return leftResult.equals(rightResult); - } - - if (x.getOperator() == SQLBinaryOperator.NotEqual || x.getOperator() == SQLBinaryOperator.LessThanOrGreater) { - if (x.getLeft() instanceof SQLNullExpr && x.getRight() instanceof SQLNullExpr) { - return false; - } - - if (leftResult == null || rightResult == null) { - return null; - } - - return !leftResult.equals(rightResult); - } - - if (x.getOperator() == SQLBinaryOperator.GreaterThan) { - if (x.getLeft() instanceof SQLNullExpr && x.getRight() instanceof SQLNullExpr) { - return false; - } - - if (leftResult == null || rightResult == null) { - return null; - } - - if (leftResult instanceof Comparable) { - return (((Comparable) leftResult).compareTo(rightResult) > 0); - } - } - - if (x.getOperator() == SQLBinaryOperator.GreaterThanOrEqual) { - if (x.getLeft() instanceof SQLNullExpr && x.getRight() instanceof SQLNullExpr) { - return false; - } - - if (leftResult == null || rightResult == null) { - return null; - } - - if (leftResult instanceof Comparable) { - return ((Comparable) leftResult).compareTo(rightResult) >= 0; - } - } - - if (x.getOperator() == SQLBinaryOperator.LessThan) { - if (x.getLeft() instanceof SQLNullExpr && x.getRight() instanceof SQLNullExpr) { - return false; - } - - if (leftResult == null || rightResult == null) { - return null; - } - - if (leftResult instanceof Comparable) { - return (((Comparable) leftResult).compareTo(rightResult) < 0); - } - } - - if (x.getOperator() == SQLBinaryOperator.LessThanOrEqual) { - if (x.getLeft() instanceof SQLNullExpr && x.getRight() instanceof SQLNullExpr) { - return false; - } - - if (leftResult == null || rightResult == null) { - return null; - } - - if (leftResult instanceof Comparable) { - return ((Comparable) leftResult).compareTo(rightResult) <= 0; - } - } - - if (x.getOperator() == SQLBinaryOperator.Concat) { - return leftResult.toString() + rightResult.toString(); - } - - if (x.getOperator() == SQLBinaryOperator.Add) { - if (leftResult == null || rightResult == null) { - return null; - } - - if (leftResult instanceof String || rightResult instanceof String) { - return leftResult.toString() + rightResult.toString(); - } - - if (leftResult instanceof Number || rightResult instanceof Number) { - return add((Number) leftResult, (Number) rightResult); - } - } - - return null; + return SQLEvalVisitorUtils.eval(dbType, x, Collections.emptyList(), false); } - private static Number add(Number a, Number b) { - if (a instanceof BigDecimal) { - return ((BigDecimal) a).add(new BigDecimal(b.toString())); + public static boolean isFirst(SQLObject x) { + if (x == null) { + return true; } - return a.longValue() + b.longValue(); + SQLObject parent = x.getParent(); + if (!(parent instanceof SQLExpr)) { + return true; + } + + if (parent instanceof SQLBinaryOpExpr) { + SQLBinaryOpExpr binaryExpr = (SQLBinaryOpExpr) parent; + if (isFirst(binaryExpr) && x == binaryExpr.getLeft()) { + return true; + } + } + + return false; + } + + public static class WallConditionContext { + + private boolean partAlwayrue; + private boolean constArithmetic = false; + private boolean xor = false; + private boolean bitwise = false; + + public boolean hasPartAlwayTrue() { + return partAlwayrue; + } + + public void setPartAlwayTrue(boolean partAllowTrue) { + this.partAlwayrue = partAllowTrue; + } + + public boolean hasConstArithmetic() { + return constArithmetic; + } + + public void setConstArithmetic(boolean constArithmetic) { + this.constArithmetic = constArithmetic; + } + + public boolean hasXor() { + return xor; + } + + public void setXor(boolean xor) { + this.xor = xor; + } + + public boolean hasBitwise() { + return bitwise; + } + + public void setBitwise(boolean bitwise) { + this.bitwise = bitwise; + } + } + + private static ThreadLocal wallConditionContextLocal = new ThreadLocal(); + + public static WallConditionContext getWallConditionContext() { + return wallConditionContextLocal.get(); + } + + public static Object getConditionValue(WallVisitor visitor, SQLExpr x, boolean alwayTrueCheck) { + final WallConditionContext old = wallConditionContextLocal.get(); + try { + wallConditionContextLocal.set(new WallConditionContext()); + final Object value = getValue(x); + + final WallConditionContext current = wallConditionContextLocal.get(); + if (current.hasPartAlwayTrue() && alwayTrueCheck) { + addViolation(visitor, "part alway true condition not allow", x); + } + + if (current.hasConstArithmetic() && !visitor.getConfig().isConstArithmeticAllow()) { + addViolation(visitor, "const arithmetic not allow", x); + } + + if (current.hasXor() && !visitor.getConfig().isConditionOpXorAllow()) { + addViolation(visitor, "xor not allow", x); + } + + if (current.hasBitwise() && !visitor.getConfig().isConditionOpBitwseAllow()) { + addViolation(visitor, "bitwise operator not allow", x); + } + + return value; + } finally { + wallConditionContextLocal.set(old); + } } public static Object getValue(SQLExpr x) { @@ -733,58 +799,113 @@ public class WallVisitorUtils { } String methodName = x.getMethodName(); + + WallContext context = WallContext.current(); + if (context != null) { + context.incrementFunctionInvoke(methodName); + } - if (visitor.getConfig().isPermitFunction(methodName.toLowerCase())) { - addViolation(visitor, x); + if (!visitor.getProvider().checkDenyFunction(methodName)) { + addViolation(visitor, "deny function : " + methodName, x); } } - private static void checkSchema(WallVisitor visitor, SQLExpr x) { + private static boolean checkSchema(WallVisitor visitor, SQLExpr x) { if (x instanceof SQLName) { String owner = ((SQLName) x).getSimleName(); owner = WallVisitorUtils.form(owner); - if (visitor.getConfig().isPermitSchema(owner)) { - addViolation(visitor, x); + if (!visitor.getProvider().checkDenySchema(owner)) { + addViolation(visitor, "deny schema : " + owner, x); + return false; } - if (visitor.getConfig().isPermitObjects(owner)) { - addViolation(visitor, x); + if (visitor.getConfig().isDenyObjects(owner)) { + addViolation(visitor, "deny object : " + owner, x); + return false; } } // if (ownerExpr instanceof SQLPropertyExpr) { if (x instanceof SQLPropertyExpr) { - checkSchema(visitor, ((SQLPropertyExpr) x).getOwner()); + return checkSchema(visitor, ((SQLPropertyExpr) x).getOwner()); } + + return true; } - public static void check(WallVisitor visitor, SQLExprTableSource x) { + public static boolean check(WallVisitor visitor, SQLExprTableSource x) { SQLExpr expr = x.getExpr(); if (expr instanceof SQLPropertyExpr) { - checkSchema(visitor, ((SQLPropertyExpr) expr).getOwner()); + boolean checkResult = checkSchema(visitor, ((SQLPropertyExpr) expr).getOwner()); + if (!checkResult) { + return false; + } } if (expr instanceof SQLName) { String tableName = ((SQLName) expr).getSimleName(); - if (visitor.isPermitTable(tableName)) { - addViolation(visitor, x); + + WallContext context = WallContext.current(); + if (context != null) { + WallSqlTableStat tableStat = context.getTableStat(tableName); + if (tableStat != null) { + SQLObject parent = x.getParent(); + + while (parent instanceof SQLTableSource) { + parent = parent.getParent(); + } + + if (parent instanceof SQLSelectQueryBlock) { + SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) parent; + if (x == queryBlock.getInto()) { + tableStat.incrementSelectIntoCount(); + } else { + tableStat.incrementSelectCount(); + } + } else if (parent instanceof SQLTruncateStatement) { + tableStat.incrementTruncateCount(); + } else if (parent instanceof SQLInsertStatement) { + tableStat.incrementInsertCount(); + } else if (parent instanceof SQLDeleteStatement) { + tableStat.incrementDeleteCount(); + } else if (parent instanceof SQLUpdateStatement) { + tableStat.incrementUpdateCount(); + } + } + } + + if (visitor.isDenyTable(tableName)) { + addViolation(visitor, "deny table : " + tableName, x); + return false; } } + + return true; } - private static void addViolation(WallVisitor visitor, SQLObject x) { - visitor.addViolation(new IllegalSQLObjectViolation(visitor.toSQL(x))); + private static void addViolation(WallVisitor visitor, String message, SQLObject x) { + visitor.addViolation(new IllegalSQLObjectViolation(message, visitor.toSQL(x))); } public static void checkUnion(WallVisitor visitor, SQLUnionQuery x) { + if (x.getOperator() == SQLUnionOperator.MINUS && !visitor.getConfig().isMinusAllow()) { + addViolation(visitor, "minus not allow", x); + return; + } + + if (x.getOperator() == SQLUnionOperator.INTERSECT && !visitor.getConfig().isIntersectAllow()) { + addViolation(visitor, "intersect not allow", x); + return; + } + if (!visitor.getConfig().isSelectUnionCheck()) { return; } if (WallVisitorUtils.queryBlockFromIsNull(x.getLeft()) || WallVisitorUtils.queryBlockFromIsNull(x.getRight())) { - addViolation(visitor, x); + addViolation(visitor, "union query not contains 'from clause'", x); } } @@ -876,7 +997,75 @@ public class WallVisitorUtils { } } } catch (IOException e) { - LOG.error("load oracle permit tables errror", e); + LOG.error("load oracle deny tables errror", e); + } + } + + public static void preVisitCheck(WallVisitor visitor, SQLObject x) { + WallConfig config = visitor.getProvider().getConfig(); + + if (!(x instanceof SQLStatement)) { + return; + } + + boolean allow = false; + String denyMessage = null; + if (x instanceof SQLInsertStatement) { + allow = true; + denyMessage = "insert not allow"; + } else if (x instanceof SQLSelectStatement) { + allow = true; + denyMessage = "select not allow"; + } else if (x instanceof SQLDeleteStatement) { + allow = true; + denyMessage = "delete not allow"; + } else if (x instanceof SQLUpdateStatement) { + allow = true; + denyMessage = "update not allow"; + } else if (x instanceof OracleMultiInsertStatement) { + allow = true; + denyMessage = "multi-insert not allow"; + } else if (x instanceof OracleMergeStatement) { + allow = true; + denyMessage = "merge not allow"; + } else if (x instanceof SQLCallStatement) { + allow = true; + denyMessage = "call not allow"; + } else if (x instanceof SQLTruncateStatement) { + allow = config.isTruncateAllow(); + denyMessage = "truncate not allow"; + } else if (x instanceof SQLCreateTableStatement) { + allow = config.isCreateTableAllow(); + denyMessage = "create table not allow"; + } else if (x instanceof SQLAlterTableStatement) { + allow = config.isAlterTableAllow(); + denyMessage = "alter table not allow"; + } else if (x instanceof SQLDropTableStatement) { + allow = config.isDropTableAllow(); + denyMessage = "drop table not allow"; + } else if (x instanceof MySqlSetCharSetStatement // + || x instanceof MySqlSetNamesStatement // + || x instanceof SQLSetStatement) { + allow = config.isSetAllow(); + denyMessage = "set not allow"; + } else if (x instanceof MySqlReplaceStatement) { + allow = config.isReplaceAllow(); + denyMessage = "replace not allow"; + } else if (x instanceof MySqlDescribeStatement) { + allow = config.isDescribeAllow(); + denyMessage = "describe not allow"; + } else if (x instanceof MySqlShowStatement) { + allow = config.isShowAllow(); + denyMessage = "show not allow"; + } else { + allow = config.isNoneBaseStatementAllow(); + } + + if (!allow) { + if (denyMessage == null) { + denyMessage = x.getClass() + " not allow"; + } + addViolation(visitor, denyMessage, x); } } } diff --git a/src/main/java/com/alibaba/druid/wall/violation/IllegalSQLObjectViolation.java b/src/main/java/com/alibaba/druid/wall/violation/IllegalSQLObjectViolation.java index b8733193c4..d13ee4e68b 100644 --- a/src/main/java/com/alibaba/druid/wall/violation/IllegalSQLObjectViolation.java +++ b/src/main/java/com/alibaba/druid/wall/violation/IllegalSQLObjectViolation.java @@ -19,13 +19,11 @@ import com.alibaba.druid.wall.Violation; public class IllegalSQLObjectViolation implements Violation { + private String message; private String sqlPart; - public IllegalSQLObjectViolation(){ - - } - - public IllegalSQLObjectViolation(String condition){ + public IllegalSQLObjectViolation(String message, String condition){ + this.message = message; this.sqlPart = condition; } @@ -41,4 +39,15 @@ public class IllegalSQLObjectViolation implements Violation { return this.sqlPart; } + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + } diff --git a/src/main/java/com/alibaba/druid/wall/violation/SyntaxErrorViolation.java b/src/main/java/com/alibaba/druid/wall/violation/SyntaxErrorViolation.java index 31f59d16da..97294b152d 100644 --- a/src/main/java/com/alibaba/druid/wall/violation/SyntaxErrorViolation.java +++ b/src/main/java/com/alibaba/druid/wall/violation/SyntaxErrorViolation.java @@ -41,4 +41,11 @@ public class SyntaxErrorViolation implements Violation { return sql; } + public String getMessage() { + if (exception == null) { + return null; + } + + return exception.getMessage(); + } } diff --git a/src/main/resources/META-INF/druid/wall/mysql/deny-function.txt b/src/main/resources/META-INF/druid/wall/mysql/deny-function.txt new file mode 100644 index 0000000000..ad53b20f9d --- /dev/null +++ b/src/main/resources/META-INF/druid/wall/mysql/deny-function.txt @@ -0,0 +1,11 @@ +version +load_file +database +schema +user +system_user +session_user +benchmark +connection_id +current_user +sleep \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/mysql/deny-schema.txt b/src/main/resources/META-INF/druid/wall/mysql/deny-schema.txt new file mode 100644 index 0000000000..a45759cb32 --- /dev/null +++ b/src/main/resources/META-INF/druid/wall/mysql/deny-schema.txt @@ -0,0 +1,3 @@ +information_schema +mysql +performance_schema \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/mysql/permit-function.txt b/src/main/resources/META-INF/druid/wall/mysql/permit-function.txt index 94141d2884..518f788238 100644 --- a/src/main/resources/META-INF/druid/wall/mysql/permit-function.txt +++ b/src/main/resources/META-INF/druid/wall/mysql/permit-function.txt @@ -1,10 +1,219 @@ -version -load_file -databse -schema -user -system_user -session_user -benchmark -connection_id -current_user \ No newline at end of file +abs +acos +adddate +addtime +aes_decrypt +aes_encrypt +ascii +asin +atan +atan2 +avg +bin +binary +bit_and +bit_count +bit_length +bit_or +bit_xor +cast +ceil +ceiling +char_length +char +character_length +charset +coalesce +coercibility +collation +compress +concat_ws +concat +conv +convert_tz +convert +cos +cot +count(distinct) +count +crc32 +curdate +current_date +current_time +current_timestamp +curtime +date_add +date_format +date_sub +date +datediff +day +dayname +dayofmonth +dayofweek +dayofyear +decode +default +degrees +des_decrypt +des_encrypt +div +elt +encode +encrypt +exp +export_set +extract +extractvalue +field +find_in_set +floor +format +found_rows +from_base64 +from_days +from_unixtime +get_format +greatest +group_concat +gtid_subset +gtid_subtract +hex +hour +if +ifnull +inet_aton +inet_ntoa +inet6_aton +inet6_ntoa +insert +instr +interval +is_free_lock +is_ipv4_compat +is_ipv4_mapped +is_ipv4 +is_ipv6 +is_used_lock +last_day +last_insert_id +lcase +least +left +length +ln +localtime +localtimestamp +locate +log10 +log2 +log +lower +lpad +ltrim +make_set +makedate +maketime +master_pos_wait +match +max +md5 +microsecond +mid +min +minute +mod +month +monthname +name_const +not +now +nullif +oct +octet_length +old_password +ord +password +period_add +period_diff +pi +position +pow +power +procedure +quarter +quote +radians +rand +regexp +release_lock +repeat +replace +reverse +right +rlike +round +row_count +rpad +rtrim +sec_to_time +second +sha1 +sha2 +sign +sin +sleep +soundex +sounds +space +sqrt +std +stddev_pop +stddev_samp +stddev +str_to_date +strcmp +subdate +substr +substring_index +substring +subtime +sum +sysdate +tan +time_format +time_to_sec +time +timediff +timestamp +timestampadd +timestampdiff +to_base64 +to_days +to_seconds +trim +truncate +ucase +uncompress +uncompressed_length +unhex +unix_timestamp +updatexml +upper +utc_date +utc_time +utc_timestamp +uuid_short +uuid +validate_password_strength +values +var_pop +var_samp +variance +wait_until_sql_thread_after_gtids +week +weekday +weekofyear +weight_string +year +yearweek \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/mysql/permit-schema.txt b/src/main/resources/META-INF/druid/wall/mysql/permit-schema.txt deleted file mode 100644 index b0fb0a2d49..0000000000 --- a/src/main/resources/META-INF/druid/wall/mysql/permit-schema.txt +++ /dev/null @@ -1,2 +0,0 @@ -information_schema -mysql \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/mysql/permit-variant.txt b/src/main/resources/META-INF/druid/wall/mysql/permit-variant.txt new file mode 100644 index 0000000000..3c3efbb201 --- /dev/null +++ b/src/main/resources/META-INF/druid/wall/mysql/permit-variant.txt @@ -0,0 +1,21 @@ +auto_increment_increment +auto_increment_offset +autocommit +automatic_sp_privileges +character_set_client +character_set_database +character_set_connection +character_set_results +character-set-server +collation_connection +collation_database +collation-server +insert_id +last_insert_id +read_only +sql_auto_is_null +sql_big_selects +sql_big_tables +sql_mode +tx_isolation +warning_count \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/oracle/deny-function.txt b/src/main/resources/META-INF/druid/wall/oracle/deny-function.txt new file mode 100644 index 0000000000..a44961cce4 --- /dev/null +++ b/src/main/resources/META-INF/druid/wall/oracle/deny-function.txt @@ -0,0 +1,3 @@ +SYS_CONTEXT +USERENV +SYS_TYPEID \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/oracle/permit-object.txt b/src/main/resources/META-INF/druid/wall/oracle/deny-object.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/oracle/permit-object.txt rename to src/main/resources/META-INF/druid/wall/oracle/deny-object.txt diff --git a/src/main/resources/META-INF/druid/wall/oracle/permit-schema.txt b/src/main/resources/META-INF/druid/wall/oracle/deny-schema.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/oracle/permit-schema.txt rename to src/main/resources/META-INF/druid/wall/oracle/deny-schema.txt diff --git a/src/main/resources/META-INF/druid/wall/oracle/permit-table.txt b/src/main/resources/META-INF/druid/wall/oracle/deny-table.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/oracle/permit-table.txt rename to src/main/resources/META-INF/druid/wall/oracle/deny-table.txt diff --git a/src/main/resources/META-INF/druid/wall/oracle/permit-variant.txt b/src/main/resources/META-INF/druid/wall/oracle/deny-variant.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/oracle/permit-variant.txt rename to src/main/resources/META-INF/druid/wall/oracle/deny-variant.txt diff --git a/src/main/resources/META-INF/druid/wall/oracle/permit-function.txt b/src/main/resources/META-INF/druid/wall/oracle/permit-function.txt index ebbdd42dfd..525d9e01bf 100644 --- a/src/main/resources/META-INF/druid/wall/oracle/permit-function.txt +++ b/src/main/resources/META-INF/druid/wall/oracle/permit-function.txt @@ -1,4 +1,159 @@ -SYS_CONTEXT -USERENV -SYS_GUID -SYS_TYPEID \ No newline at end of file +abs +acos +asin +atan +atan2 +bitand +ceil +cos +cosh +exp +floor +ln +log +mod +nanvl +power +remainder +round +sign +sin +sinh +sqrt +tan +tanh +trunc +width_bucket + +CHR +CONCAT +INITCAP +LOWER +LPAD +LTRIM +NLS_INITCAP +NLS_LOWER +NLSSORT +NLS_UPPER +REGEXP_REPLACE +REGEXP_SUBSTR +REPLACE +RPAD +RTRIM +SOUNDEX +SUBSTR +TRANSLATE +TREAT +TRIM +UPPER + +NLS_CHARSET_DECL_LEN +NLS_CHARSET_ID +NLS_CHARSET_NAME + +ASCII +INSTR +LENGTH +REGEXP_INSTR + +ADD_MONTHS +CURRENT_DATE +CURRENT_TIMESTAMP +DBTIMEZONE +EXTRACT +FROM_TZ +LAST_DAY +LOCALTIMESTAMP +MONTHS_BETWEEN +NEW_TIME +NEXT_DAY +NUMTODSINTERVAL +NUMTOYMINTERVAL +ROUND +SESSIONTIMEZONE +SYS_EXTRACT_UTC +SYSDATE +SYSTIMESTAMP +TO_CHAR +TO_TIMESTAMP +TO_TIMESTAMP_TZ +TO_DSINTERVAL +TO_YMINTERVAL +TRUNC +TZ_OFFSET + +GREATEST +LEAST + +ASCIISTR +BIN_TO_NUM +CAST +CHARTOROWID +COMPOSE +CONVERT +DECOMPOSE +HEXTORAW +NUMTODSINTERVAL +NUMTOYMINTERVAL +RAWTOHEX +RAWTONHEX +ROWIDTOCHAR +ROWIDTONCHAR +SCN_TO_TIMESTAMP +TIMESTAMP_TO_SCN +TO_BINARY_DOUBLE +TO_BINARY_FLOAT +TO_CHAR +TO_CLOB +TO_DATE +TO_DSINTERVAL +TO_LOB +TO_MULTI_BYTE +TO_NCHAR +TO_NCLOB +TO_NUMBER +TO_DSINTERVAL +TO_SINGLE_BYTE +TO_TIMESTAMP +TO_TIMESTAMP_TZ +TO_YMINTERVAL +TO_YMINTERVAL +TRANSLATE +UNISTR + +BFILENAME +EMPTY_BLOB +EMPTY_CLOB + +CARDINALITY +COLLECT +POWERMULTISET +POWERMULTISET_BY_CARDINALITY +SET + +SYS_CONNECT_BY_PATH + +CLUSTER_ID +CLUSTER_PROBABILITY +CLUSTER_SET +FEATURE_ID +FEATURE_SET +FEATURE_VALUE +PREDICTION +PREDICTION_BOUNDS +PREDICTION_COST +PREDICTION_DETAILS +PREDICTION_PROBABILITY +PREDICTION_SET + +DECODE +DUMP +ORA_HASH +VSIZE + +COALESCE +LNNVL +NULLIF +NVL +NVL2 + diff --git a/src/main/resources/META-INF/druid/wall/postgres/deny-function.txt b/src/main/resources/META-INF/druid/wall/postgres/deny-function.txt new file mode 100644 index 0000000000..829b333277 --- /dev/null +++ b/src/main/resources/META-INF/druid/wall/postgres/deny-function.txt @@ -0,0 +1,20 @@ +current_catalog +current_database +current_query +current_schema +current_schemas +current_user +inet_client_addr +inet_client_port +inet_server_addr +inet_server_port +pg_backend_pid +pg_conf_load_time +pg_is_other_temp_schema +pg_listening_channels +pg_my_temp_schema +pg_postmaster_start_time +pg_trigger_depth +session_user +user +version \ No newline at end of file diff --git a/src/main/resources/META-INF/druid/wall/sqlserver/permit-function.txt b/src/main/resources/META-INF/druid/wall/sqlserver/deny-function.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/sqlserver/permit-function.txt rename to src/main/resources/META-INF/druid/wall/sqlserver/deny-function.txt diff --git a/src/main/resources/META-INF/druid/wall/sqlserver/permit-object.txt b/src/main/resources/META-INF/druid/wall/sqlserver/deny-object.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/sqlserver/permit-object.txt rename to src/main/resources/META-INF/druid/wall/sqlserver/deny-object.txt diff --git a/src/main/resources/META-INF/druid/wall/sqlserver/permit-schema.txt b/src/main/resources/META-INF/druid/wall/sqlserver/deny-schema.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/sqlserver/permit-schema.txt rename to src/main/resources/META-INF/druid/wall/sqlserver/deny-schema.txt diff --git a/src/main/resources/META-INF/druid/wall/sqlserver/permit-table.txt b/src/main/resources/META-INF/druid/wall/sqlserver/deny-table.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/sqlserver/permit-table.txt rename to src/main/resources/META-INF/druid/wall/sqlserver/deny-table.txt diff --git a/src/main/resources/META-INF/druid/wall/sqlserver/permit-variant.txt b/src/main/resources/META-INF/druid/wall/sqlserver/deny-variant.txt similarity index 100% rename from src/main/resources/META-INF/druid/wall/sqlserver/permit-variant.txt rename to src/main/resources/META-INF/druid/wall/sqlserver/deny-variant.txt diff --git a/src/main/resources/support/http/resources/datasource.html b/src/main/resources/support/http/resources/datasource.html index 33d90dd858..cdbe47264a 100644 --- a/src/main/resources/support/http/resources/datasource.html +++ b/src/main/resources/support/http/resources/datasource.html @@ -35,8 +35,8 @@ ] var descs = ["Specify the username used when creating a new connection.", "The JDBC driver connection URL", "database type", "The fully qualifed name of the JDBC driver class", - "All the fully qualifed name of the filter classes", " Test or not when borrow a connection", "Test or not when return a connection", - "Test or not when a connection is idle for a while","The size of datasource connections to create when initial a datasource", + "All the fully qualifed name of the filter classes", " Test or not when borrow a connection", "Test or not when a connection is idle for a while", + "Test or not when return a connection","The size of datasource connections to create when initial a datasource", "The minimum number of connections a pool should hold. ", "The maximum number of connections for a pool", "", "", "", "", "", "", "", "", "Total times for wait to get a connection","Total millins for wait to get a connection", "The current waiting thread count", "The count of start transaction", "The histogram values of transaction time, [0-10 ms, 10-100 ms, 100-1 s, 1-10 s, 10-100 s, >100 s]", diff --git a/src/test/java/com/alibaba/druid/benckmark/pool/Case4.java b/src/test/java/com/alibaba/druid/benckmark/pool/Case4.java new file mode 100644 index 0000000000..ddcf23156b --- /dev/null +++ b/src/test/java/com/alibaba/druid/benckmark/pool/Case4.java @@ -0,0 +1,287 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.benckmark.pool; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.text.NumberFormat; +import java.util.concurrent.CountDownLatch; + +import javax.sql.DataSource; + +import junit.framework.TestCase; + +import org.apache.commons.dbcp.BasicDataSource; +import org.logicalcobwebs.proxool.ProxoolDataSource; + +import com.alibaba.druid.TestUtil; +import com.alibaba.druid.benckmark.pool.model.TableOperator; +import com.alibaba.druid.pool.DruidDataSource; +import com.jolbox.bonecp.BoneCPDataSource; +import com.mchange.v2.c3p0.ComboPooledDataSource; +import com.taobao.datasource.LocalTxDataSourceDO; +import com.taobao.datasource.TaobaoDataSourceFactory; +import com.taobao.datasource.resource.adapter.jdbc.local.LocalTxDataSource; + +/** + * 测试各个连接池在进行批量插入时操作的性能 + * + * @author yunnysunny 2013-3-18 下午01:11:40 + */ +public class Case4 extends TestCase { + + private String jdbcUrl; + private String user; + private String password; + private String driverClass; + private int initialSize = 10; + private int minPoolSize = 10; + private int maxPoolSize = 50; + private int maxActive = 50; + private String validationQuery = "SELECT 1"; + private int maxOpenPreparedStatements = 100; + private int threadCount = 5; + private int loopCount = 10; + final int LOOP_COUNT = 100 * 1 * 1 / threadCount; + + protected void setUp() throws Exception { + user = "root"; + password = "aaaaaaaa"; + + jdbcUrl = "jdbc:mysql://localhost:3306/dragoon_v25_masterdb"; + driverClass = "com.mysql.jdbc.Driver"; + } + + public void test_druid() throws Exception { + DruidDataSource dataSource = new DruidDataSource(); + + dataSource.setInitialSize(initialSize); + dataSource.setMaxActive(maxActive); + dataSource.setMinIdle(minPoolSize); + dataSource.setMaxIdle(maxPoolSize); + dataSource.setPoolPreparedStatements(true); + dataSource.setDriverClassName(driverClass); + dataSource.setUrl(jdbcUrl); + dataSource.setPoolPreparedStatements(true); + dataSource.setMaxOpenPreparedStatements(maxOpenPreparedStatements); + dataSource.setUsername(user); + dataSource.setPassword(password); + dataSource.setValidationQuery(validationQuery); + dataSource.setTestOnBorrow(false); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "druid", threadCount); + } + System.out.println(); + } + + public void test_jobss() throws Exception { + LocalTxDataSourceDO dataSourceDO = new LocalTxDataSourceDO(); + dataSourceDO.setBlockingTimeoutMillis(1000 * 60); + dataSourceDO.setMaxPoolSize(maxPoolSize); + dataSourceDO.setMinPoolSize(minPoolSize); + + dataSourceDO.setDriverClass(driverClass); + dataSourceDO.setConnectionURL(jdbcUrl); + dataSourceDO.setUserName(user); + dataSourceDO.setPassword(password); + + LocalTxDataSource tx = TaobaoDataSourceFactory.createLocalTxDataSource(dataSourceDO); + DataSource dataSource = tx.getDatasource(); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "jboss-datasource", threadCount); + } + System.out.println(); + } + + public void test_dbcp() throws Exception { + final BasicDataSource dataSource = new BasicDataSource(); + + dataSource.setInitialSize(initialSize); + dataSource.setMaxActive(maxActive); + dataSource.setMinIdle(minPoolSize); + dataSource.setMaxIdle(maxPoolSize); + dataSource.setPoolPreparedStatements(true); + dataSource.setDriverClassName(driverClass); + dataSource.setUrl(jdbcUrl); + dataSource.setPoolPreparedStatements(true); + dataSource.setMaxOpenPreparedStatements(maxOpenPreparedStatements); + dataSource.setUsername(user); + dataSource.setPassword(password); + dataSource.setValidationQuery("SELECT 1"); + dataSource.setTestOnBorrow(false); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "dbcp", threadCount); + } + System.out.println(); + } + + public void test_bonecp() throws Exception { + BoneCPDataSource dataSource = new BoneCPDataSource(); + // dataSource.(10); + // dataSource.setMaxActive(50); + dataSource.setMinConnectionsPerPartition(minPoolSize); + dataSource.setMaxConnectionsPerPartition(maxPoolSize); + + dataSource.setDriverClass(driverClass); + dataSource.setJdbcUrl(jdbcUrl); + dataSource.setStatementsCacheSize(maxOpenPreparedStatements); + dataSource.setServiceOrder("LIFO"); + // dataSource.setMaxOpenPreparedStatements(100); + dataSource.setUsername(user); + dataSource.setPassword(password); + // dataSource.setConnectionTestStatement("SELECT 1"); + dataSource.setPartitionCount(1); + dataSource.setAcquireIncrement(5); + dataSource.setIdleConnectionTestPeriod(0L); + // dataSource.setDisableConnectionTracking(true); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "boneCP", threadCount); + } + System.out.println(); + } + + public void test_c3p0() throws Exception { + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + // dataSource.(10); + // dataSource.setMaxActive(50); + dataSource.setMinPoolSize(minPoolSize); + dataSource.setMaxPoolSize(maxPoolSize); + + dataSource.setDriverClass(driverClass); + dataSource.setJdbcUrl(jdbcUrl); + dataSource.setMaxStatements(maxOpenPreparedStatements); + + dataSource.setUser(user); + dataSource.setPassword(password); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "c3p0", threadCount); + } + System.out.println(); + } + + public void test_proxool() throws Exception { + ProxoolDataSource dataSource = new ProxoolDataSource(); + // dataSource.(10); + // dataSource.setMaxActive(50); + dataSource.setMinimumConnectionCount(minPoolSize); + dataSource.setMaximumConnectionCount(maxPoolSize); + + dataSource.setDriver(driverClass); + dataSource.setDriverUrl(jdbcUrl); + + dataSource.setUser(user); + dataSource.setPassword(password); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "proxool", threadCount); + } + System.out.println(); + } + + public void test_tomcat_jdbc() throws Exception { + org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); + // dataSource.(10); + dataSource.setMaxIdle(maxPoolSize); + dataSource.setMinIdle(minPoolSize); + dataSource.setMaxActive(maxPoolSize); + + dataSource.setDriverClassName(driverClass); + dataSource.setUrl(jdbcUrl); + // dataSource.setPoolPreparedStatements(true); + // dataSource.setMaxOpenPreparedStatements(100); + dataSource.setUsername(user); + dataSource.setPassword(password); + + for (int i = 0; i < loopCount; ++i) { + p0(dataSource, "tomcat-jdbc", threadCount); + } + System.out.println(); + } + + private void p0(final DataSource dataSource, String name, int threadCount) throws Exception { + + final CountDownLatch startLatch = new CountDownLatch(1); + final CountDownLatch endLatch = new CountDownLatch(threadCount); + final CountDownLatch dumpLatch = new CountDownLatch(1); + + Thread[] threads = new Thread[threadCount]; + final TableOperator operator = new TableOperator(); + operator.setDataSource(dataSource); + operator.createTable(); + for (int i = 0; i < threadCount; ++i) { + Thread thread = new Thread() { + + public void run() { + try { + startLatch.await(); + + for (int i = 0; i < LOOP_COUNT; ++i) { + operator.insert(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + endLatch.countDown(); + + try { + dumpLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + threads[i] = thread; + thread.start(); + } + long startMillis = System.currentTimeMillis(); + long startYGC = TestUtil.getYoungGC(); + long startFullGC = TestUtil.getFullGC(); + startLatch.countDown(); + endLatch.await(); + + long[] threadIdArray = new long[threads.length]; + for (int i = 0; i < threads.length; ++i) { + threadIdArray[i] = threads[i].getId(); + } + ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray); + + dumpLatch.countDown(); + operator.dropTable(); + + long blockedCount = 0; + long waitedCount = 0; + for (int i = 0; i < threadInfoArray.length; ++i) { + ThreadInfo threadInfo = threadInfoArray[i]; + blockedCount += threadInfo.getBlockedCount(); + waitedCount += threadInfo.getWaitedCount(); + } + + long millis = System.currentTimeMillis() - startMillis; + long ygc = TestUtil.getYoungGC() - startYGC; + long fullGC = TestUtil.getFullGC() - startFullGC; + + System.out.println("thread " + threadCount + " " + name + " millis : " + + NumberFormat.getInstance().format(millis) + "; YGC " + ygc + " FGC " + fullGC + + " blocked " + NumberFormat.getInstance().format(blockedCount) // + + " waited " + NumberFormat.getInstance().format(waitedCount)); + + } +} diff --git a/src/test/java/com/alibaba/druid/benckmark/pool/model/TableOperator.java b/src/test/java/com/alibaba/druid/benckmark/pool/model/TableOperator.java new file mode 100644 index 0000000000..002c207266 --- /dev/null +++ b/src/test/java/com/alibaba/druid/benckmark/pool/model/TableOperator.java @@ -0,0 +1,95 @@ +package com.alibaba.druid.benckmark.pool.model; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.sql.DataSource; + +public class TableOperator { + + private DataSource dataSource; + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + private static final int COUNT = 2; + + public TableOperator(){ + + } + + public void insert() throws Exception { + + StringBuffer ddl = new StringBuffer(); + ddl.append("INSERT INTO t_big ("); + for (int i = 0; i < COUNT; ++i) { + if (i != 0) { + ddl.append(", "); + } + ddl.append("F" + i); + } + ddl.append(") VALUES ("); + for (int i = 0; i < COUNT; ++i) { + if (i != 0) { + ddl.append(", "); + } + ddl.append("?"); + } + ddl.append(")"); + + Connection conn = dataSource.getConnection(); + + // System.out.println(ddl.toString()); + try { + PreparedStatement stmt = conn.prepareStatement(ddl.toString()); + + for (int i = 0; i < COUNT; ++i) { + stmt.setInt(i + 1, i); + } + + stmt.execute(); + stmt.close(); + } finally { + + conn.close(); + } + } + + public void dropTable() throws SQLException { + + Connection conn = dataSource.getConnection(); + try { + Statement stmt = conn.createStatement(); + stmt.execute("DROP TABLE t_big"); + stmt.close(); + } finally { + conn.close(); + } + } + + public void createTable() throws SQLException { + StringBuffer ddl = new StringBuffer(); + ddl.append("CREATE TABLE t_big (FID INT AUTO_INCREMENT PRIMARY KEY "); + for (int i = 0; i < COUNT; ++i) { + ddl.append(", "); + ddl.append("F" + i); + ddl.append(" BIGINT NULL"); + } + ddl.append(")"); + + Connection conn = dataSource.getConnection(); + try { + Statement stmt = conn.createStatement(); + stmt.addBatch("DROP TABLE IF EXISTS t_big"); + stmt.addBatch(ddl.toString()); + stmt.executeBatch(); + stmt.close(); + } finally { + conn.close(); + } + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/AllWallTests.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/AllWallTests.java deleted file mode 100644 index 7cee7ac2e7..0000000000 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/AllWallTests.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.bvt.filter.wall; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * AllTests - * - * @author RaymondXiu - * @version 1.0, 2012-3-18 - * @see - */ -public class AllWallTests extends TestCase { - - public static Test suite() { - TestSuite suite = new TestSuite(AllWallTests.class.getName()); - //$JUnit-BEGIN$ - suite.addTestSuite(MySqlWallLimitTest.class); - suite.addTestSuite(MySqlWallLoadDataInfileTest.class); - suite.addTestSuite(MySqlWallPermitFunctionTest.class); - suite.addTestSuite(MySqlWallPermitTableTest.class); - suite.addTestSuite(MySqlWallPermitVariantTest.class); - suite.addTestSuite(MySqlWallTest.class); - suite.addTestSuite(OracleWallPermitFunctionTest.class); - suite.addTestSuite(OracleWallPermitObjectTest.class); - suite.addTestSuite(OracleWallPermitSchemaTest.class); - suite.addTestSuite(OracleWallPermitTableTest.class); - suite.addTestSuite(OracleWallPermitVariantTest.class); - suite.addTestSuite(OracleWallPermitVariantTest2.class); - suite.addTestSuite(OracleWallTest.class); - suite.addTestSuite(SQLServerWallPermitFunctionTest.class); - suite.addTestSuite(SQLServerWallPermitObjectTest.class); - suite.addTestSuite(SQLServerWallPermitSchemaTest.class); - suite.addTestSuite(SQLServerWallPermitTableTest.class); - suite.addTestSuite(SQLServerWallTest.class); - suite.addTestSuite(WallDeleteTest.class); - suite.addTestSuite(WallDeleteWhereTest.class); - suite.addTestSuite(WallDeleteWhereTest1.class); - suite.addTestSuite(WallDropTest.class); - suite.addTestSuite(WallDropTest1.class); - suite.addTestSuite(WallHavingTest.class); - suite.addTestSuite(WallInsertTest.class); - suite.addTestSuite(WallInsertTest2.class); - suite.addTestSuite(WallLineCommentTest.class); - suite.addTestSuite(WallMultiLineCommentTest.class); - suite.addTestSuite(WallMultiStatementTest.class); - suite.addTestSuite(WallReadOnlyTest.class); - suite.addTestSuite(WallSelectIntoTest.class); - suite.addTestSuite(WallSelectIntoTest1.class); - suite.addTestSuite(WallSelectWhereTest.class); - suite.addTestSuite(WallSelectWhereTest0.class); - suite.addTestSuite(WallSelectWhereTest1.class); - suite.addTestSuite(WallSelectWhereTest2.class); - suite.addTestSuite(WallSelectWhereTest3.class); - suite.addTestSuite(WallSelectWhereTest4.class); - suite.addTestSuite(WallSelectWhereTest5.class); - suite.addTestSuite(WallTruncateTest.class); - suite.addTestSuite(WallTruncateTest1.class); - suite.addTestSuite(WallUnionTest.class); - suite.addTestSuite(WallUnionTest2.class); - suite.addTestSuite(WallUnionTest3.class); - suite.addTestSuite(WallUnionTest4.class); - suite.addTestSuite(WallUpdateTest.class); - suite.addTestSuite(WallUpdateTest1.class); - suite.addTestSuite(WallUpdateTest2.class); - suite.addTestSuite(WallUpdateTest3.class); - suite.addTestSuite(WallUpdateTest4.class); - suite.addTestSuite(WallUpdateWhereTest.class); - suite.addTestSuite(WallVisitorUtilsTest.class); - //$JUnit-END$ - return suite; - } - -} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseAndTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseAndTest.java new file mode 100644 index 0000000000..d4acbf29f8 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseAndTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class BitwiseAndTest extends TestCase { + + public void test_false() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 & 2")); // + } + + public void test_true() throws Exception { + WallConfig config = new WallConfig(); + config.setConditionOpBitwseAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 & 2", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseInvertTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseInvertTest.java new file mode 100644 index 0000000000..c00e8c5e84 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseInvertTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class BitwiseInvertTest extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * from t where id = ~2")); // + } + + public void test_false() throws Exception { + WallConfig config = new WallConfig(); + config.setConditionOpBitwseAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * from t where id = ~2", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseOrTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseOrTest.java new file mode 100644 index 0000000000..32769b22ae --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseOrTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class BitwiseOrTest extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 | 2")); // + } + + public void test_false() throws Exception { + WallConfig config = new WallConfig(); + config.setConditionOpBitwseAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 | 2", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseXorTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseXorTest.java new file mode 100644 index 0000000000..f2ffa20853 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/BitwiseXorTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class BitwiseXorTest extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 ^ 2")); // + } + + public void test_false() throws Exception { + WallConfig config = new WallConfig(); + config.setConditionOpBitwseAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 ^ 2", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/BooleanXorTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/BooleanXorTest.java new file mode 100644 index 0000000000..fcb38d971e --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/BooleanXorTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class BooleanXorTest extends TestCase { + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 XOR id = 2")); // + } + + public void test_true() throws Exception { + WallConfig config = new WallConfig(); + config.setConditionOpXorAllow(true); + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * from t where id = 1 XOR id = 2", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/ConstantArithmeticCheckTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/ConstantArithmeticCheckTest.java new file mode 100644 index 0000000000..d0bb3f77e5 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/ConstantArithmeticCheckTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class ConstantArithmeticCheckTest extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * from t where id = 3 - 1")); // + } + + public void test_false() throws Exception { + WallConfig config = new WallConfig(); + config.setConstArithmeticAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * from t where id = 3 - 1", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/CountTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/CountTest.java new file mode 100644 index 0000000000..f5bb75ec34 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/CountTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.wall.spi.WallVisitorUtils; + +public class CountTest extends TestCase { + + public void test_isTrue() throws Exception { + + Assert.assertEquals(Boolean.TRUE, WallVisitorUtils.getValue(SQLUtils.toSQLExpr("(select count(*) from t) > 0"))); + Assert.assertEquals(Boolean.TRUE, + WallVisitorUtils.getValue(SQLUtils.toSQLExpr("(select count(*) from t) >= 0"))); + Assert.assertEquals(Boolean.FALSE, + WallVisitorUtils.getValue(SQLUtils.toSQLExpr("(select count(*) from t) < 0"))); + Assert.assertEquals(Boolean.TRUE, + WallVisitorUtils.getValue(SQLUtils.toSQLExpr("NOT (select count(*) from t) < 0"))); + + // + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/IntersectTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/IntersectTest.java new file mode 100644 index 0000000000..e1cec6ef95 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/IntersectTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class IntersectTest extends TestCase { + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidateOracle(// + "SELECT * FROM A MINUS SELECT * FROM B")); // + } + + public void test_true() throws Exception { + WallConfig config = new WallConfig(); + config.setMinusAllow(true); + Assert.assertTrue(WallUtils.isValidateOracle(// + "SELECT * FROM A MINUS SELECT * FROM B", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/LikeTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/LikeTest.java new file mode 100644 index 0000000000..2c64760487 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/LikeTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.wall.spi.WallVisitorUtils; + +public class LikeTest extends TestCase { + + public void test_isTrue() throws Exception { + Assert.assertEquals(Boolean.TRUE, WallVisitorUtils.getValue(SQLUtils.toSQLExpr("f1 like '%'"))); + Assert.assertEquals(Boolean.TRUE, WallVisitorUtils.getValue(SQLUtils.toSQLExpr("f1 like '%%'"))); + Assert.assertEquals(null, WallVisitorUtils.getValue(SQLUtils.toSQLExpr("a1 = b1 AND f1 like '%%'"))); + Assert.assertEquals(Boolean.TRUE, WallVisitorUtils.getValue(SQLUtils.toSQLExpr("a1 = b1 OR f1 like '%%'"))); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MinusTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MinusTest.java new file mode 100644 index 0000000000..460a250d59 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MinusTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class MinusTest extends TestCase { + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidateOracle(// + "SELECT * FROM A Intersect SELECT * FROM B")); // + } + + public void test_true() throws Exception { + WallConfig config = new WallConfig(); + config.setIntersectAllow(true); + Assert.assertTrue(WallUtils.isValidateOracle(// + "SELECT * FROM A Intersect SELECT * FROM B", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest10.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest10.java new file mode 100644 index 0000000000..fbba42af75 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest10.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest10 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT t.*,a.param_id FROM lhwtag AS t RIGHT JOIN lhwtag_relation AS a USING(`tag_id`) WHERE a.`type_id`=1 AND a.`param_id` IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') ORDER BY t.`content_count`")); // 前置永真 + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest11.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest11.java new file mode 100644 index 0000000000..02342b59b8 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest11.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest11 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT *, MATCH(question_content_fulltext) " + // + "AGAINST('2015431867 2636826089 3807520117 2796321160 2615920174' IN BOOLEAN MODE) AS score " + // + "FROM aws_question " + // + "WHERE MATCH(question_content_fulltext) " + // + " AGAINST('2015431867 2636826089 3807520117 2796321160 2615920174' IN BOOLEAN MODE) " + // + "ORDER BY score DESC, agree_count DESC LIMIT 10")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest12.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest12.java new file mode 100644 index 0000000000..3c1b947528 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest12.java @@ -0,0 +1,39 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest12 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT a.* FROM lhwbbs_threads a " + // + "WHERE 1 AND a.disabled=0 AND a.ifupload&1=1 " + // + "ORDER BY a.created_time DESC LIMIT 0,100")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest13.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest13.java new file mode 100644 index 0000000000..0fc4430cb6 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest13.java @@ -0,0 +1,40 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest13 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT index_privacy AS index,msgboard_privacy AS messageboard," + // + "photos_privacy AS photos,diary_privacy AS diary," + // + "owrite_privacy AS weibo " + // + "FROM pw_ouserdata WHERE uid= ?")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest14.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest14.java new file mode 100644 index 0000000000..cf83013ea1 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest14.java @@ -0,0 +1,39 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest14 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT index_privacy AS index,info_privacy AS ?,msgboard_privacy AS messageboard,photos_privacy AS photos," + // + "diary_privacy AS diary,owrite_privacy AS weibo " + // + "FROM pw_ouserdata WHERE uid= ?")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest15.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest15.java new file mode 100644 index 0000000000..1583372b3e --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest15.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest15 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT m.*, m.icon AS micon, md.uid as md.uid, md.lastmsg,md.postnum," + // + "md.rvrc,md.money,md.credit,md.currency,md.lastvisit,md.thisvisit," + // + "md.onlinetime,md.lastpost,md.todaypost, md.monthpost,md.onlineip," + // + "md.uploadtime,md.uploadnum,md.starttime,md.pwdctime,md.monoltime," + // + "md.digests,md.f_num,md.creditpop, md.jobnum,md.lastgrab,md.follows,md.fans," + // + "md.newfans,md.newreferto,md.newcomment,md.postcheck,md.punch, mi.customdata " + // + "FROM pw_members m " + // + " LEFT JOIN pw_memberdata md ON m.uid=md.uid " + // + " LEFT JOIN pw_memberinfo mi ON mi.uid=m.uid " + // + "WHERE m.uid IN (?)")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest16.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest16.java new file mode 100644 index 0000000000..5df90c4dab --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest16.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest16 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT * FROM lhwbbs_threads_cate_index FORCE INDEX(PRIMARY) WHERE cid=? AND disabled=? ORDER BY tid DESC LIMIT ?,?")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest17.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest17.java new file mode 100644 index 0000000000..3db1a565a7 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest17.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest17 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "DELETE FROM as_home_notification WHERE uid>? AND new=? AND dateline FNAME)")); // + } + + public void test_false_2() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "select * from t where NOT(UNHEX(HEX(FNAME)) < FNAME)")); // + } + + public void test_false_3() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "select * from t where NOT(UNHEX(HEX(FNAME)) NOT LIKE FNAME)")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest33.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest33.java new file mode 100644 index 0000000000..7431684e2d --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest33.java @@ -0,0 +1,45 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest33 extends TestCase { + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "DELETE FROM lhwdesign_data WHERE data_id IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?")); // + } + + public void test_true() throws Exception { + WallConfig config = new WallConfig(); + config.setStrictSyntaxCheck(false); + Assert.assertTrue(WallUtils.isValidateMySql(// + "DELETE FROM lhwdesign_data WHERE data_id IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest34.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest34.java new file mode 100644 index 0000000000..f0b4826a3f --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest34.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest34 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT @@sql_big_selects")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest4.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest4.java new file mode 100644 index 0000000000..2b0b59efb4 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest4.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest4 extends TestCase { + + public void test_stuff() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SSELECT a.*,b.name FROM vote_info a left join vote_item b on a.item_id=b.id where a.id<10 or 1=1 limit 1,10")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest5.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest5.java new file mode 100644 index 0000000000..2bcd99eb09 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest5.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest5 extends TestCase { + + public void test_stuff() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "select * from tbl_product WHERE delFlag=0 AND cateId = 40 OR EXTRACTVALUE(1,CONCAT(0x7c,database(),0x7c)) order by sort desc, productId desc limit 20,20")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest6.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest6.java new file mode 100644 index 0000000000..975bee6f55 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest6.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest6 extends TestCase { + + public void test_stuff() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT a.* FROM vote_info a where a.id<10 or (id <5 or 1=1) limit 1,10")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest7.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest7.java new file mode 100644 index 0000000000..972f727bb5 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest7.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest7 extends TestCase { + + public void test_stuff() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT a.* FROM vote_info a where a.id<10 and (id <5 or 1=1) limit 1,10")); // 部分永真 + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest8.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest8.java new file mode 100644 index 0000000000..cbc45cc605 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest8.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest8 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT a.* FROM vote_info a where 1=1 AND FID = ?")); // 前置永真 + } + + public void test_false_1() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT a.* FROM vote_info a where FID = ? AND 1=1")); // 后置永真,拦截 + } + + public void test_false_2() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT a.* FROM vote_info a where FID = ? OR (FID = ? AND 1=1)")); // 后置永真,拦截 + } + + public void test_false_3() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT a.* FROM vote_info a where FID = ? OR (1=1 AND FID = ?)")); // 后置永真,拦截 + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest9.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest9.java new file mode 100644 index 0000000000..d943859b06 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest9.java @@ -0,0 +1,39 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest9 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "REPLACE INTO lhwonline_guest (`ip`, `created_time`, `modify_time`, `fid`, `tid`, `request`)" + // + "\nVALUES ('1', '1364366764', '1364368276', '0', '3436'" + // + "\n , 'bbs/read/run')")); // 前置永真 + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest_var.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest_var.java new file mode 100644 index 0000000000..7e97f3da8e --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest_var.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest_var extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT @@GLOBAL.sql_mode")); // + } + + public void test_true_1() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT @@SESSION.sql_mode;")); // + } + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * FROM T WHERE @@SESSION.sql_mode = 'ANSI'")); // + } + + public void test_false_1() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT * FROM T WHERE @@sql_mode = 'ANSI'")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest_var_autoincrement.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest_var_autoincrement.java new file mode 100644 index 0000000000..8cee8795f3 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/MySqlWallTest_var_autoincrement.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class MySqlWallTest_var_autoincrement extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "/* mysql-connector-java-5.? ( Revision: bzr.revision-id ) */SELECT @@session.auto_increment_increment")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/OracleWallTest1.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/OracleWallTest1.java new file mode 100644 index 0000000000..5be821529a --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/OracleWallTest1.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +public class OracleWallTest1 extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateOracle("SELECT DICT_ID,NAME,VALUE,STATUS FROM T_EBM_DICT WHERE T_EBM_DICT.PID=10 OR T_EBM_DICT.PID=11")); + Assert.assertTrue(WallUtils.isValidateMySql("SELECT DICT_ID,NAME,VALUE,STATUS FROM T_EBM_DICT WHERE T_EBM_DICT.PID=10 OR T_EBM_DICT.PID=11")); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/PGDenyFunctionTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/PGDenyFunctionTest.java new file mode 100644 index 0000000000..c533ea5b8d --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/PGDenyFunctionTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class PGDenyFunctionTest extends TestCase { + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidatePostgres(// + "SELECT current_catalog() from t where id = ?")); // + } + + public void test_true() throws Exception { + WallConfig config = new WallConfig(); + config.setFunctionCheck(false); + Assert.assertTrue(WallUtils.isValidatePostgres(// + "SELECT current_catalog() from t where id = ?", config)); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/PGWallTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/PGWallTest.java new file mode 100644 index 0000000000..fe16ffc867 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/PGWallTest.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +public class PGWallTest extends TestCase { + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidatePostgres(// + "select wm_concat(article_id) over() from t_nds_web_article")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/StrictSyntaxCheckTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/StrictSyntaxCheckTest.java new file mode 100644 index 0000000000..1796272f21 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/StrictSyntaxCheckTest.java @@ -0,0 +1,23 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallUtils; + +public class StrictSyntaxCheckTest extends TestCase { + + public void test_syntax() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "SELECT SELECT")); // 部分永真 + } + + public void test_syntax_1() throws Exception { + WallConfig config = new WallConfig(); + config.setStrictSyntaxCheck(false); + Assert.assertTrue(WallUtils.isValidateMySql(// + "SELECT SELECT", config)); // 部分永真 + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/TAEWallTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/TAEWallTest.java new file mode 100644 index 0000000000..792a1ed4d2 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/TAEWallTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallUtils; + +/** + * SQLServerWallTest + * + * @author RaymondXiu + * @version 1.0, 2012-3-18 + * @see + */ +public class TAEWallTest extends TestCase { + + public void test_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql(// + "select * from t where 1=1 AND status = 1")); // + } + + public void test_false() throws Exception { + Assert.assertFalse(WallUtils.isValidateMySql(// + "select * from t where status = 1 AND 1=1")); // + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/TenantSelectTest4.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/TenantSelectTest4.java new file mode 100644 index 0000000000..df461be3d8 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/TenantSelectTest4.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.util.JdbcConstants; +import com.alibaba.druid.wall.WallCheckResult; +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class TenantSelectTest4 extends TestCase { + + private String sql = "SELECT a.*,b.name " + // + "FROM vote_info a left join vote_item b on a.item_id=b.id " + // + "where 1=1 limit 1,10"; + + private WallConfig config = new WallConfig(); + + protected void setUp() throws Exception { + config.setTenantTablePattern("*"); + config.setTenantColumn("tenant"); + } + + public void testMySql() throws Exception { + WallProvider.setTenantValue(123); + MySqlWallProvider provider = new MySqlWallProvider(config); + WallCheckResult checkResult = provider.check(sql); + Assert.assertEquals(0, checkResult.getViolations().size()); + + String resultSql = SQLUtils.toSQLString(checkResult.getStatementList(), JdbcConstants.MYSQL); + Assert.assertEquals("SELECT a.*, b.name" + // + "\nFROM vote_info a" + // + "\n\tLEFT JOIN vote_item b ON b.tenant = 123" + // + "\n\t\tAND a.item_id = b.id" + // + "\nWHERE a.tenant = 123" + // + "\n\tAND 1 = 1" + // + "\nLIMIT 1, 10", resultSql); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallCommentTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallCommentTest.java new file mode 100644 index 0000000000..6c5aeafa12 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallCommentTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + +/** + * @author wenshao + */ +public class WallCommentTest extends TestCase { + + public void testORACLE() throws Exception { + String sql = "SELECT F1, F2 FROM ABC --test"; + + OracleWallProvider provider = new OracleWallProvider(); + Assert.assertFalse(provider.checkValid(sql)); + + Assert.assertEquals(1, provider.getCommentDenyStat().getDenyCount()); + } + + public void testmysql() throws Exception { + String sql = "SELECT F1, F2 FROM ABC --test"; + + MySqlWallProvider provider = new MySqlWallProvider(); + Assert.assertFalse(provider.checkValid(sql)); + + Assert.assertEquals(1, provider.getCommentDenyStat().getDenyCount()); + } + + public void testsqlserver() throws Exception { + String sql = "SELECT F1, F2 FROM ABC --test"; + + SQLServerWallProvider provider = new SQLServerWallProvider(); + Assert.assertFalse(provider.checkValid(sql)); + + Assert.assertEquals(1, provider.getCommentDenyStat().getDenyCount()); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDeleteWhereTest1.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDeleteWhereTest1.java index 0c4ff180ff..db1d902d46 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDeleteWhereTest1.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDeleteWhereTest1.java @@ -19,21 +19,37 @@ import junit.framework.TestCase; import org.junit.Assert; +import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallUtils; /** * 这个场景,检测可疑的Having条件 + * * @author wenshao - * */ public class WallDeleteWhereTest1 extends TestCase { + private String sql = "DELETE FROM T"; public void testMySql() throws Exception { - Assert.assertFalse(WallUtils.isValidateMySql(sql)); + Assert.assertTrue(WallUtils.isValidateMySql(sql)); } - + public void testORACLE() throws Exception { - Assert.assertFalse(WallUtils.isValidateOracle(sql)); + Assert.assertTrue(WallUtils.isValidateOracle(sql)); + } + + public void testMySql_false() throws Exception { + WallConfig config = new WallConfig(); + config.setDeleteWhereNoneCheck(true); + + Assert.assertFalse(WallUtils.isValidateMySql(sql, config)); + } + + public void testORACLE_false() throws Exception { + WallConfig config = new WallConfig(); + config.setDeleteWhereNoneCheck(true); + + Assert.assertFalse(WallUtils.isValidateOracle(sql, config)); } } diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenySchemaTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenySchemaTest.java new file mode 100644 index 0000000000..846426a250 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenySchemaTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.spi.OracleWallProvider; + +/** + * @author wenshao + */ +public class WallDenySchemaTest extends TestCase { + + public void testORACLE() throws Exception { + String sql = "SELECT F1, F2 FROM ALL_ALL_TABLES"; + + OracleWallProvider provider = new OracleWallProvider(); + Assert.assertFalse(provider.checkValid(sql)); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenyTableTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenyTableTest.java new file mode 100644 index 0000000000..c93ed910a2 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenyTableTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.spi.OracleWallProvider; + +/** + * @author wenshao + */ +public class WallDenyTableTest extends TestCase { + + public void testORACLE() throws Exception { + String sql = "SELECT F1, F2 FROM SYS.ABC"; + + OracleWallProvider provider = new OracleWallProvider(); + Assert.assertFalse(provider.checkValid(sql)); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest.java index 86231a8d24..280389b8d6 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest.java @@ -19,20 +19,33 @@ import junit.framework.TestCase; import org.junit.Assert; +import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallUtils; /** * 这个场景,被攻击者用于测试当前SQL拥有多少字段 + * * @author wenshao - * */ public class WallDropTest extends TestCase { public void testMySql() throws Exception { - Assert.assertFalse(WallUtils.isValidateMySql("DROP TABLE T1")); + WallConfig config = new WallConfig(); + config.setDropTableAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql("DROP TABLE T1", config)); } - + public void testOracle() throws Exception { - Assert.assertFalse(WallUtils.isValidateOracle("DROP TABLE T1")); + WallConfig config = new WallConfig(); + config.setDropTableAllow(false); + Assert.assertFalse(WallUtils.isValidateOracle("DROP TABLE T1", config)); + } + + public void testMySql_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateMySql("DROP TABLE T1")); + } + + public void testOracle_true() throws Exception { + Assert.assertTrue(WallUtils.isValidateOracle("DROP TABLE T1")); } } diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest1.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest1.java index 4084308f25..eef70873d5 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest1.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDropTest1.java @@ -29,7 +29,7 @@ public class WallDropTest1 extends TestCase { private WallConfig config = new WallConfig(); protected void setUp() throws Exception { - config.setNoneBaseStatementAllow(true); + config.setDropTableAllow(true); } public void testMySql() throws Exception { diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest.java index a883648ce0..e6224353f8 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest.java @@ -31,7 +31,7 @@ public class WallReadOnlyTest extends TestCase { private WallConfig config = new WallConfig(); protected void setUp() throws Exception { - config.getReadOnlyTables().add("members"); + config.addReadOnlyTable("members"); } private String sql = "SELECT F1, F2 members"; private String insert_sql = "INSERT INTO members (FID, FNAME) VALUES (?, ?)"; diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest2.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest2.java new file mode 100644 index 0000000000..cc8c844341 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallReadOnlyTest2.java @@ -0,0 +1,63 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallConfig; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; + +/** + * 这个场景,检测可疑的Having条件 + * + * @author wenshao + */ +public class WallReadOnlyTest2 extends TestCase { + + private WallConfig config = new WallConfig(); + + protected void setUp() throws Exception { + config.addReadOnlyTable("members"); + } + + private String sql = "SELECT F1, F2 members"; + private String insert_sql = "INSERT INTO members (FID, FNAME) VALUES (?, ?)"; + private String update_sql = "UPDATE members SET FNAME = ? WHERe FID = ?"; + private String delete_sql = "DELETE members WHERE FID = ?"; + + public void testMySql() throws Exception { + MySqlWallProvider provider = new MySqlWallProvider(config); + Assert.assertTrue(provider.checkValid(sql)); + + Assert.assertFalse(provider.checkValid(insert_sql)); + Assert.assertFalse(provider.checkValid(update_sql)); + Assert.assertFalse(provider.checkValid(delete_sql)); + + } + + public void testORACLE() throws Exception { + OracleWallProvider provider = new OracleWallProvider(config); + Assert.assertTrue(provider.checkValid(sql)); + + Assert.assertFalse(provider.checkValid(insert_sql)); + Assert.assertFalse(provider.checkValid(update_sql)); + Assert.assertFalse(provider.checkValid(delete_sql)); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest3.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest3.java index 1ba0404c0c..3e333b223c 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest3.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest3.java @@ -22,7 +22,6 @@ import org.junit.Assert; import com.alibaba.druid.wall.WallUtils; /** - * 这个场景,检测可疑的Having条件 * @author wenshao * */ @@ -30,10 +29,10 @@ public class WallSelectWhereTest3 extends TestCase { private String sql = "select * from t WHERE FID = 256 AND CHR(67)||CHR(65)||CHR(84) = 'CAT'"; public void testMySql() throws Exception { - Assert.assertTrue(WallUtils.isValidateMySql(sql)); + Assert.assertFalse(WallUtils.isValidateMySql(sql)); } public void testORACLE() throws Exception { - Assert.assertTrue(WallUtils.isValidateOracle(sql)); + Assert.assertFalse(WallUtils.isValidateOracle(sql)); } } diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest5.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest5.java index fa20b64a7e..1071fc3c7b 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest5.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest5.java @@ -22,7 +22,6 @@ import org.junit.Assert; import com.alibaba.druid.wall.WallUtils; /** - * 这个场景,检测可疑的Having条件 * @author wenshao * */ diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_WhiteList.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_WhiteList.java new file mode 100644 index 0000000000..ee404dc669 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_WhiteList.java @@ -0,0 +1,38 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class WallStatTest_WhiteList extends TestCase { + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + + for (int i = 0; i < 1001; ++i) { + String sql = "select * from t where id = " + i; + Assert.assertTrue(provider.checkValid(sql)); + } + + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1001, tableStat.getSelectCount()); + Assert.assertEquals(0, provider.getBlackListHitCount()); + Assert.assertEquals(0, provider.getWhiteListHitCount()); + Assert.assertEquals(1000, provider.getWhiteList().size()); + Assert.assertEquals(1001, provider.getCheckCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_alter_table.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_alter_table.java new file mode 100644 index 0000000000..81f2e049ce --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_alter_table.java @@ -0,0 +1,54 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + + +public class WallStatTest_alter_table extends TestCase { + public void testMySql() throws Exception { + String sql = "alter table t add column fname varchar(50)"; + WallProvider provider = new MySqlWallProvider(); + provider.getConfig().setAlterTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getAlterCount()); + } + + public void testOracle() throws Exception { + String sql = "alter table t add (fname varchar(50))"; + WallProvider provider = new OracleWallProvider(); + provider.getConfig().setAlterTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getAlterCount()); + } + +// public void testPG() throws Exception { +// WallProvider provider = new PGWallProvider(); +// provider.getConfig().setAlterTableAllow(true); +// +// Assert.assertTrue(provider.checkValid(sql)); +// WallTableStat tableStat = provider.getTableStat("t"); +// Assert.assertEquals(1, tableStat.getAlterCount()); +// } +// +// public void testSQLServer() throws Exception { +// WallProvider provider = new SQLServerWallProvider(); +// provider.getConfig().setAlterTableAllow(true); +// +// Assert.assertTrue(provider.checkValid(sql)); +// WallTableStat tableStat = provider.getTableStat("t"); +// Assert.assertEquals(1, tableStat.getAlterCount()); +// } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blackList_1.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blackList_1.java new file mode 100644 index 0000000000..5a194d5d59 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blackList_1.java @@ -0,0 +1,39 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class WallStatTest_blackList_1 extends TestCase { + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + + for (int i = 0; i < 1001; ++i) { + String sql = "select * from t where id = " + i + " OR 1 = 1"; + Assert.assertFalse(provider.checkValid(sql)); + } + + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1001, tableStat.getSelectCount()); + Assert.assertEquals(0, provider.getBlackListHitCount()); + Assert.assertEquals(0, provider.getWhiteListHitCount()); + Assert.assertEquals(0, provider.getWhiteList().size()); + Assert.assertEquals(1000, provider.getBlackList().size()); + Assert.assertEquals(1001, provider.getCheckCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blackList_syntaxError.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blackList_syntaxError.java new file mode 100644 index 0000000000..cf42c68993 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blackList_syntaxError.java @@ -0,0 +1,53 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class WallStatTest_blackList_syntaxError extends TestCase { + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + + String sql = "select xx * x *"; + Assert.assertFalse(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(0, tableStat.getSelectCount()); + Assert.assertEquals(0, provider.getBlackListHitCount()); + Assert.assertEquals(0, provider.getWhiteListHitCount()); + Assert.assertEquals(0, provider.getWhiteList().size()); + Assert.assertEquals(1, provider.getBlackList().size()); + Assert.assertEquals(1, provider.getCheckCount()); + Assert.assertEquals(1, provider.getSyntaxErrorCount()); + Assert.assertEquals(1, provider.getHardCheckCount()); + } + + Assert.assertFalse(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(0, tableStat.getSelectCount()); + Assert.assertEquals(1, provider.getBlackListHitCount()); + Assert.assertEquals(0, provider.getWhiteListHitCount()); + Assert.assertEquals(0, provider.getWhiteList().size()); + Assert.assertEquals(1, provider.getBlackList().size()); + Assert.assertEquals(2, provider.getCheckCount()); + Assert.assertEquals(2, provider.getSyntaxErrorCount()); + Assert.assertEquals(1, provider.getHardCheckCount()); + } + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blacklist.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blacklist.java new file mode 100644 index 0000000000..3840a6802e --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_blacklist.java @@ -0,0 +1,36 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class WallStatTest_blacklist extends TestCase { + + private String sql = "select * from t where id = ? and 1 = 1"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + for (int i = 0; i < 10; ++i) { + Assert.assertFalse(provider.checkValid(sql)); + } + + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(10, tableStat.getSelectCount()); + Assert.assertEquals(0, provider.getWhiteListHitCount()); + Assert.assertEquals(9, provider.getBlackListHitCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_create_table.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_create_table.java new file mode 100644 index 0000000000..996ef88dab --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_create_table.java @@ -0,0 +1,54 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + + +public class WallStatTest_create_table extends TestCase { + private String sql = "create table t (fid int, fname varchar(50))"; + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + provider.getConfig().setCreateTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getCreateCount()); + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + provider.getConfig().setCreateTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getCreateCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + provider.getConfig().setCreateTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getCreateCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + provider.getConfig().setCreateTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getCreateCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_delete.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_delete.java new file mode 100644 index 0000000000..26f7e1642f --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_delete.java @@ -0,0 +1,55 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + +public class WallStatTest_delete extends TestCase { + + private String sql = "delete from T where fid = ?"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDeleteCount()); + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDeleteCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDeleteCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDeleteCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_drop_table.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_drop_table.java new file mode 100644 index 0000000000..a2cdc60008 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_drop_table.java @@ -0,0 +1,63 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + +public class WallStatTest_drop_table extends TestCase { + + private String sql = "drop table t"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + provider.getConfig().setDropTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDropCount()); + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + provider.getConfig().setDropTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDropCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + provider.getConfig().setDropTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDropCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + provider.getConfig().setDropTableAllow(true); + + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getDropCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_function_stats.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_function_stats.java new file mode 100644 index 0000000000..2a12cf9363 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_function_stats.java @@ -0,0 +1,48 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallFunctionStat; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class WallStatTest_function_stats extends TestCase { + + private String sql = "select len(fname), len(fdesc) from t"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + { + WallFunctionStat functionStat = provider.getFunctionStat("len"); + Assert.assertEquals(2, functionStat.getInvokeCount()); + } + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(2, tableStat.getSelectCount()); + } + { + WallFunctionStat functionStat = provider.getFunctionStat("len"); + Assert.assertEquals(4, functionStat.getInvokeCount()); + } + } + + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_insert.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_insert.java new file mode 100644 index 0000000000..21d13bc62b --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_insert.java @@ -0,0 +1,46 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + + +public class WallStatTest_insert extends TestCase { + private String sql = "insert into t (fid, fname) values (?, ?)"; + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getInsertCount()); + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getInsertCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getInsertCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getInsertCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select.java new file mode 100644 index 0000000000..b2ab732de8 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select.java @@ -0,0 +1,55 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + +public class WallStatTest_select extends TestCase { + + private String sql = "select * from t where id = ?"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_1.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_1.java new file mode 100644 index 0000000000..5ffb05c620 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_1.java @@ -0,0 +1,79 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + +public class WallStatTest_select_1 extends TestCase { + + private String sql = "SELECT b.* FROM lhwbbs_posts_reply a LEFT JOIN lhwbbs_posts b ON a.pid=b.pid WHERE a.rpid=? AND b.disabled=? ORDER BY a.pid DESC"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts_reply"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts_reply"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts_reply"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts_reply"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + { + WallTableStat tableStat = provider.getTableStat("lhwbbs_posts"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_into.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_into.java new file mode 100644 index 0000000000..0ba4ecb6b6 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_select_into.java @@ -0,0 +1,64 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + +public class WallStatTest_select_into extends TestCase { + + private String sql = "select * into x from t where id = ?"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + Assert.assertEquals(0, tableStat.getSelectIntoCount()); + } + { + WallTableStat tableStat = provider.getTableStat("x"); + Assert.assertEquals(0, tableStat.getSelectCount()); + Assert.assertEquals(1, tableStat.getSelectIntoCount()); + } + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getSelectCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_update.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_update.java new file mode 100644 index 0000000000..f936b83883 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_update.java @@ -0,0 +1,55 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; +import com.alibaba.druid.wall.spi.OracleWallProvider; +import com.alibaba.druid.wall.spi.PGWallProvider; +import com.alibaba.druid.wall.spi.SQLServerWallProvider; + + +public class WallStatTest_update extends TestCase { + private String sql = "update t set fname = ? where fid = ?"; + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getUpdateCount()); + } + + public void testOracle() throws Exception { + WallProvider provider = new OracleWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getUpdateCount()); + } + + public void testPG() throws Exception { + WallProvider provider = new PGWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getUpdateCount()); + } + + public void testSQLServer() throws Exception { + WallProvider provider = new SQLServerWallProvider(); + Assert.assertTrue(provider.checkValid(sql)); + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(1, tableStat.getUpdateCount()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_whiteList_syntaxError.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_whiteList_syntaxError.java new file mode 100644 index 0000000000..555cbaa954 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallStatTest_whiteList_syntaxError.java @@ -0,0 +1,54 @@ +package com.alibaba.druid.bvt.filter.wall; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.wall.WallContext; +import com.alibaba.druid.wall.WallProvider; +import com.alibaba.druid.wall.WallTableStat; +import com.alibaba.druid.wall.spi.MySqlWallProvider; + +public class WallStatTest_whiteList_syntaxError extends TestCase { + + protected void setUp() throws Exception { + WallContext.clearContext(); + } + + protected void tearDown() throws Exception { + WallContext.clearContext(); + } + + public void testMySql() throws Exception { + WallProvider provider = new MySqlWallProvider(); + provider.getConfig().setStrictSyntaxCheck(false); + + String sql = "select xx * x *"; + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(0, tableStat.getSelectCount()); + Assert.assertEquals(0, provider.getBlackListHitCount()); + Assert.assertEquals(0, provider.getWhiteListHitCount()); + Assert.assertEquals(1, provider.getWhiteList().size()); + Assert.assertEquals(0, provider.getBlackList().size()); + Assert.assertEquals(1, provider.getCheckCount()); + Assert.assertEquals(1, provider.getSyntaxErrorCount()); + Assert.assertEquals(1, provider.getHardCheckCount()); + } + + Assert.assertTrue(provider.checkValid(sql)); + { + WallTableStat tableStat = provider.getTableStat("t"); + Assert.assertEquals(0, tableStat.getSelectCount()); + Assert.assertEquals(0, provider.getBlackListHitCount()); + Assert.assertEquals(1, provider.getWhiteListHitCount()); + Assert.assertEquals(1, provider.getWhiteList().size()); + Assert.assertEquals(0, provider.getBlackList().size()); + Assert.assertEquals(2, provider.getCheckCount()); + Assert.assertEquals(2, provider.getSyntaxErrorCount()); + Assert.assertEquals(1, provider.getHardCheckCount()); + } + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallTruncateTest.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallTruncateTest.java index 02312a278b..1d2b179e5a 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallTruncateTest.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallTruncateTest.java @@ -25,18 +25,30 @@ import com.alibaba.druid.wall.WallUtils; public class WallTruncateTest extends TestCase { private String sql = "TRUNCATE TABLE T1"; - private WallConfig config = new WallConfig(); protected void setUp() throws Exception { //config.setTruncateAllow(true); } public void testMySql() throws Exception { - Assert.assertFalse(WallUtils.isValidateMySql(sql, config)); + WallConfig config = new WallConfig(); + Assert.assertTrue(WallUtils.isValidateMySql(sql, config)); } public void testORACLE() throws Exception { - + WallConfig config = new WallConfig(); + Assert.assertTrue(WallUtils.isValidateOracle(sql, config)); + } + + public void testMySql_false() throws Exception { + WallConfig config = new WallConfig(); + config.setTruncateAllow(false); + Assert.assertFalse(WallUtils.isValidateMySql(sql, config)); + } + + public void testORACLE_false() throws Exception { + WallConfig config = new WallConfig(); + config.setTruncateAllow(false); Assert.assertFalse(WallUtils.isValidateOracle(sql, config)); } } diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUnionTest3.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUnionTest3.java index 4136262786..d78259425d 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUnionTest3.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUnionTest3.java @@ -29,8 +29,8 @@ import com.alibaba.druid.wall.WallUtils; public class WallUnionTest3 extends TestCase { public void testMySql() throws Exception { - Assert.assertFalse(WallUtils.isValidateMySql("SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'")); - Assert.assertFalse(WallUtils.isValidateMySql("SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x';")); +// Assert.assertFalse(WallUtils.isValidateMySql("SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'")); +// Assert.assertFalse(WallUtils.isValidateMySql("SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x';")); Assert.assertFalse(WallUtils.isValidateMySql("SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'/*,10 ;")); } } diff --git a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUpdateTest2.java b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUpdateTest2.java index f9731ba4ab..72cbb0f14f 100644 --- a/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUpdateTest2.java +++ b/src/test/java/com/alibaba/druid/bvt/filter/wall/WallUpdateTest2.java @@ -22,22 +22,29 @@ import org.junit.Assert; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallUtils; - public class WallUpdateTest2 extends TestCase { + private String sql = "UPDATE T_USER SET FNAME = ?"; - - private WallConfig config = new WallConfig(); - - protected void setUp() throws Exception { - config.setUpdateAllow(true); + + public void testMySql_true() throws Exception { + WallConfig config = new WallConfig(); + Assert.assertTrue(WallUtils.isValidateMySql(sql, config)); } - public void testMySql() throws Exception { + public void testORACLE_true() throws Exception { + WallConfig config = new WallConfig(); + Assert.assertTrue(WallUtils.isValidateOracle(sql, config)); + } + + public void testMySql_false() throws Exception { + WallConfig config = new WallConfig(); + config.setUpdateAllow(false); Assert.assertFalse(WallUtils.isValidateMySql(sql, config)); } - public void testORACLE() throws Exception { - + public void testORACLE_false() throws Exception { + WallConfig config = new WallConfig(); + config.setUpdateAllow(false); Assert.assertFalse(WallUtils.isValidateOracle(sql, config)); } } diff --git a/src/test/java/com/alibaba/druid/bvt/pool/SpringIbatisFilterTest.java b/src/test/java/com/alibaba/druid/bvt/pool/SpringIbatisFilterTest.java index 6dfd5fbd01..2d630d5e5e 100644 --- a/src/test/java/com/alibaba/druid/bvt/pool/SpringIbatisFilterTest.java +++ b/src/test/java/com/alibaba/druid/bvt/pool/SpringIbatisFilterTest.java @@ -18,14 +18,16 @@ package com.alibaba.druid.bvt.pool; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; +import java.util.Collections; +import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicLong; import javax.sql.DataSource; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.alibaba.druid.filter.FilterAdapter; @@ -34,6 +36,8 @@ import com.alibaba.druid.proxy.jdbc.ConnectionProxy; import com.alibaba.druid.spring.IUserService; import com.alibaba.druid.spring.User; import com.alibaba.druid.stat.DruidDataSourceStatManager; +import com.alibaba.druid.stat.DruidStatService; +import com.alibaba.druid.support.json.JSONUtils; public class SpringIbatisFilterTest extends TestCase { @@ -101,6 +105,11 @@ public class SpringIbatisFilterTest extends TestCase { conn.close(); } + Assert.assertEquals(1, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); + + Map wallStats = DruidStatService.getInstance().getWallStatMap(Collections.emptyMap()); + + System.out.println("wall-stats : " + JSONUtils.toJSONString(wallStats)); context.close(); diff --git a/src/test/java/com/alibaba/druid/bvt/pool/SpringMybatisFilterTest.java b/src/test/java/com/alibaba/druid/bvt/pool/SpringMybatisFilterTest.java index 6511190f60..300d5fb031 100644 --- a/src/test/java/com/alibaba/druid/bvt/pool/SpringMybatisFilterTest.java +++ b/src/test/java/com/alibaba/druid/bvt/pool/SpringMybatisFilterTest.java @@ -20,11 +20,11 @@ import java.sql.Statement; import javax.sql.DataSource; -import junit.framework.Assert; import junit.framework.TestCase; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; +import org.junit.Assert; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.alibaba.druid.spring.User; diff --git a/src/test/java/com/alibaba/druid/bvt/sql/MybatisTest.java b/src/test/java/com/alibaba/druid/bvt/sql/MybatisTest.java index 6c934cdd72..5761ea86e1 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/MybatisTest.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/MybatisTest.java @@ -15,9 +15,10 @@ */ package com.alibaba.druid.bvt.sql; -import junit.framework.Assert; import junit.framework.TestCase; +import org.junit.Assert; + import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.util.JdbcUtils; diff --git a/src/test/java/com/alibaba/druid/bvt/sql/cobar/DMLDeleteParserTest.java b/src/test/java/com/alibaba/druid/bvt/sql/cobar/DMLDeleteParserTest.java index cf12fc7646..6616f86e24 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/cobar/DMLDeleteParserTest.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/cobar/DMLDeleteParserTest.java @@ -32,8 +32,7 @@ public class DMLDeleteParserTest extends TestCase { SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); - Assert.assertEquals("DELETE LOW_PRIORITY FROM id1.id, id\n" + // - "USING t1 a" + // + Assert.assertEquals("DELETE LOW_PRIORITY FROM id1.id, id USING (t1) AS a" + // "\nWHERE col1 = ?", output); } @@ -53,8 +52,8 @@ public class DMLDeleteParserTest extends TestCase { SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); - Assert.assertEquals("DELETE FROM offer.*, wp_image.*\n" + // - "USING offer a, wp_image b\n" + // + Assert.assertEquals("DELETE FROM offer.*, wp_image.*" + // + " USING (offer) AS a, wp_image b\n" + // "WHERE a.member_id = b.member_id\n" + // "\tAND a.member_id = 'abc'", output); } diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBinTest.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBinTest.java new file mode 100644 index 0000000000..1632b0b615 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBinTest.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + + +public class EvalMethodBinTest extends TestCase { + public void test_reverse() throws Exception { + Assert.assertEquals(32, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "BIT_LENGTH('text')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBitLengthTest.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBitLengthTest.java new file mode 100644 index 0000000000..66640fd710 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBitLengthTest.java @@ -0,0 +1,14 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + + +public class EvalMethodBitLengthTest extends TestCase { + public void test_reverse() throws Exception { + Assert.assertEquals("1100", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "BIN(12)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Char.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Char.java new file mode 100644 index 0000000000..a0bc929430 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Char.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + + +public class EvalMethodTest_Char extends TestCase { + public void test_reverse() throws Exception { + Assert.assertEquals("MySQL", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "CHAR(77,121,83,81,'76')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Char_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Char_1.java new file mode 100644 index 0000000000..6461b72c32 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Char_1.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + + +public class EvalMethodTest_Char_1 extends TestCase { + public void test_reverse() throws Exception { + Assert.assertEquals("MMM", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "CHAR(77,77.3,'77.3')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Elt.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Elt.java new file mode 100644 index 0000000000..147549e6be --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Elt.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_Elt extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("ej", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "ELT(1, 'ej', 'Heja', 'hej', 'foo')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Elt_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Elt_1.java new file mode 100644 index 0000000000..f4ac3fa399 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_Elt_1.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_Elt_1 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(null, + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "ELT(11, 'ej', 'Heja', 'hej', 'foo')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert.java new file mode 100644 index 0000000000..c1642951c1 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_insert extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("Quadratic", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "INSERT('Quadratic', -1, 4, 'What')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert_1.java new file mode 100644 index 0000000000..9f0d65bd39 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert_1.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_insert_1 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("QuWhattic", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "INSERT('Quadratic', 3, 4, 'What')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert_2.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert_2.java new file mode 100644 index 0000000000..4d735f4fcd --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_insert_2.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_insert_2 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("QuWhat", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "INSERT('Quadratic', 3, 100, 'What')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr.java new file mode 100644 index 0000000000..07bdaf9ecf --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_instr extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(4, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "INSTR('foobarbar', 'bar')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr_1.java new file mode 100644 index 0000000000..28ae98dd62 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_instr_1.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_instr_1 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(0, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "INSTR('xbar', 'foobar')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lcase.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lcase.java new file mode 100644 index 0000000000..47e9ce3b78 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lcase.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_lcase extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("quadratically", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LOWER('QUADRATICALLY')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_left.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_left.java new file mode 100644 index 0000000000..fec8f694ce --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_left.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_left extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("fooba", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LEFT('foobarbar', 5)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_len.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_len.java new file mode 100644 index 0000000000..96f8701e12 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_len.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_len extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(4, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LENGTH('text')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate.java new file mode 100644 index 0000000000..0abe83a11b --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_locate extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(4, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LOCATE('bar', 'foobarbar')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate_1.java new file mode 100644 index 0000000000..5d0631e6d6 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate_1.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_locate_1 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(0, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LOCATE('xbar', 'foobar')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate_2.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate_2.java new file mode 100644 index 0000000000..83058931fc --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_locate_2.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_locate_2 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals(7, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LOCATE('bar', 'foobarbar', 5)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lower.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lower.java new file mode 100644 index 0000000000..479c97e3ee --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lower.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_lower extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("quadratically", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LOWER('QUADRATICALLY')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lpad.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lpad.java new file mode 100644 index 0000000000..2d2ee9552d --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lpad.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_lpad extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("??hi", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LPAD('hi',4,'??')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lpad_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lpad_1.java new file mode 100644 index 0000000000..eaae5c649b --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_lpad_1.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_lpad_1 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("h", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LPAD('hi',1,'??')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_ltrim.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_ltrim.java new file mode 100644 index 0000000000..7a6147bf7e --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_ltrim.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_ltrim extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("barbar", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "LTRIM(' barbar')")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_mid.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_mid.java new file mode 100644 index 0000000000..416622cfd5 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_mid.java @@ -0,0 +1,15 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_mid extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("ratically", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "mid('Quadratically',5)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring.java new file mode 100644 index 0000000000..c67465746d --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_substring extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("barbar", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "SUBSTRING('foobarbar' FROM 4)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_1.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_1.java new file mode 100644 index 0000000000..2db890e7fb --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_1.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_substring_1 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("ratica", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "SUBSTRING('Quadratically',5,6)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_2.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_2.java new file mode 100644 index 0000000000..7551658b8b --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_2.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_substring_2 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("ila", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "SUBSTRING('Sakila', -3)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_3.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_3.java new file mode 100644 index 0000000000..1a5ed41894 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_3.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_substring_3 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("aki", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "SUBSTRING('Sakila', -5, 3)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_4.java b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_4.java new file mode 100644 index 0000000000..8a31e32ac3 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodTest_substring_4.java @@ -0,0 +1,16 @@ +package com.alibaba.druid.bvt.sql.eval; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class EvalMethodTest_substring_4 extends TestCase { + + public void test_method() throws Exception { + Assert.assertEquals("ki", + SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "SUBSTRING('Sakila' FROM -4 FOR 2)")); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/DeleteSyntaxTest.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/DeleteSyntaxTest.java index e5969c33b7..d991d015d2 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/mysql/DeleteSyntaxTest.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/DeleteSyntaxTest.java @@ -73,7 +73,7 @@ public class DeleteSyntaxTest extends TestCase { String text = output(stmtList); - Assert.assertEquals("DELETE FROM a1, a2\nUSING t1 a1" + // + Assert.assertEquals("DELETE FROM a1, a2 USING (t1) AS a1" + // "\n\tINNER JOIN t2 a2\nWHERE a1.id = a2.id;", text); } diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableAddPrimaryKey_1.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableAddPrimaryKey_1.java new file mode 100644 index 0000000000..4f85296ab4 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableAddPrimaryKey_1.java @@ -0,0 +1,39 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.parser.Token; + +public class MySqlAlterTableAddPrimaryKey_1 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "alter table tabelname add constraint mYconstraint primary key(id)"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tabelname" + // + "\n\tADD CONSTRAINT mYconstraint PRIAMRY KEY (id)", output); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableDisableKeys.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableDisableKeys.java new file mode 100644 index 0000000000..0874bd9179 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableDisableKeys.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableDisableKeys extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "alter table tableName DISABLE KEYS"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tableName" + // + "\n\tDISABLE KEYS", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableDropPrimaryKey.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableDropPrimaryKey.java new file mode 100644 index 0000000000..f8f28d69be --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableDropPrimaryKey.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableDropPrimaryKey extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "alter table tableName DROP PRIMARY KEY"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tableName" + // + "\n\tDROP PRIMARY KEY", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableEnableKeys.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableEnableKeys.java new file mode 100644 index 0000000000..3e924613dd --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableEnableKeys.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableEnableKeys extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "alter table tableName ENABLE KEYS"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tableName" + // + "\n\tENABLE KEYS", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest10.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest10.java new file mode 100644 index 0000000000..a055489588 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest10.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest10 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE t1 CHANGE a b INTEGER;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE t1" + // + "\n\tCHANGE COLUMN a b INTEGER", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(1, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest11.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest11.java new file mode 100644 index 0000000000..2abad52a91 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest11.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest11 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE t1 MODIFY b BIGINT NOT NULL;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE t1" + + "\n\tMODIFY COLUMN b BIGINT NOT NULL", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(1, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest12.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest12.java new file mode 100644 index 0000000000..34be4192ff --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest12.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest12 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tbl_name" + // + "\n\tDROP FOREIGN KEY fk_symbol", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest13.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest13.java new file mode 100644 index 0000000000..15985e6541 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest13.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest13 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE tbl_name DISCARD TABLESPACE;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tbl_name" + // + "\n\tDISCARD TABLESPACE", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest14.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest14.java new file mode 100644 index 0000000000..36250bacd8 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest14.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest14 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE tbl_name IMPORT TABLESPACE;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tbl_name" + // + "\n\tIMPORT TABLESPACE", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest4.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest4.java new file mode 100644 index 0000000000..8b1b6f1cf5 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest4.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest4 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "alter table test add dspcode char(200)"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE test" + // + "\n\tADD COLUMN dspcode char(200)", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(1, visitor.getColumns().size()); + Assert.assertTrue(visitor.getColumns().contains(new Column("test", "dspcode"))); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest5.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest5.java new file mode 100644 index 0000000000..c1cd845126 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest5.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest5 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE table_name change COLUMN column_name column_newname char(50)"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE table_name" + // + "\n\tCHANGE COLUMN column_name column_newname char(50)", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(1, visitor.getColumns().size()); + Assert.assertTrue(visitor.getColumns().contains(new Column("table_name", "column_name"))); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest6.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest6.java new file mode 100644 index 0000000000..85d6a14059 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest6.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest6 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "alter table tableName DROP FOREIGN KEY fk_symbol"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE tableName" + // + "\n\tDROP FOREIGN KEY fk_symbol", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest7.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest7.java new file mode 100644 index 0000000000..6e94bbd3bd --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest7.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest7 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE t1 ENGINE = InnoDB;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE t1" + // + "\n\tENGINE = InnoDB", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest8.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest8.java new file mode 100644 index 0000000000..bc879c3c51 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest8.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest8 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE t2 AUTO_INCREMENT = 3"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE t2" + // + "\n\tAUTO_INCREMENT = 3", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest9.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest9.java new file mode 100644 index 0000000000..54d3cb8671 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlAlterTableTest9.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.sql.parser.Token; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlAlterTableTest9 extends TestCase { + + public void test_alter_first() throws Exception { + String sql = "ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;"; + MySqlStatementParser parser = new MySqlStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + parser.match(Token.EOF); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + String output = SQLUtils.toMySqlString(stmt); + Assert.assertEquals("ALTER TABLE t2" + // + "\n\tDROP COLUMN c," + // + "\n\tDROP COLUMN d", output); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(2, visitor.getColumns().size()); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest5.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest5.java new file mode 100644 index 0000000000..76547b82db --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest5.java @@ -0,0 +1,66 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlCreateTableTest5 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "CREATE TABLE `test` (" + // + " `id` bigint(20) NOT NULL AUTO_INCREMENT," + // + " `dspcode` char(200) DEFAULT NULL," + // + " PRIMARY KEY (`id`)," + // + " KEY `index_name` (`dspcode`)" + // + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + Assert.assertEquals("utf8", stmt.getTableOptions().get("CHARSET")); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(2, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("test"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("test", "id"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("test", "dspcode"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest6.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest6.java new file mode 100644 index 0000000000..ee7dcdee1c --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest6.java @@ -0,0 +1,67 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlCreateTableTest6 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "CREATE TABLE Persons\n" + // + "(\n" + // + "Id_P int NOT NULL,\n" + // + "LastName varchar(255) NOT NULL,\n" + // + "FirstName varchar(255),\n" + // + "Address varchar(255),\n" + // + "City varchar(255),\n" + // + "UNIQUE (Id_P)\n" + // + ")"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(5, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("Persons"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "Id_P"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "LastName"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest7.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest7.java new file mode 100644 index 0000000000..dbd5c0a565 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest7.java @@ -0,0 +1,67 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlCreateTableTest7 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "CREATE TABLE Orders\n" + // + "(\n" + // + "O_Id int NOT NULL,\n" + // + "OrderNo int NOT NULL,\n" + // + "Id_P int,\n" + // + "PRIMARY KEY (O_Id),\n" + // + "FOREIGN KEY (Id_P) REFERENCES Persons(Id_P)\n" + // + ")"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(3, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("Orders"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("Orders", "O_Id"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Orders", "OrderNo"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Orders", "Id_P"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest8.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest8.java new file mode 100644 index 0000000000..b60984ab3b --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest8.java @@ -0,0 +1,70 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlCreateTableTest8 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "CREATE TABLE Persons\n" + // + "(\n" + // + "Id_P int NOT NULL,\n" + // + "LastName varchar(255) NOT NULL,\n" + // + "FirstName varchar(255),\n" + // + "Address varchar(255),\n" + // + "City varchar(255),\n" + // + "CHECK (Id_P>0)\n" + // + ")"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(5, visitor.getColumns().size()); + Assert.assertEquals(1, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("Persons"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "Id_P"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "LastName"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "FirstName"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "Address"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Persons", "City"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest9.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest9.java new file mode 100644 index 0000000000..a78baa0ee3 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateTableTest9.java @@ -0,0 +1,64 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlCreateTableTest9 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "CREATE VIEW v AS\n" + // + "SELECT ProductID,ProductName\n" + // + "FROM Products\n" + // + "WHERE Discontinued=No"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLCreateViewStatement stmt = (SQLCreateViewStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(4, visitor.getColumns().size()); + Assert.assertEquals(2, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("Products"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "ProductID"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "ProductName"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "Discontinued"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "No"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateViewTest.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateViewTest.java new file mode 100644 index 0000000000..39913dd643 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlCreateViewTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlCreateViewTest extends MysqlTest { + + public void test_0() throws Exception { + String sql = "CREATE OR REPLACE VIEW view_name AS\n" + // + "SELECT fname\n" + // + "FROM table_name\n" + // + "WHERE fid = ?"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLCreateViewStatement stmt = (SQLCreateViewStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(2, visitor.getColumns().size()); + Assert.assertEquals(1, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("table_name"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("table_name", "fid"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("table_name", "fname"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDeleteTest_1.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDeleteTest_1.java index 11677fc912..3c92a3ee67 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDeleteTest_1.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDeleteTest_1.java @@ -46,14 +46,15 @@ public class MySqlDeleteTest_1 extends MysqlTest { System.out.println("coditions : " + visitor.getConditions()); System.out.println("orderBy : " + visitor.getOrderByColumns()); - Assert.assertEquals(2, visitor.getTables().size()); + Assert.assertEquals(3, visitor.getTables().size()); Assert.assertEquals(2, visitor.getColumns().size()); Assert.assertEquals(2, visitor.getConditions().size()); - Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("t1"))); + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("a1"))); + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("a2"))); Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); - Assert.assertTrue(visitor.getColumns().contains(new Column("t1", "id"))); - Assert.assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("a1", "id"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("a2", "id"))); } } diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDropViewTest.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDropViewTest.java new file mode 100644 index 0000000000..06f2a96e49 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDropViewTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDropViewStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlDropViewTest extends MysqlTest { + + public void test_0() throws Exception { + String sql = "DROP VIEW view_name"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + MySqlDropViewStatement stmt = (MySqlDropViewStatement) statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("view_name"))); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test.java new file mode 100644 index 0000000000..b749baa9cf --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; + +public class MySqlError_test extends MysqlTest { + + public void test_0() throws Exception { + String sql = "insert into userdetectitem26 (nick,volume) values(?,?) " + // + "ON DUPLICATE KEY UPDATE title = ?,picURL = ?,scoreExceed = ?,score="; + + Exception error = null; + + try { + MySqlStatementParser parser = new MySqlStatementParser(sql); + parser.parseStatementList(); + } catch (Exception e) { + error = e; + } + + Assert.assertNotNull(error); + Assert.assertEquals("EOF, score=", error.getMessage()); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_1.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_1.java new file mode 100644 index 0000000000..59b5226fa5 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_1.java @@ -0,0 +1,40 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; + +public class MySqlError_test_1 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "SELECT * FROM pp_items WHERE uid= ORDER BY id DESC LIMIT ?,?"; + Exception error = null; + + try { + MySqlStatementParser parser = new MySqlStatementParser(sql); + parser.parseStatementList(); + } catch (Exception e) { + error = e; + } + + Assert.assertNotNull(error); +// error.printStackTrace(); + Assert.assertEquals("ERROR. token : ORDER, pos : 39", error.getMessage()); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_2.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_2.java new file mode 100644 index 0000000000..f5761914a2 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_2.java @@ -0,0 +1,40 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; + +public class MySqlError_test_2 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "Describe sdb_goods free_postage"; + Exception error = null; + + try { + MySqlStatementParser parser = new MySqlStatementParser(sql); + parser.parseStatementList(); + } catch (Exception e) { + error = e; + } + + Assert.assertNotNull(error); +// error.printStackTrace(); + Assert.assertEquals("syntax error, IDENTIFIER free_postage, pos 31", error.getMessage()); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_3.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_3.java new file mode 100644 index 0000000000..511cba095f --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlError_test_3.java @@ -0,0 +1,44 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; + +public class MySqlError_test_3 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "SELECT count(*) AS num FROM sdb_products AS P" + // + " LEFT JOIN sdb_goods AS G ON G.goods_id = P.goods_id" + // + " LEFT JOIN sdb_goods_cat AS C ON C.cat_id = G.cat_id" + // + " LEFT JOIN sdb_brand AS B ON B.brand_id = G.brand_id" + // + " WHERE P.disabled = ? AND P.op_status = LIMIT ?, ?"; + Exception error = null; + + try { + MySqlStatementParser parser = new MySqlStatementParser(sql); + parser.parseStatementList(); + } catch (Exception e) { + error = e; + } + + Assert.assertNotNull(error); +// error.printStackTrace(); + Assert.assertEquals("syntax error, QUES LIMIT, pos 248", error.getMessage()); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlSelectTest_9.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlSelectTest_9.java new file mode 100644 index 0000000000..10a652ff71 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlSelectTest_9.java @@ -0,0 +1,61 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLSelect; +import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; + +public class MySqlSelectTest_9 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "SELECT `group`.* FROM `group` WHERE (group.group_id=159754)"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement stmt = statementList.get(0); + + SQLSelectStatement selectStmt = (SQLSelectStatement) stmt; + + SQLSelect select = selectStmt.getSelect(); + Assert.assertNotNull(select.getQuery()); + MySqlSelectQueryBlock queryBlock = (MySqlSelectQueryBlock) select.getQuery(); + Assert.assertNull(queryBlock.getOrderBy()); + + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(2, visitor.getColumns().size()); + Assert.assertEquals(1, visitor.getConditions().size()); + Assert.assertEquals(0, visitor.getOrderByColumns().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("group"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlShowTest_table.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlShowTest_table.java new file mode 100644 index 0000000000..9eb377e788 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlShowTest_table.java @@ -0,0 +1,51 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLSelect; +import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; +import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; + +public class MySqlShowTest_table extends MysqlTest { + + public void test_0() throws Exception { + String sql = "SHOW FULL TABLES FROM sonar LIKE 'a'"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement stmt = statementList.get(0); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + Assert.assertEquals(0, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getConditions().size()); + Assert.assertEquals(0, visitor.getOrderByColumns().size()); + + // Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("mytable"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlUpdateTest_1.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlUpdateTest_1.java new file mode 100644 index 0000000000..6e2669b862 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlUpdateTest_1.java @@ -0,0 +1,60 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class MySqlUpdateTest_1 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "UPDATE t_price, t_basic_store s " + // + "SET purchasePrice = :purchasePrice, operaterId = :operaterId, " + // + " operaterRealName = :operaterRealName, operateDateline = :operateDateline " + // + "WHERE goodsId = :goodsId AND s.id = storeId AND s.areaId = :areaId"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement statemen = statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + statemen.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(2, visitor.getTables().size()); + Assert.assertEquals(8, visitor.getColumns().size()); + Assert.assertEquals(4, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("t_price"))); + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("t_basic_store"))); + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlUseTest_0.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlUseTest_0.java new file mode 100644 index 0000000000..bce74157bd --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlUseTest_0.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.List; + +import org.junit.Assert; + +import com.alibaba.druid.sql.MysqlTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; +import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor; + +public class MySqlUseTest_0 extends MysqlTest { + + public void test_0() throws Exception { + String sql = "use db;"; + + MySqlStatementParser parser = new MySqlStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement stmt = statementList.get(0); + + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); + stmt.accept(visitor); + + Assert.assertEquals(0, visitor.getTables().size()); + Assert.assertEquals(0, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getConditions().size()); + Assert.assertEquals(0, visitor.getOrderByColumns().size()); + + // Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("mytable"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/SQLUtilsTest.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/SQLUtilsTest.java new file mode 100644 index 0000000000..a376d3b0a6 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/SQLUtilsTest.java @@ -0,0 +1,21 @@ +package com.alibaba.druid.bvt.sql.mysql; + +import java.util.Arrays; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.SQLUtils; +import com.alibaba.druid.util.JdbcConstants; + +public class SQLUtilsTest extends TestCase { + + public void test_format() throws Exception { + String formattedSql = SQLUtils.format("select * from t where id = ?", JdbcConstants.MYSQL, + Arrays. asList("abc")); + Assert.assertEquals("SELECT *" + // + "\nFROM t" + // + "\nWHERE id = 'abc'", formattedSql); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/mysql/StringFunctionsTest.java b/src/test/java/com/alibaba/druid/bvt/sql/mysql/StringFunctionsTest.java index 47ee627c55..d475d6c51e 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/mysql/StringFunctionsTest.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/mysql/StringFunctionsTest.java @@ -519,7 +519,7 @@ public class StringFunctionsTest extends TestCase { String text = output(stmtList); - Assert.assertEquals("SELECT SUBSTRING('Sakila' FROM -4 FOR 2);", text); + Assert.assertEquals("SELECT SUBSTRING('Sakila', -4, 2);", text); } public void test_45() throws Exception { @@ -530,7 +530,7 @@ public class StringFunctionsTest extends TestCase { String text = output(stmtList); - Assert.assertEquals("SELECT SUBSTRING('foobarbar' FROM 4);", text); + Assert.assertEquals("SELECT SUBSTRING('foobarbar', 4);", text); } public void test_46() throws Exception { diff --git a/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSelectTest40.java b/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSelectTest40.java new file mode 100644 index 0000000000..a4ed5a6376 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSelectTest40.java @@ -0,0 +1,77 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.oracle; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.OracleTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; + +public class OracleSelectTest40 extends OracleTest { + + public void test_0() throws Exception { + String sql = // + "WITH a AS (" + // + " SELECT TO_CHAR(csl.create_time,'yyyyMMdd') create_time, cwl.client_key ck, csl.src_id src_id " + // + " FROM xxxx csl, xxxx cwl " + // + " WHERE 1 =1 AND csl.src_id = cwl.src_id AND csl.curr_url = cwl.curr_url " + // + " AND TO_CHAR(csl.create_time,'yyyyMMdd') BETWEEN ? " + // + " AND ? AND cwl.day = TO_CHAR(csl.create_time,'yyyyMMdd') " + // + " GROUP BY cwl.client_key, csl.src_id, csl.create_time ORDER BY csl.src_id )" + // + ", b AS (" + // + " SELECT itn.buyerpaytime, itn.esc_orderid, itn.oldck, " + // + " MAX(con.PAYED_AMOUNT) gmv, MAX(con.buyer_onlyid) buyer " + // + " FROM xxxx itn, xxxx don, xxxx con " + // + " WHERE don.esc_orderid = itn.esc_orderid " + // + " AND con.esc_orderid = itn.esc_orderid " + // + " AND don.order_status IN (4,5,6,7,8) AND itn.buyerpaytime BETWEEN ? AND ? " + // + " GROUP BY itn.esc_orderid, itn.oldck, itn.buyerpaytime ) " + // + "SELECT MAX(cos.location) AS position , a.src_id AS srcid , " + // + " COUNT(DISTINCT b.esc_orderid) AS orders , SUM(b.gmv) AS uvGmv, " + // + " COUNT(DISTINCT buyer) AS buyers FROM a, b, cp_operate_statistics cos " + // + "WHERE a.ck = b.oldck(+) AND TO_CHAR(cos.day,'yyyyMMdd') = a.create_time " + // + " AND a.create_time = b.buyerpaytime AND a.src_id = cos.src_id GROUP BY a.src_id ORDER BY a.src_id"; // + + OracleStatementParser parser = new OracleStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement statemen = statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); + statemen.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("relationships : " + visitor.getRelationships()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(2, visitor.getTables().size()); + + Assert.assertEquals(15, visitor.getColumns().size()); + + // Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh"))); + + // Assert.assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSelectTest41.java b/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSelectTest41.java new file mode 100644 index 0000000000..6d79c7c53c --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSelectTest41.java @@ -0,0 +1,81 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.oracle; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.OracleTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser; +import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; + +public class OracleSelectTest41 extends OracleTest { + + public void test_0() throws Exception { + String sql = // + "WITH RESULTVIEW AS" + // + " (" + // + " SELECT" + // + " AA.USERID," + // + " DECODE(AA.USERTYPE," + // + " '1'," + // + " (SELECT ORG_TABLE.ORGNAME" + // + " FROM ORG_TABLE" + // + " WHERE ORG_TABLE.ORGID = AA.BELONGORG)," + // + " '2'," + // + " (SELECT CUST_TABLE.CUSTOMERNAME" + // + " FROM CUST_TABLE" + // + " WHERE CUST_TABLE.CUSTOMERID = AA.BELONGORG)) ORGNAME" + // + " FROM AA" + // + " LEFT JOIN AAPWD" + // + " ON AA.USERID = AAPWD.USERID" + // + " WHERE AA.BELONGORG IN" + // + " (1,2,3)" + // + " ORDER BY AA.USERID DESC" + // + " )" + // + "SELECT *" + // + " FROM (SELECT RESULTVIEW.*, ROWNUM AS RESULTNUMS FROM RESULTVIEW)" + // + " WHERE RESULTNUMS > 1" + // + " AND RESULTNUMS <= 10"; // + + OracleStatementParser parser = new OracleStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement statemen = statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); + statemen.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("relationships : " + visitor.getRelationships()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(4, visitor.getTables().size()); + + Assert.assertEquals(9, visitor.getColumns().size()); + + // Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh"))); + + // Assert.assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGSelectTest10.java b/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGSelectTest10.java new file mode 100644 index 0000000000..6dbc0f60d5 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGSelectTest10.java @@ -0,0 +1,55 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.postgresql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.PGTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.postgresql.parser.PGSQLStatementParser; +import com.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor; + +public class PGSelectTest10 extends PGTest { + + public void test_0() throws Exception { + String sql = "SELECT nextval('passport_id_seq'::regclass) as id"; + + PGSQLStatementParser parser = new PGSQLStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement statemen = statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + PGSchemaStatVisitor visitor = new PGSchemaStatVisitor(); + statemen.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + + Assert.assertEquals(0, visitor.getColumns().size()); + Assert.assertEquals(0, visitor.getTables().size()); + } +} + +// select categoryId , offerIds from cnres.function_select_get_spt_p4p_offer_list (' 1031918 , 1031919 , 1037004 ') as +// a(categoryId numeric,offerIds character varying(4000)) +// select memberId , offerIds from cnres.function_select_get_seller_hot_offer_list('\'gzyyd168\'') as a(memberId +// character varying(20),offerIds character varying(4000)) + diff --git a/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGSelectTest9.java b/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGSelectTest9.java new file mode 100644 index 0000000000..1362abeefe --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGSelectTest9.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.postgresql; + +import java.util.List; + +import junit.framework.Assert; + +import com.alibaba.druid.sql.PGTest; +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.postgresql.parser.PGSQLStatementParser; +import com.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor; + +public class PGSelectTest9 extends PGTest { + + public void test_0() throws Exception { + String sql = "SELECT res.restaurant_id, row_number() " + // + "over (order by ST_Distance(res.restaurant_point,GeomFromEWKT(?))*111.12 ) as row_id " + // + "FROM restaurant res where res.city_id = ? and res.is_delete =false and res.restaurant_id <1000000 limit 10"; + + PGSQLStatementParser parser = new PGSQLStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLStatement statemen = statementList.get(0); + print(statementList); + + Assert.assertEquals(1, statementList.size()); + + PGSchemaStatVisitor visitor = new PGSchemaStatVisitor(); + statemen.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + + Assert.assertEquals(4, visitor.getColumns().size()); + Assert.assertEquals(1, visitor.getTables().size()); + } +} + +// select categoryId , offerIds from cnres.function_select_get_spt_p4p_offer_list (' 1031918 , 1031919 , 1037004 ') as +// a(categoryId numeric,offerIds character varying(4000)) +// select memberId , offerIds from cnres.function_select_get_seller_hot_offer_list('\'gzyyd168\'') as a(memberId +// character varying(20),offerIds character varying(4000)) + diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerCreateTableTest.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerCreateTableTest.java new file mode 100644 index 0000000000..31f00e9005 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerCreateTableTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.sqlserver; + +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement; +import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser; +import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor; +import com.alibaba.druid.stat.TableStat; +import com.alibaba.druid.stat.TableStat.Column; + +public class SQLServerCreateTableTest extends TestCase { + + public void test_0() throws Exception { + String sql = "CREATE VIEW [Current Product List] AS\n" + // + "SELECT ProductID,ProductName\n" + // + "FROM Products\n" + // + "WHERE Discontinued=No"; + + SQLServerStatementParser parser = new SQLServerStatementParser(sql); + List statementList = parser.parseStatementList(); + SQLCreateViewStatement stmt = (SQLCreateViewStatement) statementList.get(0); + + Assert.assertEquals(1, statementList.size()); + + SQLServerSchemaStatVisitor visitor = new SQLServerSchemaStatVisitor(); + stmt.accept(visitor); + + System.out.println("Tables : " + visitor.getTables()); + System.out.println("fields : " + visitor.getColumns()); + System.out.println("coditions : " + visitor.getConditions()); + System.out.println("orderBy : " + visitor.getOrderByColumns()); + + Assert.assertEquals(1, visitor.getTables().size()); + Assert.assertEquals(4, visitor.getColumns().size()); + Assert.assertEquals(2, visitor.getConditions().size()); + + Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("Products"))); + + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "ProductID"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "ProductName"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "Discontinued"))); + Assert.assertTrue(visitor.getColumns().contains(new Column("Products", "No"))); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest.java index 377ecac09b..f968392e31 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest.java @@ -36,7 +36,7 @@ public class SQLServerRowNumberTest extends TestCase { "WHERE TerritoryID IS NOT NULL " + // " AND SalesYTD <> 0;"; - String expect = "SELECT c.FirstName, c.LastName, ROW_NUMBER() OVER () ORDER BY SalesYTD DESC AS 'Row Number', s.SalesYTD, a.PostalCode" // + String expect = "SELECT c.FirstName, c.LastName, ROW_NUMBER() OVER (ORDER BY SalesYTD DESC) AS 'Row Number', s.SalesYTD, a.PostalCode" // + "\nFROM Sales.SalesPerson s" + "\n\tINNER JOIN Person.Contact c ON s.SalesPersonID = c.ContactID" + "\n\tINNER JOIN Person.Address a ON a.AddressID = c.ContactID" // diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest2.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest2.java index dfa6d284ee..2f32dbfead 100644 --- a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest2.java +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerRowNumberTest2.java @@ -35,7 +35,7 @@ public class SQLServerRowNumberTest2 extends TestCase { " WHERE RowNumber BETWEEN ? AND ?"; String expect = "SELECT *" + - "\nFROM (SELECT ROW_NUMBER() OVER () ORDER BY FAlertDate DESC, FAlertLevel, FAlertType AS RowNumber, *" + + "\nFROM (SELECT ROW_NUMBER() OVER (ORDER BY FAlertDate DESC, FAlertLevel, FAlertType) AS RowNumber, *" + "\n\tFROM monitor_business" + "\n\tWHERE FRemoveAlert = ?" + "\n\t) temp_table" + diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest12.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest12.java new file mode 100644 index 0000000000..854d3677ab --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest12.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.sqlserver; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser; +import com.alibaba.druid.sql.test.TestUtils; + +public class SQLServerSelectTest12 extends TestCase { + + public void test_simple() throws Exception { + String sql = "SELECT Row, Name " + // + "FROM(" + // + "SELECT ROW_NUMBER() OVER (ORDER BY ProductID) AS Row, Name " + // + "FROM Product " + // + ") AS ProductsWithRowNumbers " + // + "WHERE Row >= 6 AND Row <= 10"; + + String expect = "SELECT Row, Name" + // + "\nFROM (SELECT ROW_NUMBER() OVER (ORDER BY ProductID) AS Row, Name" + // + "\n\tFROM Product" + // + "\n\t) ProductsWithRowNumbers" + // + "\nWHERE Row >= 6" + // + "\n\tAND Row <= 10"; + + SQLServerStatementParser parser = new SQLServerStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + + String text = TestUtils.outputSqlServer(stmt); + + Assert.assertEquals(expect, text); + + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest13.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest13.java new file mode 100644 index 0000000000..7591ecdcfd --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest13.java @@ -0,0 +1,95 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.sqlserver; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser; +import com.alibaba.druid.sql.test.TestUtils; + +public class SQLServerSelectTest13 extends TestCase { + + public void test_simple() throws Exception { + String sql = "SELECT" + // + " a.* " + // + "FROM" + // + " (" + // + " SELECT" + // + " row_number () over (ORDER BY a.time_add DESC) ROW," + // + " a.detail_no AS detailNo," + // + " a.ba_id AS baId," + // + " a.ba_name AS baName," + // + " a.tran_no AS tranNo," + // + " a.tran_name AS tranName, " + // + " a.tran_type AS tranType, " + // + " a.balance_type AS balanceType, " + // + " a.detail_income AS detailIncome, " + // + " a.detail_payout AS detailPayout, " + // + " a.before_balance AS beforeBalance, " + // + " a.after_balance AS afterBalance, " + // + " a.time_add AS timeAdd, " + // + " a.user_add AS userAdd, " + // + " a.remark AS remark, " + // + " ( " + // + " SELECT " + // + " top 1 t.param_name " + // + " FROM " + // + " config.sys_params t " + // + " WHERE " + // + " t.param_type = ? " + // + " AND t.param_value = a.tran_type " + // + " ) AS tranTypeName " + // + " FROM " + // + " bussiness.account_detail a " + // + " WHERE " + // + " 1 = 1 " + // + " AND a.time_add >= ? " + // + " AND a.time_add <= ? " + // + " ) a " + // + "WHERE " + // + " a. ROW BETWEEN (?+ 1) " + // + "AND (?+?)"; // + + String expect = "SELECT a.*" + + "\nFROM (SELECT ROW_NUMBER() OVER (ORDER BY a.time_add DESC) AS ROW, a.detail_no AS detailNo, a.ba_id AS baId, a.ba_name AS baName, a.tran_no AS tranNo" + + "\n\t\t, a.tran_name AS tranName, a.tran_type AS tranType, a.balance_type AS balanceType, a.detail_income AS detailIncome, a.detail_payout AS detailPayout" + + "\n\t\t, a.before_balance AS beforeBalance, a.after_balance AS afterBalance, a.time_add AS timeAdd, a.user_add AS userAdd, a.remark AS remark" + + "\n\t\t, (" + + "\n\t\t\tSELECT TOP 1 t.param_name" + + "\n\t\t\tFROM config.sys_params t" + + "\n\t\t\tWHERE t.param_type = ?" + + "\n\t\t\t\tAND t.param_value = a.tran_type" + + "\n\t\t\t) AS tranTypeName" + + "\n\tFROM bussiness.account_detail a" + + "\n\tWHERE 1 = 1" + + "\n\t\tAND a.time_add >= ?" + + "\n\t\tAND a.time_add <= ?" + + "\n\t) a" + + "\nWHERE a.ROW BETWEEN ? + 1 AND ? + ?"; + + SQLServerStatementParser parser = new SQLServerStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + + String text = TestUtils.outputSqlServer(stmt); + + Assert.assertEquals(expect, text); + + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest14.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest14.java new file mode 100644 index 0000000000..7663683c77 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest14.java @@ -0,0 +1,98 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.sqlserver; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser; +import com.alibaba.druid.sql.test.TestUtils; + +public class SQLServerSelectTest14 extends TestCase { + + public void test_simple() throws Exception { + String sql = "SELECT " + // + " a.* " + // + "FROM " + // + " ( " + // + " SELECT " + // + " row_number () over (ORDER BY a.time_add DESC) ROW, " + // + " a.detail_no AS detailNo, " + // + " a.ba_id AS baId, " + // + " a.ba_name AS baName, " + // + " a.tran_no AS tranNo, " + // + " a.tran_name AS tranName, " + // + " a.tran_type AS tranType, " + // + " a.balance_type AS balanceType, " + // + " a.detail_income AS detailIncome, " + // + " a.detail_payout AS detailPayout, " + // + " a.before_balance AS beforeBalance, " + // + " a.after_balance AS afterBalance, " + // + " a.time_add AS timeAdd, " + // + " a.user_add AS userAdd, " + // + " a.remark AS remark, " + // + " ( " + // + " SELECT " + // + " top 1 t.param_name " + // + " FROM " + // + " config.sys_params t " + // + " WHERE " + // + " t.param_type = 2 " + // + " AND t.param_value = a.tran_type " + // + " ) AS tranTypeName " + // + " FROM " + // + " bussiness.account_detail a " + // + " WHERE " + // + " 1 = 1 " + // + " AND a.time_add >= 2 " + // + " AND a.time_add <= 3 " + // + " ) a " + // + "WHERE " + // + " a.ROW BETWEEN (10+2) AND 20 "; // + + String expect = "SELECT a.*" + + // + "\nFROM (SELECT ROW_NUMBER() OVER (ORDER BY a.time_add DESC) AS ROW, a.detail_no AS detailNo, a.ba_id AS baId, a.ba_name AS baName, a.tran_no AS tranNo" + + // + "\n\t\t, a.tran_name AS tranName, a.tran_type AS tranType, a.balance_type AS balanceType, a.detail_income AS detailIncome, a.detail_payout AS detailPayout" + + // + "\n\t\t, a.before_balance AS beforeBalance, a.after_balance AS afterBalance, a.time_add AS timeAdd, a.user_add AS userAdd, a.remark AS remark" + + // + "\n\t\t, (" + // + "\n\t\t\tSELECT TOP 1 t.param_name" + // + "\n\t\t\tFROM config.sys_params t" + // + "\n\t\t\tWHERE t.param_type = 2" + // + "\n\t\t\t\tAND t.param_value = a.tran_type" + // + "\n\t\t\t) AS tranTypeName" + // + "\n\tFROM bussiness.account_detail a" + // + "\n\tWHERE 1 = 1" + // + "\n\t\tAND a.time_add >= 2" + // + "\n\t\tAND a.time_add <= 3" + // + "\n\t) a" + // + "\nWHERE a.ROW BETWEEN 10 + 2 AND 20"; + + SQLServerStatementParser parser = new SQLServerStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + + String text = TestUtils.outputSqlServer(stmt); + + Assert.assertEquals(expect, text); + + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest15.java b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest15.java new file mode 100644 index 0000000000..e52b3b28f1 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/sql/sqlserver/SQLServerSelectTest15.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.bvt.sql.sqlserver; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.sql.ast.SQLStatement; +import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser; +import com.alibaba.druid.sql.test.TestUtils; + +public class SQLServerSelectTest15 extends TestCase { + + public void test_simple() throws Exception { + String sql = "SELECT TOP 50 PERCENT * FROM Persons"; // + + String expect = "SELECT TOP 50 PERCENT *\n" + // + "FROM Persons"; + + SQLServerStatementParser parser = new SQLServerStatementParser(sql); + SQLStatement stmt = parser.parseStatementList().get(0); + + String text = TestUtils.outputSqlServer(stmt); + + Assert.assertEquals(expect, text); + + System.out.println(text); + } +} diff --git a/src/test/java/com/alibaba/druid/mysql/MySqlHexTest.java b/src/test/java/com/alibaba/druid/mysql/MySqlHexTest.java new file mode 100644 index 0000000000..bdb494bc28 --- /dev/null +++ b/src/test/java/com/alibaba/druid/mysql/MySqlHexTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.mysql; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +import junit.framework.TestCase; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.util.JdbcUtils; + +public class MySqlHexTest extends TestCase { + final int COUNT = 800; + + private String jdbcUrl; + private String user; + private String password; + private String driverClass; + + private DruidDataSource dataSource; + + protected void setUp() throws Exception { + jdbcUrl = "jdbc:mysql://hbase-01:3306/sonar"; + user = "sonar"; + password = "sonar"; + driverClass = "com.mysql.jdbc.Driver"; + + dataSource = new DruidDataSource(); + dataSource.setDriverClassName(driverClass); + dataSource.setUrl(jdbcUrl); + dataSource.setPoolPreparedStatements(true); + dataSource.setUsername(user); + dataSource.setPassword(password); + + } + + + public void test_0() throws Exception { + + Connection conn = dataSource.getConnection(); + + String sql = "SELECT INSERT('Quadratic', 1, 4, 'What')"; + + PreparedStatement stmt = conn.prepareStatement(sql); + + ResultSet rs = stmt.executeQuery(); + JdbcUtils.printResultSet(rs); + rs.close(); + stmt.close(); + + conn.close(); + } + +} diff --git a/src/test/resources/com/alibaba/druid/pool/dataSource.xml b/src/test/resources/com/alibaba/druid/pool/dataSource.xml index 976ca8a8ba..8061bd0921 100644 --- a/src/test/resources/com/alibaba/druid/pool/dataSource.xml +++ b/src/test/resources/com/alibaba/druid/pool/dataSource.xml @@ -15,7 +15,8 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/ - + +