├── .gitignore ├── ChangeLog.md ├── README.md ├── doc ├── BestPratice.md └── GettingStarted.md ├── pom.xml └── src ├── main └── java │ └── com │ └── taobao │ └── tdhs │ ├── client │ ├── TDHSClient.java │ ├── TDHSClientImpl.java │ ├── common │ │ ├── IMySQLHandlerErrorCodes.java │ │ ├── MySQLHandlerErrorCodes.java │ │ └── TDHSCommon.java │ ├── easy │ │ ├── And.java │ │ ├── Insert.java │ │ ├── Query.java │ │ ├── Set.java │ │ ├── Where.java │ │ └── impl │ │ │ ├── AndImpl.java │ │ │ ├── InsertImpl.java │ │ │ ├── QueryImpl.java │ │ │ ├── SetImpl.java │ │ │ └── WhereImpl.java │ ├── exception │ │ ├── TDHSBatchException.java │ │ ├── TDHSEncodeException.java │ │ ├── TDHSException.java │ │ └── TDHSTimeoutException.java │ ├── net │ │ ├── AbstractTDHSNet.java │ │ ├── ConnectionPool.java │ │ ├── NetParameters.java │ │ ├── TDHSNet.java │ │ └── netty │ │ │ ├── TDHSClientHandler.java │ │ │ ├── TDHSDecoder.java │ │ │ ├── TDHSEncoder.java │ │ │ ├── TDHSNetForNetty.java │ │ │ ├── TDHSNetForNettyByBlocking.java │ │ │ └── TDHSPiplelineFactoty.java │ ├── packet │ │ └── BasePacket.java │ ├── protocol │ │ ├── TDHSProtocol.java │ │ ├── TDHSProtocolBinary.java │ │ └── TDHSProtocolBinaryV2.java │ ├── request │ │ ├── Filter.java │ │ ├── Filters.java │ │ ├── Get.java │ │ ├── Insert.java │ │ ├── Request.java │ │ ├── RequestWithCharset.java │ │ ├── TableInfo.java │ │ ├── Update.java │ │ └── ValueEntry.java │ ├── response │ │ ├── TDHSBlob.java │ │ ├── TDHSClob.java │ │ ├── TDHSMetaData.java │ │ ├── TDHSMySQLResultSetWrap.java │ │ ├── TDHSResponse.java │ │ ├── TDHSResponseEnum.java │ │ ├── TDHSResultSet.java │ │ └── TDHSResultSetMetaData.java │ ├── statement │ │ ├── BatchStatement.java │ │ ├── BatchStatementImpl.java │ │ ├── Statement.java │ │ └── StatementImpl.java │ └── util │ │ ├── ByteOrderUtil.java │ │ ├── ConvertUtil.java │ │ └── MysqlUtil.java │ └── jdbc │ ├── Driver.java │ ├── NonRegisteringDriver.java │ ├── SimplePooledTDHSDataSource.java │ ├── TDHSClientInstance.java │ ├── TDHSConnection.java │ ├── TDHSDatabaseMetaData.java │ ├── TDHSPreparedStatement.java │ ├── TDHSStatement.java │ ├── exception │ └── TDHSSQLException.java │ ├── sqlparser │ ├── Entry.java │ ├── HintStruct.java │ ├── OperationStruct.java │ ├── OrderByType.java │ ├── ParseSQL.java │ ├── SQLType.java │ └── TreeNode.java │ └── util │ ├── ConvertUtil.java │ └── StringUtil.java └── test ├── java ├── benchmark │ ├── GenerateData.groovy │ ├── PropUtil.groovy │ ├── RandomUtil.java │ ├── StressTest.groovy │ ├── TableUtil.groovy │ ├── batch │ │ └── tdhs_batch.groovy │ ├── get │ │ ├── hs_all_cache.groovy │ │ ├── hs_part_cache.groovy │ │ ├── sql_all_cache.groovy │ │ ├── sql_part_cache.groovy │ │ ├── tdhs_all_cache.groovy │ │ └── tdhs_part_cache.groovy │ ├── insert │ │ ├── hs_insert.groovy │ │ ├── hs_insert_one_table.groovy │ │ ├── sql_insert.groovy │ │ ├── sql_insert_one_table.groovy │ │ ├── tdhs_insert.groovy │ │ ├── tdhs_insert_one_table.groovy │ │ └── tdhs_insert_one_table_real.groovy │ └── update │ │ ├── hs_set.groovy │ │ ├── sql_add.groovy │ │ └── tdhs_add.groovy └── com │ └── taobao │ └── tdhs │ ├── client │ ├── response │ │ └── TDHSClobTest.java │ └── test │ │ ├── BatchTest.java │ │ ├── BetweenTest.java │ │ ├── CharsetTest.java │ │ ├── ClientCrudTest.java │ │ ├── ClientDeleteExceptionTest.java │ │ ├── ClientGetExceptionTest.java │ │ ├── ClientInsertExceptionTest.java │ │ ├── ClientTest.java │ │ ├── ClientUpdateExceptionTest.java │ │ ├── CountTest.java │ │ ├── DataTest.java │ │ ├── EasyDeleteTest.java │ │ ├── EasyInsertTest.java │ │ ├── EasyPackageTest.java │ │ ├── EasySelectTest.java │ │ ├── EasyUpdateTest.java │ │ └── TestBase.java │ └── jdbc │ ├── NonRegisteringDriverTest.java │ ├── SimplePooledTDHSDataSourceTest.java │ ├── sqlparser │ ├── HintStructTest.java │ └── ParseSQLTest.java │ ├── test │ ├── BlobInsertTest.java │ ├── BlobUpdateTest.java │ ├── CRUDTest.java │ ├── ComplexCRUDTest.java │ ├── ErrorTest.java │ ├── JDBCBatchTest.java │ ├── SimpleSelectJDBCTest.java │ ├── TestBase.java │ └── mybatis │ │ ├── CRUDMyBatisTest.java │ │ ├── ComplexCRUDMyBatisTest.java │ │ ├── MySQLDataSource.java │ │ ├── SimpleSelectMyBatisTest.java │ │ ├── TDHSDataSource.java │ │ ├── TestBase.java │ │ ├── mapper │ │ ├── OrderMapper.java │ │ ├── PersonMapper.java │ │ └── TestMapper.java │ │ └── vo │ │ ├── BaseVO.java │ │ ├── OrderVO.java │ │ ├── Person.java │ │ └── TestVO.java │ └── util │ └── StringUtilTest.java └── resources ├── benchmark.sql ├── db.sql ├── global.properties ├── log4j.properties └── order.csv /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | *.iml 3 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | 0.5(2013-03-01) 2 | --------------------------- 3 | * Support between 4 | 5 | 0.4.1(2012-10-11) 6 | --------------------------- 7 | * Support above TDH_Socket 0.4 8 | * Lazy create connection 9 | 10 | 0.3.2.5(2012-09-24) 11 | --------------------------- 12 | * Fix bug for enum cache 13 | * add TDHSMySQLResultSetWrap for MySQL ResultSet compatible. 14 | 15 | 0.3.2.3(2012-07-12) 16 | --------------------------- 17 | * JDBC hint support custom hash 18 | 19 | 0.3.2.2(2012-06-29) 20 | --------------------------- 21 | * Fix wrong word (Some API change name! -..-!) 22 | * Support Blob and Clob 23 | * Fix some sql parse bug! 24 | * Add SimplePooledTDHSDataSource 25 | * Support byte[] data with insert/update 26 | * Add MySQL handler error code description 27 | * Fix enum with unknown value 28 | 29 | 0.3.2.1(2012-06-08) 30 | --------------------------- 31 | * Fix some sql parse bug! 32 | 33 | 0.3.2(2012-05-16) 34 | --------------------------- 35 | * Init Version -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | TDHS-JAVA-CLIENT is a practical TDH_Socket(https://github.com/taobao/TDH_Socket) client for Java. 5 | TDH_Socket is a MySQL plugin developed by me. 6 | 7 | If you are using maven to build your project,you can try it by: 8 | 9 | 10 | com.taobao 11 | tdhs-java-client 12 | 0.4.1 13 | 14 | 15 | 16 | ----------------------------------- 17 | 18 | * Author: Kevin.Huang 19 | * Email: zephyrleaves@gmail.com 20 | * Date: 2012-5-3 -------------------------------------------------------------------------------- /doc/BestPratice.md: -------------------------------------------------------------------------------- 1 | BestPratice 2 | =========== 3 | 4 | * TDHSClient is thread-safe,so you must use it as SINGLETON object in your application. 5 | * Statement which create by ``TDHSClient.createStatement()`` or ``TDHSClient.createBatchStatement()`` is **not** thread-safe 6 | * You can set hashcode with ``TDHSClient.createStatement(hashcode)`` to assign the thread which server-side to run. -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/TDHSClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client; 13 | 14 | import com.taobao.tdhs.client.statement.BatchStatement; 15 | import com.taobao.tdhs.client.statement.Statement; 16 | 17 | import java.util.concurrent.TimeUnit; 18 | 19 | /** 20 | * The TDH_Socket Client interface 21 | * 22 | * @author 文通 23 | * @since 11-12-26 下午4:53 24 | */ 25 | public interface TDHSClient extends Statement { 26 | 27 | public static final String CONNECTION_NUMBER = "connectionNumber"; 28 | public static final String TIME_OUT = "timeOut"; 29 | public static final String NEED_RECONNECT = "needReconnect"; 30 | public static final String CONNECT_TIMEOUT = "connectTimeout"; 31 | public static final String CHARSET_NAME = "charsetName"; 32 | public static final String READ_CODE = "readCode"; 33 | public static final String WRITE_CODE = "writeCode"; 34 | public static final String LOWER_CASE_TABLE_NAMES = "lowerCaseTableNames"; 35 | public static final String VERSION = "version"; 36 | 37 | 38 | /** 39 | * Method getCharsetName returns the charsetName of this TDHSClient object. 40 | * like UTF8 for the string encoding when read and send 41 | * 42 | * @return the charsetName (type String) of this TDHSClient object. 43 | */ 44 | String getCharsetName(); 45 | 46 | /** 47 | * Method setCharsetName sets the charsetName of this TDHSClient object. 48 | * like UTF8 for the string encoding when read and send 49 | * 50 | * @param charsetName the charsetName of this TDHSClient object. 51 | */ 52 | void setCharsetName(String charsetName); 53 | 54 | /** 55 | * Method isLowerCaseTableNames returns the lowerCaseTableNames of this TDHSClient object. 56 | * 57 | * @return the lowerCaseTableNames (type boolean) of this TDHSClient object. 58 | */ 59 | boolean isLowerCaseTableNames(); 60 | 61 | /** 62 | * Method setLowerCaseTableNames sets the lowerCaseTableNames of this TDHSClient object. 63 | * 64 | * @param lowerCaseTableNames the lowerCaseTableNames of this TDHSClient object. 65 | */ 66 | void setLowerCaseTableNames(boolean lowerCaseTableNames); 67 | 68 | 69 | /** 70 | * wait for connected 71 | * 72 | * @param timeout of type long 73 | * @param unit of type TimeUnit 74 | * 75 | * @return boolean , true mean connected ,false mean not connected 76 | */ 77 | boolean awaitForConnected(long timeout, TimeUnit unit); 78 | 79 | /** 80 | * Method createStatement ... 81 | *

82 | * create a statement for one thread 83 | * 84 | * @return Statement 85 | */ 86 | Statement createStatement(); 87 | 88 | /** 89 | * Method createStatement ... 90 | *

91 | * create a statement for one thread 92 | * 93 | * @param hash of type int, use hash to make sure the request from this statement will 94 | * be run a assigned thread on the server-side 95 | * the thread is hash%thread_count 96 | * 97 | * @return Statement 98 | */ 99 | Statement createStatement(int hash); 100 | 101 | /** 102 | * create Batch Statement ... 103 | * 104 | * @return BatchStatement 105 | */ 106 | BatchStatement createBatchStatement(); 107 | 108 | /** 109 | * shutdown the client 110 | * stop the thread for io 111 | */ 112 | void shutdown(); 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/common/IMySQLHandlerErrorCodes.java: -------------------------------------------------------------------------------- 1 | package com.taobao.tdhs.client.common; 2 | 3 | /** 4 | * @author 文通 5 | * @since 12-7-9 下午1:20 6 | */ 7 | public interface IMySQLHandlerErrorCodes { 8 | String name(); 9 | 10 | int getCode(); 11 | 12 | String getDesc(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/common/TDHSCommon.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.common; 13 | 14 | import com.taobao.tdhs.client.protocol.TDHSProtocol; 15 | import com.taobao.tdhs.client.protocol.TDHSProtocolBinary; 16 | import com.taobao.tdhs.client.protocol.TDHSProtocolBinaryV2; 17 | import org.apache.commons.lang.StringUtils; 18 | 19 | /** 20 | * @author 文通 21 | * @since 11-11-1 上午10:51 22 | */ 23 | public final class TDHSCommon { 24 | 25 | public static final int REQUEST_MAX_FIELD_NUM = 256; 26 | 27 | public static final int REQUEST_MAX_KEY_NUM = 10; 28 | 29 | 30 | public enum ProtocolVersion { 31 | V1(new TDHSProtocolBinary()), V2(new TDHSProtocolBinaryV2()); 32 | /** 33 | * Enum ProtocolVersion ... 34 | * 35 | * @author zephyrleaves 36 | * Created on 12-10-11 37 | */ 38 | private TDHSProtocol tdhsProtocol; 39 | 40 | private ProtocolVersion(TDHSProtocol tdhsProtocol) { 41 | this.tdhsProtocol = tdhsProtocol; 42 | } 43 | 44 | public TDHSProtocol getTdhsProtocol() { 45 | return tdhsProtocol; 46 | } 47 | 48 | /** 49 | * Method fromProp ... 50 | * 51 | * @param prop of type String 52 | * 53 | * @return ProtocolVersion 54 | */ 55 | public static ProtocolVersion fromProp(String prop) { 56 | if (StringUtils.isNotBlank(prop) && (prop.equals("2") || prop.equalsIgnoreCase("v2"))) { 57 | return V2; 58 | } 59 | return V1; 60 | } 61 | } 62 | 63 | public enum RequestType { 64 | GET(0), COUNT(1), UPDATE(10), DELETE(11), INSERT(12), BATCH(20), SHAKE_HAND(0xFFFF); 65 | 66 | private int value; 67 | 68 | RequestType(int value) { 69 | this.value = value; 70 | } 71 | 72 | public int getValue() { 73 | return value; 74 | } 75 | 76 | } 77 | 78 | public enum FindFlag { 79 | TDHS_EQ(0), TDHS_GE(1), TDHS_LE(2), TDHS_GT(3), TDHS_LT(4), TDHS_IN(5), TDHS_DEQ(6), TDHS_BETWEEN(7); 80 | 81 | private int value; 82 | 83 | FindFlag(int value) { 84 | this.value = value; 85 | } 86 | 87 | public int getValue() { 88 | return value; 89 | } 90 | 91 | } 92 | 93 | public enum FilterFlag { 94 | TDHS_EQ(0), TDHS_GE(1), TDHS_LE(2), TDHS_GT(3), TDHS_LT(4), TDHS_NOT(5); 95 | 96 | private int value; 97 | 98 | FilterFlag(int value) { 99 | this.value = value; 100 | } 101 | 102 | public int getValue() { 103 | return value; 104 | } 105 | 106 | } 107 | 108 | public enum UpdateFlag { 109 | TDHS_UPDATE_SET(0), TDHS_UPDATE_ADD(1), TDHS_UPDATE_SUB(2), TDHS_UPDATE_NOW(3); 110 | 111 | private int value; 112 | 113 | UpdateFlag(int value) { 114 | this.value = value; 115 | } 116 | 117 | public int getValue() { 118 | return value; 119 | } 120 | 121 | } 122 | 123 | 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/And.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy; 13 | 14 | /** 15 | * @author 文通 16 | * @since 11-12-27 下午3:04 17 | */ 18 | public interface And { 19 | /** 20 | * assign field 21 | * 22 | * @param field of type String 23 | * 24 | * @return And 25 | */ 26 | And field(String field); 27 | 28 | /** 29 | * field equal value 30 | * 31 | * @param value of type String 32 | * 33 | * @return Query 34 | */ 35 | Query equal(String value); 36 | 37 | /** 38 | * field greaterEqual value 39 | * 40 | * @param value of type String 41 | * 42 | * @return Query 43 | */ 44 | Query greaterEqual(String value); 45 | 46 | /** 47 | * field lessEqual value 48 | * 49 | * @param value of type String 50 | * 51 | * @return Query 52 | */ 53 | Query lessEqual(String value); 54 | 55 | /** 56 | * field greaterThan value 57 | * 58 | * @param value of type String 59 | * 60 | * @return Query 61 | */ 62 | Query greaterThan(String value); 63 | 64 | /** 65 | * field lessThan value 66 | * 67 | * @param value of type String 68 | * 69 | * @return Query 70 | */ 71 | Query lessThan(String value); 72 | 73 | /** 74 | * field not value 75 | * 76 | * @param value of type String 77 | * 78 | * @return Query 79 | */ 80 | Query not(String value); 81 | 82 | /** 83 | * field is null 84 | * 85 | * @return Query 86 | */ 87 | Query isNull(); 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/Insert.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSException; 16 | import com.taobao.tdhs.client.response.TDHSResponse; 17 | import org.jetbrains.annotations.Nullable; 18 | 19 | /** 20 | * @author 文通 21 | * @since 11-12-27 下午3:22 22 | */ 23 | public interface Insert { 24 | 25 | /** 26 | * assign the db 27 | * 28 | * @param db of type String 29 | * 30 | * @return Insert 31 | */ 32 | Insert use(String db); 33 | 34 | /** 35 | * assign the table 36 | * 37 | * @param table of type String 38 | * 39 | * @return Insert 40 | */ 41 | Insert from(String table); 42 | 43 | /** 44 | * insert the value into field 45 | * 46 | * @param field of type String 47 | * @param value of type String 48 | * 49 | * @return Insert 50 | */ 51 | Insert value(String field, @Nullable String value); 52 | 53 | /** 54 | * insert the value into field 55 | * 56 | * @param field of type String 57 | * @param value of type long 58 | * 59 | * @return Insert 60 | */ 61 | Insert value(String field, long value); 62 | 63 | /** 64 | * insert the value into field 65 | * 66 | * @param field of type String 67 | * @param value of type int 68 | * 69 | * @return Insert 70 | */ 71 | Insert value(String field, int value); 72 | 73 | /** 74 | * insert the value into field 75 | * 76 | * @param field of type String 77 | * @param value of type short 78 | * 79 | * @return Insert 80 | */ 81 | Insert value(String field, short value); 82 | 83 | /** 84 | * insert the value into field 85 | * 86 | * @param field of type String 87 | * @param value of type char 88 | * 89 | * @return Insert 90 | */ 91 | Insert value(String field, char value); 92 | 93 | /** 94 | * insert the value into field 95 | * 96 | * @param field of type String 97 | * @param value of type byte 98 | * 99 | * @return Insert 100 | */ 101 | Insert value(String field, byte value); 102 | 103 | /** 104 | * insert the value into field 105 | * 106 | * @param field of type String 107 | * @param value of type byte[] 108 | * 109 | * @return Insert 110 | */ 111 | Insert value(String field, byte[] value); 112 | 113 | /** 114 | * insert now() into field 115 | * 116 | * @param field of type String 117 | * 118 | * @return Insert 119 | */ 120 | Insert valueSetNow(String field); 121 | 122 | /** 123 | * insert null into field 124 | * 125 | * @param field of type String 126 | * 127 | * @return Insert 128 | */ 129 | Insert valueSetNull(String field); 130 | 131 | /** 132 | * insert the value into field 133 | * 134 | * @param field of type String 135 | * @param flag of type UpdateFlag 136 | * @param value of type String 137 | * 138 | * @return Insert 139 | */ 140 | Insert value(String field, TDHSCommon.UpdateFlag flag, String value); 141 | 142 | /** 143 | * execute insert operation 144 | * 145 | * @return TDHSResponse 146 | * 147 | * @throws TDHSException when 148 | */ 149 | TDHSResponse insert() throws TDHSException; 150 | 151 | /** 152 | * execute insert operation with charsetName 153 | * 154 | * @param charsetName of type String 155 | * 156 | * @return TDHSResponse 157 | * 158 | * @throws TDHSException when 159 | */ 160 | TDHSResponse insert(String charsetName) throws TDHSException; 161 | 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/Query.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy; 13 | 14 | import com.taobao.tdhs.client.exception.TDHSException; 15 | import com.taobao.tdhs.client.response.TDHSResponse; 16 | 17 | /** 18 | * @author 文通 19 | * @since 11-12-27 下午2:45 20 | */ 21 | public interface Query { 22 | 23 | /** 24 | * assign the db 25 | * 26 | * @param db of type String 27 | * 28 | * @return Query 29 | */ 30 | Query use(String db); 31 | 32 | /** 33 | * assign the table. 34 | * 35 | * @param table of type String 36 | * 37 | * @return Query 38 | */ 39 | Query from(String table); 40 | 41 | /** 42 | * select the fields 43 | * 44 | * @param fields of type String... 45 | * 46 | * @return Query 47 | */ 48 | Query select(String... fields); 49 | 50 | /** 51 | * start where condition for index 52 | * 53 | * @return Where 54 | */ 55 | Where where(); 56 | 57 | /** 58 | * start and condition for filter 59 | * 60 | * @return And 61 | */ 62 | And and(); 63 | 64 | /** 65 | * start Set for update values 66 | * 67 | * @return Set 68 | */ 69 | Set set(); 70 | 71 | /** 72 | * set start and limit 73 | * 74 | * @param start of type int 75 | * @param limit of type int 76 | * 77 | * @return Query 78 | */ 79 | Query limit(int start, int limit); 80 | 81 | /** 82 | * execute get operation 83 | * 84 | * @return TDHSResponse 85 | * 86 | * @throws TDHSException when 87 | */ 88 | TDHSResponse get() throws TDHSException; 89 | 90 | /** 91 | * execute delete operation 92 | * 93 | * @return TDHSResponse 94 | * 95 | * @throws TDHSException when 96 | */ 97 | TDHSResponse delete() throws TDHSException; 98 | 99 | /** 100 | * execute count operation 101 | * 102 | * @return TDHSResponse 103 | * 104 | * @throws TDHSException when 105 | */ 106 | TDHSResponse count() throws TDHSException; 107 | 108 | /** 109 | * execute update operation 110 | * 111 | * @return TDHSResponse 112 | * 113 | * @throws TDHSException when 114 | */ 115 | TDHSResponse update() throws TDHSException; 116 | 117 | /** 118 | * execute get operation with charsetName 119 | * 120 | * @param charsetName of type String 121 | * 122 | * @return TDHSResponse 123 | * 124 | * @throws TDHSException when 125 | */ 126 | TDHSResponse get(String charsetName) throws TDHSException; 127 | 128 | /** 129 | * execute count operation with charsetName 130 | * 131 | * @param charsetName of type String 132 | * 133 | * @return TDHSResponse 134 | * 135 | * @throws TDHSException when 136 | */ 137 | TDHSResponse count(String charsetName) throws TDHSException; 138 | 139 | /** 140 | * execute delete operation with charsetName 141 | * 142 | * @param charsetName of type String 143 | * 144 | * @return TDHSResponse 145 | * 146 | * @throws TDHSException when 147 | */ 148 | TDHSResponse delete(String charsetName) throws TDHSException; 149 | 150 | /** 151 | * execute update operation with charsetName 152 | * 153 | * @param charsetName of type String 154 | * 155 | * @return TDHSResponse 156 | * 157 | * @throws TDHSException when 158 | */ 159 | TDHSResponse update(String charsetName) throws TDHSException; 160 | } 161 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/Set.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy; 13 | 14 | import org.jetbrains.annotations.Nullable; 15 | 16 | /** 17 | * Set Value when update 18 | * 19 | * @author 文通 20 | * @since 11-12-27 下午3:15 21 | */ 22 | public interface Set { 23 | 24 | /** 25 | * set field which need be update 26 | * 27 | * @param field of type String 28 | * 29 | * @return Set 30 | */ 31 | Set field(String field); 32 | 33 | /** 34 | * add some number to field 35 | * 36 | * @param value of type long 37 | * 38 | * @return Query 39 | */ 40 | Query add(long value); 41 | 42 | /** 43 | * sub some number to field 44 | * 45 | * @param value of type long 46 | * 47 | * @return Query 48 | */ 49 | Query sub(long value); 50 | 51 | /** 52 | * set some value to field 53 | * 54 | * @param value of type String 55 | * 56 | * @return Query 57 | */ 58 | Query set(@Nullable String value); 59 | 60 | /** 61 | * set some number to field 62 | * 63 | * @param value of type long 64 | * 65 | * @return Query 66 | */ 67 | Query set(long value); 68 | 69 | /** 70 | * set some number to field 71 | * 72 | * @param value of type int 73 | * 74 | * @return Query 75 | */ 76 | Query set(int value); 77 | 78 | /** 79 | * set some number to field 80 | * 81 | * @param value of type short 82 | * 83 | * @return Query 84 | */ 85 | Query set(short value); 86 | 87 | /** 88 | * set some number to field 89 | * 90 | * @param value of type char 91 | * 92 | * @return Query 93 | */ 94 | Query set(char value); 95 | 96 | /** 97 | * Method set ... 98 | * 99 | * @param value of type byte 100 | * 101 | * @return Query 102 | */ 103 | Query set(byte value); 104 | 105 | /** 106 | * Method set ... 107 | * 108 | * @param value of type byte[] 109 | * 110 | * @return Query 111 | */ 112 | Query set(byte[] value); 113 | 114 | /** 115 | * set now() to field 116 | * 117 | * @return Query 118 | */ 119 | Query setNow(); 120 | 121 | /** 122 | * set null to field 123 | * 124 | * @return Query 125 | */ 126 | Query setNull(); 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/Where.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * Where condition 18 | * 19 | * @author 文通 20 | * @since 11-12-27 下午2:49 21 | */ 22 | public interface Where { 23 | 24 | /** 25 | * assign the fields in the index 26 | * 27 | * @param field of type String... 28 | * 29 | * @return Where 30 | */ 31 | Where fields(String... field); 32 | 33 | /** 34 | * assign the ndex 35 | * 36 | * @param index of type String 37 | * 38 | * @return Where 39 | */ 40 | Where index(String index); 41 | 42 | /** 43 | * Method equal ... 44 | * 45 | * @param key of type String... 46 | * 47 | * @return Query 48 | */ 49 | Query equal(String... key); 50 | 51 | /** 52 | * Method descEqual ... 53 | * 54 | * @param key of type String... 55 | * 56 | * @return Query 57 | */ 58 | Query descEqual(String... key); 59 | 60 | /** 61 | * Method greaterEqual ... 62 | * 63 | * @param key of type String... 64 | * 65 | * @return Query 66 | */ 67 | Query greaterEqual(String... key); 68 | 69 | /** 70 | * Method lessEqual ... 71 | * 72 | * @param key of type String... 73 | * 74 | * @return Query 75 | */ 76 | Query lessEqual(String... key); 77 | 78 | /** 79 | * Method greaterThan ... 80 | * 81 | * @param key of type String... 82 | * 83 | * @return Query 84 | */ 85 | Query greaterThan(String... key); 86 | 87 | /** 88 | * Method lessThan ... 89 | * 90 | * @param key of type String... 91 | * 92 | * @return Query 93 | */ 94 | Query lessThan(String... key); 95 | 96 | /** 97 | * Method in ... 98 | * 99 | * @param keys of type String[]... 100 | * 101 | * @return Query 102 | */ 103 | Query in(String[]... keys); 104 | 105 | /** 106 | * Method in ... 107 | * 108 | * @param keys of type List... 109 | * 110 | * @return Query 111 | */ 112 | Query in(List... keys); 113 | 114 | /** 115 | * Between query. 116 | * 117 | * @param beforeKey the before key 118 | * @param afterKey the after key 119 | * 120 | * @return the query 121 | */ 122 | Query between(String[] beforeKey, String[] afterKey); 123 | 124 | /** 125 | * Between query. 126 | * 127 | * @param beforeKey the before key 128 | * @param afterKey the after key 129 | * 130 | * @return the query 131 | */ 132 | Query between(List beforeKey, List afterKey); 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/impl/AndImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy.impl; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.easy.And; 16 | import com.taobao.tdhs.client.easy.Query; 17 | import com.taobao.tdhs.client.request.Get; 18 | import org.jetbrains.annotations.Nullable; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-12-27 下午3:55 23 | */ 24 | public class AndImpl implements And { 25 | 26 | private String field = null; 27 | 28 | private final Get get; 29 | 30 | private final Query query; 31 | 32 | public AndImpl(Get get, Query query) { 33 | this.query = query; 34 | this.get = get; 35 | } 36 | 37 | public And field(String field) { 38 | if (this.field != null) { 39 | throw new IllegalArgumentException("can't field twice!"); 40 | } 41 | this.field = field; 42 | return this; 43 | } 44 | 45 | private Query filter(@Nullable String value, TDHSCommon.FilterFlag filterFlag) { 46 | if (this.field == null) { 47 | throw new IllegalArgumentException("no field!"); 48 | } 49 | this.get.addFilter(field, filterFlag, value); 50 | this.field = null; 51 | return query; 52 | } 53 | 54 | public Query equal(String value) { 55 | return filter(value, TDHSCommon.FilterFlag.TDHS_EQ); 56 | } 57 | 58 | 59 | public Query greaterEqual(String value) { 60 | return filter(value, TDHSCommon.FilterFlag.TDHS_GE); 61 | } 62 | 63 | public Query lessEqual(String value) { 64 | return filter(value, TDHSCommon.FilterFlag.TDHS_LE); 65 | } 66 | 67 | public Query greaterThan(String value) { 68 | return filter(value, TDHSCommon.FilterFlag.TDHS_GT); 69 | } 70 | 71 | public Query lessThan(String value) { 72 | return filter(value, TDHSCommon.FilterFlag.TDHS_LT); 73 | } 74 | 75 | public Query not(String value) { 76 | return filter(value, TDHSCommon.FilterFlag.TDHS_NOT); 77 | } 78 | 79 | public Query isNull() { 80 | return filter(null, TDHSCommon.FilterFlag.TDHS_EQ); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/impl/QueryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy.impl; 13 | 14 | import com.taobao.tdhs.client.easy.And; 15 | import com.taobao.tdhs.client.easy.Query; 16 | import com.taobao.tdhs.client.easy.Set; 17 | import com.taobao.tdhs.client.easy.Where; 18 | import com.taobao.tdhs.client.exception.TDHSException; 19 | import com.taobao.tdhs.client.request.Get; 20 | import com.taobao.tdhs.client.request.TableInfo; 21 | import com.taobao.tdhs.client.request.Update; 22 | import com.taobao.tdhs.client.response.TDHSResponse; 23 | import com.taobao.tdhs.client.statement.Statement; 24 | 25 | import java.util.Collections; 26 | 27 | /** 28 | * @author 文通 29 | * @since 11-12-27 下午3:27 30 | */ 31 | public class QueryImpl implements Query { 32 | private final Get get; 33 | 34 | private final Update update; 35 | 36 | private final Where where; 37 | 38 | private final And and; 39 | 40 | private final Set set; 41 | 42 | private final Statement statement; 43 | 44 | public QueryImpl(Statement statement) { 45 | this.statement = statement; 46 | this.get = new Get(new TableInfo()); 47 | this.update = new Update(this.get); 48 | this.where = new WhereImpl(get, this); 49 | this.and = new AndImpl(get, this); 50 | this.set = new SetImpl(get, update, this); 51 | } 52 | 53 | public Query use(String db) { 54 | get.getTableInfo().setDb(db); 55 | return this; 56 | } 57 | 58 | public Query from(String table) { 59 | get.getTableInfo().setTable(table); 60 | return this; 61 | } 62 | 63 | public Query select(String... fields) { 64 | if (fields != null) { 65 | Collections.addAll(get.getTableInfo().getFields(), fields); 66 | } 67 | return this; 68 | } 69 | 70 | public Where where() { 71 | return this.where; 72 | } 73 | 74 | public And and() { 75 | return this.and; 76 | } 77 | 78 | public Set set() { 79 | return this.set; 80 | } 81 | 82 | public Query limit(int start, int limit) { 83 | get.setStart(start); 84 | get.setLimit(limit); 85 | return this; 86 | } 87 | 88 | public TDHSResponse get() throws TDHSException { 89 | return statement.get(get); 90 | } 91 | 92 | public TDHSResponse delete() throws TDHSException { 93 | return statement.delete(get); 94 | } 95 | 96 | public TDHSResponse count() throws TDHSException { 97 | return statement.count(get); 98 | } 99 | 100 | public TDHSResponse update() throws TDHSException { 101 | return statement.update(update); 102 | } 103 | 104 | public TDHSResponse get(String charsetName) throws TDHSException { 105 | get.setCharsetName(charsetName); 106 | return statement.get(get); 107 | } 108 | 109 | public TDHSResponse count(String charsetName) throws TDHSException { 110 | get.setCharsetName(charsetName); 111 | return statement.count(get); 112 | } 113 | 114 | public TDHSResponse delete(String charsetName) throws TDHSException { 115 | get.setCharsetName(charsetName); 116 | return statement.delete(get); 117 | } 118 | 119 | public TDHSResponse update(String charsetName) throws TDHSException { 120 | update.setCharsetName(charsetName); 121 | return statement.update(update); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/easy/impl/WhereImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.easy.impl; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.easy.Query; 16 | import com.taobao.tdhs.client.easy.Where; 17 | import com.taobao.tdhs.client.request.Get; 18 | import org.apache.commons.lang.StringUtils; 19 | 20 | import java.util.List; 21 | 22 | /** 23 | * @author 文通 24 | * @since 11-12-27 下午3:48 25 | */ 26 | public class WhereImpl implements Where { 27 | 28 | private final Get get; 29 | 30 | private final Query query; 31 | 32 | public WhereImpl(Get get, Query query) { 33 | this.get = get; 34 | this.query = query; 35 | } 36 | 37 | public Where fields(String... field) { 38 | StringBuilder sb = new StringBuilder("|"); 39 | for (String f : field) { 40 | if (StringUtils.isNotBlank((f))) { 41 | sb.append(f); 42 | sb.append('|'); 43 | } 44 | } 45 | get.getTableInfo().setIndex(sb.toString()); 46 | return this; 47 | } 48 | 49 | public Where index(String index) { 50 | get.getTableInfo().setIndex(index); 51 | return this; 52 | } 53 | 54 | public Query equal(String... key) { 55 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_EQ); 56 | get.setKey(key); 57 | return query; 58 | } 59 | 60 | public Query descEqual(String... key) { 61 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_DEQ); 62 | get.setKey(key); 63 | return query; 64 | } 65 | 66 | public Query greaterEqual(String... key) { 67 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_GE); 68 | get.setKey(key); 69 | return query; 70 | } 71 | 72 | public Query lessEqual(String... key) { 73 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_LE); 74 | get.setKey(key); 75 | return query; 76 | } 77 | 78 | public Query greaterThan(String... key) { 79 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_GT); 80 | get.setKey(key); 81 | return query; 82 | } 83 | 84 | public Query lessThan(String... key) { 85 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_LT); 86 | get.setKey(key); 87 | return query; 88 | } 89 | 90 | public Query in(String[]... keys) { 91 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_IN); 92 | get.setKey(keys); 93 | return query; 94 | } 95 | 96 | public Query in(List... keys) { 97 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_IN); 98 | get.setKey(keys); 99 | return query; 100 | } 101 | 102 | public Query between(String[] beforeKey, String[] afterKey) { 103 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_BETWEEN); 104 | get.setKey(new String[][]{beforeKey, afterKey}); 105 | return query; 106 | } 107 | 108 | public Query between(List beforeKey, List afterKey) { 109 | get.setFindFlag(TDHSCommon.FindFlag.TDHS_BETWEEN); 110 | get.setKey(new String[][]{beforeKey.toArray(new String[beforeKey.size()]), 111 | afterKey.toArray(new String[afterKey.size()])}); 112 | return query; 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/exception/TDHSBatchException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.exception; 13 | 14 | import com.taobao.tdhs.client.response.TDHSResponse; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-2-21 下午5:07 19 | */ 20 | public class TDHSBatchException extends TDHSException { 21 | private TDHSResponse response; 22 | 23 | public TDHSBatchException(TDHSResponse response) { 24 | this.response = response; 25 | } 26 | 27 | public TDHSResponse getResponse() { 28 | return response; 29 | } 30 | 31 | @Override public String toString() { 32 | return "TDHSBatchException{" + 33 | "response=" + response + 34 | '}'; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/exception/TDHSEncodeException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.exception; 13 | 14 | /** 15 | * @author 文通 16 | * @since 11-12-2 下午1:28 17 | */ 18 | public class TDHSEncodeException extends TDHSException { 19 | 20 | private static final long serialVersionUID = 4248787784350507825L; 21 | 22 | public TDHSEncodeException() { 23 | } 24 | 25 | public TDHSEncodeException(String message) { 26 | super(message); 27 | } 28 | 29 | public TDHSEncodeException(String message, Throwable cause) { 30 | super(message, cause); 31 | } 32 | 33 | public TDHSEncodeException(Throwable cause) { 34 | super(cause); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/exception/TDHSException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.exception; 13 | 14 | /** 15 | * @author 文通 16 | * @since 11-12-2 上午11:43 17 | */ 18 | public class TDHSException extends Exception { 19 | private static final long serialVersionUID = 450727724481426515L; 20 | 21 | public TDHSException() { 22 | } 23 | 24 | public TDHSException(String message) { 25 | super(message); 26 | } 27 | 28 | public TDHSException(String message, Throwable cause) { 29 | super(message, cause); 30 | } 31 | 32 | public TDHSException(Throwable cause) { 33 | super(cause); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/exception/TDHSTimeoutException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.exception; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-2-9 下午2:11 17 | */ 18 | public class TDHSTimeoutException extends TDHSException { 19 | private static final long serialVersionUID = -6031912630289588430L; 20 | 21 | public TDHSTimeoutException() { 22 | } 23 | 24 | public TDHSTimeoutException(String message) { 25 | super(message); 26 | } 27 | 28 | public TDHSTimeoutException(String message, Throwable cause) { 29 | super(message, cause); 30 | } 31 | 32 | public TDHSTimeoutException(Throwable cause) { 33 | super(cause); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/ConnectionPool.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net; 13 | 14 | import java.util.ArrayList; 15 | import java.util.Iterator; 16 | import java.util.List; 17 | import java.util.concurrent.locks.ReadWriteLock; 18 | import java.util.concurrent.locks.ReentrantReadWriteLock; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-12-26 下午3:55 23 | */ 24 | public class ConnectionPool { 25 | private List pool; 26 | 27 | private int index = 0; 28 | 29 | private ReadWriteLock rwLock = new ReentrantReadWriteLock(); 30 | 31 | public ConnectionPool(int num) { 32 | pool = new ArrayList(num); 33 | } 34 | 35 | public void add(T t, Handler handler) { 36 | rwLock.writeLock().lock(); 37 | try { 38 | if (handler != null) { 39 | handler.execute(t); 40 | } 41 | pool.add(t); 42 | } finally { 43 | rwLock.writeLock().unlock(); 44 | } 45 | } 46 | 47 | public boolean remove(T t) { 48 | rwLock.writeLock().lock(); 49 | try { 50 | return pool.remove(t); 51 | } finally { 52 | rwLock.writeLock().unlock(); 53 | } 54 | } 55 | 56 | /** 57 | * Method get ... 58 | * 59 | * @return Channel 60 | */ 61 | public T get() { 62 | rwLock.readLock().lock(); 63 | try { 64 | if (pool.isEmpty()) { 65 | return null; 66 | } 67 | int idx = Math.abs(index++ % pool.size()); 68 | return pool.get(idx); 69 | } finally { 70 | rwLock.readLock().unlock(); 71 | } 72 | } 73 | 74 | public void close(Handler handler) { 75 | rwLock.writeLock().lock(); 76 | try { 77 | Iterator iterator = pool.iterator(); 78 | while (iterator.hasNext()) { 79 | T t = iterator.next(); 80 | if (handler != null) { 81 | handler.execute(t); 82 | } 83 | iterator.remove(); 84 | } 85 | } finally { 86 | rwLock.writeLock().unlock(); 87 | } 88 | } 89 | 90 | public int size() { 91 | rwLock.readLock().lock(); 92 | try { 93 | return pool.size(); 94 | } finally { 95 | rwLock.readLock().unlock(); 96 | } 97 | } 98 | 99 | public boolean isEmpty() { 100 | rwLock.readLock().lock(); 101 | try { 102 | return pool.isEmpty(); 103 | } finally { 104 | rwLock.readLock().unlock(); 105 | } 106 | } 107 | 108 | 109 | public interface Handler { 110 | void execute(T t); 111 | } 112 | 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/NetParameters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net; 13 | 14 | import java.net.InetSocketAddress; 15 | 16 | /** 17 | * @author 文通 18 | * @since 11-12-26 下午4:24 19 | */ 20 | public class NetParameters { 21 | 22 | private InetSocketAddress address; 23 | 24 | private int connectionNumber; 25 | 26 | private boolean needReconnect; 27 | 28 | public InetSocketAddress getAddress() { 29 | return address; 30 | } 31 | 32 | public void setAddress(InetSocketAddress address) { 33 | this.address = address; 34 | } 35 | 36 | public int getConnectionNumber() { 37 | return connectionNumber; 38 | } 39 | 40 | public void setConnectionNumber(int connectionNumber) { 41 | this.connectionNumber = connectionNumber; 42 | } 43 | 44 | public boolean isNeedReconnect() { 45 | return needReconnect; 46 | } 47 | 48 | public void setNeedReconnect(boolean needReconnect) { 49 | this.needReconnect = needReconnect; 50 | } 51 | 52 | public void isVaild() { 53 | if (connectionNumber <= 0) { 54 | throw new IllegalArgumentException("connectionNumber can't be less then one!"); 55 | } 56 | if (address == null) { 57 | throw new IllegalArgumentException("address can't be null!"); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/TDHSNet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net; 13 | 14 | import com.taobao.tdhs.client.exception.TDHSException; 15 | import com.taobao.tdhs.client.packet.BasePacket; 16 | 17 | import java.util.Map; 18 | import java.util.concurrent.ArrayBlockingQueue; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | /** 22 | * @author 文通 23 | * @since 11-12-26 下午4:08 24 | */ 25 | public interface TDHSNet { 26 | 27 | /** 28 | * init the net parameters 29 | * 30 | * @param parameters of type NetParameters 31 | * @param shakeHandPacket of type BasePacket 32 | * @param responses of type Map> 33 | */ 34 | void initNet(NetParameters parameters, BasePacket shakeHandPacket, 35 | Map> responses); 36 | 37 | /** 38 | * await for connected ... 39 | * 40 | * @param timeout of type long 41 | * @param unit of type TimeUnit 42 | * 43 | * @return boolean 44 | */ 45 | boolean awaitForConnected(long timeout, TimeUnit unit); 46 | 47 | /** 48 | * write packet 49 | * 50 | * @param packet of type BasePacket 51 | * 52 | * @throws TDHSException when 53 | */ 54 | void write(BasePacket packet) throws TDHSException; 55 | 56 | /** 57 | * release resource when shutdown 58 | */ 59 | void release(); 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/netty/TDHSClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net.netty; 13 | 14 | import com.taobao.tdhs.client.net.ConnectionPool; 15 | import com.taobao.tdhs.client.packet.BasePacket; 16 | import org.jboss.netty.channel.*; 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | 20 | import java.util.Map; 21 | import java.util.concurrent.ArrayBlockingQueue; 22 | 23 | /** 24 | * @author 文通 25 | * @since 11-10-31 下午1:38 26 | */ 27 | public class TDHSClientHandler extends SimpleChannelUpstreamHandler { 28 | 29 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 30 | 31 | private BasePacket shakeHandeMessage; 32 | 33 | private Map> responses; 34 | 35 | private TDHSNetForNetty tdhsNetForNetty; 36 | 37 | public TDHSClientHandler(BasePacket shakeHandeMessage, 38 | Map> responses, TDHSNetForNetty tdhsNetForNetty) { 39 | this.shakeHandeMessage = shakeHandeMessage; 40 | this.responses = responses; 41 | this.tdhsNetForNetty = tdhsNetForNetty; 42 | } 43 | 44 | @Override 45 | public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 46 | //握手需要被连接池的写锁保护起来 47 | Channel channel = e.getChannel(); 48 | logger.info("channelConnected! channel id:" + channel.getId()); 49 | this.tdhsNetForNetty.addConnectedConnectionToPool(channel, new ConnectionPool.Handler() { 50 | public void execute(Channel channel) { 51 | channel.write(shakeHandeMessage); 52 | } 53 | }); 54 | } 55 | 56 | 57 | @Override 58 | public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 59 | Channel channel = e.getChannel(); 60 | Integer id = channel != null ? channel.getId() : -1; 61 | logger.info("channelDisconnected! channel id:" + id); 62 | tdhsNetForNetty.needCloseChannel(channel); 63 | } 64 | 65 | @Override 66 | public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { 67 | 68 | BasePacket packet = (BasePacket) e.getMessage(); 69 | ArrayBlockingQueue blockingQueue = responses.get(packet.getSeqId()); 70 | if (blockingQueue != null) { 71 | blockingQueue.put(packet); 72 | } 73 | } 74 | 75 | @Override 76 | public void exceptionCaught( 77 | ChannelHandlerContext ctx, ExceptionEvent e) { 78 | // Close the connection when an com.taobao.tdhs.client.exception is raised. 79 | Channel channel = e.getChannel(); 80 | Integer id = channel != null ? channel.getId() : -1; 81 | logger.error("exceptionCaught! channel id:" + id, e.getCause()); 82 | tdhsNetForNetty.needCloseChannel(channel); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/netty/TDHSDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net.netty; 13 | 14 | import com.taobao.tdhs.client.packet.BasePacket; 15 | import com.taobao.tdhs.client.response.TDHSResponseEnum; 16 | import com.taobao.tdhs.client.util.ConvertUtil; 17 | import org.jboss.netty.buffer.ChannelBuffer; 18 | import org.jboss.netty.channel.Channel; 19 | import org.jboss.netty.channel.ChannelHandlerContext; 20 | import org.jboss.netty.handler.codec.frame.FrameDecoder; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | /** 25 | * @author 文通 26 | * @since 11-10-31 下午2:50 27 | */ 28 | public class TDHSDecoder extends FrameDecoder { 29 | 30 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 31 | 32 | /** 33 | * Method decode ... 34 | * 35 | * @param ctx of type ChannelHandlerContext 36 | * @param channel of type Channel 37 | * @param buffer of type ChannelBuffer 38 | * 39 | * @return Object 40 | * 41 | * @throws Exception when 42 | */ 43 | @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) 44 | throws Exception { 45 | if (buffer.readableBytes() < BasePacket.TDH_SOCKET_HEADER_LENGTH) { 46 | return null; 47 | } 48 | 49 | //read length 50 | long dataLength = buffer.getUnsignedInt( 51 | buffer.readerIndex() + BasePacket.TDH_SOCKET_HEADER_LENGTH - BasePacket.TDH_SOCKET_SIZE_LENGTH); 52 | if (buffer.readableBytes() < BasePacket.TDH_SOCKET_HEADER_LENGTH + dataLength) { 53 | return null; 54 | } 55 | 56 | //read magic code 57 | //long magicCode = buffer.getUnsignedInt(buffer.readerIndex()); 58 | 59 | //read resp code 60 | long response = buffer.getUnsignedInt(buffer.readerIndex() + BasePacket.TDHS_MAGIC_CODE_SIZE); 61 | 62 | //read seq id 63 | long seqId = buffer.getUnsignedInt( 64 | buffer.readerIndex() + BasePacket.TDHS_MAGIC_CODE_SIZE + BasePacket.TDH_SOCKET_COMAND_LENGTH); 65 | 66 | long reserved = buffer.getUnsignedInt( 67 | buffer.readerIndex() + BasePacket.TDHS_MAGIC_CODE_SIZE + BasePacket.TDH_SOCKET_COMAND_LENGTH + 68 | BasePacket.TDH_SOCKET_ID_LENGTH); 69 | 70 | byte data[] = new byte[(int) dataLength]; 71 | int dataOffset = buffer.readerIndex() + BasePacket.TDH_SOCKET_HEADER_LENGTH; 72 | buffer.getBytes(dataOffset, data); 73 | buffer.readerIndex(dataOffset + (int) dataLength); 74 | 75 | if (logger.isDebugEnabled()) { 76 | StringBuilder sb = new StringBuilder("Response data hex:["); 77 | for (byte b : data) { 78 | sb.append(ConvertUtil.toHex(b)); 79 | sb.append(" "); 80 | } 81 | sb.append("]"); 82 | logger.debug(sb.toString()); 83 | } 84 | return new BasePacket(TDHSResponseEnum.ClientStatus.valueOf((int) response), seqId, reserved, data); 85 | } 86 | 87 | // private long getUnsignInt(final ChannelBuffer buffer, final int pos) { 88 | // long ret = 0; 89 | // byte data[] = new byte[4]; 90 | // buffer.getBytes(pos, data); 91 | // for (int i = 0; i < 4; i++) { 92 | // ret += ((data[i] & 0xFF) << (8 * i)); 93 | // } 94 | // return ret; 95 | // } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/netty/TDHSEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net.netty; 13 | 14 | import com.taobao.tdhs.client.packet.BasePacket; 15 | import org.jboss.netty.buffer.ChannelBuffers; 16 | import org.jboss.netty.channel.Channel; 17 | import org.jboss.netty.channel.ChannelHandlerContext; 18 | import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; 19 | 20 | import java.nio.ByteOrder; 21 | 22 | /** 23 | * @author 文通 24 | * @since 11-10-31 下午2:50 25 | */ 26 | public class TDHSEncoder extends OneToOneEncoder { 27 | @Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { 28 | if (!(msg instanceof BasePacket)) { 29 | return msg; 30 | } 31 | return ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, ((BasePacket) msg).toByteArray()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/netty/TDHSNetForNetty.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net.netty; 13 | 14 | import com.taobao.tdhs.client.exception.TDHSException; 15 | import com.taobao.tdhs.client.net.AbstractTDHSNet; 16 | import com.taobao.tdhs.client.net.ConnectionPool; 17 | import com.taobao.tdhs.client.net.NetParameters; 18 | import com.taobao.tdhs.client.net.TDHSNet; 19 | import com.taobao.tdhs.client.packet.BasePacket; 20 | import org.jboss.netty.bootstrap.ClientBootstrap; 21 | import org.jboss.netty.channel.Channel; 22 | import org.jboss.netty.channel.ChannelFuture; 23 | import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import java.net.InetSocketAddress; 28 | import java.util.Map; 29 | import java.util.concurrent.ArrayBlockingQueue; 30 | import java.util.concurrent.Executors; 31 | 32 | /** 33 | * @author 文通 34 | * @since 11-12-26 下午4:21 35 | */ 36 | public class TDHSNetForNetty extends AbstractTDHSNet implements TDHSNet { 37 | 38 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 39 | 40 | protected ClientBootstrap bootstrap; 41 | 42 | private transient boolean isReleasing = false; 43 | 44 | 45 | public void write(BasePacket packet) throws TDHSException { 46 | Channel channel = connectionPool.get(); 47 | if (channel == null) { 48 | throw new TDHSException("no available connection! maybe server has something error!"); 49 | } 50 | channel.write(packet); 51 | } 52 | 53 | protected void _initNet(NetParameters parameters, BasePacket shakeHandPacket, 54 | Map> responses) { 55 | parameters.isVaild(); 56 | bootstrap = new ClientBootstrap( 57 | new NioClientSocketChannelFactory( 58 | Executors.newCachedThreadPool(), 59 | Executors.newCachedThreadPool())); 60 | bootstrap.setPipelineFactory( 61 | new TDHSPiplelineFactoty(shakeHandPacket, responses, this)); 62 | } 63 | 64 | @Override 65 | protected Channel _connect(InetSocketAddress address) { 66 | ChannelFuture future = bootstrap.connect(address); 67 | Channel channel = future.awaitUninterruptibly().getChannel(); 68 | if (!future.isSuccess()) { 69 | logger.error("connect failed!", future.getCause()); 70 | return null; 71 | } else { 72 | return channel; 73 | } 74 | } 75 | 76 | protected void _release() { 77 | logger.info("client is Releasing now!"); 78 | isReleasing = true; 79 | connectionPool.close(new ConnectionPool.Handler() { 80 | public void execute(Channel channel) { 81 | channel.close(); 82 | } 83 | }); 84 | bootstrap.releaseExternalResources(); 85 | } 86 | 87 | public void needCloseChannel(Channel channel) { 88 | if (isReleasing) { 89 | //Releasing will close channel by self 90 | return; 91 | } 92 | boolean ret = connectionPool.remove(channel); 93 | if (channel.isOpen()) { 94 | channel.close(); 95 | } 96 | if (ret) { 97 | needConnectionNumber.incrementAndGet(); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/netty/TDHSNetForNettyByBlocking.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net.netty; 13 | 14 | import com.taobao.tdhs.client.net.NetParameters; 15 | import com.taobao.tdhs.client.net.TDHSNet; 16 | import com.taobao.tdhs.client.packet.BasePacket; 17 | import org.jboss.netty.bootstrap.ClientBootstrap; 18 | import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import java.util.Map; 23 | import java.util.concurrent.ArrayBlockingQueue; 24 | import java.util.concurrent.Executors; 25 | 26 | /** 27 | * 没有被使用哦~ 28 | * 29 | * @author 文通 30 | * @since 11-12-26 下午4:21 31 | */ 32 | public class TDHSNetForNettyByBlocking extends TDHSNetForNetty implements TDHSNet { 33 | 34 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 35 | 36 | protected void _initNet(NetParameters parameters, BasePacket shakeHandPacket, 37 | Map> responses) { 38 | parameters.isVaild(); 39 | bootstrap = new ClientBootstrap( 40 | new OioClientSocketChannelFactory( 41 | Executors.newCachedThreadPool())); 42 | bootstrap.setPipelineFactory( 43 | new TDHSPiplelineFactoty(shakeHandPacket, responses, this)); 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/net/netty/TDHSPiplelineFactoty.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.net.netty; 13 | 14 | import com.taobao.tdhs.client.packet.BasePacket; 15 | import org.jboss.netty.channel.ChannelPipeline; 16 | import org.jboss.netty.channel.ChannelPipelineFactory; 17 | import org.jboss.netty.channel.Channels; 18 | 19 | import java.util.Map; 20 | import java.util.concurrent.ArrayBlockingQueue; 21 | 22 | /** 23 | * @author 文通 24 | * @since 11-10-31 下午4:04 25 | */ 26 | public class TDHSPiplelineFactoty implements ChannelPipelineFactory { 27 | private BasePacket shakeHandeMessage; 28 | 29 | private Map> responses; 30 | 31 | private TDHSNetForNetty tdhsNetForNetty; 32 | 33 | public TDHSPiplelineFactoty(BasePacket shakeHandeMessage, 34 | Map> responses, TDHSNetForNetty tdhsNetForNetty) { 35 | this.responses = responses; 36 | this.shakeHandeMessage = shakeHandeMessage; 37 | this.tdhsNetForNetty = tdhsNetForNetty; 38 | } 39 | 40 | public ChannelPipeline getPipeline() throws Exception { 41 | ChannelPipeline pipeline = Channels.pipeline(); 42 | pipeline.addLast("decoder", new TDHSDecoder()); 43 | pipeline.addLast("encoder", new TDHSEncoder()); 44 | pipeline.addLast("handler", new TDHSClientHandler(shakeHandeMessage, responses, tdhsNetForNetty)); 45 | return pipeline; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/protocol/TDHSProtocol.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.protocol; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | import com.taobao.tdhs.client.packet.BasePacket; 17 | import com.taobao.tdhs.client.request.RequestWithCharset; 18 | import org.jetbrains.annotations.Nullable; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-12-2 上午11:09 23 | */ 24 | public interface TDHSProtocol { 25 | /** 26 | * get the shakeHand Packet 27 | * 28 | * @param timeOut 29 | * 30 | * @return BasePacket 31 | */ 32 | BasePacket shakeHandPacket(int timeOut, @Nullable String readCode, 33 | @Nullable String writeCode); 34 | 35 | /** 36 | * encode Request to packet data 37 | * 38 | * @param o of type Object ,request 39 | * 40 | * @return byte[] ,the packet data 41 | * 42 | * @throws com.taobao.tdhs.client.exception.TDHSEncodeException 43 | * 44 | */ 45 | byte[] encode(RequestWithCharset o) throws TDHSEncodeException; 46 | 47 | 48 | /** 49 | * Method getProtocolVersion returns the protocolVersion of this TDHSProtocol object. 50 | * 51 | * @return the protocolVersion (type ProtocolVersion) of this TDHSProtocol object. 52 | */ 53 | TDHSCommon.ProtocolVersion getProtocolVersion(); 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/protocol/TDHSProtocolBinaryV2.java: -------------------------------------------------------------------------------- 1 | package com.taobao.tdhs.client.protocol; 2 | 3 | import com.taobao.tdhs.client.common.TDHSCommon; 4 | import com.taobao.tdhs.client.packet.BasePacket; 5 | import org.jetbrains.annotations.Nullable; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.io.ByteArrayOutputStream; 10 | import java.io.IOException; 11 | 12 | /** 13 | * @author 文通 14 | * @since 12-10-11 下午1:04 15 | */ 16 | public class TDHSProtocolBinaryV2 extends TDHSProtocolBinary { 17 | 18 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 19 | 20 | /** 21 | * Method shakeHandPacket ... 22 | * 23 | * @param timeOut of type int 24 | * @param readCode of type String 25 | * @param writeCode of type String 26 | * 27 | * @return BasePacket 28 | */ 29 | @Override 30 | public BasePacket shakeHandPacket(int timeOut, @Nullable String readCode, 31 | @Nullable String writeCode) { 32 | 33 | try { 34 | ByteArrayOutputStream out = new ByteArrayOutputStream(12 + 2 + 200); 35 | out.write("TDHS".getBytes()); 36 | writeInt32ToStream(2, out);//版本号 37 | writeInt32ToStream(timeOut, out);//超时时间 38 | writeToStream(readCode, out, null); //read code 39 | writeToStream(writeCode, out, null);//write code 40 | return new BasePacket(TDHSCommon.RequestType.SHAKE_HAND, 0, out.toByteArray()); 41 | } catch (IOException e) { 42 | assert false; //不应该发生 43 | logger.error("shakeHandPacket failed!", e); 44 | return null; 45 | } 46 | } 47 | 48 | @Override 49 | public TDHSCommon.ProtocolVersion getProtocolVersion() { 50 | return TDHSCommon.ProtocolVersion.V2; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/Filter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | 17 | /** 18 | * @author 文通 19 | * @since 11-12-13 下午1:25 20 | */ 21 | 22 | public class Filter implements Request { 23 | private String _field; 24 | 25 | private int _____flag; 26 | 27 | private String _value; 28 | 29 | 30 | public Filter(String _field, TDHSCommon.FilterFlag flag, String value) { 31 | this._field = _field; 32 | this._____flag = flag.getValue(); 33 | this._value = value; 34 | } 35 | 36 | public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { 37 | //nothing 38 | } 39 | 40 | @Override public String toString() { 41 | return "Filter{" + 42 | "field='" + _field + '\'' + 43 | ", flag=" + _____flag + 44 | ", value='" + _value + '\'' + 45 | '}'; 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/Filters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-12-13 下午1:01 23 | */ 24 | public class Filters implements Request { 25 | 26 | private List _filter = new ArrayList(1); 27 | 28 | public void addFilter(String field, TDHSCommon.FilterFlag flag, String value) { 29 | _filter.add(new Filter(field, flag, value)); 30 | } 31 | 32 | public void addFilter(Filter filter) { 33 | _filter.add(filter); 34 | } 35 | 36 | 37 | public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { 38 | if (_filter != null && _filter.size() > TDHSCommon.REQUEST_MAX_FIELD_NUM) { 39 | throw new TDHSEncodeException("too many filter , larger than 256!"); 40 | } 41 | } 42 | 43 | @Override public String toString() { 44 | return "Filters{" + 45 | "filter=" + _filter + 46 | '}'; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/Insert.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-12-19 下午5:45 23 | */ 24 | public class Insert extends RequestWithCharset implements Request { 25 | private TableInfo tableInfo; 26 | 27 | private List _values = new ArrayList(); 28 | 29 | public Insert(TableInfo tableInfo) { 30 | this.tableInfo = tableInfo; 31 | } 32 | 33 | public Insert(TableInfo tableInfo, ValueEntry values[]) { 34 | this(tableInfo); 35 | if (values != null && values.length > 0) { 36 | for (ValueEntry u : values) { 37 | this.addValue(u); 38 | } 39 | } 40 | } 41 | 42 | public Insert(TableInfo tableInfo, String values[]) { 43 | this(tableInfo); 44 | if (values != null && values.length > 0) { 45 | for (String u : values) { 46 | this.addValue(u); 47 | } 48 | } 49 | } 50 | 51 | public void addValue(String entry) { 52 | addValue(TDHSCommon.UpdateFlag.TDHS_UPDATE_SET, entry); 53 | } 54 | 55 | public void addValue(byte[] entry) { 56 | addValue(TDHSCommon.UpdateFlag.TDHS_UPDATE_SET, entry); 57 | } 58 | 59 | public void addValue(TDHSCommon.UpdateFlag flag, String value) { 60 | _values.add(new ValueEntry(flag, value)); 61 | } 62 | 63 | public void addValue(TDHSCommon.UpdateFlag flag, byte[] value) { 64 | _values.add(new ValueEntry(flag, value)); 65 | } 66 | 67 | public void addValue(ValueEntry entry) { 68 | _values.add(entry); 69 | } 70 | 71 | public TableInfo getTableInfo() { 72 | return tableInfo; 73 | } 74 | 75 | public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { 76 | if (tableInfo == null) { 77 | throw new TDHSEncodeException("tableInfo can't be empty!"); 78 | } 79 | tableInfo.isValid(version); 80 | if (_values.size() != tableInfo.getFields().size()) { 81 | throw new TDHSEncodeException("field's size not match values's size"); 82 | } 83 | if (_values.size() > TDHSCommon.REQUEST_MAX_FIELD_NUM) { 84 | throw new TDHSEncodeException("too many insert values , larger than 256!"); 85 | } 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return "Insert{" + 91 | "tableInfo=" + tableInfo + 92 | ", values=" + _values + 93 | '}'; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/Request.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | 17 | /** 18 | * @author 文通 19 | * @since 11-12-12 下午5:08 20 | */ 21 | public interface Request { 22 | 23 | /** 24 | * Method isValid ... 25 | * 26 | * @param version of type ProtocolVersion 27 | * 28 | * @throws TDHSEncodeException when 29 | */ 30 | void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException; 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/RequestWithCharset.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-1-17 下午1:04 17 | */ 18 | public abstract class RequestWithCharset implements Request { 19 | 20 | private String charsetName; 21 | 22 | /** 23 | * Method getCharsetName returns the charsetName of this RequestWithCharest object. 24 | * 25 | * @return the charsetName (type String) of this RequestWithCharest object. 26 | */ 27 | public String getCharsetName() { 28 | return charsetName; 29 | } 30 | 31 | /** 32 | * Method setCharsetName sets the charsetName of this RequestWithCharest object. 33 | * 34 | * @param charsetName the charsetName of this RequestWithCharest object. 35 | */ 36 | public void setCharsetName(String charsetName) { 37 | this.charsetName = charsetName; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/TableInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | import org.apache.commons.lang.StringUtils; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.List; 21 | 22 | /** 23 | * @author 文通 24 | * @since 11-12-13 上午11:36 25 | */ 26 | public class TableInfo implements Request { 27 | 28 | private String _db; 29 | private String _table; 30 | private String _index; 31 | private List _fields = new ArrayList(10); 32 | 33 | private boolean needField; 34 | 35 | public TableInfo() { 36 | } 37 | 38 | public TableInfo(String db, String table, String index, String[] fields) { 39 | this._db = db; 40 | this._table = table; 41 | this._index = index; 42 | if (fields != null) { 43 | Collections.addAll(this._fields, fields); 44 | } 45 | this.needField = true; 46 | } 47 | 48 | public String getDb() { 49 | return _db; 50 | } 51 | 52 | public void setDb(String db) { 53 | this._db = db; 54 | } 55 | 56 | public String getTable() { 57 | return _table; 58 | } 59 | 60 | public void setTable(String _table) { 61 | this._table = _table; 62 | } 63 | 64 | public String getIndex() { 65 | return _index; 66 | } 67 | 68 | public void setIndex(String _index) { 69 | this._index = _index; 70 | } 71 | 72 | public List getFields() { 73 | return _fields; 74 | } 75 | 76 | public void setNeedField(boolean needField) { 77 | this.needField = needField; 78 | } 79 | 80 | public void tableNameToLowerCase() { 81 | this._db = this._db != null ? this._db.toLowerCase() : null; 82 | this._table = this._table != null ? this._table.toLowerCase() : null; 83 | 84 | } 85 | 86 | 87 | public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { 88 | if (StringUtils.isBlank(_db)) { 89 | throw new TDHSEncodeException("db can't be empty!"); 90 | } 91 | if (StringUtils.isBlank(_table)) { 92 | throw new TDHSEncodeException("table can't be empty!"); 93 | } 94 | if (needField && (_fields == null || _fields.size() == 0)) { 95 | throw new TDHSEncodeException("field can't be empty!"); 96 | } 97 | if (needField && _fields != null && _fields.size() > TDHSCommon.REQUEST_MAX_FIELD_NUM) { 98 | throw new TDHSEncodeException("too many field , larger than 256!"); 99 | } 100 | 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "TableInfo{" + 106 | "db='" + _db + '\'' + 107 | ", table='" + _table + '\'' + 108 | ", index='" + _index + '\'' + 109 | ", fields=" + _fields + 110 | ", needField=" + needField + 111 | '}'; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/Update.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-12-14 下午4:28 23 | */ 24 | public class Update extends RequestWithCharset implements Request { 25 | 26 | private Get get; 27 | 28 | private List _valueEntries = new ArrayList(1); 29 | 30 | public Update(Get get) { 31 | this.get = get; 32 | } 33 | 34 | public Update(Get get, ValueEntry valueEntry[]) { 35 | this(get); 36 | if (valueEntry != null && valueEntry.length > 0) { 37 | for (ValueEntry u : valueEntry) { 38 | this.addEntry(u); 39 | } 40 | } 41 | } 42 | 43 | 44 | public void addEntry(TDHSCommon.UpdateFlag flag, String value) { 45 | _valueEntries.add(new ValueEntry(flag, value)); 46 | } 47 | 48 | public void addEntry(TDHSCommon.UpdateFlag flag, byte[] value) { 49 | _valueEntries.add(new ValueEntry(flag, value)); 50 | } 51 | 52 | public void addEntry(ValueEntry entry) { 53 | _valueEntries.add(entry); 54 | } 55 | 56 | public Get getGet() { 57 | return get; 58 | } 59 | 60 | public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { 61 | if (get == null) { 62 | throw new TDHSEncodeException("get can't be empty!"); 63 | } 64 | get.isValid(version); 65 | if (_valueEntries.size() != get.getTableInfo().getFields().size()) { 66 | throw new TDHSEncodeException("field's size not match updateEntries's size"); 67 | } 68 | if (_valueEntries.size() > TDHSCommon.REQUEST_MAX_FIELD_NUM) { 69 | throw new TDHSEncodeException("too many updateEntries , larger than 256!"); 70 | } 71 | } 72 | 73 | @Override 74 | public String toString() { 75 | return "Update{" + 76 | "get=" + get + 77 | ", valueEntries=" + _valueEntries + 78 | '}'; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/request/ValueEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.request; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSEncodeException; 16 | 17 | /** 18 | * @author 文通 19 | * @since 11-12-14 下午4:30 20 | */ 21 | public class ValueEntry implements Request { 22 | private int ____flag; 23 | //String or byte 24 | private Object _value; 25 | 26 | /** 27 | * Constructor ValueEntry creates a new ValueEntry instance. 28 | * 29 | * @param flag of type UpdateFlag 30 | * @param _value of type String 31 | */ 32 | public ValueEntry(TDHSCommon.UpdateFlag flag, String _value) { 33 | this.____flag = flag.getValue(); 34 | this._value = _value; 35 | } 36 | 37 | /** 38 | * Constructor ValueEntry creates a new ValueEntry instance. 39 | * 40 | * @param flag of type UpdateFlag 41 | * @param _value of type byte[] 42 | */ 43 | public ValueEntry(TDHSCommon.UpdateFlag flag, byte[] _value) { 44 | this.____flag = flag.getValue(); 45 | this._value = _value; 46 | } 47 | 48 | /** 49 | * Method isValid ... 50 | * 51 | * @throws TDHSEncodeException when 52 | */ 53 | public void isValid(TDHSCommon.ProtocolVersion version) throws TDHSEncodeException { 54 | } 55 | 56 | /** 57 | * Method toString ... 58 | * 59 | * @return String 60 | */ 61 | @Override 62 | public String toString() { 63 | return "ValueEntry{" + 64 | "flag=" + ____flag + 65 | ", value='" + _value + '\'' + 66 | '}'; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/response/TDHSMetaData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.response; 13 | 14 | import com.taobao.tdhs.client.request.TableInfo; 15 | 16 | import java.util.List; 17 | 18 | /** 19 | * @author 文通 20 | * @since 12-3-23 下午1:46 21 | */ 22 | public class TDHSMetaData { 23 | 24 | private String db; 25 | 26 | private String table; 27 | 28 | private List fieldNames; 29 | 30 | public TDHSMetaData(TableInfo info) { 31 | this.db = info.getDb(); 32 | this.table = info.getTable(); 33 | this.fieldNames = info.getFields(); 34 | } 35 | 36 | 37 | public TDHSMetaData(TableInfo info, List fieldNames) { 38 | this.db = info.getDb(); 39 | this.table = info.getTable(); 40 | this.fieldNames = fieldNames; 41 | } 42 | 43 | 44 | public TDHSMetaData(String db, String table, List fieldNames) { 45 | this.db = db; 46 | this.table = table; 47 | this.fieldNames = fieldNames; 48 | } 49 | 50 | public String getDb() { 51 | return db; 52 | } 53 | 54 | public String getTable() { 55 | return table; 56 | } 57 | 58 | public List getFieldNames() { 59 | return fieldNames; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/statement/BatchStatement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.statement; 13 | 14 | import com.taobao.tdhs.client.exception.TDHSException; 15 | import com.taobao.tdhs.client.response.TDHSResponse; 16 | 17 | /** 18 | * BatchStatement for commit some request in a transaction 19 | * @author 文通 20 | * @since 12-2-21 上午10:06 21 | */ 22 | public interface BatchStatement extends Statement { 23 | 24 | /** 25 | * commit the batch statement 26 | * 27 | * @return TDHSResponse[] 28 | * 29 | * @throws TDHSException when has some error. 30 | */ 31 | TDHSResponse[] commit() throws TDHSException; 32 | 33 | /** 34 | * Method setTimeOut sets the timeOut of this BatchStatement object. 35 | * 36 | * @param timeOut the timeOut of this BatchStatement object. 37 | */ 38 | void setTimeOut(int timeOut); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/client/util/ByteOrderUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.util; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-1-12 下午12:31 17 | */ 18 | final public class ByteOrderUtil { 19 | 20 | public static void writeIntToNet(byte[] bytes, int i, long value) { 21 | if (i > (bytes.length - 4)) { 22 | throw new IllegalArgumentException("out of range"); 23 | } 24 | for (int j = 3; j >= 0; i++, j--) { 25 | bytes[i] = (byte) ((value >>> (8 * j)) & 0XFF); 26 | } 27 | } 28 | 29 | 30 | public static long getUnsignInt(final byte data[], final int pos) { 31 | int v = (data[pos] & 0xff) << 24 | 32 | (data[pos + 1] & 0xff) << 16 | 33 | (data[pos + 2] & 0xff) << 8 | 34 | (data[pos + 3] & 0xff) << 0; 35 | return v & 0xFFFFFFFFL; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/Driver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc; 13 | 14 | import java.sql.SQLException; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-3-6 下午2:58 19 | */ 20 | public class Driver extends NonRegisteringDriver implements java.sql.Driver { 21 | 22 | // ~ Static fields/initializers 23 | // --------------------------------------------- 24 | 25 | // 26 | // Register ourselves with the DriverManager 27 | // 28 | static { 29 | try { 30 | java.sql.DriverManager.registerDriver(new Driver()); 31 | } catch (SQLException E) { 32 | throw new RuntimeException("Can't register driver!"); 33 | } 34 | } 35 | 36 | // ~ Constructors 37 | // ----------------------------------------------------------- 38 | 39 | /** 40 | * Construct a new driver and register it with DriverManager 41 | * 42 | * @throws SQLException if a database error occurs. 43 | */ 44 | public Driver() throws SQLException { 45 | // Required for Class.forName().newInstance() 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/exception/TDHSSQLException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.exception; 13 | 14 | import java.sql.SQLException; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-3-9 上午11:11 19 | */ 20 | public class TDHSSQLException extends SQLException { 21 | 22 | public TDHSSQLException(String reason, String sql) { 23 | super(reason + " SQL:[" + sql + "]"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/sqlparser/Entry.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.sqlparser; 13 | 14 | import java.util.Map; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-3-9 上午9:41 19 | */ 20 | public class Entry { 21 | 22 | private final K key; 23 | 24 | private final V value; 25 | 26 | public Entry(K key, V value) { 27 | this.key = key; 28 | this.value = value; 29 | } 30 | 31 | public K getKey() { 32 | return key; 33 | } 34 | 35 | public V getValue() { 36 | return value; 37 | } 38 | 39 | public final boolean equals(Object o) { 40 | if (!(o instanceof Map.Entry)) 41 | return false; 42 | Map.Entry e = (Map.Entry) o; 43 | Object k1 = getKey(); 44 | Object k2 = e.getKey(); 45 | if (k1 == k2 || (k1 != null && k1.equals(k2))) { 46 | Object v1 = getValue(); 47 | Object v2 = e.getValue(); 48 | if (v1 == v2 || (v1 != null && v1.equals(v2))) 49 | return true; 50 | } 51 | return false; 52 | } 53 | 54 | public final int hashCode() { 55 | return (key == null ? 0 : key.hashCode()) ^ 56 | (value == null ? 0 : value.hashCode()); 57 | } 58 | 59 | public final String toString() { 60 | return getKey() + "=" + getValue(); 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/sqlparser/HintStruct.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.sqlparser; 13 | 14 | import com.taobao.tdhs.jdbc.util.ConvertUtil; 15 | import org.apache.log4j.Logger; 16 | 17 | import java.util.Collections; 18 | import java.util.LinkedList; 19 | import java.util.List; 20 | 21 | /** 22 | * @author danchen 23 | */ 24 | public class HintStruct { 25 | private static Logger logger = Logger.getLogger(HintStruct.class); 26 | /*tdhs:[idx_ab(a,b)]*/ 27 | private final String hintString; 28 | private String indexName; 29 | private List listIndexColumns; 30 | private String errmsg; 31 | private int hash; 32 | 33 | public HintStruct(String hintString) { 34 | this.hintString = hintString.trim().replace(" ", ""); 35 | this.indexName = ""; 36 | this.errmsg = ""; 37 | this.listIndexColumns = new LinkedList(); 38 | } 39 | 40 | public void AnalyzeHint() { 41 | int k = 0; 42 | if (!this.hintString.substring(0, 2).equals("/*")) { 43 | errmsg = "hint syntax is not right."; 44 | return; 45 | } 46 | k = k + 2; 47 | 48 | if (!(k + 5 < hintString.length() && hintString.substring(k, k + 5).equals("tdhs:"))) { 49 | errmsg = "hint syntax is not right."; 50 | return; 51 | } 52 | k = k + 5; 53 | 54 | int hash_left = hintString.indexOf("<"); 55 | int hash_right = hintString.indexOf(">"); 56 | if (hash_left > 0 && hash_left >= k && hash_right > 0 && hash_right > hash_left) { 57 | String hashCode = hintString.substring(hash_left + 1, hash_right); 58 | k += (hashCode.length() + 2); 59 | this.hash = ConvertUtil.safeConvertInt(hashCode, 0); 60 | } 61 | 62 | int idx_left = hintString.indexOf("["); 63 | int idx_right = hintString.indexOf("]"); 64 | 65 | if (idx_left > 0 && idx_left >= k && idx_right > 0 && idx_right > idx_left) { 66 | String indexHint = hintString.substring(idx_left + 1, idx_right); 67 | k += (indexHint.length() + 2); 68 | int addr = indexHint.indexOf("("); 69 | if (addr > 0) { 70 | this.indexName = indexHint.substring(0, addr); 71 | } else { 72 | errmsg = "hint syntax is not right."; 73 | return; 74 | } 75 | 76 | int addr_right = indexHint.indexOf(")"); 77 | if (addr_right > 0 && addr_right > addr) { 78 | String allColumns = indexHint.substring(addr + 1, addr_right); 79 | String[] array_column = allColumns.split(","); 80 | Collections.addAll(listIndexColumns, array_column); 81 | } else { 82 | errmsg = "hint syntax is not right."; 83 | return; 84 | } 85 | 86 | } 87 | 88 | if (!hintString.substring(k).equals("*/")) { 89 | errmsg = "hint syntax is not right."; 90 | return; 91 | } 92 | } 93 | 94 | public String getHintString() { 95 | return hintString; 96 | } 97 | 98 | public String getIndexName() { 99 | return indexName; 100 | } 101 | 102 | public List getListIndexColumns() { 103 | return listIndexColumns; 104 | } 105 | 106 | public String getErrmsg() { 107 | return errmsg; 108 | } 109 | 110 | public int getHash() { 111 | return hash; 112 | } 113 | 114 | @Override 115 | public String toString() { 116 | return "HintStruct{" + 117 | "hintString='" + hintString + '\'' + 118 | ", indexName='" + indexName + '\'' + 119 | ", listIndexColumns=" + listIndexColumns + 120 | ", errmsg='" + errmsg + '\'' + 121 | ", hash=" + hash + 122 | '}'; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/sqlparser/OperationStruct.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.sqlparser; 13 | 14 | import org.apache.commons.lang.StringUtils; 15 | 16 | /** 17 | * @author danchen 18 | */ 19 | public class OperationStruct { 20 | private String columnName; 21 | private String oper; 22 | private String value; 23 | 24 | public OperationStruct() { 25 | super(); 26 | } 27 | 28 | public String getColumnName() { 29 | return columnName; 30 | } 31 | 32 | public void setColumnName(String columnName) { 33 | this.columnName = columnName; 34 | } 35 | 36 | public String getOper() { 37 | return oper; 38 | } 39 | 40 | public void setOper(String oper) { 41 | oper = StringUtils.trim(oper); 42 | if ("is".equalsIgnoreCase(oper)) { 43 | this.oper = "="; 44 | } else { 45 | this.oper = oper; 46 | } 47 | } 48 | 49 | public String getValue() { 50 | return value; 51 | } 52 | 53 | public void setValue(String value) { 54 | this.value = value; 55 | } 56 | 57 | @Override 58 | public boolean equals(Object o) { 59 | if (this == o) return true; 60 | if (!(o instanceof OperationStruct)) return false; 61 | 62 | OperationStruct that = (OperationStruct) o; 63 | 64 | if (columnName != null ? !columnName.equals(that.columnName) : that.columnName != null) return false; 65 | if (oper != null ? !oper.equals(that.oper) : that.oper != null) return false; 66 | if (value != null ? !value.equals(that.value) : that.value != null) return false; 67 | 68 | return true; 69 | } 70 | 71 | @Override 72 | public int hashCode() { 73 | int result = columnName != null ? columnName.hashCode() : 0; 74 | result = 31 * result + (oper != null ? oper.hashCode() : 0); 75 | result = 31 * result + (value != null ? value.hashCode() : 0); 76 | return result; 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | return "OperationStruct [columnName=" + columnName + ", oper=" + oper 82 | + ", value=" + value + "]"; 83 | } 84 | 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/sqlparser/OrderByType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.sqlparser; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-3-9 下午2:49 17 | */ 18 | public enum OrderByType { 19 | ASC, DESC 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/sqlparser/SQLType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.sqlparser; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-3-8 上午10:25 17 | */ 18 | public enum SQLType { 19 | INSERT(0), UPDATE(1), DELETE(2), SELECT(3); 20 | 21 | private int value; 22 | 23 | private SQLType(int value) { 24 | this.value = value; 25 | } 26 | 27 | public int getValue() { 28 | return value; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/sqlparser/TreeNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | /** 13 | * (C) 2011-2012 Alibaba Group Holding Limited. 14 | * 15 | * This program is free software; you can redistribute it and/or 16 | * modify it under the terms of the GNU General Public License 17 | * version 2 as published by the Free Software Foundation. 18 | * 19 | * 20 | * Authors: 21 | * danchen 22 | * 23 | */ 24 | package com.taobao.tdhs.jdbc.sqlparser; 25 | 26 | public class TreeNode { 27 | //当前结点的内容 28 | public String node_content; 29 | //类型:列名 1;操作符>,<,=,>=,<= in like is 2;value 3;条件运算符 and or 4 30 | public int node_type; 31 | //左子树 32 | public TreeNode left_node; 33 | //右子树 34 | public TreeNode right_node; 35 | //父亲 36 | public TreeNode parent_node; 37 | 38 | //初始化这个结点的内容 39 | public TreeNode() 40 | { 41 | node_content=null; 42 | node_type=-1; 43 | left_node=null; 44 | right_node=null; 45 | parent_node=null; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/taobao/tdhs/jdbc/util/ConvertUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.util; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-3-7 下午12:15 17 | */ 18 | public final class ConvertUtil { 19 | 20 | public static int safeConvertInt(String v, int defaults) { 21 | try { 22 | return Integer.valueOf(v); 23 | } catch (NumberFormatException e) { 24 | return defaults; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/benchmark/GenerateData.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark 13 | 14 | import groovy.sql.Sql 15 | import java.util.concurrent.atomic.AtomicLong 16 | 17 | /** 18 | * @author 文通 19 | * @since 12-2-9 下午2:27 20 | * 21 | */ 22 | 23 | def client_num = 50 24 | 25 | AtomicLong id = new AtomicLong(0) 26 | 27 | 28 | private List connent(int num) { 29 | def result = [] 30 | 1.upto(num) {result.add(Sql.newInstance("jdbc:mysql://" + PropUtil.host + ":3309/benchmark", "test", "test", "com.mysql.jdbc.Driver"))} 31 | return result 32 | } 33 | 34 | def clients = connent(client_num) 35 | 36 | def s = new StressTest(count: 80000000) 37 | s.add({ 38 | Sql client = clients.get(it) 39 | long _id = id.incrementAndGet() 40 | String table = TableUtil.getTable("test_", _id % 256); 41 | client.execute("INSERT INTO `" + table + "` (`k`, `i`, `c`) VALUES ('10000', '" + _id.toString() + "', '" + _id.toString() + "_abcdefghijklmnopqrstuvwxyz" + "')") 42 | }, client_num) 43 | 44 | s.run() 45 | 46 | 47 | clients.each {it.close()} 48 | 49 | -------------------------------------------------------------------------------- /src/test/java/benchmark/PropUtil.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-3-23 上午10:13 17 | * 18 | */ 19 | class PropUtil { 20 | static String host = "t-wentong" 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/benchmark/RandomUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark; 13 | 14 | import java.math.BigDecimal; 15 | import java.util.Random; 16 | import java.util.concurrent.atomic.AtomicLong; 17 | 18 | import org.junit.Ignore; 19 | 20 | /** 21 | * @author 文通 22 | * @since 11-11-9 下午5:07 23 | */ 24 | @Ignore 25 | public final class RandomUtil { 26 | 27 | private static final Random RANDOM = new Random(); 28 | 29 | public static BigDecimal getId(BigDecimal total, BigDecimal step) { 30 | return step.multiply(new BigDecimal(RANDOM.nextInt(total.intValue()))); 31 | } 32 | 33 | public static BigDecimal getSid(BigDecimal total, AtomicLong sid) { 34 | BigDecimal ret = new BigDecimal(sid.getAndIncrement()); 35 | if (ret.longValue() > total.longValue()) { 36 | sid.set(1); 37 | } 38 | return ret; 39 | } 40 | 41 | public static int nextInt(int i) { 42 | return RANDOM.nextInt(i); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/benchmark/TableUtil.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark 13 | 14 | /** 15 | * @author 文通 16 | * @since 11-11-9 下午1:12 17 | * 18 | */ 19 | final class TableUtil { 20 | 21 | public static String getTable(String prefix, long index) { 22 | return prefix + index.toString().padLeft(4, "0"); 23 | } 24 | 25 | public static void main(String[] args) { 26 | println getTable("test_", 123); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/benchmark/batch/tdhs_batch.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.batch 13 | 14 | import benchmark.PropUtil 15 | import benchmark.StressTest 16 | import com.taobao.tdhs.client.TDHSClient 17 | import com.taobao.tdhs.client.TDHSClientImpl 18 | import com.taobao.tdhs.client.statement.BatchStatement 19 | import java.util.concurrent.atomic.AtomicLong 20 | 21 | /** 22 | * @author 文通 23 | * @since 12-2-22 下午2:04 24 | * 25 | */ 26 | 27 | 28 | AtomicLong v = new AtomicLong(1) 29 | 30 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 31 | 32 | def s = new StressTest() 33 | s.add({ 34 | BatchStatement b = client.createBatchStatement() 35 | b.insert().use("test").from("test") 36 | .value("data", v.getAndIncrement().toString() + "_aaa") 37 | .insert() 38 | b.insert().use("test").from("test") 39 | .value("data", v.getAndIncrement().toString() + "_bbb") 40 | .insert() 41 | b.insert().use("test").from("test") 42 | .value("data", v.getAndIncrement().toString() + "_ccc") 43 | .insert() 44 | 45 | b.commit() 46 | }, 100) 47 | 48 | s.run() 49 | client.shutdown() 50 | -------------------------------------------------------------------------------- /src/test/java/benchmark/get/hs_all_cache.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.RandomUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import com.google.code.hs4j.HSClient 18 | import com.google.code.hs4j.IndexSession 19 | import com.google.code.hs4j.impl.HSClientImpl 20 | import benchmark.PropUtil 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-2-9 下午3:32 25 | * 26 | */ 27 | 28 | HSClient hsClient = new HSClientImpl(new InetSocketAddress(PropUtil.host, 8889), 3); 29 | List sesson_pool = [] 30 | 31 | 0.upto(256 - 1) { 32 | String table = TableUtil.getTable("test_", it); 33 | sesson_pool.add(hsClient.openIndexSession("benchmark", table, 34 | "idx_i", ["id", "k", "i", "c"] as String[])) 35 | } 36 | 37 | def s = new StressTest() 38 | s.add({ 39 | def _id = RandomUtil.getId(1024, 1) + 1 40 | 41 | IndexSession session = sesson_pool.get((_id.longValue() % 256).intValue()) 42 | session.find([_id.toString()] as String[]); 43 | }, 100) 44 | 45 | 46 | s.run() 47 | hsClient.shutdown() 48 | -------------------------------------------------------------------------------- /src/test/java/benchmark/get/hs_part_cache.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.RandomUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import com.google.code.hs4j.HSClient 18 | import com.google.code.hs4j.IndexSession 19 | import com.google.code.hs4j.impl.HSClientImpl 20 | import benchmark.PropUtil 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-2-9 下午3:32 25 | * 26 | */ 27 | 28 | def getId() { 29 | if (RandomUtil.nextInt(100) < 95) { 30 | Integer i = RandomUtil.nextInt(1024) + 1; 31 | return i 32 | } else { 33 | Integer i = RandomUtil.nextInt(80000000) + 1; 34 | return i 35 | } 36 | } 37 | 38 | HSClient hsClient = new HSClientImpl(new InetSocketAddress(PropUtil.host, 8888), 3); 39 | List sesson_pool = [] 40 | 41 | 0.upto(256 - 1) { 42 | String table = TableUtil.getTable("test_", it); 43 | sesson_pool.add(hsClient.openIndexSession("benchmark", table, 44 | "idx_i", ["id", "k", "i", "c"] as String[])) 45 | } 46 | 47 | def s = new StressTest() 48 | s.add({ 49 | def _id = getId() 50 | 51 | IndexSession session = sesson_pool.get((_id.longValue() % 256).intValue()) 52 | session.find([_id.toString()] as String[]); 53 | }, 100) 54 | 55 | 56 | s.run() 57 | hsClient.shutdown() 58 | -------------------------------------------------------------------------------- /src/test/java/benchmark/get/sql_all_cache.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.PropUtil 15 | import benchmark.RandomUtil 16 | import benchmark.StressTest 17 | import benchmark.TableUtil 18 | import groovy.sql.Sql 19 | 20 | /** 21 | * @author 文通 22 | * @since 12-2-9 下午2:14 23 | * 24 | */ 25 | def client_num = 70 26 | 27 | private List connent(int num) { 28 | def result = [] 29 | 1.upto(num) {result.add(Sql.newInstance("jdbc:mysql://" + PropUtil.host + ":3309/benchmark", "test", "test", "com.mysql.jdbc.Driver"))} 30 | return result 31 | } 32 | 33 | def clients = connent(client_num) 34 | 35 | def s = new StressTest() 36 | s.add({ 37 | Sql client = clients.get(it) 38 | def _id = RandomUtil.getId(1024, 1) + 1 39 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 40 | client.execute("select id ,k,i,c from " + table + " where i =" + _id.toString()) 41 | }, client_num) 42 | 43 | s.run() 44 | 45 | 46 | clients.each {it.close()} 47 | -------------------------------------------------------------------------------- /src/test/java/benchmark/get/sql_part_cache.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.PropUtil 15 | import benchmark.RandomUtil 16 | import benchmark.StressTest 17 | import benchmark.TableUtil 18 | import groovy.sql.Sql 19 | 20 | /** 21 | * @author 文通 22 | * @since 12-2-9 下午2:14 23 | * 24 | */ 25 | def client_num = 70 26 | 27 | def getId() { 28 | if (RandomUtil.nextInt(100) < 95) { 29 | Integer i = RandomUtil.nextInt(1024) + 1; 30 | return i 31 | } else { 32 | Integer i = RandomUtil.nextInt(80000000) + 1; 33 | return i 34 | } 35 | } 36 | 37 | private List connent(int num) { 38 | def result = [] 39 | 1.upto(num) {result.add(Sql.newInstance("jdbc:mysql://" + PropUtil.host + ":3309/benchmark", "test", "test", "com.mysql.jdbc.Driver"))} 40 | return result 41 | } 42 | 43 | def clients = connent(client_num) 44 | 45 | def s = new StressTest() 46 | s.add({ 47 | Sql client = clients.get(it) 48 | def _id = getId() 49 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 50 | client.execute("select id ,k,i,c from " + table + " where i =" + _id.toString()) 51 | }, client_num) 52 | 53 | s.run() 54 | 55 | 56 | clients.each {it.close()} 57 | -------------------------------------------------------------------------------- /src/test/java/benchmark/get/tdhs_all_cache.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.RandomUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import com.taobao.tdhs.client.TDHSClient 18 | import com.taobao.tdhs.client.TDHSClientImpl 19 | import com.taobao.tdhs.client.response.TDHSResponse 20 | import com.taobao.tdhs.client.response.TDHSResponseEnum 21 | import benchmark.PropUtil 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-2-9 下午3:31 26 | * 27 | */ 28 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 29 | 30 | def s = new StressTest() 31 | s.add({ 32 | def _id = RandomUtil.getId(1024, 1) + 1 33 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 34 | TDHSResponse response = client.createStatement(3).query().use("benchmark").from("test_0001") 35 | .select("id", "k", "i", "c") 36 | .where().fields("i").equal(_id.toString()).get() 37 | 38 | if (response != null && response.getStatus() != TDHSResponseEnum.ClientStatus.OK) { 39 | System.out.println(response); 40 | } 41 | }, 100) 42 | 43 | s.run() 44 | client.shutdown() 45 | -------------------------------------------------------------------------------- /src/test/java/benchmark/get/tdhs_part_cache.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.RandomUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import com.taobao.tdhs.client.TDHSClient 18 | import com.taobao.tdhs.client.TDHSClientImpl 19 | import com.taobao.tdhs.client.response.TDHSResponse 20 | import benchmark.PropUtil 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-2-9 下午3:31 25 | * 26 | */ 27 | def getId() { 28 | if (RandomUtil.nextInt(100) < 95) { 29 | Integer i = RandomUtil.nextInt(1024) + 1; 30 | return i 31 | } else { 32 | Integer i = RandomUtil.nextInt(80000000) + 1; 33 | return i 34 | } 35 | } 36 | 37 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 38 | 39 | def s = new StressTest() 40 | s.add({ 41 | def _id = getId() 42 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 43 | try { 44 | TDHSResponse response = client.query().use("benchmark").from(table) 45 | .select("id", "k", "i", "c") 46 | .where().index("idx_i").equal(_id.toString()).get() 47 | } catch (Exception e) { 48 | } 49 | 50 | // if (response != null && response.getStatus() != TDHSResponseEnum.ClientStatus.OK) { 51 | // System.out.println(response); 52 | // } 53 | }, 100) 54 | 55 | s.run() 56 | client.shutdown() 57 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/hs_insert.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.StressTest 15 | import benchmark.TableUtil 16 | import com.google.code.hs4j.HSClient 17 | import com.google.code.hs4j.IndexSession 18 | import com.google.code.hs4j.impl.HSClientImpl 19 | import java.util.concurrent.atomic.AtomicLong 20 | import benchmark.PropUtil 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-2-9 下午3:32 25 | * 26 | */ 27 | 28 | 29 | AtomicLong id = new AtomicLong(0) 30 | HSClient hsClient = new HSClientImpl(new InetSocketAddress(PropUtil.host, 8889), 3); 31 | List sesson_pool = [] 32 | 33 | 0.upto(256 - 1) { 34 | String table = TableUtil.getTable("test_", it); 35 | sesson_pool.add(hsClient.openIndexSession("benchmark_insert", table, 36 | "PRIMARY", ["k", "i", "c"] as String[])) 37 | } 38 | 39 | def s = new StressTest() 40 | s.add({ 41 | def _id = id.incrementAndGet() 42 | 43 | IndexSession session = sesson_pool.get((_id.longValue() % 256).intValue()) 44 | session.insert("10000", _id.toString(), _id.toString() + "_abcdefghijklmnopqrstuvwxyz") 45 | }, 100) 46 | 47 | 48 | s.run() 49 | hsClient.shutdown() 50 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/hs_insert_one_table.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.StressTest 15 | import com.google.code.hs4j.HSClient 16 | import com.google.code.hs4j.IndexSession 17 | import com.google.code.hs4j.impl.HSClientImpl 18 | import java.util.concurrent.atomic.AtomicLong 19 | import benchmark.PropUtil 20 | 21 | /** 22 | * @author 文通 23 | * @since 12-2-9 下午3:32 24 | * 25 | */ 26 | 27 | 28 | AtomicLong id = new AtomicLong(0) 29 | HSClient hsClient = new HSClientImpl(new InetSocketAddress(PropUtil.host, 8889), 3); 30 | 31 | IndexSession session = hsClient.openIndexSession("benchmark_insert", "test", 32 | "PRIMARY", ["k", "i", "c"] as String[]) 33 | def s = new StressTest() 34 | s.add({ 35 | def _id = id.incrementAndGet() 36 | 37 | session.insert("10000", _id.toString(), _id.toString() + "_abcdefghijklmnopqrstuvwxyz") 38 | }, 100) 39 | 40 | 41 | s.run() 42 | hsClient.shutdown() 43 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/sql_insert.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.PropUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import groovy.sql.Sql 18 | import java.util.concurrent.atomic.AtomicLong 19 | 20 | /** 21 | * @author 文通 22 | * @since 12-2-9 下午2:27 23 | * 24 | */ 25 | 26 | def client_num = 50 27 | 28 | AtomicLong id = new AtomicLong(0) 29 | 30 | 31 | private List connent(int num) { 32 | def result = [] 33 | 1.upto(num) {result.add(Sql.newInstance("jdbc:mysql://" + PropUtil.host + ":3309/benchmark_insert", "test", "test", "com.mysql.jdbc.Driver"))} 34 | return result 35 | } 36 | 37 | def clients = connent(client_num) 38 | 39 | def s = new StressTest(count: 10000000) 40 | s.add({ 41 | Sql client = clients.get(it) 42 | long _id = id.incrementAndGet() 43 | String table = TableUtil.getTable("test_", _id % 256); 44 | client.execute("INSERT INTO `" + table + "` (`k`, `i`, `c`) VALUES ('10000', '" + _id.toString() + "', '" + _id.toString() + "_abcdefghijklmnopqrstuvwxyz" + "')") 45 | }, client_num) 46 | 47 | s.run() 48 | 49 | 50 | clients.each {it.close()} 51 | 52 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/sql_insert_one_table.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.PropUtil 15 | import benchmark.StressTest 16 | import groovy.sql.Sql 17 | import java.util.concurrent.atomic.AtomicLong 18 | 19 | /** 20 | * @author 文通 21 | * @since 12-2-9 下午2:27 22 | * 23 | */ 24 | 25 | def client_num = 50 26 | 27 | AtomicLong id = new AtomicLong(0) 28 | 29 | 30 | private List connent(int num) { 31 | def result = [] 32 | 1.upto(num) {result.add(Sql.newInstance("jdbc:mysql://" + PropUtil.host + ":3309/benchmark_insert", "test", "test", "com.mysql.jdbc.Driver"))} 33 | return result 34 | } 35 | 36 | def clients = connent(client_num) 37 | 38 | def s = new StressTest(count: 10000000) 39 | s.add({ 40 | Sql client = clients.get(it) 41 | long _id = id.incrementAndGet() 42 | String table = "test"; 43 | client.execute("INSERT INTO `" + table + "` (`k`, `i`, `c`) VALUES ('10000', '" + _id.toString() + "', '" + _id.toString() + "_abcdefghijklmnopqrstuvwxyz" + "')") 44 | }, client_num) 45 | 46 | s.run() 47 | 48 | 49 | clients.each {it.close()} 50 | 51 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/tdhs_insert.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.StressTest 15 | import benchmark.TableUtil 16 | import com.taobao.tdhs.client.TDHSClient 17 | import com.taobao.tdhs.client.TDHSClientImpl 18 | import com.taobao.tdhs.client.response.TDHSResponse 19 | import com.taobao.tdhs.client.response.TDHSResponseEnum 20 | import java.util.concurrent.atomic.AtomicLong 21 | import benchmark.PropUtil 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-2-9 下午3:31 26 | * 27 | */ 28 | 29 | AtomicLong id = new AtomicLong(0) 30 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 31 | 32 | def s = new StressTest() 33 | s.add({ 34 | def _id = id.incrementAndGet() 35 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 36 | TDHSResponse response = client.insert().use("benchmark_insert").from(table) 37 | .value("k", "10000") 38 | .value("i", _id.toString()) 39 | .value("c", _id.toString() + "_abcdefghijklmnopqrstuvwxyz").insert() 40 | 41 | if (response != null && response.getStatus() != TDHSResponseEnum.ClientStatus.OK) { 42 | System.out.println(response); 43 | } 44 | }, 100) 45 | 46 | s.run() 47 | client.shutdown() 48 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/tdhs_insert_one_table.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.StressTest 15 | import com.taobao.tdhs.client.TDHSClient 16 | import com.taobao.tdhs.client.TDHSClientImpl 17 | import com.taobao.tdhs.client.response.TDHSResponse 18 | import com.taobao.tdhs.client.response.TDHSResponseEnum 19 | import java.util.concurrent.atomic.AtomicLong 20 | import benchmark.PropUtil 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-2-9 下午3:31 25 | * 26 | */ 27 | 28 | int cur = 16 29 | AtomicLong id = new AtomicLong(0) 30 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 31 | 32 | def s = new StressTest() 33 | s.add({ 34 | def _id = id.incrementAndGet() 35 | int end = it % cur 36 | String table = "test_" + end.toString().padLeft(4, "0"); 37 | TDHSResponse response = client.createStatement(end).insert().use("benchmark_insert").from(table) 38 | .value("k", "10000") 39 | .value("i", _id.toString()) 40 | .value("c", _id.toString() + "_abcdefghijklmnopqrstuvwxyz").insert() 41 | 42 | if (response != null && response.getStatus() != TDHSResponseEnum.ClientStatus.OK) { 43 | System.out.println(response); 44 | } 45 | }, 100) 46 | 47 | s.run() 48 | client.shutdown() 49 | -------------------------------------------------------------------------------- /src/test/java/benchmark/insert/tdhs_insert_one_table_real.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.insert 13 | 14 | import benchmark.StressTest 15 | import com.taobao.tdhs.client.TDHSClient 16 | import com.taobao.tdhs.client.TDHSClientImpl 17 | import com.taobao.tdhs.client.response.TDHSResponse 18 | import com.taobao.tdhs.client.response.TDHSResponseEnum 19 | import java.util.concurrent.atomic.AtomicLong 20 | import benchmark.PropUtil 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-2-9 下午3:31 25 | * 26 | */ 27 | 28 | int step = 100000000 29 | 30 | int index = Integer.valueOf(args[0]) 31 | 32 | AtomicLong id = new AtomicLong((index - 1) * step + 1) 33 | 34 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 35 | 36 | def s = new StressTest(count: step) 37 | s.add({ 38 | def _id = id.incrementAndGet() 39 | String table = "test" 40 | TDHSResponse response = client.createStatement(index).insert().use("benchmark_insert").from(table) 41 | .value("id", _id.toString()) 42 | .value("k", "10000") 43 | .value("i", _id.toString()) 44 | .value("c", _id.toString() + "_abcdefghijklmnopqrstuvwxyz").insert() 45 | 46 | if (response != null && response.getStatus() != TDHSResponseEnum.ClientStatus.OK) { 47 | System.out.println(response); 48 | } 49 | }, 100) 50 | 51 | s.run() 52 | client.shutdown() 53 | -------------------------------------------------------------------------------- /src/test/java/benchmark/update/hs_set.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.update 13 | 14 | import benchmark.RandomUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import com.google.code.hs4j.FindOperator 18 | import com.google.code.hs4j.HSClient 19 | import com.google.code.hs4j.IndexSession 20 | import com.google.code.hs4j.impl.HSClientImpl 21 | import benchmark.PropUtil 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-2-9 下午3:32 26 | * 27 | */ 28 | 29 | HSClient hsClient = new HSClientImpl(new InetSocketAddress(PropUtil.host, 8889), 3); 30 | List sesson_pool = [] 31 | 32 | 0.upto(256 - 1) { 33 | String table = TableUtil.getTable("test_", it); 34 | sesson_pool.add(hsClient.openIndexSession("benchmark", table, 35 | "idx_i", ["kc"] as String[])) 36 | } 37 | 38 | def s = new StressTest() 39 | s.add({ 40 | def _id = RandomUtil.getId(1024, 1) + 1 41 | 42 | IndexSession session = sesson_pool.get((_id.longValue() % 256).intValue()) 43 | session.update([_id.toString()] as String[], [RandomUtil.nextInt(1024).toString()] as String[], FindOperator.EQ); 44 | }, 100) 45 | 46 | 47 | s.run() 48 | hsClient.shutdown() 49 | -------------------------------------------------------------------------------- /src/test/java/benchmark/update/sql_add.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.get 13 | 14 | import benchmark.PropUtil 15 | import benchmark.RandomUtil 16 | import benchmark.StressTest 17 | import benchmark.TableUtil 18 | import groovy.sql.Sql 19 | 20 | /** 21 | * @author 文通 22 | * @since 12-2-9 下午2:14 23 | * 24 | */ 25 | def client_num = 70 26 | 27 | private List connent(int num) { 28 | def result = [] 29 | 1.upto(num) {result.add(Sql.newInstance("jdbc:mysql://" + PropUtil.host + ":3309/benchmark", "test", "test", "com.mysql.jdbc.Driver"))} 30 | return result 31 | } 32 | 33 | def clients = connent(client_num) 34 | 35 | def s = new StressTest() 36 | s.add({ 37 | Sql client = clients.get(it) 38 | def _id = RandomUtil.getId(1024, 1) + 1 39 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 40 | client.execute("UPDATE " + table + " SET kc=kc+1 WHERE i=" + _id.toString()) 41 | }, client_num) 42 | 43 | s.run() 44 | 45 | 46 | clients.each {it.close()} 47 | -------------------------------------------------------------------------------- /src/test/java/benchmark/update/tdhs_add.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package benchmark.update 13 | 14 | import benchmark.RandomUtil 15 | import benchmark.StressTest 16 | import benchmark.TableUtil 17 | import com.taobao.tdhs.client.TDHSClient 18 | import com.taobao.tdhs.client.TDHSClientImpl 19 | import com.taobao.tdhs.client.response.TDHSResponse 20 | import com.taobao.tdhs.client.response.TDHSResponseEnum 21 | import benchmark.PropUtil 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-2-9 下午3:31 26 | * 27 | */ 28 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress(PropUtil.host, 9999), 2); 29 | 30 | def s = new StressTest() 31 | s.add({ 32 | def _id = RandomUtil.getId(1024, 1) + 1 33 | String table = TableUtil.getTable("test_", _id.longValue() % 256); 34 | TDHSResponse response = client.query().use("benchmark").from(table) 35 | .set().field("kc").add(1) 36 | .where().index("idx_i").equal(_id.toString()).update() 37 | 38 | if (response != null && response.getStatus() != TDHSResponseEnum.ClientStatus.OK) { 39 | System.out.println(response); 40 | } 41 | }, 100) 42 | 43 | s.run() 44 | client.shutdown() 45 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/response/TDHSClobTest.java: -------------------------------------------------------------------------------- 1 | package com.taobao.tdhs.client.response; 2 | 3 | import junit.framework.Assert; 4 | import org.junit.Test; 5 | 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * @author 文通 10 | * @since 12-6-29 上午11:54 11 | */ 12 | public class TDHSClobTest { 13 | private String value = "1234567890"; 14 | 15 | private TDHSClob clob = new TDHSClob(value); 16 | 17 | @Test 18 | public void testLength() throws Exception { 19 | Assert.assertEquals(value.length(), clob.length()); 20 | } 21 | 22 | @Test 23 | public void testGetSubString() throws Exception { 24 | Assert.assertEquals("123", clob.getSubString(1, 3)); 25 | Assert.assertEquals("2345", clob.getSubString(2, 4)); 26 | 27 | } 28 | 29 | @Test 30 | public void testPosition1() throws Exception { 31 | Assert.assertEquals(2, clob.position("234", 1)); 32 | } 33 | 34 | @Test 35 | public void testPosition2() throws Exception { 36 | Assert.assertEquals(3, clob.position(new TDHSClob("34"), 1)); 37 | 38 | } 39 | 40 | @Test(expected = SQLException.class) 41 | public void testPositionError() throws Exception { 42 | Assert.assertEquals(2, clob.position("234", 0)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/BatchTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import com.taobao.tdhs.client.exception.TDHSException; 15 | import com.taobao.tdhs.client.response.TDHSResponse; 16 | import com.taobao.tdhs.client.response.TDHSResponseEnum; 17 | import com.taobao.tdhs.client.statement.BatchStatement; 18 | import junit.framework.Assert; 19 | import org.junit.After; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-4-12 上午9:06 26 | */ 27 | public class BatchTest extends TestBase { 28 | @Before 29 | @After 30 | public void clean() throws TDHSException { 31 | client.query().use(db).from(table).where().greaterEqual("-1").delete(); 32 | } 33 | 34 | @Test 35 | public void testBatchDone() throws TDHSException { 36 | BatchStatement batchStatement = client.createBatchStatement(); 37 | batchStatement.insert().use(db).from(table) 38 | .value("id", "1") 39 | .value("name", "a") 40 | .value("level", "1").insert(); 41 | batchStatement.insert().use(db).from(table) 42 | .value("id", "2") 43 | .value("name", "b") 44 | .value("level", "2").insert(); 45 | batchStatement.insert().use(db).from(table) 46 | .value("id", "3") 47 | .value("name", "c") 48 | .value("level", "3").insert(); 49 | TDHSResponse[] responses = batchStatement.commit(); 50 | Assert.assertEquals(3, responses.length); 51 | for (TDHSResponse r : responses) { 52 | Assert.assertEquals(TDHSResponseEnum.ClientStatus.OK, r.getStatus()); 53 | } 54 | } 55 | 56 | @Test 57 | public void testBatchFailed() throws TDHSException { 58 | BatchStatement batchStatement = client.createBatchStatement(); 59 | batchStatement.insert().use(db).from(table) 60 | .value("id", "1") 61 | .value("name", "a") 62 | .value("level", "1").insert(); 63 | batchStatement.insert().use(db).from(table) 64 | .value("id", "2") 65 | .value("name", "b") 66 | .value("level", "2").insert(); 67 | batchStatement.insert().use(db).from(table) 68 | .value("id", "1") 69 | .value("name", "c") 70 | .value("level", "1").insert(); 71 | TDHSResponse[] responses = batchStatement.commit(); 72 | Assert.assertEquals(3, responses.length); 73 | Assert.assertEquals(responses[0].getStatus(), TDHSResponseEnum.ClientStatus.SERVER_ERROR); 74 | Assert.assertEquals(responses[0].getErrorCode(), TDHSResponseEnum.ErrorCode.CLIENT_ERROR_CODE_FAILED_TO_COMMIT); 75 | Assert.assertEquals(responses[1].getStatus(), TDHSResponseEnum.ClientStatus.SERVER_ERROR); 76 | Assert.assertEquals(responses[1].getErrorCode(), TDHSResponseEnum.ErrorCode.CLIENT_ERROR_CODE_FAILED_TO_COMMIT); 77 | Assert.assertEquals(responses[2].getStatus(), TDHSResponseEnum.ClientStatus.DB_ERROR); 78 | Assert.assertEquals(responses[2].getDbErrorCode(), 121); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/BetweenTest.java: -------------------------------------------------------------------------------- 1 | package com.taobao.tdhs.client.test; 2 | 3 | import com.taobao.tdhs.client.TDHSClient; 4 | import com.taobao.tdhs.client.TDHSClientImpl; 5 | import com.taobao.tdhs.client.exception.TDHSException; 6 | import com.taobao.tdhs.client.response.TDHSResponse; 7 | import org.junit.Test; 8 | 9 | import java.net.InetSocketAddress; 10 | import java.util.List; 11 | 12 | /** 13 | * @author 文通 14 | * @since 13-3-1 上午10:35 15 | */ 16 | public class BetweenTest { 17 | 18 | @Test 19 | public void testBetween() throws TDHSException { 20 | TDHSClient client = new TDHSClientImpl(new InetSocketAddress("t-wentong-u.local", 9999), 1); 21 | 22 | TDHSResponse r = client.query().use("test").select("id", "v", "i").from("test").where().fields("i") 23 | .between(new String[]{"2"}, 24 | new String[]{"5"}).and().field("i").not("2").and().field("i").not("5").get(); 25 | 26 | List> fieldData = r.getFieldData(); 27 | for (List fd : fieldData) { 28 | for (String v : fd) { 29 | System.out.print(v + " "); 30 | } 31 | System.out.print("\n"); 32 | } 33 | client.shutdown(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/CharsetTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon.FindFlag; 15 | import com.taobao.tdhs.client.exception.TDHSException; 16 | import com.taobao.tdhs.client.response.TDHSResponse; 17 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 18 | import junit.framework.Assert; 19 | import org.junit.Test; 20 | 21 | /** 22 | * 23 | * @author yuanfeng.mc 24 | * 25 | */ 26 | public class CharsetTest extends TestBase{ 27 | private final String db = "unit_test"; 28 | private final String table = "unit_test_utf8"; 29 | private final String[] fields = { "id", "name", "level" }; 30 | 31 | @Test 32 | public void testDifferentCharset() throws TDHSException { 33 | try { 34 | client.setCharsetName("gbk"); 35 | 36 | TDHSResponse r = client.insert(db, table, fields, new String[] { 37 | "999", "中文", "999" }); 38 | 39 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 40 | 41 | r = client.get(db, table, null, fields, 42 | new String[][] { { "999" } }); 43 | 44 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 45 | Assert.assertEquals("", r.getFieldData().get(0).get(1)); 46 | 47 | client.setCharsetName("utf8"); 48 | 49 | } finally { 50 | TDHSResponse r = client.delete(db, table, null, 51 | new String[][] { { "999" } }, FindFlag.TDHS_EQ, 0, 1, null); 52 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 53 | Assert.assertEquals("1", r.getFieldData().get(0).get(0)); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/ClientDeleteExceptionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import com.taobao.tdhs.client.common.TDHSCommon.FindFlag; 18 | import com.taobao.tdhs.client.exception.TDHSException; 19 | import com.taobao.tdhs.client.request.Filter; 20 | 21 | public class ClientDeleteExceptionTest extends TestBase { 22 | @Test 23 | public void testNullProperty() throws TDHSException { 24 | try { 25 | client.delete(db, table, null, null, FindFlag.TDHS_EQ, -1, -1, null); 26 | } catch (Exception e) { 27 | Assert.assertEquals("key can't be missing!", e.getMessage()); 28 | } 29 | 30 | try { 31 | client.delete(db, table, null, new String[0][], FindFlag.TDHS_EQ, 32 | -1, -1, null); 33 | } catch (Exception e) { 34 | Assert.assertEquals("key can't be missing!", e.getMessage()); 35 | } 36 | 37 | try { 38 | client.delete(db, table, null, new String[1][0], FindFlag.TDHS_EQ, 39 | -1, -1, null); 40 | } catch (Exception e) { 41 | Assert.assertEquals("key can't be empty!", e.getMessage()); 42 | } 43 | 44 | try { 45 | client.delete(db, table, null, new String[1][0], FindFlag.TDHS_EQ, 46 | -1, -1, new Filter[0]); 47 | } catch (Exception e) { 48 | Assert.assertEquals("key can't be empty!", e.getMessage()); 49 | } 50 | } 51 | 52 | @Test 53 | public void testNull() throws TDHSException { 54 | try { 55 | client.delete(null); 56 | } catch (Exception e) { 57 | Assert.assertEquals("get is null!", e.getMessage()); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/ClientInsertExceptionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import com.taobao.tdhs.client.common.TDHSCommon.FindFlag; 18 | import com.taobao.tdhs.client.exception.TDHSException; 19 | import com.taobao.tdhs.client.response.TDHSResponse; 20 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 21 | 22 | public class ClientInsertExceptionTest extends TestBase { 23 | @Test 24 | public void testNullProperty() throws TDHSException { 25 | try { 26 | client.insert(db, table, null, null); 27 | } catch (Exception e) { 28 | Assert.assertEquals("field can't be empty!", e.getMessage()); 29 | } 30 | 31 | try { 32 | client.insert(db, table, new String[0], null); 33 | } catch (Exception e) { 34 | Assert.assertEquals("field can't be empty!", e.getMessage()); 35 | } 36 | 37 | try { 38 | TDHSResponse r = client.insert(db, table, 39 | new String[] { fields[2] }, new String[] { "0" }); 40 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 41 | } catch (Exception e) { 42 | Assert.assertEquals("field's size not match values's size", 43 | e.getMessage()); 44 | } finally { 45 | client.delete(db, table, null, new String[][] { { "0" } }, 46 | FindFlag.TDHS_EQ, 0, 1, null); 47 | } 48 | } 49 | 50 | @Test 51 | public void testNull() throws TDHSException { 52 | try { 53 | client.insert(null); 54 | } catch (Exception e) { 55 | Assert.assertEquals("insert is null!", e.getMessage()); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/ClientTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import org.junit.Test; 15 | 16 | /** 17 | *

18 | * 创建客户端 19 | *

20 | *

21 | *

    22 | *
  1. 正常创建
  2. 23 | *
  3. 不正常IP创建
  4. 24 | *
25 | *

26 | * 27 | * @author yuanfeng.mc 28 | * 29 | */ 30 | public class ClientTest { 31 | @Test 32 | public void testErrorCreateClient() { 33 | // TDHSClient c = null; 34 | // try { 35 | // c = new TDHSClientImpl(new InetSocketAddress("这不是个IP地址", 9999), 1, 36 | // 1, false, 1); 37 | // } catch (TDHSException e) { 38 | // Assert.assertEquals("connect time out", e.getMessage()); 39 | // } finally { 40 | // if (c != null) { 41 | // c.shutdown(); 42 | // } 43 | // } 44 | } 45 | 46 | @Test 47 | public void testCreateErrorClient() { 48 | // TDHSClient c = null; 49 | // try { 50 | // c = new TDHSClientImpl(new InetSocketAddress("这不是个IP地址", 9999), 51 | // -10); 52 | // } catch (Exception e) { 53 | // Assert.assertEquals("connectionNumber must be positive!", 54 | // e.getMessage()); 55 | // } finally { 56 | // if (c != null) { 57 | // c.shutdown(); 58 | // } 59 | // } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/ClientUpdateExceptionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import com.taobao.tdhs.client.request.ValueEntry; 15 | import org.junit.Assert; 16 | import org.junit.Test; 17 | 18 | import com.taobao.tdhs.client.common.TDHSCommon.FindFlag; 19 | import com.taobao.tdhs.client.exception.TDHSException; 20 | import com.taobao.tdhs.client.response.TDHSResponse; 21 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 22 | 23 | public class ClientUpdateExceptionTest extends TestBase { 24 | @Test 25 | public void testNullUpdateEntry() throws TDHSException { 26 | try { 27 | client.update("a", "b", "c", new String[] { "d" }, null, 28 | new String[][] { { "e" } }, FindFlag.TDHS_EQ, 0, 100, null); 29 | } catch (Exception e) { 30 | Assert.assertEquals("field's size not match updateEntries's size", 31 | e.getMessage()); 32 | } 33 | 34 | try { 35 | client.update("a", "b", "c", new String[] { "d" }, 36 | new ValueEntry[0], new String[][] { { "e" } }, 37 | FindFlag.TDHS_EQ, 0, 100, null); 38 | } catch (Exception e) { 39 | Assert.assertEquals("field's size not match updateEntries's size", 40 | e.getMessage()); 41 | } 42 | 43 | TDHSResponse r = client.update("a", "b", "c", new String[] { "d" }, 44 | new ValueEntry[1], new String[][] { { "e" } }, 45 | FindFlag.TDHS_EQ, 0, 100, null); 46 | Assert.assertEquals(ClientStatus.BAD_REQUEST, r.getStatus()); 47 | } 48 | 49 | @Test 50 | public void testNullUpdate() throws TDHSException { 51 | try { 52 | client.update(null); 53 | } catch (IllegalArgumentException e) { 54 | Assert.assertEquals("update is null!", e.getMessage()); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/CountTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon; 15 | import com.taobao.tdhs.client.exception.TDHSException; 16 | import com.taobao.tdhs.client.request.Get; 17 | import com.taobao.tdhs.client.request.TableInfo; 18 | import com.taobao.tdhs.client.response.TDHSResponse; 19 | import com.taobao.tdhs.client.response.TDHSResponseEnum; 20 | import junit.framework.Assert; 21 | import org.junit.Test; 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-3-28 下午5:41 26 | */ 27 | public class CountTest extends TestBase { 28 | 29 | private final String db = "unit_test"; 30 | private final String table = "unit_test_data"; 31 | private final String[] fields = {"id", "name", "level"}; 32 | 33 | @Test 34 | public void testTenThousand() throws TDHSException { 35 | TableInfo tableInfo = new TableInfo(db, table, null, fields); 36 | Get get = new Get(tableInfo, new String[][]{{"-1"}}, 37 | TDHSCommon.FindFlag.TDHS_GE, 0, 10000); 38 | TDHSResponse r = client.count(get); 39 | Assert.assertEquals(TDHSResponseEnum.ClientStatus.OK, r.getStatus()); 40 | Assert.assertEquals(1, r.getFieldData().size()); 41 | Assert.assertEquals("10000", r.getFieldData().get(0).get(0)); 42 | } 43 | 44 | @Test 45 | public void testHundredThousand() throws TDHSException { 46 | TableInfo tableInfo = new TableInfo(db, table, null, 47 | new String[]{fields[0]}); 48 | Get get = new Get(tableInfo, new String[][]{{"-1"}}, 49 | TDHSCommon.FindFlag.TDHS_GE, 0, 100000); 50 | TDHSResponse r = client.count(get); 51 | Assert.assertEquals(TDHSResponseEnum.ClientStatus.OK, r.getStatus()); 52 | Assert.assertEquals(1, r.getFieldData().size()); 53 | Assert.assertEquals("100000", r.getFieldData().get(0).get(0)); 54 | } 55 | 56 | @Test 57 | public void testCustom() throws TDHSException { 58 | TDHSResponse r = client.query().use(db).from(table).where().lessEqual("9898").count(); 59 | Assert.assertEquals(TDHSResponseEnum.ClientStatus.OK, r.getStatus()); 60 | Assert.assertEquals(1, r.getFieldData().size()); 61 | Assert.assertEquals("9898", r.getFieldData().get(0).get(0)); 62 | } 63 | 64 | @Test 65 | public void testAllCustom() throws TDHSException { 66 | TDHSResponse r = client.query().use(db).from(table).where().lessEqual("1989800").count(); 67 | Assert.assertEquals(TDHSResponseEnum.ClientStatus.OK, r.getStatus()); 68 | Assert.assertEquals(1, r.getFieldData().size()); 69 | Assert.assertEquals("100000", r.getFieldData().get(0).get(0)); 70 | } 71 | 72 | @Test 73 | public void testCustom2() throws TDHSException { 74 | TDHSResponse r = client.query().use(db).from(table).where().lessEqual("1989800").and().field("id").greaterThan( 75 | "1000").count(); 76 | Assert.assertEquals(TDHSResponseEnum.ClientStatus.OK, r.getStatus()); 77 | Assert.assertEquals(1, r.getFieldData().size()); 78 | Assert.assertEquals("99000", r.getFieldData().get(0).get(0)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/DataTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import com.taobao.tdhs.client.common.TDHSCommon.FindFlag; 15 | import com.taobao.tdhs.client.exception.TDHSException; 16 | import com.taobao.tdhs.client.request.Get; 17 | import com.taobao.tdhs.client.request.TableInfo; 18 | import com.taobao.tdhs.client.response.TDHSResponse; 19 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 20 | import junit.framework.Assert; 21 | import org.junit.Test; 22 | 23 | public class DataTest extends TestBase { 24 | private final String db = "unit_test"; 25 | private final String table = "unit_test_data"; 26 | private final String[] fields = {"id", "name", "level"}; 27 | 28 | @Test 29 | public void testTenThousand() throws TDHSException { 30 | TableInfo tableInfo = new TableInfo(db, table, null, fields); 31 | Get get = new Get(tableInfo, new String[][]{{"-1"}}, 32 | FindFlag.TDHS_GE, 0, 10000); 33 | TDHSResponse r = client.get(get); 34 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 35 | Assert.assertEquals(10000, r.getFieldData().size()); 36 | } 37 | 38 | @Test 39 | public void testHundredThousand() throws TDHSException { 40 | TableInfo tableInfo = new TableInfo(db, table, null, 41 | new String[]{fields[0]}); 42 | Get get = new Get(tableInfo, new String[][]{{"-1"}}, 43 | FindFlag.TDHS_GE, 0, 100000); 44 | TDHSResponse r = client.get(get); 45 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 46 | Assert.assertEquals(100000, r.getFieldData().size()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/EasyDeleteTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import com.taobao.tdhs.client.exception.TDHSException; 18 | import com.taobao.tdhs.client.response.TDHSResponse; 19 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 20 | 21 | public class EasyDeleteTest extends TestBase { 22 | private void prepare() throws TDHSException { 23 | TDHSResponse r = client.insert().use(db).from(table) 24 | .value(fields[0], "100").value(fields[1], "name_100") 25 | .value(fields[2], "1000").insert(); 26 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 27 | 28 | client.insert().use(db).from(table).value(fields[0], "200") 29 | .value(fields[1], "name_200").value(fields[2], "2000").insert(); 30 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 31 | 32 | client.insert().use(db).from(table).value(fields[0], "300") 33 | .value(fields[1], "name_300").value(fields[2], "3000").insert(); 34 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 35 | 36 | client.insert().use(db).from(table).value(fields[0], "400") 37 | .value(fields[1], "name_400").value(fields[2], "4000").insert(); 38 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 39 | 40 | client.insert().use(db).from(table).value(fields[0], "500") 41 | .value(fields[1], "name_500").value(fields[2], "5000").insert(); 42 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 43 | } 44 | 45 | @Test 46 | public void testNoRecords() throws TDHSException { 47 | TDHSResponse r = client.query().use(db).from(table).where() 48 | .in(new String[] { "1", "2", "3" }).delete(); 49 | Assert.assertEquals(ClientStatus.NOT_FOUND, r.getStatus()); 50 | } 51 | 52 | @Test 53 | public void testPartRecords() throws TDHSException { 54 | TDHSResponse r = client.query().use(db).from(table).where() 55 | .in(new String[] { "100", "200", "3" }).delete(); 56 | Assert.assertEquals(ClientStatus.NOT_FOUND, r.getStatus()); 57 | } 58 | 59 | @Test 60 | public void testAllRecords() throws TDHSException { 61 | prepare(); 62 | 63 | TDHSResponse r = client.query().use(db).from(table).select(fields) 64 | .where().in(new String[] { "100" }).delete(); 65 | Assert.assertEquals("1", r.getFieldData().get(0).get(0)); 66 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 67 | 68 | r = client.query().use(db).from(table).select(fields).where() 69 | .greaterThan("100").delete(); 70 | Assert.assertEquals("4", r.getFieldData().get(0).get(0)); 71 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/EasyInsertTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import com.taobao.tdhs.client.common.TDHSCommon.FindFlag; 18 | import com.taobao.tdhs.client.exception.TDHSException; 19 | import com.taobao.tdhs.client.response.TDHSResponse; 20 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 21 | 22 | public class EasyInsertTest extends TestBase { 23 | /** 24 | * 此处自动把非数字字符串转换0,具体需要在数据库中my.ini中配置 25 | * sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 26 | */ 27 | @Test 28 | public void testIllegalValue() throws TDHSException { 29 | TDHSResponse r = client.insert().use(db).from(table) 30 | .value(fields[0], "asd").value(fields[1], "31") 31 | .value(fields[2], "mmm").insert(); 32 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 33 | 34 | r = client.delete(db, table, null, new String[][] { { "0" } }, 35 | FindFlag.TDHS_EQ, 0, 100, null); 36 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 37 | } 38 | 39 | /** 40 | * 此处自动把非数字字符串转换0,具体需要在数据库中my.ini中配置 41 | * sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 42 | */ 43 | @Test 44 | public void testMissField() throws TDHSException { 45 | TDHSResponse r = client.insert().use(db).from(table) 46 | .value(fields[0], "1").value(fields[2], "10").insert(); 47 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 48 | 49 | r = client.delete(db, table, null, new String[][] { { "1" } }, 50 | FindFlag.TDHS_EQ, 0, 100, null); 51 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 52 | } 53 | 54 | @Test 55 | public void testNullValue() throws TDHSException { 56 | TDHSResponse r = client.insert().use(db).from(table) 57 | .value(fields[0], (String) null).insert(); 58 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 59 | 60 | r = client.delete(db, table, null, new String[][] { { "0" } }, 61 | FindFlag.TDHS_EQ, 0, 100, null); 62 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 63 | 64 | r = client.insert().use(db).from(table).value(fields[0], "").insert(); 65 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 66 | 67 | r = client.delete(db, table, null, new String[][] { { "0" } }, 68 | FindFlag.TDHS_EQ, 0, 100, null); 69 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 70 | } 71 | 72 | @Test 73 | public void testNullField() throws TDHSException { 74 | TDHSResponse r = client.insert().use(db).from(table).value(null, "abc") 75 | .insert(); 76 | Assert.assertEquals(ClientStatus.NOT_FOUND, r.getStatus()); 77 | 78 | client.insert().use(db).from(table).value("", "abc").insert(); 79 | Assert.assertEquals(ClientStatus.NOT_FOUND, r.getStatus()); 80 | } 81 | 82 | @Test 83 | public void testSpecialChar() throws TDHSException { 84 | TDHSResponse r = client 85 | .insert() 86 | .use(db) 87 | .from(table) 88 | .value("~!@#$%^&*()_+-={}[]<>?,./:;\\\"'", 89 | "~!@#$%^&*()_+-={}[]<>?,./:;\\\"'").insert(); 90 | Assert.assertEquals(ClientStatus.NOT_FOUND, r.getStatus()); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/EasyUpdateTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import com.taobao.tdhs.client.exception.TDHSException; 18 | import com.taobao.tdhs.client.response.TDHSResponse; 19 | import com.taobao.tdhs.client.response.TDHSResponseEnum.ClientStatus; 20 | 21 | public class EasyUpdateTest extends TestBase { 22 | @Test 23 | public void testNoRecords() throws TDHSException { 24 | TDHSResponse r = client.query().use(db).from(table).set().field("name") 25 | .set("ccc").where().equal("1").update(); 26 | Assert.assertEquals("0", r.getFieldData().get(0).get(0)); 27 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 28 | 29 | r = client.query().use(db).from(table).set().field("name").add(1213) 30 | .where().equal("1").update(); 31 | Assert.assertEquals("0", r.getFieldData().get(0).get(0)); 32 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 33 | 34 | r = client.query().use(db).from(table).set().field("name").sub(1213) 35 | .where().equal("1").update(); 36 | Assert.assertEquals("0", r.getFieldData().get(0).get(0)); 37 | Assert.assertEquals(ClientStatus.OK, r.getStatus()); 38 | } 39 | 40 | @Test 41 | public void testNoFields() throws TDHSException { 42 | TDHSResponse r = client.query().use(db).from(table).set() 43 | .field("NoThisFields").set("ccc").where().equal("1").update(); 44 | Assert.assertEquals(ClientStatus.NOT_FOUND, r.getStatus()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/client/test/TestBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.client.test; 13 | 14 | import com.taobao.tdhs.client.TDHSClient; 15 | import com.taobao.tdhs.client.TDHSClientImpl; 16 | import com.taobao.tdhs.client.exception.TDHSException; 17 | import org.junit.AfterClass; 18 | import org.junit.Assert; 19 | import org.junit.BeforeClass; 20 | import org.junit.Ignore; 21 | 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.net.InetSocketAddress; 25 | import java.util.Properties; 26 | 27 | @Ignore 28 | public class TestBase { 29 | protected static TDHSClient client; 30 | protected static String db; 31 | protected static String table; 32 | protected static String index; 33 | protected static String[] fields; 34 | 35 | private static Properties global; 36 | 37 | @BeforeClass 38 | public static void init() throws IOException { 39 | if (global == null || client == null) { 40 | global = new Properties(); 41 | InputStream is = null; 42 | try { 43 | is = ClassLoader.getSystemResourceAsStream("global.properties"); 44 | global.load(is); 45 | 46 | db = global.getProperty("db.name"); 47 | table = global.getProperty("table.name"); 48 | index = global.getProperty("index.name"); 49 | fields = global.getProperty("field.name").split(","); 50 | } finally { 51 | if (is != null) { 52 | is.close(); 53 | } 54 | } 55 | 56 | try { 57 | client = new TDHSClientImpl(new InetSocketAddress(global.getProperty("server.host"), 58 | Integer.parseInt(global.getProperty("server.port", "9999"))), 1, 3000, false, 3000); 59 | } catch (TDHSException e) { 60 | Assert.fail("Init exception:" + e.getMessage()); 61 | } 62 | } 63 | } 64 | 65 | @AfterClass 66 | public static void destory() { 67 | if (client != null) { 68 | client.shutdown(); 69 | client = null; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/NonRegisteringDriverTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import java.util.Properties; 18 | 19 | /** 20 | * @author 文通 21 | * @since 12-3-7 上午10:15 22 | */ 23 | public class NonRegisteringDriverTest { 24 | 25 | 26 | @Test 27 | public void testParseURLDone() throws Exception { 28 | NonRegisteringDriver driver = new NonRegisteringDriver(); 29 | Properties properties = driver.parseURL("jdbc:tdhs://1.2.3.4/testdb?a=1&b=2", null); 30 | Assert.assertEquals(5, properties.size()); 31 | Assert.assertEquals("1.2.3.4", properties.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY)); 32 | Assert.assertEquals("9999", properties.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY)); 33 | Assert.assertEquals("testdb", properties.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY)); 34 | Assert.assertEquals("1", properties.getProperty("a")); 35 | Assert.assertEquals("2", properties.getProperty("b")); 36 | } 37 | 38 | @Test 39 | public void testParseURLDoneWithPort() throws Exception { 40 | NonRegisteringDriver driver = new NonRegisteringDriver(); 41 | Properties properties = driver.parseURL("jdbc:tdhs://1.2.3.4:8888/testdb?a=1&b=2", null); 42 | Assert.assertEquals(5, properties.size()); 43 | Assert.assertEquals("1.2.3.4", properties.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY)); 44 | Assert.assertEquals("8888", properties.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY)); 45 | Assert.assertEquals("testdb", properties.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY)); 46 | Assert.assertEquals("1", properties.getProperty("a")); 47 | Assert.assertEquals("2", properties.getProperty("b")); 48 | } 49 | 50 | @Test 51 | public void testParseURLDoneWithPortAndDefault() throws Exception { 52 | NonRegisteringDriver driver = new NonRegisteringDriver(); 53 | Properties defaultProperties = new Properties(); 54 | defaultProperties.put("c", "3"); 55 | defaultProperties.put("d", "4"); 56 | Properties properties = driver.parseURL("jdbc:tdhs://1.2.3.4:8888/testdb?a=1&b=2", defaultProperties); 57 | Assert.assertEquals(5, properties.size()); 58 | Assert.assertEquals("1.2.3.4", properties.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY)); 59 | Assert.assertEquals("8888", properties.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY)); 60 | Assert.assertEquals("testdb", properties.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY)); 61 | Assert.assertEquals("1", properties.getProperty("a")); 62 | Assert.assertEquals("2", properties.getProperty("b")); 63 | Assert.assertEquals("3", properties.getProperty("c")); 64 | Assert.assertEquals("4", properties.getProperty("d")); 65 | } 66 | 67 | @Test 68 | public void testParseURLDoneWithNone() throws Exception { 69 | NonRegisteringDriver driver = new NonRegisteringDriver(); 70 | Properties properties = driver.parseURL("jdbc:tdhs://", null); 71 | Assert.assertEquals(2, properties.size()); 72 | Assert.assertEquals("localhost", properties.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY)); 73 | Assert.assertEquals("9999", properties.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY)); 74 | Assert.assertEquals(null, properties.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY)); 75 | 76 | } 77 | 78 | @Test 79 | public void testParseURLError() throws Exception { 80 | NonRegisteringDriver driver = new NonRegisteringDriver(); 81 | Properties properties = driver.parseURL(null, null); 82 | Assert.assertNull(properties); 83 | properties = driver.parseURL("jdbc:mysql://1.2.3.4:8888/testdb?a=1&b=2", null); 84 | Assert.assertNull(properties); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/SimplePooledTDHSDataSourceTest.java: -------------------------------------------------------------------------------- 1 | package com.taobao.tdhs.jdbc; 2 | 3 | import junit.framework.Assert; 4 | import org.junit.BeforeClass; 5 | import org.junit.Test; 6 | 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.lang.reflect.Field; 10 | import java.sql.Connection; 11 | import java.util.Properties; 12 | import java.util.concurrent.atomic.AtomicLong; 13 | 14 | /** 15 | * @author 文通 16 | * @since 12-6-26 下午5:28 17 | */ 18 | public class SimplePooledTDHSDataSourceTest { 19 | private static int tdhsPort; 20 | private static String host; 21 | 22 | 23 | @BeforeClass 24 | public static void _init() throws IOException { 25 | Properties global = new Properties(); 26 | InputStream is = null; 27 | try { 28 | is = ClassLoader.getSystemResourceAsStream("global.properties"); 29 | global.load(is); 30 | 31 | tdhsPort = Integer.parseInt(global.getProperty("server.port")); 32 | host = global.getProperty("server.host"); 33 | } finally { 34 | if (is != null) { 35 | is.close(); 36 | } 37 | } 38 | 39 | } 40 | 41 | 42 | @Test 43 | public void testGetConnection() throws Exception { 44 | String url = "jdbc:tdhs://" + host + ":" + tdhsPort + "/jdbc_test"; 45 | SimplePooledTDHSDataSource source = new SimplePooledTDHSDataSource(url); 46 | 47 | Field fieldUrl = SimplePooledTDHSDataSource.class.getDeclaredField("url"); 48 | fieldUrl.setAccessible(true); 49 | Assert.assertEquals(url, fieldUrl.get(source)); 50 | 51 | Field fieldCount = SimplePooledTDHSDataSource.class.getDeclaredField("count"); 52 | fieldCount.setAccessible(true); 53 | 54 | Field fieldLastOne = SimplePooledTDHSDataSource.class.getDeclaredField("lastOne"); 55 | fieldLastOne.setAccessible(true); 56 | 57 | Assert.assertEquals(0, ((AtomicLong) fieldCount.get(source)).get()); 58 | Assert.assertNull(fieldLastOne.get(source)); 59 | 60 | Connection connection = source.getConnection(); 61 | Assert.assertEquals(1, ((AtomicLong) fieldCount.get(source)).get()); 62 | Assert.assertNull(fieldLastOne.get(source)); 63 | 64 | connection.close(); 65 | Assert.assertEquals(0, ((AtomicLong) fieldCount.get(source)).get()); 66 | Assert.assertNotNull(fieldLastOne.get(source)); 67 | 68 | connection = source.getConnection(); 69 | Assert.assertEquals(1, ((AtomicLong) fieldCount.get(source)).get()); 70 | Assert.assertNull(fieldLastOne.get(source)); 71 | 72 | connection.close(); 73 | Assert.assertEquals(0, ((AtomicLong) fieldCount.get(source)).get()); 74 | Assert.assertNotNull(fieldLastOne.get(source)); 75 | 76 | Connection connection1 = source.getConnection(); 77 | 78 | Assert.assertEquals(1, ((AtomicLong) fieldCount.get(source)).get()); 79 | Assert.assertNull(fieldLastOne.get(source)); 80 | Assert.assertEquals(connection, connection1); 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/sqlparser/HintStructTest.java: -------------------------------------------------------------------------------- 1 | package com.taobao.tdhs.jdbc.sqlparser; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | 9 | /** 10 | * @author 文通 11 | * @since 12-7-12 上午11:28 12 | */ 13 | public class HintStructTest { 14 | @Test 15 | public void testAnalyzeHint1() throws Exception { 16 | HintStruct h = new HintStruct("/*tdhs:<213>[ind(a,b)]*/"); 17 | h.AnalyzeHint(); 18 | assertEquals(213, h.getHash()); 19 | assertEquals("ind", h.getIndexName()); 20 | assertArrayEquals(new String[]{"a", "b"}, h.getListIndexColumns().toArray(new String[2])); 21 | 22 | } 23 | 24 | @Test 25 | public void testAnalyzeHint2() throws Exception { 26 | HintStruct h = new HintStruct("/*tdhs:<21ad3>[ind(a,b)]*/"); 27 | h.AnalyzeHint(); 28 | assertEquals(0, h.getHash()); 29 | assertEquals("ind", h.getIndexName()); 30 | assertArrayEquals(new String[]{"a", "b"}, h.getListIndexColumns().toArray(new String[2])); 31 | 32 | } 33 | 34 | @Test 35 | public void testAnalyzeHint3() throws Exception { 36 | HintStruct h = new HintStruct("/*tdhs:[ind(a,b)]*/"); 37 | h.AnalyzeHint(); 38 | assertEquals(0, h.getHash()); 39 | assertEquals("ind", h.getIndexName()); 40 | assertArrayEquals(new String[]{"a", "b"}, h.getListIndexColumns().toArray(new String[2])); 41 | 42 | } 43 | 44 | @Test 45 | public void testAnalyzeHint4() throws Exception { 46 | HintStruct h = new HintStruct("/*tdhs:<123>*/"); 47 | h.AnalyzeHint(); 48 | assertEquals(123, h.getHash()); 49 | assertEquals("", h.getIndexName()); 50 | assertEquals(0, h.getListIndexColumns().size()); 51 | 52 | } 53 | 54 | @Test 55 | public void testAnalyzeHint5() throws Exception { 56 | HintStruct h = new HintStruct("/*tdhs:<123>asdfasdfasdf*/"); 57 | h.AnalyzeHint(); 58 | assertTrue(StringUtils.isNotBlank(h.getErrmsg())); 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/sqlparser/ParseSQLTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.sqlparser; 13 | 14 | import org.junit.Test; 15 | 16 | 17 | public class ParseSQLTest { 18 | 19 | private void print(ParseSQL ps) { 20 | System.out.println(ps.getSql()); 21 | System.out.println(ps.getTableName()); 22 | System.out.println(ps.getErrmsg()); 23 | if (ps.getSqlType() != SQLType.INSERT) { 24 | System.out.println(ps.getHint()); 25 | System.out.println(ps.getSortMethod()); 26 | System.out.println(ps.getOrderByColumn()); 27 | System.out.println(ps.getListOperationStructs()); 28 | } 29 | if (ps.getSqlType() == SQLType.INSERT) { 30 | System.out.println(ps.getInsertEntries()); 31 | } 32 | if (ps.getSqlType() == SQLType.SELECT) { 33 | System.out.println(ps.getColumns()); 34 | System.out.println("start:" + ps.getLimitOffset()); 35 | System.out.println("limit:" + ps.getLimit()); 36 | 37 | 38 | } 39 | if (ps.getSqlType() == SQLType.UPDATE) { 40 | System.out.println(ps.getUpdateEntries()); 41 | 42 | } 43 | System.out.print("\n\n"); 44 | } 45 | 46 | @Test 47 | public void test1() { 48 | String sql = 49 | "select/* tdhs:[idx_ab(a, b)]*/ a as a1,b from db.test where id = 1 and a in (1,2,\"3\") and b is null order by a limit 1"; 50 | ParseSQL parseSQL = new ParseSQL(sql); 51 | parseSQL.sqlDispatch(); 52 | print(parseSQL); 53 | } 54 | 55 | @Test 56 | public void test2() { 57 | String sql = "delete/* tdhs:[idx_ab(a, b)]*/ from db.test where id = 1 and status=2 order by id,status desc"; 58 | ParseSQL parseSQL = new ParseSQL(sql); 59 | parseSQL.sqlDispatch(); 60 | print(parseSQL); 61 | } 62 | 63 | @Test 64 | public void test3() { 65 | String sql = 66 | "update/* tdhs:[idx_ab(a, b)]*/db.test set xxx='bbb' where id = 1 and status=2 and type=5 order by a asc"; 67 | ParseSQL parseSQL = new ParseSQL(sql); 68 | parseSQL.sqlDispatch(); 69 | print(parseSQL); 70 | } 71 | 72 | @Test 73 | public void test4() { 74 | String sql = "select/* tdhs:[idx_ab(a, b)]*/ a,b from db.test as t where t.id = 1 order by a"; 75 | ParseSQL parseSQL = new ParseSQL(sql); 76 | parseSQL.sqlDispatch(); 77 | print(parseSQL); 78 | } 79 | 80 | @Test 81 | public void test5() { 82 | String sql = "insert into test(a,b) values(\';1\',2)"; 83 | ParseSQL parseSQL = new ParseSQL(sql); 84 | parseSQL.sqlDispatch(); 85 | print(parseSQL); 86 | } 87 | 88 | @Test 89 | public void test7() { 90 | String sql = "select user_nick as unick,b from db.test as t where t.id = 1 order by a"; 91 | ParseSQL parseSQL = new ParseSQL(sql); 92 | parseSQL.sqlDispatch(); 93 | print(parseSQL); 94 | } 95 | 96 | @Test 97 | public void testUpdateSetColumns3() { 98 | String sql = "update table1 set a='=abc',b='danc\\'hen,=efk',ok=5 where id=4"; 99 | ParseSQL parseSQL = new ParseSQL(sql); 100 | parseSQL.sqlDispatch(); 101 | System.out.println(parseSQL.getUpdateEntries()); 102 | } 103 | 104 | @Test 105 | public void testUpdate4() { 106 | String sql = 107 | "update /*tdhs:<2>*/notify_bytes_msg_normal_2 set committed='1' where message_id='1C1A1FD16A9323B0D9560BD9B6888790'"; 108 | ParseSQL parseSQL = new ParseSQL(sql); 109 | parseSQL.sqlDispatch(); 110 | System.out.println(parseSQL.getHint()); 111 | System.out.println(parseSQL.getUpdateEntries()); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/ErrorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test; 13 | 14 | import com.taobao.tdhs.jdbc.exception.TDHSSQLException; 15 | import org.junit.Test; 16 | 17 | import java.sql.Connection; 18 | import java.sql.SQLException; 19 | import java.sql.Statement; 20 | 21 | /** 22 | * @author 文通 23 | * @since 12-3-26 上午10:46 24 | */ 25 | public class ErrorTest extends TestBase { 26 | 27 | public static void execute(Connection connection, String sql) throws SQLException { 28 | Statement statement = connection.createStatement(); 29 | try { 30 | statement.execute(sql); 31 | } finally { 32 | if (statement != null) { 33 | statement.close(); 34 | } 35 | connection.close(); 36 | } 37 | } 38 | 39 | @Test(expected = TDHSSQLException.class) 40 | public void testErrorSQL() throws ClassNotFoundException, SQLException { 41 | execute(getTDHSConnection(), "kill 1"); 42 | } 43 | 44 | 45 | @Test(expected = TDHSSQLException.class) 46 | public void testMissIndexField() throws ClassNotFoundException, SQLException { 47 | execute(getTDHSConnection(), 48 | "select/*tdhs:[idx_user_auction(user_id)]*/ id,user_id,auction_id,auction_name,number,deleted,created,last_modify from orders where user_id =1 and auction_name!=\"Book\" order by auction_id desc;"); 49 | } 50 | 51 | @Test(expected = TDHSSQLException.class) 52 | public void testHaveOr() throws ClassNotFoundException, SQLException { 53 | execute(getTDHSConnection(), 54 | "select id,user_id,auction_id,auction_name,number,deleted,created,last_modify from orders where id>1 and user_id = 1 or auction_id = 1"); 55 | } 56 | 57 | @Test(expected = TDHSSQLException.class) 58 | public void testHaveOr2() throws ClassNotFoundException, SQLException { 59 | execute(getTDHSConnection(), 60 | "select id,user_id,auction_id,auction_name,number,deleted,created,last_modify from orders where id>1 and (user_id = 1 or auction_id = 1)"); 61 | } 62 | 63 | @Test(expected = TDHSSQLException.class) 64 | public void testErrorField() throws ClassNotFoundException, SQLException { 65 | execute(getTDHSConnection(), 66 | "select `id,user_id,auction_id,auction_name,number,deleted,created,last_modify from orders where id>1 "); 67 | } 68 | 69 | @Test(expected = TDHSSQLException.class) 70 | public void testErrorSQL2() throws ClassNotFoundException, SQLException { 71 | execute(getTDHSConnection(), 72 | "select id,user_id,auction_id,auction_name,number,deleted,created,last_modify from orders where id>1 ;select id,user_id,auction_id,auction_name,number,deleted,created,last_modify from orders where id>1 ;"); 73 | } 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/SimpleSelectJDBCTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | import java.sql.Connection; 18 | import java.sql.ResultSet; 19 | import java.sql.SQLException; 20 | import java.sql.Statement; 21 | 22 | /** 23 | * @author 文通 24 | * @since 12-3-20 下午3:47 25 | */ 26 | public class SimpleSelectJDBCTest extends TestBase { 27 | 28 | private static Object[][] data = 29 | {{1, "Kevin", 30, "Coder"}, {2, "Vivian", 30, "Wife"}, {3, "Kitty", 2, "Daughter"}}; 30 | 31 | public static void executeSelect(Connection connection) throws SQLException { 32 | Statement statement = connection.createStatement(); 33 | ResultSet resultSet = null; 34 | try { 35 | boolean r = statement.execute("select p.id,p.name,p.age,p.memo as `m` from person as p where id>0"); 36 | Assert.assertTrue(r); 37 | resultSet = statement.getResultSet(); 38 | int size = 0; 39 | while (resultSet.next()) { 40 | Assert.assertEquals(data[size][0], resultSet.getInt(1)); 41 | Assert.assertEquals(data[size][1], resultSet.getString(2)); 42 | Assert.assertEquals(data[size][2], resultSet.getInt("age")); 43 | Assert.assertEquals(data[size][3], resultSet.getString("m")); 44 | size++; 45 | } 46 | Assert.assertEquals(data.length, size); 47 | } finally { 48 | if (resultSet != null) { 49 | resultSet.close(); 50 | } 51 | if (statement != null) { 52 | statement.close(); 53 | } 54 | connection.close(); 55 | } 56 | } 57 | 58 | public static void executeCount(Connection connection) throws SQLException { 59 | Statement statement = connection.createStatement(); 60 | ResultSet resultSet = null; 61 | try { 62 | boolean r = statement.execute("select count(*) as c from person where id>0"); 63 | Assert.assertTrue(r); 64 | resultSet = statement.getResultSet(); 65 | int size = 0; 66 | while (resultSet.next()) { 67 | Assert.assertEquals(data.length, resultSet.getInt(1)); 68 | Assert.assertEquals(data.length, resultSet.getInt("c")); 69 | size++; 70 | } 71 | Assert.assertEquals(1, size); 72 | } finally { 73 | if (resultSet != null) { 74 | resultSet.close(); 75 | } 76 | if (statement != null) { 77 | statement.close(); 78 | } 79 | connection.close(); 80 | } 81 | } 82 | 83 | 84 | @Test 85 | public void testMySQLGetData() throws ClassNotFoundException, SQLException { 86 | executeSelect(getMySQLConnection()); 87 | } 88 | 89 | @Test 90 | public void testTDHSGetData() throws ClassNotFoundException, SQLException { 91 | executeSelect(getTDHSConnection()); 92 | } 93 | 94 | @Test 95 | public void testMySQLGetCount() throws ClassNotFoundException, SQLException { 96 | executeCount(getMySQLConnection()); 97 | } 98 | 99 | @Test 100 | public void testTDHSGetCount() throws ClassNotFoundException, SQLException { 101 | executeCount(getTDHSConnection()); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/TestBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test; 13 | 14 | import org.junit.BeforeClass; 15 | import org.junit.Ignore; 16 | 17 | import java.io.IOException; 18 | import java.io.InputStream; 19 | import java.sql.Connection; 20 | import java.sql.DriverManager; 21 | import java.sql.SQLException; 22 | import java.sql.Statement; 23 | import java.util.Properties; 24 | 25 | /** 26 | * @author 文通 27 | * @since 12-3-20 下午4:50 28 | */ 29 | @Ignore 30 | public class TestBase { 31 | 32 | private static Properties global; 33 | 34 | private static int mysqlPort; 35 | 36 | private static int tdhsPort; 37 | 38 | private static String host; 39 | 40 | @BeforeClass 41 | public static void _init() throws IOException { 42 | if (global == null) { 43 | global = new Properties(); 44 | InputStream is = null; 45 | try { 46 | is = ClassLoader.getSystemResourceAsStream("global.properties"); 47 | global.load(is); 48 | 49 | mysqlPort = Integer.parseInt(global.getProperty("mysql.port")); 50 | tdhsPort = Integer.parseInt(global.getProperty("server.port")); 51 | host = global.getProperty("server.host"); 52 | } finally { 53 | if (is != null) { 54 | is.close(); 55 | } 56 | } 57 | } 58 | } 59 | 60 | public static Connection getMySQLConnection() throws SQLException, 61 | java.lang.ClassNotFoundException { 62 | String url = "jdbc:mysql://" + host + ":" + mysqlPort + "/jdbc_test"; 63 | Class.forName("com.mysql.jdbc.Driver"); 64 | String userName = "test"; 65 | String password = "test"; 66 | return DriverManager.getConnection(url, userName, password); 67 | } 68 | 69 | public static Connection getTDHSConnection() throws SQLException, 70 | java.lang.ClassNotFoundException { 71 | String url = "jdbc:tdhs://" + host + ":" + tdhsPort + "/jdbc_test"; 72 | Class.forName("com.taobao.tdhs.jdbc.Driver"); 73 | return DriverManager.getConnection(url, null, null); 74 | } 75 | 76 | public static void truncate(String table) throws ClassNotFoundException, SQLException { 77 | Connection connection = getMySQLConnection(); 78 | Statement statement = connection.createStatement(); 79 | statement.execute("set global tdh_socket_cache_table_on =0;"); //percona 5.5的truncate会重置自增id导致会lock表的meta 80 | statement.execute("truncate table " + table + ";"); 81 | statement.execute("set global tdh_socket_cache_table_on =1;"); 82 | statement.close(); 83 | connection.close(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/MySQLDataSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis; 13 | 14 | import org.junit.Ignore; 15 | 16 | import javax.sql.DataSource; 17 | import java.io.PrintWriter; 18 | import java.sql.Connection; 19 | import java.sql.SQLException; 20 | import java.sql.SQLFeatureNotSupportedException; 21 | import java.util.logging.Logger; 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-3-23 上午10:42 26 | */ 27 | @Ignore 28 | public class MySQLDataSource extends com.taobao.tdhs.jdbc.test.TestBase implements DataSource { 29 | public Connection getConnection() throws SQLException { 30 | try { 31 | _init(); 32 | return getMySQLConnection(); 33 | } catch (Exception e) { 34 | throw new SQLException(e); 35 | } 36 | } 37 | 38 | public Connection getConnection(String username, String password) throws SQLException { 39 | return getConnection(); 40 | } 41 | 42 | public PrintWriter getLogWriter() throws SQLException { 43 | return System.console().writer(); 44 | } 45 | 46 | public void setLogWriter(PrintWriter out) throws SQLException { 47 | } 48 | 49 | public void setLoginTimeout(int seconds) throws SQLException { 50 | } 51 | 52 | public int getLoginTimeout() throws SQLException { 53 | return 0; 54 | } 55 | 56 | public Logger getParentLogger() throws SQLFeatureNotSupportedException { 57 | return null; 58 | } 59 | 60 | public T unwrap(Class iface) throws SQLException { 61 | return null; 62 | } 63 | 64 | public boolean isWrapperFor(Class iface) throws SQLException { 65 | return false; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/SimpleSelectMyBatisTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis; 13 | 14 | import com.taobao.tdhs.jdbc.test.mybatis.mapper.PersonMapper; 15 | import com.taobao.tdhs.jdbc.test.mybatis.vo.Person; 16 | import org.apache.ibatis.session.SqlSession; 17 | import org.junit.Test; 18 | 19 | import java.util.List; 20 | 21 | import static org.junit.Assert.assertEquals; 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-3-23 下午2:18 26 | */ 27 | public class SimpleSelectMyBatisTest extends TestBase { 28 | private static Person[] data = 29 | {new Person(1, "Kevin", 30, "Coder"), new Person(2, "Vivian", 30, "Wife"), 30 | new Person(3, "Kitty", 2, "Daughter")}; 31 | 32 | @Test 33 | public void testSelect1() { 34 | SqlSession tdhsSession = getTDHSSession(); 35 | Person tdhsPerson = tdhsSession.getMapper(PersonMapper.class).selectPerson(2); 36 | assertEquals(data[1], tdhsPerson); 37 | SqlSession mysqlSession = getTDHSSession(); 38 | Person mysqlPerson = mysqlSession.getMapper(PersonMapper.class).selectPerson(2); 39 | assertEquals(mysqlPerson, tdhsPerson); 40 | tdhsSession.close(); 41 | mysqlSession.close(); 42 | } 43 | 44 | @Test 45 | public void testSelect2() { 46 | SqlSession tdhsSession = getTDHSSession(); 47 | Person tdhsPerson = tdhsSession.getMapper(PersonMapper.class).selectPerson(3); 48 | assertEquals(data[2], tdhsPerson); 49 | SqlSession mysqlSession = getTDHSSession(); 50 | Person mysqlPerson = mysqlSession.getMapper(PersonMapper.class).selectPerson(3); 51 | assertEquals(mysqlPerson, tdhsPerson); 52 | tdhsSession.close(); 53 | mysqlSession.close(); 54 | } 55 | 56 | @Test 57 | public void testSelect3() { 58 | SqlSession tdhsSession = getTDHSSession(); 59 | List tdhsPerson = tdhsSession.getMapper(PersonMapper.class).selectPersons(1); 60 | SqlSession mysqlSession = getTDHSSession(); 61 | List mysqlPerson = mysqlSession.getMapper(PersonMapper.class).selectPersons(1); 62 | compareRecord(mysqlPerson, tdhsPerson); 63 | tdhsSession.close(); 64 | mysqlSession.close(); 65 | } 66 | 67 | @Test 68 | public void testSelect4() { 69 | SqlSession tdhsSession = getTDHSSession(); 70 | List tdhsPerson = tdhsSession.getMapper(PersonMapper.class).selectPersons(-1); 71 | SqlSession mysqlSession = getTDHSSession(); 72 | List mysqlPerson = mysqlSession.getMapper(PersonMapper.class).selectPersons(-1); 73 | compareRecord(mysqlPerson, tdhsPerson); 74 | tdhsSession.close(); 75 | mysqlSession.close(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/TDHSDataSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis; 13 | 14 | import org.junit.Ignore; 15 | 16 | import javax.sql.DataSource; 17 | import java.io.PrintWriter; 18 | import java.sql.Connection; 19 | import java.sql.SQLException; 20 | import java.sql.SQLFeatureNotSupportedException; 21 | import java.util.logging.Logger; 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-3-23 上午10:52 26 | */ 27 | @Ignore 28 | public class TDHSDataSource extends com.taobao.tdhs.jdbc.test.TestBase implements DataSource { 29 | public Connection getConnection() throws SQLException { 30 | try { 31 | _init(); 32 | return getTDHSConnection(); 33 | } catch (Exception e) { 34 | throw new SQLException(e); 35 | } 36 | } 37 | 38 | public Connection getConnection(String username, String password) throws SQLException { 39 | return getConnection(); 40 | } 41 | 42 | public PrintWriter getLogWriter() throws SQLException { 43 | return System.console().writer(); 44 | } 45 | 46 | public void setLogWriter(PrintWriter out) throws SQLException { 47 | } 48 | 49 | public void setLoginTimeout(int seconds) throws SQLException { 50 | } 51 | 52 | public int getLoginTimeout() throws SQLException { 53 | return 0; 54 | } 55 | 56 | public Logger getParentLogger() throws SQLFeatureNotSupportedException { 57 | return null; 58 | } 59 | 60 | public T unwrap(Class iface) throws SQLException { 61 | return null; 62 | } 63 | 64 | public boolean isWrapperFor(Class iface) throws SQLException { 65 | return false; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/TestBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis; 13 | 14 | import com.taobao.tdhs.jdbc.test.mybatis.mapper.OrderMapper; 15 | import com.taobao.tdhs.jdbc.test.mybatis.mapper.PersonMapper; 16 | import com.taobao.tdhs.jdbc.test.mybatis.mapper.TestMapper; 17 | import org.apache.ibatis.mapping.Environment; 18 | import org.apache.ibatis.session.Configuration; 19 | import org.apache.ibatis.session.SqlSession; 20 | import org.apache.ibatis.session.SqlSessionFactory; 21 | import org.apache.ibatis.session.SqlSessionFactoryBuilder; 22 | import org.apache.ibatis.transaction.TransactionFactory; 23 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; 24 | import org.junit.Ignore; 25 | 26 | import javax.sql.DataSource; 27 | import java.util.List; 28 | 29 | import static org.junit.Assert.assertEquals; 30 | 31 | /** 32 | * @author 文通 33 | * @since 12-3-23 上午10:32 34 | */ 35 | @Ignore 36 | public abstract class TestBase extends com.taobao.tdhs.jdbc.test.TestBase { 37 | 38 | protected SqlSession getMySQLSession() { 39 | return createSession(new MySQLDataSource()); 40 | } 41 | 42 | protected SqlSession getTDHSSession() { 43 | return createSession(new TDHSDataSource()); 44 | } 45 | 46 | 47 | private SqlSession createSession(DataSource dataSource) { 48 | TransactionFactory transactionFactory = new JdbcTransactionFactory(); 49 | Environment environment = new Environment("development", transactionFactory, dataSource); 50 | Configuration configuration = new Configuration(environment); 51 | configuration.addMapper(PersonMapper.class); 52 | configuration.addMapper(TestMapper.class); 53 | configuration.addMapper(OrderMapper.class); 54 | SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); 55 | return sqlSessionFactory.openSession(); 56 | } 57 | 58 | protected void compareRecord(List mysqlRecord, List tdhsRrcord) { 59 | assertEquals(mysqlRecord.size(), tdhsRrcord.size()); 60 | for (int i = 0; i < mysqlRecord.size(); i++) { 61 | assertEquals(mysqlRecord.get(i), tdhsRrcord.get(i)); 62 | } 63 | } 64 | 65 | protected void compareRecord(T[] mysqlRecord, List tdhsRrcord) { 66 | assertEquals(mysqlRecord.length, tdhsRrcord.size()); 67 | for (int i = 0; i < mysqlRecord.length; i++) { 68 | assertEquals(mysqlRecord[i], tdhsRrcord.get(i)); 69 | } 70 | } 71 | 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/mapper/PersonMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis.mapper; 13 | 14 | import com.taobao.tdhs.jdbc.test.mybatis.vo.Person; 15 | import org.apache.ibatis.annotations.Select; 16 | import org.junit.Ignore; 17 | 18 | import java.util.List; 19 | 20 | /** 21 | * @author 文通 22 | * @since 12-3-23 上午11:01 23 | */ 24 | @Ignore 25 | public interface PersonMapper { 26 | @Select("select Id,name,age,meMo as mm from person where id = #{id}") 27 | Person selectPerson(int id); 28 | 29 | @Select("select Id,name,age,meMo as mm from person where id > #{id}") 30 | List selectPersons(int id); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/mapper/TestMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis.mapper; 13 | 14 | import com.taobao.tdhs.jdbc.test.mybatis.vo.TestVO; 15 | import org.apache.ibatis.annotations.Delete; 16 | import org.apache.ibatis.annotations.Insert; 17 | import org.apache.ibatis.annotations.Select; 18 | import org.apache.ibatis.annotations.Update; 19 | import org.junit.Ignore; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | * @author 文通 25 | * @since 12-3-23 下午2:46 26 | */ 27 | @Ignore 28 | public interface TestMapper { 29 | 30 | @Insert("insert into test(a,b,c,n,t ,now) values (#{aaa},#{bbb},#{ccc},#{nnn},#{ttt},now())") 31 | int insert(TestVO testVO); 32 | 33 | @Select("select id,a as aaa,b as bbb,c as ccc,n as nnn,t as ttt,now from test where id >-100") 34 | List selectAll(); 35 | 36 | @Update("update test set a = #{aaa} , now=now() where b>1") 37 | int update(TestVO testVO); 38 | 39 | @Delete("delete from test where b = #{bbb}") 40 | int delete(TestVO testVO); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/vo/BaseVO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis.vo; 13 | 14 | import org.junit.Ignore; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-3-23 下午2:41 19 | */ 20 | @Ignore 21 | public class BaseVO { 22 | 23 | protected long id; 24 | 25 | public long getId() { 26 | return id; 27 | } 28 | 29 | public void setId(long id) { 30 | this.id = id; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/vo/OrderVO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis.vo; 13 | 14 | import java.util.Date; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-3-23 下午3:28 19 | */ 20 | public class OrderVO extends BaseVO { 21 | 22 | private long userId; 23 | 24 | private long auctionId; 25 | 26 | private String auctionName; 27 | 28 | private int number; 29 | 30 | private int deleted; 31 | 32 | private Date created; 33 | 34 | private Date lastModify; 35 | 36 | public OrderVO(long userId, long acutionId, String acutionName, int number, int deleted, Date created) { 37 | this.userId = userId; 38 | this.auctionId = acutionId; 39 | this.auctionName = acutionName; 40 | this.number = number; 41 | this.deleted = deleted; 42 | this.created = created; 43 | } 44 | 45 | public OrderVO() { 46 | } 47 | 48 | public long getUserId() { 49 | return userId; 50 | } 51 | 52 | public void setUserId(long userId) { 53 | this.userId = userId; 54 | } 55 | 56 | public long getAuctionId() { 57 | return auctionId; 58 | } 59 | 60 | public void setAuctionId(long auctionId) { 61 | this.auctionId = auctionId; 62 | } 63 | 64 | public String getAuctionName() { 65 | return auctionName; 66 | } 67 | 68 | public void setAuctionName(String auctionName) { 69 | this.auctionName = auctionName; 70 | } 71 | 72 | public int getNumber() { 73 | return number; 74 | } 75 | 76 | public void setNumber(int number) { 77 | this.number = number; 78 | } 79 | 80 | public int getDeleted() { 81 | return deleted; 82 | } 83 | 84 | public void setDeleted(int deleted) { 85 | this.deleted = deleted; 86 | } 87 | 88 | public Date getCreated() { 89 | return created; 90 | } 91 | 92 | public void setCreated(Date created) { 93 | this.created = created; 94 | } 95 | 96 | public Date getLastModify() { 97 | return lastModify; 98 | } 99 | 100 | public void setLastModify(Date lastModify) { 101 | this.lastModify = lastModify; 102 | } 103 | 104 | @Override 105 | public boolean equals(Object o) { 106 | if (this == o) return true; 107 | if (!(o instanceof OrderVO)) return false; 108 | 109 | OrderVO orderVO = (OrderVO) o; 110 | 111 | if (auctionId != orderVO.auctionId) return false; 112 | if (deleted != orderVO.deleted) return false; 113 | if (number != orderVO.number) return false; 114 | if (userId != orderVO.userId) return false; 115 | if (auctionName != null ? !auctionName.equals(orderVO.auctionName) : orderVO.auctionName != null) return false; 116 | if (created != null ? !created.equals(orderVO.created) : orderVO.created != null) return false; 117 | 118 | return true; 119 | } 120 | 121 | @Override 122 | public int hashCode() { 123 | int result = (int) (userId ^ (userId >>> 32)); 124 | result = 31 * result + (int) (auctionId ^ (auctionId >>> 32)); 125 | result = 31 * result + (auctionName != null ? auctionName.hashCode() : 0); 126 | result = 31 * result + number; 127 | result = 31 * result + deleted; 128 | result = 31 * result + (created != null ? created.hashCode() : 0); 129 | return result; 130 | } 131 | 132 | 133 | @Override 134 | public String toString() { 135 | return "OrderVO{" + 136 | "userId=" + userId + 137 | ", auctionId=" + auctionId + 138 | ", auctionName='" + auctionName + '\'' + 139 | ", number=" + number + 140 | ", deleted=" + deleted + 141 | ", created=" + created + 142 | ", lastModify=" + lastModify + 143 | '}'; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/vo/Person.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis.vo; 13 | 14 | import org.junit.Ignore; 15 | 16 | /** 17 | * @author 文通 18 | * @since 12-3-23 上午10:58 19 | */ 20 | @Ignore 21 | public class Person extends BaseVO { 22 | 23 | private String name; 24 | 25 | private int age; 26 | 27 | private String mm; 28 | 29 | public Person() { 30 | } 31 | 32 | public Person(long id, String name, int age, String mm) { 33 | setId(id); 34 | this.name = name; 35 | this.age = age; 36 | this.mm = mm; 37 | } 38 | 39 | 40 | public String getName() { 41 | return name; 42 | } 43 | 44 | public void setName(String name) { 45 | this.name = name; 46 | } 47 | 48 | public int getAge() { 49 | return age; 50 | } 51 | 52 | public void setAge(int age) { 53 | this.age = age; 54 | } 55 | 56 | public String getMm() { 57 | return mm; 58 | } 59 | 60 | public void setMm(String mm) { 61 | this.mm = mm; 62 | } 63 | 64 | @Override 65 | public boolean equals(Object o) { 66 | if (this == o) return true; 67 | if (!(o instanceof Person)) return false; 68 | 69 | Person person = (Person) o; 70 | 71 | if (age != person.age) return false; 72 | if (id != person.id) return false; 73 | if (mm != null ? !mm.equals(person.mm) : person.mm != null) return false; 74 | if (name != null ? !name.equals(person.name) : person.name != null) return false; 75 | 76 | return true; 77 | } 78 | 79 | @Override 80 | public int hashCode() { 81 | int result = (int) (id ^ (id >>> 32)); 82 | result = 31 * result + (name != null ? name.hashCode() : 0); 83 | result = 31 * result + age; 84 | result = 31 * result + (mm != null ? mm.hashCode() : 0); 85 | return result; 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return "Person{" + 91 | "id=" + id + 92 | ", name='" + name + '\'' + 93 | ", age=" + age + 94 | ", mm='" + mm + '\'' + 95 | '}'; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/test/mybatis/vo/TestVO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.test.mybatis.vo; 13 | 14 | import org.junit.Ignore; 15 | 16 | import java.util.Date; 17 | 18 | /** 19 | * @author 文通 20 | * @since 12-3-23 下午2:44 21 | */ 22 | @Ignore 23 | public class TestVO extends BaseVO { 24 | private String aaa; 25 | 26 | private int bbb; 27 | 28 | private float ccc; 29 | 30 | private String nnn; 31 | 32 | private Date ttt; 33 | 34 | private Date now; 35 | 36 | public TestVO() { 37 | } 38 | 39 | public TestVO(String aaa, int bbb, float ccc, String nnn, Date ttt) { 40 | this.aaa = aaa; 41 | this.bbb = bbb; 42 | this.ccc = ccc; 43 | this.nnn = nnn; 44 | this.ttt = ttt; 45 | } 46 | 47 | public String getAaa() { 48 | return aaa; 49 | } 50 | 51 | public void setAaa(String aaa) { 52 | this.aaa = aaa; 53 | } 54 | 55 | public int getBbb() { 56 | return bbb; 57 | } 58 | 59 | public void setBbb(int bbb) { 60 | this.bbb = bbb; 61 | } 62 | 63 | public float getCcc() { 64 | return ccc; 65 | } 66 | 67 | public void setCcc(float ccc) { 68 | this.ccc = ccc; 69 | } 70 | 71 | public String getNnn() { 72 | return nnn; 73 | } 74 | 75 | public void setNnn(String nnn) { 76 | this.nnn = nnn; 77 | } 78 | 79 | public Date getTtt() { 80 | return ttt; 81 | } 82 | 83 | public void setTtt(Date ttt) { 84 | this.ttt = ttt; 85 | } 86 | 87 | public Date getNow() { 88 | return now; 89 | } 90 | 91 | public void setNow(Date now) { 92 | this.now = now; 93 | } 94 | 95 | @Override 96 | public boolean equals(Object o) { 97 | if (this == o) return true; 98 | if (!(o instanceof TestVO)) return false; 99 | 100 | TestVO testVO = (TestVO) o; 101 | 102 | if (bbb != testVO.bbb) return false; 103 | if (Float.compare(testVO.ccc, ccc) != 0) return false; 104 | if (aaa != null ? !aaa.equals(testVO.aaa) : testVO.aaa != null) return false; 105 | if (nnn != null ? !nnn.equals(testVO.nnn) : testVO.nnn != null) return false; 106 | if (ttt != null ? !ttt.equals(testVO.ttt) : testVO.ttt != null) return false; 107 | 108 | return true; 109 | } 110 | 111 | @Override 112 | public int hashCode() { 113 | int result = aaa != null ? aaa.hashCode() : 0; 114 | result = 31 * result + bbb; 115 | result = 31 * result + (ccc != +0.0f ? Float.floatToIntBits(ccc) : 0); 116 | result = 31 * result + (nnn != null ? nnn.hashCode() : 0); 117 | result = 31 * result + (ttt != null ? ttt.hashCode() : 0); 118 | return result; 119 | } 120 | 121 | @Override 122 | public String toString() { 123 | return "TestVO{" + 124 | "aaa='" + aaa + '\'' + 125 | ", bbb=" + bbb + 126 | ", ccc=" + ccc + 127 | ", nnn='" + nnn + '\'' + 128 | ", ttt=" + ttt + 129 | ", now=" + now + 130 | '}'; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/test/java/com/taobao/tdhs/jdbc/util/StringUtilTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | * 4 | * This program is free software; you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License version 2 as 6 | * published by the Free Software Foundation. 7 | * 8 | * Authors: 9 | * wentong 10 | */ 11 | 12 | package com.taobao.tdhs.jdbc.util; 13 | 14 | import org.junit.Assert; 15 | import org.junit.Test; 16 | 17 | /** 18 | * @author 文通 19 | * @since 12-3-9 下午1:53 20 | */ 21 | public class StringUtilTest { 22 | @Test 23 | public void testEscapeField() throws Exception { 24 | Assert.assertEquals("id", StringUtil.escapeField("id")); 25 | Assert.assertEquals("id", StringUtil.escapeField("`id`")); 26 | Assert.assertEquals("i\"d", StringUtil.escapeField("`i\"d`")); 27 | Assert.assertEquals("", StringUtil.escapeField("``")); 28 | Assert.assertEquals(null, StringUtil.escapeField("\"id\"")); 29 | Assert.assertEquals(null, StringUtil.escapeField("\'id\'")); 30 | Assert.assertEquals(null, StringUtil.escapeField("`")); 31 | Assert.assertEquals(null, StringUtil.escapeField("`id")); 32 | Assert.assertEquals(null, StringUtil.escapeField("id`")); 33 | } 34 | 35 | @Test 36 | public void testEscapeValue() throws Exception { 37 | Assert.assertEquals("123", StringUtil.escapeValue("123")); 38 | Assert.assertEquals("123", StringUtil.escapeValue("'123'")); 39 | Assert.assertEquals("123", StringUtil.escapeValue("\"123\"")); 40 | Assert.assertEquals(null, StringUtil.escapeValue("`123\"")); 41 | Assert.assertEquals("", StringUtil.escapeValue("\"\"")); 42 | Assert.assertEquals(null, StringUtil.escapeValue("\"")); 43 | Assert.assertEquals(null, StringUtil.escapeValue("\'")); 44 | Assert.assertEquals(null, StringUtil.escapeValue("\'123\"")); 45 | Assert.assertEquals(null, StringUtil.escapeValue(" \"123\'")); 46 | Assert.assertEquals(null, StringUtil.escapeValue(" \"123")); 47 | Assert.assertEquals(null, StringUtil.escapeValue(" \'123")); 48 | Assert.assertEquals(null, StringUtil.escapeValue(" 123\'")); 49 | Assert.assertEquals(null, StringUtil.escapeValue(" 123\"")); 50 | } 51 | 52 | @Test 53 | public void testEscapeIn() throws Exception { 54 | Assert.assertArrayEquals(null, StringUtil.escapeIn("123")); 55 | Assert.assertArrayEquals(null, StringUtil.escapeIn("(123")); 56 | Assert.assertArrayEquals(null, StringUtil.escapeIn("123)")); 57 | Assert.assertArrayEquals(null, StringUtil.escapeIn("(\"123)")); 58 | Assert.assertArrayEquals(null, StringUtil.escapeIn("(`123)")); 59 | Assert.assertArrayEquals(new String[]{}, StringUtil.escapeIn("()")); 60 | Assert.assertArrayEquals(new String[]{"123"}, StringUtil.escapeIn("(123)")); 61 | Assert.assertArrayEquals(new String[]{"123"}, StringUtil.escapeIn("(\"123\")")); 62 | Assert.assertArrayEquals(new String[]{"1", "2", "3"}, StringUtil.escapeIn("(\"1\",2,'3')")); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/resources/global.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | # 4 | # This program is free software; you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License version 2 as 6 | # published by the Free Software Foundation. 7 | # 8 | # Authors: 9 | # wentong 10 | # 11 | 12 | server.host=t-wentong 13 | server.port=9999 14 | mysql.port=3306 15 | db.name=unit_test 16 | table.name=unit_test 17 | index.name=UnitTestBTreeIndex 18 | field.name=id,name,level -------------------------------------------------------------------------------- /src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright(C) 2011-2012 Alibaba Group Holding Limited 3 | # 4 | # This program is free software; you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License version 2 as 6 | # published by the Free Software Foundation. 7 | # 8 | # Authors: 9 | # wentong 10 | # 11 | 12 | log4j.rootCategory=ERROR, stdout 13 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 14 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 15 | log4j.appender.stdout.layout.ConversionPattern=[TDHS] %p [%t] %C.%M(%L) | %m%n -------------------------------------------------------------------------------- /src/test/resources/order.csv: -------------------------------------------------------------------------------- 1 | user_id,auction_id,auction_name,number,deleted,created 2 | 1,3,Book,1,0,2012-03-21 10:16:28 3 | 1,1,Computer,1,0,2012-03-21 10:16:49 4 | 2,3,Book,2,0,2012-03-21 10:17:19 5 | 1,2,iPhone,1,0,2012-03-21 10:17:39 6 | 2,5,iPad,2,0,2012-03-21 10:17:56 7 | 3,3,Book,5,0,2012-03-21 10:18:17 8 | 3,1,Computer,2,0,2012-03-21 10:18:39 9 | 2,5,iPad,1,0,2012-03-21 10:18:56 10 | 1,5,iPad,1,0,2012-03-21 10:19:20 11 | --------------------------------------------------------------------------------