fix MySqlSchemaStatVisitor think index as column

This commit is contained in:
junyu
2014-07-11 18:05:36 +08:00
89 changed files with 3961 additions and 3026 deletions
@@ -1,36 +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;
import junit.framework.TestCase;
import com.alibaba.druid.pool.DruidDataSource;
public class DruidTest extends TestCase {
public void test_0() throws Exception {
DruidDataSource ds = new DruidDataSource();
ds.setMaxWait(30);
ds.setInitialSize(0);
ds.setUrl("jdbc:mysql:xxx");
try {
ds.getConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@@ -1,11 +1,9 @@
package com.alibaba.druid;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
import org.junit.Assert;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -17,8 +15,8 @@ import org.nutz.dao.impl.NutDao;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
/*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
@@ -79,7 +77,7 @@ public class TestRollBack {
}
@AfterClass
public static void destory() {
public static void destroy() {
c3p0.close();
druid.close();
}
@@ -1,39 +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.bug;
import java.sql.Driver;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.druid.util.Utils;
public class Bug_for_JeffYin extends TestCase {
public void test_0() throws Exception {
String url = "jdbc:sqlserver://localhost:1433;";
String driverClassName = JdbcUtils.getDriverClassName(url);
Class<?> driverClass = Utils.loadClass(driverClassName);
Assert.assertNotNull(driverClass);
Driver driver = (Driver) driverClass.newInstance();
Assert.assertTrue(driver.acceptsURL(url));
}
}
@@ -45,7 +45,7 @@ public class MySqlWallTest80 extends TestCase {
provider.getConfig().setCommentAllow(true);
Assert.assertFalse(provider.checkValid(//
Assert.assertTrue(provider.checkValid(//
"SELECT * FROM T WHERE FID = ? OR FID LIKE 1 --"));
Assert.assertEquals(1, provider.getTableStats().size());
@@ -28,26 +28,27 @@ import com.alibaba.druid.wall.spi.MySqlWallProvider;
public class TenantSelectTest3 extends TestCase {
private String sql = "SELECT ID, NAME " + //
"FROM orders o inner join users u ON o.userid = u.id " + //
"WHERE FID = ? OR FID = ?";
private String expect_sql = "SELECT ID, NAME, u.tenant, o.tenant" + //
"\nFROM orders o" + //
"\n\tINNER JOIN users u ON o.userid = u.id" + //
"\nWHERE FID = ?" + //
"\n\tOR FID = ?";
private WallConfig config = new WallConfig();
private WallConfig config_callback = new WallConfig();
private String sql = "SELECT ID, NAME " + //
"FROM orders o inner join users u ON o.userid = u.id " + //
"WHERE FID = ? OR FID = ?";
private String expect_sql = "SELECT ID, NAME, u.tenant, o.tenant" + //
"\nFROM orders o" + //
"\n\tINNER JOIN users u ON o.userid = u.id" + //
"\nWHERE FID = ?" + //
"\n\tOR FID = ?";
protected void setUp() throws Exception {
}
public void testMySql() throws Exception {
WallConfig config = new WallConfig();
WallConfig config_callback = new WallConfig();
config.setTenantTablePattern("*");
config.setTenantColumn("tenant");
config_callback.setTenantCallBack(new TenantTestCallBack());
}
public void testMySql() throws Exception {
WallProvider.setTenantValue(123);
MySqlWallProvider provider = new MySqlWallProvider(config);
WallCheckResult checkResult = provider.check(sql);
@@ -58,6 +59,13 @@ public class TenantSelectTest3 extends TestCase {
}
public void testMySql2() throws Exception {
WallConfig config = new WallConfig();
WallConfig config_callback = new WallConfig();
config.setTenantTablePattern("*");
config.setTenantColumn("tenant");
config_callback.setTenantCallBack(new TenantTestCallBack());
MySqlWallProvider provider = new MySqlWallProvider(config_callback);
WallCheckResult checkResult = provider.check(sql);
Assert.assertEquals(0, checkResult.getViolations().size());
@@ -0,0 +1,56 @@
package com.alibaba.druid.bvt.pool;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.pool.DruidDataSource;
public class DruidDataSourceTest_fill extends TestCase {
private DruidDataSource dataSource;
private int maxActive = 10;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setMaxActive(maxActive);
dataSource.setTestOnBorrow(false);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_fill_0() throws Exception {
int fillCount = dataSource.fill(3);
Assert.assertEquals(3, fillCount);
}
public void test_fill_1() throws Exception {
int fillCount = dataSource.fill(1000);
Assert.assertEquals(maxActive, fillCount);
}
public void test_fill_2() throws Exception {
int fillCount = dataSource.fill(maxActive);
Assert.assertEquals(maxActive, fillCount);
}
public void test_fill_3() throws Exception {
int fillCount = dataSource.fill();
Assert.assertEquals(maxActive, fillCount);
}
public void test_fill_5() throws Exception {
Exception error = null;
try {
dataSource.fill(-1);
} catch (IllegalArgumentException e) {
error = e;
}
Assert.assertNotNull(error);
}
}
@@ -0,0 +1,86 @@
package com.alibaba.druid.bvt.pool;
import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.pool.DruidDataSource;
public class DruidDataSourceTest_fill2 extends TestCase {
private DruidDataSource dataSource;
private int maxActive = 100;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setMaxActive(maxActive);
dataSource.setTestOnBorrow(false);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_fill() throws Exception {
final AtomicLong errorCount = new AtomicLong();
final int THREAD_COUNT = 100;
final CountDownLatch startLatch = new CountDownLatch(THREAD_COUNT);
final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i) {
threads[i] = new Thread("thread-" + i) {
public void run() {
startLatch.countDown();
try {
Connection conn = dataSource.getConnection();
Thread.sleep(2);
conn.close();
} catch (Exception e) {
errorCount.incrementAndGet();
} finally {
endLatch.countDown();
}
}
};
threads[i].start();
}
startLatch.await(1000, TimeUnit.MILLISECONDS);
final CountDownLatch fillLatch = new CountDownLatch(THREAD_COUNT);
final AtomicLong fillErrorCount = new AtomicLong();
final AtomicLong fillCount = new AtomicLong();
Thread fillThread = new Thread() {
public void run() {
try {
int count = dataSource.fill();
fillCount.getAndSet(count);
} catch (Exception e) {
fillErrorCount.incrementAndGet();
} finally {
fillLatch.countDown();
}
}
};
fillThread.start();
fillLatch.await(1000, TimeUnit.MILLISECONDS);
Assert.assertEquals(0, fillErrorCount.get());
endLatch.await(1000, TimeUnit.MILLISECONDS);
Assert.assertEquals(true, fillCount.get() > 0);
}
}
@@ -0,0 +1,37 @@
package com.alibaba.druid.bvt.pool;
import org.junit.Assert;
import junit.framework.TestCase;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
public class DruidDataSourceTest_tryGet extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setMaxActive(1);
dataSource.setInitialSize(1);
dataSource.setTestOnBorrow(false);
dataSource.init();
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_0() throws Exception {
DruidPooledConnection conn1 = this.dataSource.tryGetConnection();
Assert.assertNotNull(conn1);
DruidPooledConnection conn2 = this.dataSource.tryGetConnection();
Assert.assertNull(conn2);
conn1.close();
}
}
@@ -0,0 +1,37 @@
package com.alibaba.druid.bvt.pool;
import java.sql.Connection;
import org.junit.Assert;
import junit.framework.TestCase;
import com.alibaba.druid.pool.DruidDataSource;
public class FullTest extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.init();
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_restart() throws Exception {
Assert.assertEquals(false, dataSource.isFull());
dataSource.fill();
Assert.assertEquals(true, dataSource.isFull());
Connection conn = dataSource.getConnection();
Assert.assertEquals(true, dataSource.isFull());
conn.close();
Assert.assertEquals(true, dataSource.isFull());
}
}
@@ -8,23 +8,23 @@ import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcUtils;
public class PropertyTest_useGloalDataSourceStat extends TestCase {
public class PropertyTest_useGlobalDataSourceStat extends TestCase {
private DruidDataSource dataSource;
public void test_true() {
System.setProperty("druid.useGloalDataSourceStat", "true");
System.setProperty("druid.useGlobalDataSourceStat", "true");
dataSource = new DruidDataSource();
Assert.assertTrue(dataSource.isUseGloalDataSourceStat());
Assert.assertTrue(dataSource.isUseGlobalDataSourceStat());
}
public void test_false() {
System.setProperty("druid.useGloalDataSourceStat", "false");
System.setProperty("druid.useGlobalDataSourceStat", "false");
dataSource = new DruidDataSource();
Assert.assertFalse(dataSource.isUseGloalDataSourceStat());
Assert.assertFalse(dataSource.isUseGlobalDataSourceStat());
}
protected void tearDown() throws Exception {
System.clearProperty("druid.useGloalDataSourceStat");
System.clearProperty("druid.useGlobalDataSourceStat");
JdbcUtils.close(dataSource);
}
}
@@ -28,12 +28,12 @@ public class GlobalStatTest0 extends TestCase {
dataSourceA = new DruidDataSource();
dataSourceA.setUrl("jdbc:mock:xx_A");
dataSourceA.setFilters("stat");
dataSourceA.setUseGloalDataSourceStat(true);
dataSourceA.setUseGlobalDataSourceStat(true);
dataSourceB = new DruidDataSource();
dataSourceB.setUrl("jdbc:mock:xx_A");
dataSourceB.setFilters("stat");
dataSourceB.setUseGloalDataSourceStat(true);
dataSourceB.setUseGlobalDataSourceStat(true);
}
protected void tearDown() throws Exception {
@@ -25,12 +25,12 @@ public class GlobalStatTest1 extends TestCase {
dataSourceA = new DruidDataSource();
dataSourceA.setUrl("jdbc:mock:xx_A");
dataSourceA.setFilters("stat");
dataSourceA.setUseGloalDataSourceStat(true);
dataSourceA.setUseGlobalDataSourceStat(true);
dataSourceB = new DruidDataSource();
dataSourceB.setUrl("jdbc:mock:xx_A");
dataSourceB.setFilters("stat");
dataSourceB.setUseGloalDataSourceStat(true);
dataSourceB.setUseGlobalDataSourceStat(true);
}
protected void tearDown() throws Exception {
@@ -4,7 +4,7 @@ import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlBooleanExpr;
import com.alibaba.druid.sql.ast.expr.SQLBooleanExpr;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlExprParser;
import com.alibaba.druid.sql.parser.SQLExprParser;
@@ -13,18 +13,18 @@ public class EqualTest_boolean extends TestCase {
public void test_exits() throws Exception {
String sql = "true";
String sql_c = "false";
MySqlBooleanExpr exprA, exprB, exprC;
SQLBooleanExpr exprA, exprB, exprC;
{
SQLExprParser parser = new MySqlExprParser(sql);
exprA = (MySqlBooleanExpr) parser.expr();
exprA = (SQLBooleanExpr) parser.expr();
}
{
SQLExprParser parser = new MySqlExprParser(sql);
exprB = (MySqlBooleanExpr) parser.expr();
exprB = (SQLBooleanExpr) parser.expr();
}
{
SQLExprParser parser = new MySqlExprParser(sql_c);
exprC = (MySqlBooleanExpr) parser.expr();
exprC = (SQLBooleanExpr) parser.expr();
}
Assert.assertEquals(exprA, exprB);
Assert.assertNotEquals(exprA, exprC);
@@ -32,7 +32,7 @@ public class EqualTest_boolean extends TestCase {
Assert.assertFalse(exprA.equals(new Object()));
Assert.assertEquals(exprA.hashCode(), exprB.hashCode());
Assert.assertEquals(new MySqlBooleanExpr(), new MySqlBooleanExpr());
Assert.assertEquals(new MySqlBooleanExpr().hashCode(), new MySqlBooleanExpr().hashCode());
Assert.assertEquals(new SQLBooleanExpr(), new SQLBooleanExpr());
Assert.assertEquals(new SQLBooleanExpr().hashCode(), new SQLBooleanExpr().hashCode());
}
}
@@ -29,6 +29,13 @@ public class SQLEvalVisitorUtilsTest extends TestCase {
Assert.assertEquals(-1, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? - ?", Arrays.<Object> asList(2, 3)));
Assert.assertEquals(2, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? / ?", Arrays.<Object> asList(6, 3)));
}
public void test_evalExpr_3() throws Exception {
Assert.assertEquals(5.0f, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? + ?", "2.0", 3));
Assert.assertEquals(6.0f, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? * ?", "2.0", 3));
Assert.assertEquals(-1.0f, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? - ?", "2.0", 3));
Assert.assertEquals(2.0f, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? / ?", "6.0", 3));
}
public void test_add() throws Exception {
Assert.assertEquals(5, SQLEvalVisitorUtils.evalExpr(JdbcUtils.MYSQL, "? + ?", Arrays.<Object> asList(2, 3)));
@@ -2,6 +2,7 @@ package com.alibaba.druid.bvt.sql.mysql;
import junit.framework.TestCase;
import com.alibaba.druid.sql.ast.expr.SQLBooleanExpr;
import com.alibaba.druid.sql.dialect.mysql.ast.MySqlForceIndexHint;
import com.alibaba.druid.sql.dialect.mysql.ast.MySqlIgnoreIndexHint;
import com.alibaba.druid.sql.dialect.mysql.ast.MySqlKey;
@@ -9,7 +10,6 @@ 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;
import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlCharExpr;
import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlIntervalExpr;
import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlOutFileExpr;
@@ -101,7 +101,7 @@ public class MySqlASTVisitorAdapterTest extends TestCase {
public void test_adapter() throws Exception {
MySqlASTVisitorAdapter adapter = new MySqlASTVisitorAdapter();
new MySqlBooleanExpr().accept(adapter);
new SQLBooleanExpr().accept(adapter);
new Limit().accept(adapter);
new MySqlTableIndex().accept(adapter);
new MySqlKey().accept(adapter);
@@ -53,4 +53,57 @@ public class MySqlCreateTableTest extends MysqlTest {
// Assert.assertTrue(visitor.getColumns().contains(new Column("mytable", "last_name")));
}
public void test_1() throws Exception {
String sql = "CREATE TABLE `ins_ebay_auth` ("
+ " `auth_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键id',"
+ " `usr_id` int(10) NOT NULL COMMENT '外键,用户表',"
+ " `status` char(1) COLLATE utf8_bin NOT NULL COMMENT '状态 0.有效?1.无效',"
+ " `ebay_token` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'eBay授权码',"
+ " `ebay_name` varchar(50) COLLATE utf8_bin NOT NULL COMMENT 'eBay唯一名',"
+ " `create_time` datetime NOT NULL COMMENT '授权时间', "
+ " `invalid_time` datetime NOT NULL COMMENT '授权失效时间',"
+ " PRIMARY KEY (`auth_id`)"
+ " ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='INS_EBAY_AUTH'";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> 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(1, visitor.getTables().size());
Assert.assertEquals(7, visitor.getColumns().size());
Assert.assertEquals(0, visitor.getConditions().size());
}
public void test_2() throws Exception {
String sql = "create table t2 as select * from t1";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> 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());
}
}
@@ -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.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
public class MySqlInsertTest_9 extends MysqlTest {
public void test_0() throws Exception {
String sql = "insert into sequence values('seq_wlb_order_log',268234128+10000000,now());";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
SQLInsertStatement insertStmt = (SQLInsertStatement) stmt;
Assert.assertEquals(3, insertStmt.getValues().getValues().size());
Assert.assertEquals(0, insertStmt.getColumns().size());
Assert.assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
Assert.assertEquals("INSERT INTO sequence"
+ "\nVALUES ('seq_wlb_order_log', 268234128 + 10000000, now())", SQLUtils.toMySqlString(insertStmt));
}
}
@@ -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 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 MySqlSelectTest_18 extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT host.id as id, host.item_id as itemId, host.node_id as nodeId, host.node_type as nodeType, host.begin_time as beginTime, host.end_time as endTime, host.gmt_create as gmtCreate, host.gmt_modify as gmtModify, host.reason as reason, host.creator_id as creatorId, host.modifier_id as modifierId, user.name as creator, user.name as modifier, user.nick_name as nickName FROM notice_close_node host left join sys_user user on user.id = host.modifier_id";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> 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(14, visitor.getColumns().size());
Assert.assertEquals(2, visitor.getConditions().size());
}
}
@@ -88,6 +88,15 @@ public class SQLSelectTest extends TestCase {
output(stmtList);
}
public void test_select_7() throws Exception {
String sql = "select * from ((select * from test1) UNION (select * from test2) UNION (select * from test3)) where t1='温高铁';";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
output(stmtList);
}
private void output(List<SQLStatement> stmtList) {
for (SQLStatement stmt : stmtList) {
@@ -18,4 +18,15 @@ public class SQLUtilsTest extends TestCase {
"\nFROM t" + //
"\nWHERE id = 'abc'", formattedSql);
}
public void test_format_1() throws Exception {
String sql = "select * from t where tname LIKE \"%\"'温'\"%\"";
String formattedSql = SQLUtils.formatMySql(sql);
Assert.assertEquals("SELECT *\nFROM t\nWHERE tname LIKE CONCAT('%', '温', '%')", formattedSql);
}
public void test_format_2() throws Exception {
String sql = "begin\n" + " if (a=10) then\n" + " null;\n" + " else\n" + " null;\n" + " end if;\n" + "end;";
System.out.println(SQLUtils.formatOracle(sql));
}
}
@@ -0,0 +1,71 @@
/*
* 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.visitor;
import junit.framework.TestCase;
import com.alibaba.druid.sql.visitor.ParameterizedOutputVisitorUtils;
import com.alibaba.druid.util.JdbcConstants;
public class MySqlParameterizedOutputVisitorTest extends TestCase {
public void test_0() throws Exception {
String sql = "SELECT appsheetserialno FROM app_trans WHERE nodeid = _gbk '619' "
+ " AND alino = _gbk '2013110900031031001700thfund00163619'"
+ " AND apserialno = _gbk '201405120002300002170013205458'";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
sql = "SELECT p.AppId, p.PlayerId, p.Nickname, p.CreateTime FROM acc_playeruser AS pu INNER JOIN acc_player AS p ON (pu.AppId = p.AppId AND pu.PlayerId = p.PlayerId) WHERE pu.UserId=x'881A58F6204D4E048F66E41596A66A57';";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
sql = "SET @now := NOW(); INSERT characters (uid, name, race, career, sex, creation) VALUES (4068548, '', 58, 0, 0, @now); SET @id := LAST_INSERT_ID(); INSERT characters_data (character_id, data, creation) VALUES (@id, ' \0\0\0\0\0\0\0\04068548\0\0\0:\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0<\0\0\0d\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0d\0\0\0__\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0', @now); SELECT @id; ";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
sql = "INSERT INTO qrtz_JOB_DETAILS (SCHED_NAME, JOB_NAME, JOB_GROUP, DESCRIPTION, JOB_CLASS_NAME, IS_DURABLE, IS_NONCONCURRENT, IS_UPDATE_DATA, REQUESTS_RECOVERY, JOB_DATA) VALUES('DefaultQuartzScheduler', 'taobao.item.recommend.delete_368815794_2_35391685928', 'tasks', null, 'cn.agooo.job.TasksJob', 0, 0, 0, 0, x'ACED0005737200156F72672E71756172747A2E4A6F62446174614D61709FB083E8BFA9B0CB020000787200266F72672E71756172747A2E7574696C732E537472696E674B65794469727479466C61674D61708208E8C3FBC55D280200015A0013616C6C6F77735472616E7369656E74446174617872001D6F72672E71756172747A2E7574696C732E4469727479466C61674D617013E62EAD28760ACE0200025A000564697274794C00036D617074000F4C6A6176612F7574696C2F4D61703B787001737200116A6176612E7574696C2E486173684D61700507DAC1C31660D103000246000A6C6F6164466163746F724900097468726573686F6C6478703F4000000000000C770800000010000000017400077461736B7349647372000E6A6176612E6C616E672E4C6F6E673B8BE490CC8F23DF0200014A000576616C7565787200106A6176612E6C616E672E4E756D62657286AC951D0B94E08B020000787000000000002063227800')";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
sql = "SELECT * FROM sync_contactsdata WHERE __id=x'2EEE5AE7CB0E4AF697D966AE8BF046B8'";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
sql = "select TID,POSTFEE,RECEIVERADDRESS from tradegroup003 where (0 = 650954981082695 or tid=650954981082695) And SELLERNICK='______________' And BUYERNICK='yingge7' and CREATED > date_sub(now(), interval 48 hour) and STATUS = 'WAIT_BUYER_PAY' and func_isNotFollowgroup003(tradegroup003.tid,'______________') = 0";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
sql = "SHOW COLUMNS FROM `pms_purchase_ops`/*20140512152820##%2Fbase.php%3Fshopid%3D%26module%3Dpms%26action%3DqualityItem%26op_id%3D756%26params%3Dcase%253Aupdate%252Ctable%253Aquality%252Corder_id%253A201405090006DL%252Creceive_no%253AQCI01201405090006DL%252Creceive_treat%253AALL_DONE%260.5652460628381133*/;";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, "mysql"));
System.out.println("-----------------------");
}
public void test_1() throws Exception {
String sql = "create or replace view vtmp_log_node_204180 as select `twf_log_group_user`.`uni_id` as `user_id`, `twf_log_group_user`.`control_group_type` from `twf_log_group_user` where `twf_log_group_user`.`subjob_id` = 204180";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL));
System.out.println("-----------------------");
sql = " create view V_CustomerGoodsNf as select a.*,b.GoodsNO,b.GoodsName,b.SpecName,c.CustomerName,c.NickName,c.Tel,c.Email, StatusExt = (CASE a.curStatus WHEN (0) THEN ('待通知') WHEN (1) THEN ('已通知') WHEN (2) THEN ('已过期') WHEN (3) THEN ('被取消')END) from G_Customer_GoodsNotify a left outer join V_GoodsListBySpec b on a.GoodsID=b.GoodsID and a.SpecID=b.SpecID left outer join G_Customer_CustomerList c on a.CustomerID=c.CustomerID";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.SQL_SERVER));
System.out.println("-----------------------");
sql = "CREATE view V_API_GoodsMatch as SELECT a.SpecName, a.GoodsNO, a.GoodsName, bMatch = CONVERT(bit, (CASE isnull(b.Numiid, '') WHEN ('') THEN (0) ELSE (1) END)), issys1 = (CASE isnull(b.issys, '') WHEN ('') THEN ('无') WHEN (0) THEN ('未同步') WHEN (1) THEN ('待同步') WHEN (2) THEN ('同步失败') WHEN (3) THEN ('同步成功') END), bFixNum = isnull(b.bFixNum, 0), bVirNum = isnull(b.bVirNum, 0), issys = isnull(b.issys, 0), FixNum = isnull(b.FixNum, 0), VirNumBase = isnull(b.VirNumBase, 0), VirNumInc = isnull(b.VirNumInc, 0), b.TBName, b.TBSku, b.UpdateTime, b.syscount, b.sysLog, c.ShopName, b.TBOuterID, b.SKUOuterID, d .FlagName, b.GoodsID, b.SpecID, b.Numiid, b.Skuid, b.BTBGoods, b.sysGoodsType, b.ID, bstop = CONVERT(bit, isnull(b.bstop, 0)), b.bSingletb, b.SingleNumPer, b.VirNumTop, isnull(b.goodstype, '0') AS goodstype, CASE b.SpecID WHEN - 2 THEN 1 ELSE 0 END AS pcbs FROM V_GoodsSpec a LEFT OUTER JOIN G_API_SysMatch b ON a.GoodsID = b.GoodsID AND CASE b.SpecID WHEN - 2 THEN 1 ELSE a.specid END = CASE b.SpecID WHEN - 2 THEN 1 ELSE b.SpecID END AND b.GoodsType = 0 LEFT OUTER JOIN G_Cfg_ShopList c ON b.ShopID = c.ShopID LEFT OUTER JOIN dbo.G_Cfg_RecordFlag d ON a.FlagID = d .FlagID UNION ALL SELECT '' AS SpecName, a.GoodsNO, a.GoodsName, bMatch = CONVERT(bit, (CASE isnull(b.Numiid, '') WHEN ('') THEN (0) ELSE (1) END)), issys1 = (CASE isnull(b.issys, '') WHEN ('') THEN ('无') WHEN (0) THEN ('未同步') WHEN (1) THEN ('待同步') WHEN (2) THEN ('同步失败') WHEN (3) THEN ('同步成功') END), bFixNum = isnull(b.bFixNum, 0), bVirNum = isnull(b.bVirNum, 0), issys = isnull(b.issys, 0), FixNum = isnull(b.FixNum, 0), VirNumBase = isnull(b.VirNumBase, 0), VirNumInc = isnull(b.VirNumInc, 0), b.TBName, b.TBSku, b.UpdateTime, b.syscount, b.sysLog, c.ShopName, b.TBOuterID, b.SKUOuterID, '' AS FlagName, b.GoodsID, b.SpecID, b.Numiid, b.Skuid, b.BTBGoods, b.sysGoodsType, b.ID, bstop = CONVERT(bit, isnull(b.bstop, 0)), b.bSingletb, b.SingleNumPer, b.VirNumTop, b.goodstype, 0 AS pcbs FROM g_goods_goodslistfit a LEFT OUTER JOIN g_api_sysma";
System.out.println(ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.SQL_SERVER));
System.out.println("-----------------------");
}
}
@@ -0,0 +1,62 @@
package com.alibaba.druid.bvt.sql.oracle;
import java.util.List;
import org.junit.Assert;
import com.alibaba.druid.sql.OracleTest;
import com.alibaba.druid.sql.SQLUtils;
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;
import com.alibaba.druid.util.JdbcConstants;
public class OracleListAggTest extends OracleTest {
public void test_0() throws Exception {
String sql = "SELECT prod_id, LISTAGG(cust_first_name||' '||cust_last_name, '; ') \n" //
+ " WITHIN GROUP (ORDER BY amount_sold DESC) cust_list\n" //
+ "FROM sales, customers\n" //
+ "WHERE sales.cust_id = customers.cust_id AND cust_gender = 'M' \n" //
+ " AND cust_credit_limit = 15000 AND prod_id BETWEEN 15 AND 18 \n" //
+ " AND channel_id = 2 AND time_id > '01-JAN-01'\n" //
+ "GROUP BY prod_id;";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
Assert.assertEquals(1, statementList.size());
Assert.assertEquals("SELECT prod_id, LISTAGG(cust_first_name || ' ' || cust_last_name, '; ') WITHIN GROUP (ORDER BY amount_sold DESC) AS cust_list" //
+ "\nFROM sales, customers"//
+ "\nWHERE sales.cust_id = customers.cust_id" //
+ "\n\tAND cust_gender = 'M'" //
+ "\n\tAND cust_credit_limit = 15000" //
+ "\n\tAND prod_id BETWEEN 15 AND 18" //
+ "\n\tAND channel_id = 2" //
+ "\n\tAND time_id > '01-JAN-01'" //
+ "\nGROUP BY prod_id",//
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.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());
Assert.assertEquals(2, visitor.getTables().size());
Assert.assertEquals(10, visitor.getColumns().size());
Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("sales")));
Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("customers")));
Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("sales", "cust_id")));
Assert.assertTrue(visitor.getColumns().contains(new TableStat.Column("customers", "cust_id")));
}
}