提交 584b147f 编写于 作者: H Hongze Cheng

Merge branch 'develop' into feature/TD-1925_new

...@@ -270,19 +270,20 @@ matrix: ...@@ -270,19 +270,20 @@ matrix:
fi fi
- make > /dev/null - make > /dev/null
# - os: osx - os: osx
# language: c osx_image: xcode11.4
# compiler: clang language: c
# env: DESC="mac/clang build" compiler: clang
# git: env: DESC="mac/clang build"
# - depth: 1 git:
# addons: - depth: 1
# homebrew: addons:
# - cmake homebrew:
# - cmake
# script:
# - cd ${TRAVIS_BUILD_DIR} script:
# - mkdir debug - cd ${TRAVIS_BUILD_DIR}
# - cd debug - mkdir debug
# - cmake .. > /dev/null - cd debug
# - make > /dev/null - cmake .. > /dev/null
- make > /dev/null
...@@ -176,5 +176,84 @@ pipeline { ...@@ -176,5 +176,84 @@ pipeline {
} }
} }
} }
post {
success {
emailext (
subject: "PR-result: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: '''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0">
<table width="95%" cellpadding="0" cellspacing="0" style="font-size: 16pt; font-family: Tahoma, Arial, Helvetica, sans-serif">
<tr>
<td><br />
<b><font color="#0B610B"><font size="6">构建信息</font></font></b>
<hr size="2" width="100%" align="center" /></td>
</tr>
<tr>
<td>
<ul>
<div style="font-size:18px">
<li>构建名称>>分支:${PROJECT_NAME}</li>
<li>构建结果:<span style="color:green"> Successful </span></li>
<li>构建编号:${BUILD_NUMBER}</li>
<li>触发用户:${CAUSE}</li>
<li>提交信息:${CHANGE_TITLE}</li>
<li>构建地址:<a href=${BUILD_URL}>${BUILD_URL}</a></li>
<li>构建日志:<a href=${BUILD_URL}console>${BUILD_URL}console</a></li>
<li>变更集:${JELLY_SCRIPT}</li>
</div>
</ul>
</td>
</tr>
</table></font>
</body>
</html>''',
to: "${env.CHANGE_AUTHOR_EMAIL}",
from: "support@taosdata.com"
)
}
failure {
emailext (
subject: "PR-result: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: '''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0">
<table width="95%" cellpadding="0" cellspacing="0" style="font-size: 16pt; font-family: Tahoma, Arial, Helvetica, sans-serif">
<tr>
<td><br />
<b><font color="#0B610B"><font size="6">构建信息</font></font></b>
<hr size="2" width="100%" align="center" /></td>
</tr>
<tr>
<td>
<ul>
<div style="font-size:18px">
<li>构建名称>>分支:${PROJECT_NAME}</li>
<li>构建结果:<span style="color:green"> Successful </span></li>
<li>构建编号:${BUILD_NUMBER}</li>
<li>触发用户:${CAUSE}</li>
<li>提交信息:${CHANGE_TITLE}</li>
<li>构建地址:<a href=${BUILD_URL}>${BUILD_URL}</a></li>
<li>构建日志:<a href=${BUILD_URL}console>${BUILD_URL}console</a></li>
<li>变更集:${JELLY_SCRIPT}</li>
</div>
</ul>
</td>
</tr>
</table></font>
</body>
</html>''',
to: "${env.CHANGE_AUTHOR_EMAIL}",
from: "support@taosdata.com"
)
}
}
} }
...@@ -126,7 +126,7 @@ cmake .. -DCPUTYPE=aarch32 && cmake --build . ...@@ -126,7 +126,7 @@ cmake .. -DCPUTYPE=aarch32 && cmake --build .
If you use the Visual Studio 2013, please open a command window by executing "cmd.exe". If you use the Visual Studio 2013, please open a command window by executing "cmd.exe".
Please specify "x86_amd64" for 64 bits Windows or specify "x86" is for 32 bits Windows when you execute vcvarsall.bat. Please specify "x86_amd64" for 64 bits Windows or specify "x86" is for 32 bits Windows when you execute vcvarsall.bat.
``` ```cmd
mkdir debug && cd debug mkdir debug && cd debug
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" < x86_amd64 | x86 > "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" < x86_amd64 | x86 >
cmake .. -G "NMake Makefiles" cmake .. -G "NMake Makefiles"
...@@ -137,7 +137,8 @@ If you use the Visual Studio 2019 or 2017: ...@@ -137,7 +137,8 @@ If you use the Visual Studio 2019 or 2017:
please open a command window by executing "cmd.exe". please open a command window by executing "cmd.exe".
Please specify "x64" for 64 bits Windows or specify "x86" is for 32 bits Windows when you execute vcvarsall.bat. Please specify "x64" for 64 bits Windows or specify "x86" is for 32 bits Windows when you execute vcvarsall.bat.
```
```cmd
mkdir debug && cd debug mkdir debug && cd debug
"c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" < x64 | x86 > "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" < x64 | x86 >
cmake .. -G "NMake Makefiles" cmake .. -G "NMake Makefiles"
...@@ -145,27 +146,37 @@ nmake ...@@ -145,27 +146,37 @@ nmake
``` ```
Or, you can simply open a command window by clicking Windows Start -> "Visual Studio < 2019 | 2017 >" folder -> "x64 Native Tools Command Prompt for VS < 2019 | 2017 >" or "x86 Native Tools Command Prompt for VS < 2019 | 2017 >" depends what architecture your Windows is, then execute commands as follows: Or, you can simply open a command window by clicking Windows Start -> "Visual Studio < 2019 | 2017 >" folder -> "x64 Native Tools Command Prompt for VS < 2019 | 2017 >" or "x86 Native Tools Command Prompt for VS < 2019 | 2017 >" depends what architecture your Windows is, then execute commands as follows:
``` ```cmd
mkdir debug && cd debug mkdir debug && cd debug
cmake .. -G "NMake Makefiles" cmake .. -G "NMake Makefiles"
nmake nmake
``` ```
### On Mac OS X platform
Please install XCode command line tools and cmake. Verified with XCode 11.4+ on Catalina and Big Sur.
```shell
mkdir debug && cd debug
cmake .. && cmake --build .
```
# Quick Run # Quick Run
# Quick Run # Quick Run
To quickly start a TDengine server after building, run the command below in terminal: To quickly start a TDengine server after building, run the command below in terminal:
```cmd ```bash
./build/bin/taosd -c test/cfg ./build/bin/taosd -c test/cfg
``` ```
In another terminal, use the TDengine shell to connect the server: In another terminal, use the TDengine shell to connect the server:
``` ```bash
./build/bin/taos -c test/cfg ./build/bin/taos -c test/cfg
``` ```
option "-c test/cfg" specifies the system configuration file directory. option "-c test/cfg" specifies the system configuration file directory.
# Installing # Installing
After building successfully, TDengine can be installed by: After building successfully, TDengine can be installed by:
```cmd ```bash
make install make install
``` ```
Users can find more information about directories installed on the system in the [directory and files](https://www.taosdata.com/en/documentation/administrator/#Directory-and-Files) section. It should be noted that installing from source code does not configure service management for TDengine. Users can find more information about directories installed on the system in the [directory and files](https://www.taosdata.com/en/documentation/administrator/#Directory-and-Files) section. It should be noted that installing from source code does not configure service management for TDengine.
......
...@@ -32,7 +32,7 @@ ELSEIF (TD_WINDOWS) ...@@ -32,7 +32,7 @@ ELSEIF (TD_WINDOWS)
#INSTALL(TARGETS taos RUNTIME DESTINATION driver) #INSTALL(TARGETS taos RUNTIME DESTINATION driver)
#INSTALL(TARGETS shell RUNTIME DESTINATION .) #INSTALL(TARGETS shell RUNTIME DESTINATION .)
IF (TD_MVN_INSTALLED) IF (TD_MVN_INSTALLED)
INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.17-dist.jar DESTINATION connector/jdbc) INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.18-dist.jar DESTINATION connector/jdbc)
ENDIF () ENDIF ()
ELSEIF (TD_DARWIN) ELSEIF (TD_DARWIN)
SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh") SET(TD_MAKE_INSTALL_SH "${TD_COMMUNITY_DIR}/packaging/tools/make_install.sh")
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
TDengine 提供了遵循 JDBC 标准(3.0)API 规范的 `taos-jdbcdriver` 实现,可在 maven 的中央仓库 [Sonatype Repository][1] 搜索下载。 TDengine 提供了遵循 JDBC 标准(3.0)API 规范的 `taos-jdbcdriver` 实现,可在 maven 的中央仓库 [Sonatype Repository][1] 搜索下载。
`taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTful(taos-jdbcdriver-2.0.17 开始支持 JDBC-RESTful)。 JDBC-JNI 通过调用客户端 libtaos.so(或 taos.dll )的本地方法实现, JDBC-RESTful 则在内部封装了 RESTful 接口实现。 `taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTful(taos-jdbcdriver-2.0.18 开始支持 JDBC-RESTful)。 JDBC-JNI 通过调用客户端 libtaos.so(或 taos.dll )的本地方法实现, JDBC-RESTful 则在内部封装了 RESTful 接口实现。
![tdengine-connector](../assets/tdengine-jdbc-connector.png) ![tdengine-connector](../assets/tdengine-jdbc-connector.png)
...@@ -67,7 +67,7 @@ maven 项目中使用如下 pom.xml 配置即可: ...@@ -67,7 +67,7 @@ maven 项目中使用如下 pom.xml 配置即可:
<dependency> <dependency>
<groupId>com.taosdata.jdbc</groupId> <groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId> <artifactId>taos-jdbcdriver</artifactId>
<version>2.0.17</version> <version>2.0.18</version>
</dependency> </dependency>
``` ```
...@@ -334,16 +334,16 @@ conn.close(); ...@@ -334,16 +334,16 @@ conn.close();
```java ```java
public static void main(String[] args) throws SQLException { public static void main(String[] args) throws SQLException {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
// jdbc properties
config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log"); config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log");
config.setUsername("root"); config.setUsername("root");
config.setPassword("taosdata"); config.setPassword("taosdata");
// connection pool configurations
config.setMinimumIdle(3); //minimum number of idle connection config.setMinimumIdle(3); //minimum number of idle connection
config.setMaximumPoolSize(10); //maximum number of connection in the pool config.setMaximumPoolSize(10); //maximum number of connection in the pool
config.setConnectionTimeout(10000); //maximum wait milliseconds for get connection from pool config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool
config.setIdleTimeout(60000); // max idle time for recycle idle connection config.setIdleTimeout(0); // max idle time for recycle idle connection
config.setConnectionTestQuery("describe log.dn"); //validation query config.setConnectionTestQuery("select server_status()"); //validation query
config.setValidationTimeout(3000); //validation query timeout
HikariDataSource ds = new HikariDataSource(config); //create datasource HikariDataSource ds = new HikariDataSource(config); //create datasource
...@@ -376,25 +376,17 @@ conn.close(); ...@@ -376,25 +376,17 @@ conn.close();
```java ```java
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Properties properties = new Properties(); Properties properties = new Properties();
// jdbc properties
properties.put("driverClassName","com.taosdata.jdbc.TSDBDriver"); properties.put("driverClassName","com.taosdata.jdbc.TSDBDriver");
properties.put("url","jdbc:TAOS://127.0.0.1:6030/log"); properties.put("url","jdbc:TAOS://127.0.0.1:6030/log");
properties.put("username","root"); properties.put("username","root");
properties.put("password","taosdata"); properties.put("password","taosdata");
// pool configurations
properties.put("maxActive","10"); //maximum number of connection in the pool properties.put("maxActive","10"); //maximum number of connection in the pool
properties.put("initialSize","3");//initial number of connection properties.put("initialSize","3"); //initial number of connection
properties.put("maxWait","10000");//maximum wait milliseconds for get connection from pool properties.put("minIdle","3"); //minimum number of connection in the pool
properties.put("minIdle","3");//minimum number of connection in the pool properties.put("maxWait","30000"); //maximum wait milliseconds for get connection from pool
properties.put("validationQuery","select server_status()"); //validation query
properties.put("timeBetweenEvictionRunsMillis","3000");// the interval milliseconds to test connection
properties.put("minEvictableIdleTimeMillis","60000");//the minimum milliseconds to keep idle
properties.put("maxEvictableIdleTimeMillis","90000");//the maximum milliseconds to keep idle
properties.put("validationQuery","describe log.dn"); //validation query
properties.put("testWhileIdle","true"); // test connection while idle
properties.put("testOnBorrow","false"); // don't need while testWhileIdle is true
properties.put("testOnReturn","false"); // don't need while testWhileIdle is true
//create druid datasource //create druid datasource
DataSource ds = DruidDataSourceFactory.createDataSource(properties); DataSource ds = DruidDataSourceFactory.createDataSource(properties);
......
...@@ -43,6 +43,7 @@ mkdir -p ${pkg_dir}${install_home_path}/include ...@@ -43,6 +43,7 @@ mkdir -p ${pkg_dir}${install_home_path}/include
mkdir -p ${pkg_dir}${install_home_path}/init.d mkdir -p ${pkg_dir}${install_home_path}/init.d
mkdir -p ${pkg_dir}${install_home_path}/script mkdir -p ${pkg_dir}${install_home_path}/script
echo "" > ${pkg_dir}${install_home_path}/email
cp ${compile_dir}/../packaging/cfg/taos.cfg ${pkg_dir}${install_home_path}/cfg cp ${compile_dir}/../packaging/cfg/taos.cfg ${pkg_dir}${install_home_path}/cfg
cp ${compile_dir}/../packaging/deb/taosd ${pkg_dir}${install_home_path}/init.d cp ${compile_dir}/../packaging/deb/taosd ${pkg_dir}${install_home_path}/init.d
cp ${compile_dir}/../packaging/tools/post.sh ${pkg_dir}${install_home_path}/script cp ${compile_dir}/../packaging/tools/post.sh ${pkg_dir}${install_home_path}/script
......
...@@ -51,6 +51,7 @@ mkdir -p %{buildroot}%{homepath}/include ...@@ -51,6 +51,7 @@ mkdir -p %{buildroot}%{homepath}/include
mkdir -p %{buildroot}%{homepath}/init.d mkdir -p %{buildroot}%{homepath}/init.d
mkdir -p %{buildroot}%{homepath}/script mkdir -p %{buildroot}%{homepath}/script
echo "" > %{buildroot}%{homepath}/email
cp %{_compiledir}/../packaging/cfg/taos.cfg %{buildroot}%{homepath}/cfg cp %{_compiledir}/../packaging/cfg/taos.cfg %{buildroot}%{homepath}/cfg
cp %{_compiledir}/../packaging/rpm/taosd %{buildroot}%{homepath}/init.d cp %{_compiledir}/../packaging/rpm/taosd %{buildroot}%{homepath}/init.d
cp %{_compiledir}/../packaging/tools/post.sh %{buildroot}%{homepath}/script cp %{_compiledir}/../packaging/tools/post.sh %{buildroot}%{homepath}/script
......
...@@ -749,7 +749,10 @@ static int32_t tscProcessCurrentUser(SSqlObj *pSql) { ...@@ -749,7 +749,10 @@ static int32_t tscProcessCurrentUser(SSqlObj *pSql) {
static int32_t tscProcessCurrentDB(SSqlObj *pSql) { static int32_t tscProcessCurrentDB(SSqlObj *pSql) {
char db[TSDB_DB_NAME_LEN] = {0}; char db[TSDB_DB_NAME_LEN] = {0};
pthread_mutex_lock(&pSql->pTscObj->mutex);
extractDBName(pSql->pTscObj->db, db); extractDBName(pSql->pTscObj->db, db);
pthread_mutex_unlock(&pSql->pTscObj->mutex);
SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex); SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
......
...@@ -62,7 +62,7 @@ static int32_t setShowInfo(SSqlObj* pSql, SSqlInfo* pInfo); ...@@ -62,7 +62,7 @@ static int32_t setShowInfo(SSqlObj* pSql, SSqlInfo* pInfo);
static char* getAccountId(SSqlObj* pSql); static char* getAccountId(SSqlObj* pSql);
static bool has(SArray* pFieldList, int32_t startIdx, const char* name); static bool has(SArray* pFieldList, int32_t startIdx, const char* name);
static char* getCurrentDBName(SSqlObj* pSql); static char* cloneCurrentDBName(SSqlObj* pSql);
static bool hasSpecifyDB(SStrToken* pTableName); static bool hasSpecifyDB(SStrToken* pTableName);
static bool validateTableColumnInfo(SArray* pFieldList, SSqlCmd* pCmd); static bool validateTableColumnInfo(SArray* pFieldList, SSqlCmd* pCmd);
static bool validateTagParams(SArray* pTagsList, SArray* pFieldList, SSqlCmd* pCmd); static bool validateTagParams(SArray* pTagsList, SArray* pFieldList, SSqlCmd* pCmd);
...@@ -923,16 +923,19 @@ int32_t tscSetTableFullName(STableMetaInfo* pTableMetaInfo, SStrToken* pTableNam ...@@ -923,16 +923,19 @@ int32_t tscSetTableFullName(STableMetaInfo* pTableMetaInfo, SStrToken* pTableNam
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
} else { // get current DB name first, and then set it into path } else { // get current DB name first, and then set it into path
char* t = getCurrentDBName(pSql); char* t = cloneCurrentDBName(pSql);
if (strlen(t) == 0) { if (strlen(t) == 0) {
return TSDB_CODE_TSC_DB_NOT_SELECTED; return TSDB_CODE_TSC_DB_NOT_SELECTED;
} }
code = tNameFromString(&pTableMetaInfo->name, t, T_NAME_ACCT | T_NAME_DB); code = tNameFromString(&pTableMetaInfo->name, t, T_NAME_ACCT | T_NAME_DB);
if (code != 0) { if (code != 0) {
free(t);
return TSDB_CODE_TSC_DB_NOT_SELECTED; return TSDB_CODE_TSC_DB_NOT_SELECTED;
} }
free(t);
if (pTableName->n >= TSDB_TABLE_NAME_LEN) { if (pTableName->n >= TSDB_TABLE_NAME_LEN) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
...@@ -1246,8 +1249,12 @@ static bool has(SArray* pFieldList, int32_t startIdx, const char* name) { ...@@ -1246,8 +1249,12 @@ static bool has(SArray* pFieldList, int32_t startIdx, const char* name) {
static char* getAccountId(SSqlObj* pSql) { return pSql->pTscObj->acctId; } static char* getAccountId(SSqlObj* pSql) { return pSql->pTscObj->acctId; }
static char* getCurrentDBName(SSqlObj* pSql) { static char* cloneCurrentDBName(SSqlObj* pSql) {
return pSql->pTscObj->db; pthread_mutex_lock(&pSql->pTscObj->mutex);
char *p = strdup(pSql->pTscObj->db);
pthread_mutex_unlock(&pSql->pTscObj->mutex);
return p;
} }
/* length limitation, strstr cannot be applied */ /* length limitation, strstr cannot be applied */
...@@ -4302,6 +4309,77 @@ static void doAddJoinTagsColumnsIntoTagList(SSqlCmd* pCmd, SQueryInfo* pQueryInf ...@@ -4302,6 +4309,77 @@ static void doAddJoinTagsColumnsIntoTagList(SSqlCmd* pCmd, SQueryInfo* pQueryInf
} }
} }
static int32_t validateTagCondExpr(SSqlCmd* pCmd, tExprNode *p) {
const char *msg1 = "invalid tag operator";
const char* msg2 = "not supported filter condition";
do {
if (p->nodeType != TSQL_NODE_EXPR) {
break;
}
if (!p->_node.pLeft || !p->_node.pRight) {
break;
}
if (IS_ARITHMETIC_OPTR(p->_node.optr)) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
}
if (!IS_RELATION_OPTR(p->_node.optr)) {
break;
}
tVariant * vVariant = NULL;
int32_t schemaType = -1;
if (p->_node.pLeft->nodeType == TSQL_NODE_VALUE && p->_node.pRight->nodeType == TSQL_NODE_COL) {
if (!p->_node.pRight->pSchema) {
break;
}
vVariant = p->_node.pLeft->pVal;
schemaType = p->_node.pRight->pSchema->type;
} else if (p->_node.pLeft->nodeType == TSQL_NODE_COL && p->_node.pRight->nodeType == TSQL_NODE_VALUE) {
if (!p->_node.pLeft->pSchema) {
break;
}
vVariant = p->_node.pRight->pVal;
schemaType = p->_node.pLeft->pSchema->type;
} else {
break;
}
if (schemaType >= TSDB_DATA_TYPE_TINYINT && schemaType <= TSDB_DATA_TYPE_BIGINT) {
schemaType = TSDB_DATA_TYPE_BIGINT;
} else if (schemaType == TSDB_DATA_TYPE_FLOAT || schemaType == TSDB_DATA_TYPE_DOUBLE) {
schemaType = TSDB_DATA_TYPE_DOUBLE;
}
int32_t retVal = TSDB_CODE_SUCCESS;
if (schemaType == TSDB_DATA_TYPE_BINARY) {
char *tmp = calloc(1, vVariant->nLen + TSDB_NCHAR_SIZE);
retVal = tVariantDump(vVariant, tmp, schemaType, false);
free(tmp);
} else if (schemaType == TSDB_DATA_TYPE_NCHAR) {
// pRight->val.nLen + 1 is larger than the actual nchar string length
char *tmp = calloc(1, (vVariant->nLen + 1) * TSDB_NCHAR_SIZE);
retVal = tVariantDump(vVariant, tmp, schemaType, false);
free(tmp);
} else {
double tmp;
retVal = tVariantDump(vVariant, (char*)&tmp, schemaType, false);
}
if (retVal != TSDB_CODE_SUCCESS) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
}
}while (0);
return TSDB_CODE_SUCCESS;
}
static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondExpr* pCondExpr, tSQLExpr** pExpr) { static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondExpr* pCondExpr, tSQLExpr** pExpr) {
int32_t ret = TSDB_CODE_SUCCESS; int32_t ret = TSDB_CODE_SUCCESS;
...@@ -4344,6 +4422,10 @@ static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondE ...@@ -4344,6 +4422,10 @@ static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondE
tsSetSTableQueryCond(&pQueryInfo->tagCond, uid, &bw); tsSetSTableQueryCond(&pQueryInfo->tagCond, uid, &bw);
doCompactQueryExpr(pExpr); doCompactQueryExpr(pExpr);
if (ret == TSDB_CODE_SUCCESS) {
ret = validateTagCondExpr(pCmd, p);
}
tSqlExprDestroy(p1); tSqlExprDestroy(p1);
tExprTreeDestroy(p, NULL); tExprTreeDestroy(p, NULL);
...@@ -4351,6 +4433,10 @@ static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondE ...@@ -4351,6 +4433,10 @@ static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondE
if (pQueryInfo->tagCond.pCond != NULL && taosArrayGetSize(pQueryInfo->tagCond.pCond) > 0 && !UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) { if (pQueryInfo->tagCond.pCond != NULL && taosArrayGetSize(pQueryInfo->tagCond.pCond) > 0 && !UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), "filter on tag not supported for normal table"); return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), "filter on tag not supported for normal table");
} }
if (ret) {
break;
}
} }
pCondExpr->pTagCond = NULL; pCondExpr->pTagCond = NULL;
......
...@@ -1250,8 +1250,10 @@ int32_t tscBuildShowMsg(SSqlObj *pSql, SSqlInfo *pInfo) { ...@@ -1250,8 +1250,10 @@ int32_t tscBuildShowMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0); STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
if (tNameIsEmpty(&pTableMetaInfo->name)) { if (tNameIsEmpty(&pTableMetaInfo->name)) {
tstrncpy(pShowMsg->db, pObj->db, sizeof(pShowMsg->db)); pthread_mutex_lock(&pObj->mutex);
tstrncpy(pShowMsg->db, pObj->db, sizeof(pShowMsg->db));
pthread_mutex_unlock(&pObj->mutex);
} else { } else {
tNameGetFullDbName(&pTableMetaInfo->name, pShowMsg->db); tNameGetFullDbName(&pTableMetaInfo->name, pShowMsg->db);
} }
...@@ -1611,9 +1613,14 @@ int tscBuildConnectMsg(SSqlObj *pSql, SSqlInfo *pInfo) { ...@@ -1611,9 +1613,14 @@ int tscBuildConnectMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
// TODO refactor full_name // TODO refactor full_name
char *db; // ugly code to move the space char *db; // ugly code to move the space
pthread_mutex_lock(&pObj->mutex);
db = strstr(pObj->db, TS_PATH_DELIMITER); db = strstr(pObj->db, TS_PATH_DELIMITER);
db = (db == NULL) ? pObj->db : db + 1; db = (db == NULL) ? pObj->db : db + 1;
tstrncpy(pConnect->db, db, sizeof(pConnect->db)); tstrncpy(pConnect->db, db, sizeof(pConnect->db));
pthread_mutex_unlock(&pObj->mutex);
tstrncpy(pConnect->clientVersion, version, sizeof(pConnect->clientVersion)); tstrncpy(pConnect->clientVersion, version, sizeof(pConnect->clientVersion));
tstrncpy(pConnect->msgVersion, "", sizeof(pConnect->msgVersion)); tstrncpy(pConnect->msgVersion, "", sizeof(pConnect->msgVersion));
...@@ -2131,10 +2138,13 @@ int tscProcessConnectRsp(SSqlObj *pSql) { ...@@ -2131,10 +2138,13 @@ int tscProcessConnectRsp(SSqlObj *pSql) {
SConnectRsp *pConnect = (SConnectRsp *)pRes->pRsp; SConnectRsp *pConnect = (SConnectRsp *)pRes->pRsp;
tstrncpy(pObj->acctId, pConnect->acctId, sizeof(pObj->acctId)); // copy acctId from response tstrncpy(pObj->acctId, pConnect->acctId, sizeof(pObj->acctId)); // copy acctId from response
pthread_mutex_lock(&pObj->mutex);
int32_t len = sprintf(temp, "%s%s%s", pObj->acctId, TS_PATH_DELIMITER, pObj->db); int32_t len = sprintf(temp, "%s%s%s", pObj->acctId, TS_PATH_DELIMITER, pObj->db);
assert(len <= sizeof(pObj->db)); assert(len <= sizeof(pObj->db));
tstrncpy(pObj->db, temp, sizeof(pObj->db)); tstrncpy(pObj->db, temp, sizeof(pObj->db));
pthread_mutex_unlock(&pObj->mutex);
if (pConnect->epSet.numOfEps > 0) { if (pConnect->epSet.numOfEps > 0) {
tscEpSetHtons(&pConnect->epSet); tscEpSetHtons(&pConnect->epSet);
...@@ -2161,11 +2171,18 @@ int tscProcessConnectRsp(SSqlObj *pSql) { ...@@ -2161,11 +2171,18 @@ int tscProcessConnectRsp(SSqlObj *pSql) {
int tscProcessUseDbRsp(SSqlObj *pSql) { int tscProcessUseDbRsp(SSqlObj *pSql) {
STscObj * pObj = pSql->pTscObj; STscObj * pObj = pSql->pTscObj;
STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0); STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
return tNameExtractFullName(&pTableMetaInfo->name, pObj->db);
pthread_mutex_lock(&pObj->mutex);
int ret = tNameExtractFullName(&pTableMetaInfo->name, pObj->db);
pthread_mutex_unlock(&pObj->mutex);
return ret;
} }
int tscProcessDropDbRsp(SSqlObj *pSql) { int tscProcessDropDbRsp(SSqlObj *pSql) {
pSql->pTscObj->db[0] = 0; //TODO LOCK DB WHEN MODIFY IT
//pSql->pTscObj->db[0] = 0;
taosHashEmpty(tscTableMetaInfo); taosHashEmpty(tscTableMetaInfo);
return 0; return 0;
} }
......
...@@ -137,7 +137,7 @@ int32_t tsTableIncStepPerVnode = TSDB_TABLES_STEP; ...@@ -137,7 +137,7 @@ int32_t tsTableIncStepPerVnode = TSDB_TABLES_STEP;
int8_t tsEnableBalance = 1; int8_t tsEnableBalance = 1;
int8_t tsAlternativeRole = 0; int8_t tsAlternativeRole = 0;
int32_t tsBalanceInterval = 300; // seconds int32_t tsBalanceInterval = 300; // seconds
int32_t tsOfflineThreshold = 86400 * 100; // seconds 10days int32_t tsOfflineThreshold = 86400 * 100; // seconds 100 days
int32_t tsMnodeEqualVnodeNum = 4; int32_t tsMnodeEqualVnodeNum = 4;
int8_t tsEnableFlowCtrl = 1; int8_t tsEnableFlowCtrl = 1;
int8_t tsEnableSlaveQuery = 1; int8_t tsEnableSlaveQuery = 1;
...@@ -591,7 +591,7 @@ static void doInitGlobalConfig(void) { ...@@ -591,7 +591,7 @@ static void doInitGlobalConfig(void) {
cfg.valType = TAOS_CFG_VTYPE_INT32; cfg.valType = TAOS_CFG_VTYPE_INT32;
cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW; cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW;
cfg.minValue = 3; cfg.minValue = 3;
cfg.maxValue = 7200000; cfg.maxValue = 86400 * 365;
cfg.ptrLength = 0; cfg.ptrLength = 0;
cfg.unitType = TAOS_CFG_UTYPE_SECOND; cfg.unitType = TAOS_CFG_UTYPE_SECOND;
taosInitConfigOption(cfg); taosInitConfigOption(cfg);
......
...@@ -430,7 +430,7 @@ static FORCE_INLINE int32_t convertToInteger(tVariant *pVariant, int64_t *result ...@@ -430,7 +430,7 @@ static FORCE_INLINE int32_t convertToInteger(tVariant *pVariant, int64_t *result
} }
errno = 0; errno = 0;
if (IS_SIGNED_NUMERIC_TYPE(pVariant->nType)) { if (IS_SIGNED_NUMERIC_TYPE(pVariant->nType) || (pVariant->nType == TSDB_DATA_TYPE_BOOL)) {
*result = pVariant->i64; *result = pVariant->i64;
} else if (IS_UNSIGNED_NUMERIC_TYPE(pVariant->nType)) { } else if (IS_UNSIGNED_NUMERIC_TYPE(pVariant->nType)) {
*result = pVariant->u64; *result = pVariant->u64;
......
...@@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED) ...@@ -8,7 +8,7 @@ IF (TD_MVN_INSTALLED)
ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME} ADD_CUSTOM_COMMAND(OUTPUT ${JDBC_CMD_NAME}
POST_BUILD POST_BUILD
COMMAND mvn -Dmaven.test.skip=true install -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml COMMAND mvn -Dmaven.test.skip=true install -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.17-dist.jar ${LIBRARY_OUTPUT_PATH} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/target/taos-jdbcdriver-2.0.18-dist.jar ${LIBRARY_OUTPUT_PATH}
COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml COMMAND mvn -Dmaven.test.skip=true clean -f ${CMAKE_CURRENT_SOURCE_DIR}/pom.xml
COMMENT "build jdbc driver") COMMENT "build jdbc driver")
ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME}) ADD_CUSTOM_TARGET(${JDBC_TARGET_NAME} ALL WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} DEPENDS ${JDBC_CMD_NAME})
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<groupId>com.taosdata.jdbc</groupId> <groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId> <artifactId>taos-jdbcdriver</artifactId>
<version>2.0.17</version> <version>2.0.18</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>JDBCDriver</name> <name>JDBCDriver</name>
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.taosdata.jdbc</groupId> <groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId> <artifactId>taos-jdbcdriver</artifactId>
<version>2.0.17</version> <version>2.0.18</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>JDBCDriver</name> <name>JDBCDriver</name>
<url>https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc</url> <url>https://github.com/taosdata/TDengine/tree/master/src/connector/jdbc</url>
...@@ -126,7 +126,7 @@ ...@@ -126,7 +126,7 @@
<include>**/*Test.java</include> <include>**/*Test.java</include>
</includes> </includes>
<excludes> <excludes>
<exclude>**/BatchInsertTest.java</exclude> <exclude>**/AppMemoryLeakTest.java</exclude>
<exclude>**/FailOverTest.java</exclude> <exclude>**/FailOverTest.java</exclude>
</excludes> </excludes>
<testFailureIgnore>true</testFailureIgnore> <testFailureIgnore>true</testFailureIgnore>
......
...@@ -19,9 +19,12 @@ import java.util.Map; ...@@ -19,9 +19,12 @@ import java.util.Map;
public abstract class TSDBConstants { public abstract class TSDBConstants {
public static final String STATEMENT_CLOSED = "Statement already closed.";
public static final String DEFAULT_PORT = "6200"; public static final String DEFAULT_PORT = "6200";
public static final String UNSUPPORT_METHOD_EXCEPTIONZ_MSG = "this operation is NOT supported currently!"; public static final String UNSUPPORT_METHOD_EXCEPTIONZ_MSG = "this operation is NOT supported currently!";
public static final String INVALID_VARIABLES = "invalid variables"; public static final String INVALID_VARIABLES = "invalid variables";
public static final String RESULT_SET_IS_CLOSED = "resultSet is closed.";
public static Map<Integer, String> DATATYPE_MAP = null; public static Map<Integer, String> DATATYPE_MAP = null;
public static final long JNI_NULL_POINTER = 0L; public static final long JNI_NULL_POINTER = 0L;
...@@ -74,7 +77,7 @@ public abstract class TSDBConstants { ...@@ -74,7 +77,7 @@ public abstract class TSDBConstants {
} }
static { static {
DATATYPE_MAP = new HashMap<Integer, String>(); DATATYPE_MAP = new HashMap<>();
DATATYPE_MAP.put(1, "BOOL"); DATATYPE_MAP.put(1, "BOOL");
DATATYPE_MAP.put(2, "TINYINT"); DATATYPE_MAP.put(2, "TINYINT");
DATATYPE_MAP.put(3, "SMALLINT"); DATATYPE_MAP.put(3, "SMALLINT");
......
...@@ -100,7 +100,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -100,7 +100,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
* order to process those supported SQLs. * order to process those supported SQLs.
*/ */
private void preprocessSql() { private void preprocessSql() {
/***** For processing some of Spark SQLs*****/ /***** For processing some of Spark SQLs*****/
// should replace it first // should replace it first
this.rawSql = this.rawSql.replaceAll("or (.*) is null", ""); this.rawSql = this.rawSql.replaceAll("or (.*) is null", "");
...@@ -149,7 +148,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -149,7 +148,6 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
rawSql = rawSql.replace(matcher.group(1), tableFullName); rawSql = rawSql.replace(matcher.group(1), tableFullName);
} }
/***** for inner queries *****/ /***** for inner queries *****/
} }
/** /**
...@@ -196,7 +194,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -196,7 +194,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
@Override @Override
public void setNull(int parameterIndex, int sqlType) throws SQLException { public void setNull(int parameterIndex, int sqlType) throws SQLException {
setObject(parameterIndex, new String("NULL")); setObject(parameterIndex, "NULL");
} }
@Override @Override
......
...@@ -52,12 +52,18 @@ public class TSDBStatement implements Statement { ...@@ -52,12 +52,18 @@ public class TSDBStatement implements Statement {
this.isClosed = false; this.isClosed = false;
} }
@Override
public <T> T unwrap(Class<T> iface) throws SQLException { public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw new SQLException("Unable to unwrap to " + iface.toString());
}
} }
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException { public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); return iface.isInstance(this);
} }
public ResultSet executeQuery(String sql) throws SQLException { public ResultSet executeQuery(String sql) throws SQLException {
...@@ -130,10 +136,15 @@ public class TSDBStatement implements Statement { ...@@ -130,10 +136,15 @@ public class TSDBStatement implements Statement {
} }
public void setMaxFieldSize(int max) throws SQLException { public void setMaxFieldSize(int max) throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
public int getMaxRows() throws SQLException { public int getMaxRows() throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
// always set maxRows to zero, meaning unlimitted rows in a resultSet // always set maxRows to zero, meaning unlimitted rows in a resultSet
return 0; return 0;
} }
......
package com.taosdata.jdbc.rs; package com.taosdata.jdbc.rs;
import com.taosdata.jdbc.TSDBConstants;
import java.sql.ResultSetMetaData; import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
public class RestfulResultSetMetaData implements ResultSetMetaData { public class RestfulResultSetMetaData implements ResultSetMetaData {
private final String database; private final String database;
private ArrayList<RestfulResultSet.Field> fields; private ArrayList<RestfulResultSet.Field> fields;
private final RestfulResultSet resultSet;
public RestfulResultSetMetaData(String database, ArrayList<RestfulResultSet.Field> fields) { public RestfulResultSetMetaData(String database, ArrayList<RestfulResultSet.Field> fields, RestfulResultSet resultSet) {
this.database = database; this.database = database;
this.fields = fields; this.fields = fields;
this.resultSet = resultSet;
} }
@Override @Override
...@@ -26,13 +31,12 @@ public class RestfulResultSetMetaData implements ResultSetMetaData { ...@@ -26,13 +31,12 @@ public class RestfulResultSetMetaData implements ResultSetMetaData {
@Override @Override
public boolean isCaseSensitive(int column) throws SQLException { public boolean isCaseSensitive(int column) throws SQLException {
//TODO
return false; return false;
} }
@Override @Override
public boolean isSearchable(int column) throws SQLException { public boolean isSearchable(int column) throws SQLException {
return false; return true;
} }
@Override @Override
...@@ -42,17 +46,30 @@ public class RestfulResultSetMetaData implements ResultSetMetaData { ...@@ -42,17 +46,30 @@ public class RestfulResultSetMetaData implements ResultSetMetaData {
@Override @Override
public int isNullable(int column) throws SQLException { public int isNullable(int column) throws SQLException {
if (column == 1)
return ResultSetMetaData.columnNoNulls;
return ResultSetMetaData.columnNullable; return ResultSetMetaData.columnNullable;
} }
@Override @Override
public boolean isSigned(int column) throws SQLException { public boolean isSigned(int column) throws SQLException {
return false; String type = this.fields.get(column - 1).type.toUpperCase();
switch (type) {
case "TINYINT":
case "SMALLINT":
case "INT":
case "BIGINT":
case "FLOAT":
case "DOUBLE":
return true;
default:
return false;
}
} }
@Override @Override
public int getColumnDisplaySize(int column) throws SQLException { public int getColumnDisplaySize(int column) throws SQLException {
return 0; return this.fields.get(column - 1).length;
} }
@Override @Override
...@@ -62,27 +79,46 @@ public class RestfulResultSetMetaData implements ResultSetMetaData { ...@@ -62,27 +79,46 @@ public class RestfulResultSetMetaData implements ResultSetMetaData {
@Override @Override
public String getColumnName(int column) throws SQLException { public String getColumnName(int column) throws SQLException {
return null; return fields.get(column - 1).name;
} }
@Override @Override
public String getSchemaName(int column) throws SQLException { public String getSchemaName(int column) throws SQLException {
return this.database; return "";
} }
@Override @Override
public int getPrecision(int column) throws SQLException { public int getPrecision(int column) throws SQLException {
return 0; String type = this.fields.get(column - 1).type.toUpperCase();
switch (type) {
case "FLOAT":
return 5;
case "DOUBLE":
return 9;
case "BINARY":
case "NCHAR":
return this.fields.get(column - 1).length;
default:
return 0;
}
} }
@Override @Override
public int getScale(int column) throws SQLException { public int getScale(int column) throws SQLException {
return 0; String type = this.fields.get(column - 1).type.toUpperCase();
switch (type) {
case "FLOAT":
return 5;
case "DOUBLE":
return 9;
default:
return 0;
}
} }
@Override @Override
public String getTableName(int column) throws SQLException { public String getTableName(int column) throws SQLException {
return null; return "";
} }
@Override @Override
...@@ -92,17 +128,41 @@ public class RestfulResultSetMetaData implements ResultSetMetaData { ...@@ -92,17 +128,41 @@ public class RestfulResultSetMetaData implements ResultSetMetaData {
@Override @Override
public int getColumnType(int column) throws SQLException { public int getColumnType(int column) throws SQLException {
return 0; String type = this.fields.get(column - 1).type.toUpperCase();
switch (type) {
case "BOOL":
return java.sql.Types.BOOLEAN;
case "TINYINT":
return java.sql.Types.TINYINT;
case "SMALLINT":
return java.sql.Types.SMALLINT;
case "INT":
return java.sql.Types.INTEGER;
case "BIGINT":
return java.sql.Types.BIGINT;
case "FLOAT":
return java.sql.Types.FLOAT;
case "DOUBLE":
return java.sql.Types.DOUBLE;
case "BINARY":
return java.sql.Types.BINARY;
case "TIMESTAMP":
return java.sql.Types.TIMESTAMP;
case "NCHAR":
return java.sql.Types.NCHAR;
}
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
} }
@Override @Override
public String getColumnTypeName(int column) throws SQLException { public String getColumnTypeName(int column) throws SQLException {
return null; String type = fields.get(column - 1).type;
return type.toUpperCase();
} }
@Override @Override
public boolean isReadOnly(int column) throws SQLException { public boolean isReadOnly(int column) throws SQLException {
return false; return true;
} }
@Override @Override
...@@ -117,16 +177,43 @@ public class RestfulResultSetMetaData implements ResultSetMetaData { ...@@ -117,16 +177,43 @@ public class RestfulResultSetMetaData implements ResultSetMetaData {
@Override @Override
public String getColumnClassName(int column) throws SQLException { public String getColumnClassName(int column) throws SQLException {
return null; String type = this.fields.get(column - 1).type;
String columnClassName = "";
switch (type) {
case "BOOL":
return Boolean.class.getName();
case "TINYINT":
case "SMALLINT":
return Short.class.getName();
case "INT":
return Integer.class.getName();
case "BIGINT":
return Long.class.getName();
case "FLOAT":
return Float.class.getName();
case "DOUBLE":
return Double.class.getName();
case "TIMESTAMP":
return Timestamp.class.getName();
case "BINARY":
case "NCHAR":
return String.class.getName();
}
return columnClassName;
} }
@Override @Override
public <T> T unwrap(Class<T> iface) throws SQLException { public <T> T unwrap(Class<T> iface) throws SQLException {
return null; try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw new SQLException("Unable to unwrap to " + iface.toString());
}
} }
@Override @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException { public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false; return iface.isInstance(this);
} }
} }
...@@ -14,7 +14,6 @@ import java.util.stream.Collectors; ...@@ -14,7 +14,6 @@ import java.util.stream.Collectors;
public class RestfulStatement implements Statement { public class RestfulStatement implements Statement {
private static final String STATEMENT_CLOSED = "Statement already closed.";
private boolean closed; private boolean closed;
private String database; private String database;
private final RestfulConnection conn; private final RestfulConnection conn;
...@@ -65,37 +64,18 @@ public class RestfulStatement implements Statement { ...@@ -65,37 +64,18 @@ public class RestfulStatement implements Statement {
public ResultSet executeQuery(String sql) throws SQLException { public ResultSet executeQuery(String sql) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException("statement already closed"); throw new SQLException("statement already closed");
if (!SqlSyntaxValidator.isSelectSql(sql)) if (!SqlSyntaxValidator.isValidForExecuteQuery(sql))
throw new SQLException("not a select sql for executeQuery: " + sql); throw new SQLException("not a valid sql for executeQuery: " + sql);
final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql"; final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql";
// row data if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) {
String result = HttpClientPoolUtil.execute(url, sql); return executeOneQuery(url, sql);
JSONObject resultJson = JSON.parseObject(result);
if (resultJson.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + resultJson.getString("desc") + "\n" + "error code: " + resultJson.getString("code")));
} }
// parse table name from sql if (this.database == null || this.database.isEmpty())
String[] tableIdentifiers = parseTableIdentifier(sql); throw new SQLException("Database not specified or available");
if (tableIdentifiers != null) { HttpClientPoolUtil.execute(url, "use " + this.database);
List<JSONObject> fieldJsonList = new ArrayList<>(); return executeOneQuery(url, sql);
for (String tableIdentifier : tableIdentifiers) {
// field meta
String fields = HttpClientPoolUtil.execute(url, "DESCRIBE " + tableIdentifier);
JSONObject fieldJson = JSON.parseObject(fields);
if (fieldJson.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + fieldJson.getString("desc") + "\n" + "error code: " + fieldJson.getString("code")));
}
fieldJsonList.add(fieldJson);
}
this.resultSet = new RestfulResultSet(database, this, resultJson, fieldJsonList);
} else {
this.resultSet = new RestfulResultSet(database, this, resultJson);
}
this.affectedRows = 0;
return resultSet;
} }
@Override @Override
...@@ -105,19 +85,15 @@ public class RestfulStatement implements Statement { ...@@ -105,19 +85,15 @@ public class RestfulStatement implements Statement {
if (!SqlSyntaxValidator.isValidForExecuteUpdate(sql)) if (!SqlSyntaxValidator.isValidForExecuteUpdate(sql))
throw new SQLException("not a valid sql for executeUpdate: " + sql); throw new SQLException("not a valid sql for executeUpdate: " + sql);
if (this.database == null) final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql";
throw new SQLException("Database not specified or available"); if (SqlSyntaxValidator.isDatabaseUnspecifiedUpdate(sql)) {
return executeOneUpdate(url, sql);
final String url = "http://" + conn.getHost().trim() + ":" + conn.getPort() + "/rest/sql";
// HttpClientPoolUtil.execute(url, "use " + conn.getDatabase());
String result = HttpClientPoolUtil.execute(url, sql);
JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + jsonObject.getString("desc") + "\n" + "error code: " + jsonObject.getString("code")));
} }
this.resultSet = null;
this.affectedRows = Integer.parseInt(jsonObject.getString("rows")); if (this.database == null || this.database.isEmpty())
return this.affectedRows; throw new SQLException("Database not specified or available");
HttpClientPoolUtil.execute(url, "use " + this.database);
return executeOneUpdate(url, sql);
} }
@Override @Override
...@@ -131,14 +107,14 @@ public class RestfulStatement implements Statement { ...@@ -131,14 +107,14 @@ public class RestfulStatement implements Statement {
@Override @Override
public int getMaxFieldSize() throws SQLException { public int getMaxFieldSize() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return TSDBConstants.maxFieldSize; return TSDBConstants.maxFieldSize;
} }
@Override @Override
public void setMaxFieldSize(int max) throws SQLException { public void setMaxFieldSize(int max) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (max < 0) if (max < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES); throw new SQLException(TSDBConstants.INVALID_VARIABLES);
// nothing to do // nothing to do
...@@ -147,14 +123,14 @@ public class RestfulStatement implements Statement { ...@@ -147,14 +123,14 @@ public class RestfulStatement implements Statement {
@Override @Override
public int getMaxRows() throws SQLException { public int getMaxRows() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return 0; return 0;
} }
@Override @Override
public void setMaxRows(int max) throws SQLException { public void setMaxRows(int max) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (max < 0) if (max < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES); throw new SQLException(TSDBConstants.INVALID_VARIABLES);
// nothing to do // nothing to do
...@@ -163,20 +139,20 @@ public class RestfulStatement implements Statement { ...@@ -163,20 +139,20 @@ public class RestfulStatement implements Statement {
@Override @Override
public void setEscapeProcessing(boolean enable) throws SQLException { public void setEscapeProcessing(boolean enable) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(RestfulStatement.STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
} }
@Override @Override
public int getQueryTimeout() throws SQLException { public int getQueryTimeout() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return 0; return 0;
} }
@Override @Override
public void setQueryTimeout(int seconds) throws SQLException { public void setQueryTimeout(int seconds) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (seconds < 0) if (seconds < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES); throw new SQLException(TSDBConstants.INVALID_VARIABLES);
} }
...@@ -189,7 +165,7 @@ public class RestfulStatement implements Statement { ...@@ -189,7 +165,7 @@ public class RestfulStatement implements Statement {
@Override @Override
public SQLWarning getWarnings() throws SQLException { public SQLWarning getWarnings() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return null; return null;
} }
...@@ -197,53 +173,93 @@ public class RestfulStatement implements Statement { ...@@ -197,53 +173,93 @@ public class RestfulStatement implements Statement {
public void clearWarnings() throws SQLException { public void clearWarnings() throws SQLException {
// nothing to do // nothing to do
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
} }
@Override @Override
public void setCursorName(String name) throws SQLException { public void setCursorName(String name) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(RestfulStatement.STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public boolean execute(String sql) throws SQLException { public boolean execute(String sql) throws SQLException {
if (isClosed()) { if (isClosed())
throw new SQLException("Invalid method call on a closed statement."); throw new SQLException("Invalid method call on a closed statement.");
} if (!SqlSyntaxValidator.isValidForExecute(sql))
throw new SQLException("not a valid sql for execute: " + sql);
//如果执行了use操作应该将当前Statement的catalog设置为新的database //如果执行了use操作应该将当前Statement的catalog设置为新的database
final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql";
if (SqlSyntaxValidator.isUseSql(sql)) { if (SqlSyntaxValidator.isUseSql(sql)) {
HttpClientPoolUtil.execute(url, sql);
this.database = sql.trim().replace("use", "").trim(); this.database = sql.trim().replace("use", "").trim();
this.conn.setCatalog(this.database); this.conn.setCatalog(this.database);
} else if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) {
executeOneQuery(url, sql);
} else if (SqlSyntaxValidator.isDatabaseUnspecifiedUpdate(sql)) {
executeOneUpdate(url, sql);
} else {
if (SqlSyntaxValidator.isValidForExecuteQuery(sql)) {
executeQuery(sql);
} else {
executeUpdate(sql);
}
} }
if (this.database == null)
throw new SQLException("Database not specified or available");
if (SqlSyntaxValidator.isSelectSql(sql)) { return true;
executeQuery(sql); }
} else if (SqlSyntaxValidator.isShowSql(sql) || SqlSyntaxValidator.isDescribeSql(sql)) {
final String url = "http://" + conn.getHost().trim() + ":" + conn.getPort() + "/rest/sql"; private ResultSet executeOneQuery(String url, String sql) throws SQLException {
if (!SqlSyntaxValidator.isShowDatabaseSql(sql)) { if (!SqlSyntaxValidator.isValidForExecuteQuery(sql))
HttpClientPoolUtil.execute(url, "use " + conn.getDatabase()); throw new SQLException("not a select sql for executeQuery: " + sql);
}
String result = HttpClientPoolUtil.execute(url, sql); // row data
JSONObject resultJson = JSON.parseObject(result); String result = HttpClientPoolUtil.execute(url, sql);
if (resultJson.getString("status").equals("error")) { JSONObject resultJson = JSON.parseObject(result);
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + resultJson.getString("desc") + "\n" + "error code: " + resultJson.getString("code"))); if (resultJson.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + resultJson.getString("desc") + "\n" + "error code: " + resultJson.getString("code")));
}
// parse table name from sql
String[] tableIdentifiers = parseTableIdentifier(sql);
if (tableIdentifiers != null) {
List<JSONObject> fieldJsonList = new ArrayList<>();
for (String tableIdentifier : tableIdentifiers) {
// field meta
String fields = HttpClientPoolUtil.execute(url, "DESCRIBE " + tableIdentifier);
JSONObject fieldJson = JSON.parseObject(fields);
if (fieldJson.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + fieldJson.getString("desc") + "\n" + "error code: " + fieldJson.getString("code")));
}
fieldJsonList.add(fieldJson);
} }
this.resultSet = new RestfulResultSet(database, this, resultJson); this.resultSet = new RestfulResultSet(database, this, resultJson, fieldJsonList);
} else { } else {
executeUpdate(sql); this.resultSet = new RestfulResultSet(database, this, resultJson);
} }
this.affectedRows = 0;
return resultSet;
}
return true; private int executeOneUpdate(String url, String sql) throws SQLException {
if (!SqlSyntaxValidator.isValidForExecuteUpdate(sql))
throw new SQLException("not a valid sql for executeUpdate: " + sql);
String result = HttpClientPoolUtil.execute(url, sql);
JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + jsonObject.getString("desc") + "\n" + "error code: " + jsonObject.getString("code")));
}
this.resultSet = null;
this.affectedRows = Integer.parseInt(jsonObject.getString("rows"));
return this.affectedRows;
} }
@Override @Override
public ResultSet getResultSet() throws SQLException { public ResultSet getResultSet() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return resultSet; return resultSet;
} }
...@@ -275,7 +291,7 @@ public class RestfulStatement implements Statement { ...@@ -275,7 +291,7 @@ public class RestfulStatement implements Statement {
@Override @Override
public void setFetchSize(int rows) throws SQLException { public void setFetchSize(int rows) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (rows < 0) if (rows < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES); throw new SQLException(TSDBConstants.INVALID_VARIABLES);
//nothing to do //nothing to do
...@@ -284,28 +300,28 @@ public class RestfulStatement implements Statement { ...@@ -284,28 +300,28 @@ public class RestfulStatement implements Statement {
@Override @Override
public int getFetchSize() throws SQLException { public int getFetchSize() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return 0; return 0;
} }
@Override @Override
public int getResultSetConcurrency() throws SQLException { public int getResultSetConcurrency() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return this.resultSet.getConcurrency(); return this.resultSet.getConcurrency();
} }
@Override @Override
public int getResultSetType() throws SQLException { public int getResultSetType() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return this.resultSet.getType(); return this.resultSet.getType();
} }
@Override @Override
public void addBatch(String sql) throws SQLException { public void addBatch(String sql) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
//TODO: //TODO:
} }
...@@ -323,14 +339,14 @@ public class RestfulStatement implements Statement { ...@@ -323,14 +339,14 @@ public class RestfulStatement implements Statement {
@Override @Override
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return this.conn; return this.conn;
} }
@Override @Override
public boolean getMoreResults(int current) throws SQLException { public boolean getMoreResults(int current) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (resultSet == null) if (resultSet == null)
return false; return false;
...@@ -388,7 +404,7 @@ public class RestfulStatement implements Statement { ...@@ -388,7 +404,7 @@ public class RestfulStatement implements Statement {
@Override @Override
public int getResultSetHoldability() throws SQLException { public int getResultSetHoldability() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return this.resultSet.getHoldability(); return this.resultSet.getHoldability();
} }
...@@ -400,28 +416,28 @@ public class RestfulStatement implements Statement { ...@@ -400,28 +416,28 @@ public class RestfulStatement implements Statement {
@Override @Override
public void setPoolable(boolean poolable) throws SQLException { public void setPoolable(boolean poolable) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
//nothing to do //nothing to do
} }
@Override @Override
public boolean isPoolable() throws SQLException { public boolean isPoolable() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return false; return false;
} }
@Override @Override
public void closeOnCompletion() throws SQLException { public void closeOnCompletion() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
this.closeOnCompletion = true; this.closeOnCompletion = true;
} }
@Override @Override
public boolean isCloseOnCompletion() throws SQLException { public boolean isCloseOnCompletion() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(STATEMENT_CLOSED); throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return this.closeOnCompletion; return this.closeOnCompletion;
} }
......
...@@ -20,8 +20,11 @@ import java.sql.Connection; ...@@ -20,8 +20,11 @@ import java.sql.Connection;
public class SqlSyntaxValidator { public class SqlSyntaxValidator {
private static final String[] updateSQL = {"insert", "update", "delete", "create", "alter", "drop", "show", "describe", "use", "import"}; private static final String[] SQL = {"select", "insert", "import", "create", "use", "alter", "drop", "set", "show", "describe"};
private static final String[] querySQL = {"select"}; private static final String[] updateSQL = {"insert", "import", "create", "use", "alter", "drop", "set"};
private static final String[] querySQL = {"select", "show", "describe"};
private static final String[] databaseUnspecifiedShow = {"databases", "dnodes", "mnodes", "variables"};
private TSDBConnection tsdbConnection; private TSDBConnection tsdbConnection;
...@@ -37,8 +40,38 @@ public class SqlSyntaxValidator { ...@@ -37,8 +40,38 @@ public class SqlSyntaxValidator {
return false; return false;
} }
public static boolean isValidForExecuteQuery(String sql) {
for (String prefix : querySQL) {
if (sql.trim().toLowerCase().startsWith(prefix))
return true;
}
return false;
}
public static boolean isValidForExecute(String sql) {
for (String prefix : SQL) {
if (sql.trim().toLowerCase().startsWith(prefix))
return true;
}
return false;
}
public static boolean isDatabaseUnspecifiedQuery(String sql) {
for (String databaseObj : databaseUnspecifiedShow) {
if (sql.trim().toLowerCase().matches("show\\s+" + databaseObj + ".*"))
return true;
}
return false;
}
public static boolean isDatabaseUnspecifiedUpdate(String sql) {
sql = sql.trim().toLowerCase();
return sql.matches("create\\s+database.*") || sql.startsWith("set") || sql.matches("drop\\s+database.*");
}
public static boolean isUseSql(String sql) { public static boolean isUseSql(String sql) {
return sql.trim().toLowerCase().startsWith("use") || sql.trim().toLowerCase().matches("create\\s*database.*") || sql.toLowerCase().toLowerCase().matches("drop\\s*database.*"); return sql.trim().toLowerCase().startsWith("use");
// || sql.trim().toLowerCase().matches("create\\s*database.*") || sql.toLowerCase().toLowerCase().matches("drop\\s*database.*");
} }
public static boolean isShowSql(String sql) { public static boolean isShowSql(String sql) {
...@@ -58,8 +91,9 @@ public class SqlSyntaxValidator { ...@@ -58,8 +91,9 @@ public class SqlSyntaxValidator {
return sql.trim().toLowerCase().startsWith("select"); return sql.trim().toLowerCase().startsWith("select");
} }
public static boolean isShowDatabaseSql(String sql) { public static boolean isShowDatabaseSql(String sql) {
return sql.trim().toLowerCase().matches("show\\s*databases"); return sql.trim().toLowerCase().matches("show\\s*databases");
} }
} }
package com.taosdata.jdbc;
import com.taosdata.jdbc.utils.TDNodes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
public abstract class BaseTest {
private static boolean testCluster = false;
private static TDNodes nodes = new TDNodes();
@BeforeClass
public static void setupEnv() {
try {
if (nodes.getTDNode(1).getTaosdPid() != null) {
System.out.println("Kill taosd before running JDBC test");
nodes.getTDNode(1).setRunning(1);
nodes.stop(1);
}
nodes.setTestCluster(testCluster);
nodes.deploy(1);
nodes.start(1);
} catch (Exception e) {
e.printStackTrace();
}
}
@AfterClass
public static void cleanUpEnv() {
nodes.stop(1);
}
}
\ No newline at end of file
package com.taosdata.jdbc;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.*;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class BatchInsertTest {
private Connection connection;
private static String dbName = "test";
private static String stbName = "meters";
private static String host = "127.0.0.1";
private static int numOfTables = 30;
private static int numOfRecordsPerTable = 1000;
private static long ts = 1496732686000l;
private static String tablePrefix = "t";
@Before
public void createDatabase() throws SQLException {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) {
return;
}
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
Statement stmt = connection.createStatement();
stmt.execute("drop database if exists " + dbName);
stmt.execute("create database if not exists " + dbName);
stmt.execute("use " + dbName);
String createTableSql = "create table " + stbName + "(ts timestamp, f1 int, f2 int, f3 int) tags(areaid int, loc binary(20))";
stmt.execute(createTableSql);
for (int i = 0; i < numOfTables; i++) {
String loc = i % 2 == 0 ? "beijing" : "shanghai";
String createSubTalbesSql = "create table " + tablePrefix + i + " using " + stbName + " tags(" + i + ", '" + loc + "')";
stmt.execute(createSubTalbesSql);
}
stmt.close();
}
@Test
public void testBatchInsert() throws SQLException {
ExecutorService executorService = Executors.newFixedThreadPool(numOfTables);
for (int i = 0; i < numOfTables; i++) {
final int index = i;
executorService.execute(() -> {
try {
long startTime = System.currentTimeMillis();
Statement statement = connection.createStatement(); // get statement
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO " + tablePrefix + index + " VALUES");
Random rand = new Random();
for (int j = 1; j <= numOfRecordsPerTable; j++) {
sb.append("(" + (ts + j) + ", ");
sb.append(rand.nextInt(100) + ", ");
sb.append(rand.nextInt(100) + ", ");
sb.append(rand.nextInt(100) + ")");
}
statement.addBatch(sb.toString());
statement.executeBatch();
long endTime = System.currentTimeMillis();
System.out.println("Thread " + index + " takes " + (endTime - startTime) + " microseconds");
connection.commit();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from meters");
int num = 0;
while (rs.next()) {
num++;
}
assertEquals(num, numOfTables * numOfRecordsPerTable);
rs.close();
}
@After
public void close() {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package com.taosdata.jdbc; package com.taosdata.jdbc;
import org.junit.AfterClass; import org.junit.*;
import org.junit.BeforeClass; import org.junit.runners.MethodSorters;
import org.junit.FixMethodOrder;
import org.junit.Test;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
...@@ -11,14 +9,13 @@ import java.util.Properties; ...@@ -11,14 +9,13 @@ import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@FixMethodOrder() @FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class PreparedStatementTest extends BaseTest { public class PreparedStatementTest {
static Connection connection = null; static Connection connection;
static PreparedStatement statement = null; static TSDBPreparedStatement statement;
static String dbName = "test"; static String dbName = "test";
static String tName = "t0"; static String tName = "t0";
static String host = "localhost"; static String host = "localhost";
static ResultSet resSet = null;
@BeforeClass @BeforeClass
public static void createConnection() throws SQLException { public static void createConnection() throws SQLException {
...@@ -28,19 +25,16 @@ public class PreparedStatementTest extends BaseTest { ...@@ -28,19 +25,16 @@ public class PreparedStatementTest extends BaseTest {
return; return;
} }
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
String sql = "drop database if exists " + dbName; String sql = "drop database if exists " + dbName;
statement = (TSDBPreparedStatement) connection.prepareStatement(sql); statement = (TSDBPreparedStatement) connection.prepareStatement(sql);
} }
@Test @Test
public void createTableAndQuery() throws SQLException { public void case001_createTableAndQuery() throws SQLException {
long ts = System.currentTimeMillis(); long ts = System.currentTimeMillis();
statement.executeUpdate("create database if not exists " + dbName); statement.executeUpdate("create database if not exists " + dbName);
...@@ -48,141 +42,132 @@ public class PreparedStatementTest extends BaseTest { ...@@ -48,141 +42,132 @@ public class PreparedStatementTest extends BaseTest {
statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", 1)"); statement.executeUpdate("insert into " + dbName + "." + tName + " values (" + ts + ", 1)");
PreparedStatement selectStatement = connection.prepareStatement("select * from " + dbName + "." + tName); PreparedStatement selectStatement = connection.prepareStatement("select * from " + dbName + "." + tName);
ResultSet resultSet = selectStatement.executeQuery(); ResultSet resultSet = selectStatement.executeQuery();
assertTrue(null != resultSet); assertTrue(null != resultSet);
boolean isClosed = statement.isClosed(); boolean isClosed = statement.isClosed();
assertEquals(false, isClosed); assertEquals(false, isClosed);
selectStatement.close();
} }
@Test @Test
public void testPreparedStatement() throws SQLException { public void case002_testPreparedStatement() throws SQLException {
long ts = System.currentTimeMillis() + 20000; long ts = System.currentTimeMillis() + 20000;
PreparedStatement saveStatement = connection
.prepareStatement("insert into " + dbName + "." + tName + " values (" + ts + ", 1)");
PreparedStatement saveStatement = connection.prepareStatement("insert into " + dbName + "." + tName + " values (" + ts + ", 1)");
int affectedRows = saveStatement.executeUpdate(); int affectedRows = saveStatement.executeUpdate();
assertTrue(1 == affectedRows); assertTrue(1 == affectedRows);
saveStatement.close();
} }
@Test @Test
public void testSavedPreparedStatement() throws SQLException { public void case003_testSavedPreparedStatement() throws SQLException {
long ts = System.currentTimeMillis(); long ts = System.currentTimeMillis();
TSDBPreparedStatement saveStatement = (TSDBPreparedStatement) connection.prepareStatement("insert into " + dbName + "." + tName + " values (?, ?)");
TSDBPreparedStatement saveStatement = (TSDBPreparedStatement) connection
.prepareStatement("insert into " + dbName + "." + tName + " values (?, ?)");
saveStatement.setObject(1, ts + 10000); saveStatement.setObject(1, ts + 10000);
saveStatement.setObject(2, 3); saveStatement.setObject(2, 3);
int rows = saveStatement.executeUpdate(); int rows = saveStatement.executeUpdate();
assertEquals(1, rows); assertEquals(1, rows);
saveStatement.close();
} }
@Test @Test
public void testUnsupport() { public void case004_testUnsupport() throws SQLException {
// if(null == resSet) {
// return; Assert.assertNotNull(statement.unwrap(TSDBPreparedStatement.class));
// } Assert.assertTrue(statement.isWrapperFor(TSDBPreparedStatement.class));
TSDBPreparedStatement tsdbStatement = (TSDBPreparedStatement) statement;
try {
tsdbStatement.unwrap(null);
} catch (SQLException e) {
}
try {
tsdbStatement.isWrapperFor(null);
} catch (SQLException e) {
}
try { try {
tsdbStatement.getMaxFieldSize(); statement.getMaxFieldSize();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setMaxFieldSize(0); statement.setMaxFieldSize(0);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setEscapeProcessing(true); statement.setEscapeProcessing(true);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.cancel(); statement.cancel();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getWarnings(); statement.getWarnings();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.clearWarnings(); statement.clearWarnings();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setCursorName(null); statement.setCursorName(null);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getMoreResults(); statement.getMoreResults();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setFetchDirection(0); statement.setFetchDirection(0);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getFetchDirection(); statement.getFetchDirection();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getResultSetConcurrency(); statement.getResultSetConcurrency();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getResultSetType(); statement.getResultSetType();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getConnection(); statement.getConnection();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getMoreResults(); statement.getMoreResults();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getGeneratedKeys(); statement.getGeneratedKeys();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.executeUpdate(null, 0); statement.executeUpdate(null, 0);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.executeUpdate(null, new int[]{0}); statement.executeUpdate(null, new int[]{0});
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.executeUpdate(null, new String[]{"str1", "str2"}); statement.executeUpdate(null, new String[]{"str1", "str2"});
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getResultSetHoldability(); statement.getResultSetHoldability();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setPoolable(true); statement.setPoolable(true);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.isPoolable(); statement.isPoolable();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.closeOnCompletion(); statement.closeOnCompletion();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.isCloseOnCompletion(); statement.isCloseOnCompletion();
} catch (SQLException e) { } catch (SQLException e) {
} }
} }
......
...@@ -6,76 +6,67 @@ import org.junit.Test; ...@@ -6,76 +6,67 @@ import org.junit.Test;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
import java.util.Random;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.*;
import static org.junit.Assert.assertTrue;
public class QueryDataTest extends BaseTest { public class QueryDataTest {
static Connection connection = null; static Connection connection;
static Statement statement = null; static Statement statement;
static String dbName = "test"; static String dbName = "test";
static String stbName = "meters"; static String stbName = "meters";
static String host = "localhost"; static String host = "127.0.0.1";
static int numOfTables = 30;
final static int numOfRecordsPerTable = 1000;
static long ts = 1496732686000l;
final static String tablePrefix = "t";
@Before @Before
public void createDatabase() throws SQLException { public void createDatabase() {
try { try {
Class.forName("com.taosdata.jdbc.TSDBDriver"); Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) { Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("use " + dbName);
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))";
statement.executeUpdate(createTableSql);
} catch (ClassNotFoundException | SQLException e) {
return; return;
} }
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("use " + dbName);
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(6))";
statement.executeUpdate(createTableSql);
} }
@Test
public void testQueryBinaryData() throws SQLException{
String insertSql = "insert into " + stbName + " values(now, 'taosda')";
System.out.println(insertSql);
@Test
public void testQueryBinaryData() throws SQLException {
String insertSql = "insert into " + stbName + " values(now, 'taosdata')";
System.out.println(insertSql);
statement.executeUpdate(insertSql); statement.executeUpdate(insertSql);
String querySql = "select * from " + stbName; String querySql = "select * from " + stbName;
ResultSet rs = statement.executeQuery(querySql); ResultSet rs = statement.executeQuery(querySql);
while(rs.next()) { while (rs.next()) {
String name = rs.getString(2) + "001"; String name = rs.getString(2);
System.out.println("name = " + name); System.out.println("name = " + name);
assertEquals(name, "taosda001"); assertEquals("taosdata", name);
} }
rs.close(); rs.close();
} }
@After @After
public void close() throws Exception { public void close() {
statement.close(); try {
connection.close(); if (statement != null)
Thread.sleep(10); statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
package com.taosdata.jdbc; package com.taosdata.jdbc;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
...@@ -13,42 +14,37 @@ import java.util.Properties; ...@@ -13,42 +14,37 @@ import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class ResultSetTest extends BaseTest { public class ResultSetTest {
static Connection connection = null; static Connection connection;
static Statement statement = null; static Statement statement;
static String dbName = "test"; static String dbName = "test";
static String tName = "t0"; static String tName = "t0";
static String host = "localhost"; static String host = "localhost";
static ResultSet resSet = null; static ResultSet resSet;
@BeforeClass @BeforeClass
public static void createDatabaseAndTable() throws SQLException { public static void createDatabaseAndTable() {
try { try {
Class.forName("com.taosdata.jdbc.TSDBDriver"); Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) { Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName);
statement.execute("use " + dbName);
statement.executeUpdate("create table if not exists " + dbName + "." + tName + " (ts timestamp, k1 int, k2 bigint, k3 float, k4 double, k5 binary(30), k6 smallint, k7 bool, k8 nchar(20))");
} catch (ClassNotFoundException | SQLException e) {
return; return;
} }
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("create table if not exists " + dbName + "." + tName +
" (ts timestamp, k1 int, k2 bigint, k3 float, k4 double, k5 binary(30), k6 smallint, k7 bool, k8 nchar(20))");
statement.executeQuery("use " + dbName);
} }
@Test @Test
public void testResultSet() { public void testResultSet() {
String sql = null; String sql;
long ts = 1496732686000l; long ts = 1496732686000l;
int v1 = 2147483600; int v1 = 2147483600;
long v2 = ts + 1000; long v2 = ts + 1000;
...@@ -119,16 +115,8 @@ public class ResultSetTest extends BaseTest { ...@@ -119,16 +115,8 @@ public class ResultSetTest extends BaseTest {
public void testUnsupport() throws SQLException { public void testUnsupport() throws SQLException {
statement.executeQuery("show databases"); statement.executeQuery("show databases");
resSet = statement.getResultSet(); resSet = statement.getResultSet();
try { Assert.assertNotNull(resSet.unwrap(TSDBResultSet.class));
resSet.unwrap(null); Assert.assertTrue(resSet.isWrapperFor(TSDBResultSet.class));
} catch (SQLException e) {
assertTrue(e.getMessage().contains("this operation is NOT supported currently!"));
}
try {
resSet.isWrapperFor(null);
} catch (SQLException e) {
assertTrue(e.getMessage().contains("this operation is NOT supported currently!"));
}
try { try {
resSet.getAsciiStream(0); resSet.getAsciiStream(0);
} catch (SQLException e) { } catch (SQLException e) {
...@@ -815,13 +803,18 @@ public class ResultSetTest extends BaseTest { ...@@ -815,13 +803,18 @@ public class ResultSetTest extends BaseTest {
assertEquals(res.length, 2); assertEquals(res.length, 2);
statement.clearBatch(); statement.clearBatch();
} }
@AfterClass
public static void close() throws Exception {
statement.executeUpdate("drop database " + dbName);
statement.close();
connection.close();
Thread.sleep(10);
@AfterClass
public static void close() {
try {
statement.executeUpdate("drop database " + dbName);
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -29,6 +29,7 @@ public class StableTest { ...@@ -29,6 +29,7 @@ public class StableTest {
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
statement.execute("drop database if exists " + dbName);
statement.execute("create database if not exists " + dbName); statement.execute("create database if not exists " + dbName);
statement.execute("use " + dbName); statement.execute("use " + dbName);
statement.close(); statement.close();
......
package com.taosdata.jdbc; package com.taosdata.jdbc;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
...@@ -16,23 +17,22 @@ public class StatementTest { ...@@ -16,23 +17,22 @@ public class StatementTest {
static String dbName = "test"; static String dbName = "test";
static String tName = "t0"; static String tName = "t0";
static String host = "localhost"; static String host = "localhost";
static ResultSet resSet = null;
@BeforeClass @BeforeClass
public static void createConnection() throws SQLException { public static void createConnection() throws SQLException {
try { try {
Class.forName("com.taosdata.jdbc.TSDBDriver"); Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
return; return;
} }
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", properties);
statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
} }
@Test @Test
...@@ -49,7 +49,6 @@ public class StatementTest { ...@@ -49,7 +49,6 @@ public class StatementTest {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Test @Test
...@@ -67,118 +66,46 @@ public class StatementTest { ...@@ -67,118 +66,46 @@ public class StatementTest {
assertEquals(false, isClosed); assertEquals(false, isClosed);
} }
@Test @Test(expected = SQLException.class)
public void testUnsupport() { public void testUnsupport() throws SQLException {
TSDBStatement tsdbStatement = (TSDBStatement) statement; Assert.assertNotNull(statement.unwrap(TSDBStatement.class));
try { Assert.assertTrue(statement.isWrapperFor(TSDBStatement.class));
tsdbStatement.unwrap(null);
} catch (SQLException e) { statement.getMaxFieldSize();
} statement.setMaxFieldSize(0);
try { statement.setEscapeProcessing(true);
tsdbStatement.isWrapperFor(null); statement.cancel();
} catch (SQLException e) { statement.getWarnings();
} statement.clearWarnings();
try { statement.setCursorName(null);
tsdbStatement.getMaxFieldSize(); statement.getMoreResults();
} catch (SQLException e) { statement.setFetchDirection(0);
} statement.getFetchDirection();
try { statement.getResultSetConcurrency();
tsdbStatement.setMaxFieldSize(0); statement.getResultSetType();
} catch (SQLException e) { statement.getConnection();
} statement.getMoreResults();
try { statement.getGeneratedKeys();
tsdbStatement.setEscapeProcessing(true); statement.executeUpdate(null, 0);
} catch (SQLException e) { statement.executeUpdate(null, new int[]{0});
} statement.executeUpdate(null, new String[]{"str1", "str2"});
try { statement.getResultSetHoldability();
tsdbStatement.cancel(); statement.setPoolable(true);
} catch (SQLException e) { statement.isPoolable();
} statement.closeOnCompletion();
try { statement.isCloseOnCompletion();
tsdbStatement.getWarnings();
} catch (SQLException e) {
}
try {
tsdbStatement.clearWarnings();
} catch (SQLException e) {
}
try {
tsdbStatement.setCursorName(null);
} catch (SQLException e) {
}
try {
tsdbStatement.getMoreResults();
} catch (SQLException e) {
}
try {
tsdbStatement.setFetchDirection(0);
} catch (SQLException e) {
}
try {
tsdbStatement.getFetchDirection();
} catch (SQLException e) {
}
try {
tsdbStatement.getResultSetConcurrency();
} catch (SQLException e) {
}
try {
tsdbStatement.getResultSetType();
} catch (SQLException e) {
}
try {
tsdbStatement.getConnection();
} catch (SQLException e) {
}
try {
tsdbStatement.getMoreResults();
} catch (SQLException e) {
}
try {
tsdbStatement.getGeneratedKeys();
} catch (SQLException e) {
}
try {
tsdbStatement.executeUpdate(null, 0);
} catch (SQLException e) {
}
try {
tsdbStatement.executeUpdate(null, new int[]{0});
} catch (SQLException e) {
}
try {
tsdbStatement.executeUpdate(null, new String[]{"str1", "str2"});
} catch (SQLException e) {
}
try {
tsdbStatement.getResultSetHoldability();
} catch (SQLException e) {
}
try {
tsdbStatement.setPoolable(true);
} catch (SQLException e) {
}
try {
tsdbStatement.isPoolable();
} catch (SQLException e) {
}
try {
tsdbStatement.closeOnCompletion();
} catch (SQLException e) {
}
try {
tsdbStatement.isCloseOnCompletion();
} catch (SQLException e) {
}
} }
@AfterClass @AfterClass
public static void close() throws Exception { public static void close() {
if (!statement.isClosed()) { try {
statement.executeUpdate("drop database if exists " + dbName); statement.execute("drop database if exists " + dbName);
statement.close(); if (statement != null)
connection.close(); statement.close();
Thread.sleep(10); if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
...@@ -10,36 +10,37 @@ import java.sql.SQLException; ...@@ -10,36 +10,37 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.Properties; import java.util.Properties;
public class SubscribeTest extends BaseTest { public class SubscribeTest {
Connection connection = null; Connection connection;
Statement statement = null; Statement statement;
String dbName = "test"; String dbName = "test";
String tName = "t0"; String tName = "t0";
String host = "localhost"; String host = "localhost";
String topic = "test"; String topic = "test";
@Before @Before
public void createDatabase() throws SQLException { public void createDatabase() {
try { try {
Class.forName("com.taosdata.jdbc.TSDBDriver"); Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) { Properties properties = new Properties();
return; properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
} properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("create database if not exists " + dbName); statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)"); statement.executeUpdate("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
long ts = System.currentTimeMillis(); long ts = System.currentTimeMillis();
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
ts += i; ts += i;
String sql = "insert into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")"; String sql = "insert into " + dbName + "." + tName + " values (" + ts + ", " + (100 + i) + ", " + i + ")";
statement.executeUpdate(sql); statement.executeUpdate(sql);
}
} catch (ClassNotFoundException | SQLException e) {
return;
} }
} }
...@@ -79,10 +80,16 @@ public class SubscribeTest extends BaseTest { ...@@ -79,10 +80,16 @@ public class SubscribeTest extends BaseTest {
} }
@After @After
public void close() throws Exception { public void close() {
statement.executeQuery("drop database " + dbName); try {
statement.close(); statement.executeQuery("drop database " + dbName);
connection.close(); if (statement != null)
Thread.sleep(10); statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -6,37 +6,9 @@ import java.sql.*; ...@@ -6,37 +6,9 @@ import java.sql.*;
import java.util.Properties; import java.util.Properties;
public class TSDBDatabaseMetaDataTest { public class TSDBDatabaseMetaDataTest {
private TSDBDatabaseMetaData metaData;
private static final String host = "127.0.0.1"; private static final String host = "127.0.0.1";
private Connection connection; private static Connection connection;
private static TSDBDatabaseMetaData metaData;
@BeforeClass
public void before() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata", properties);
metaData = connection.getMetaData().unwrap(TSDBDatabaseMetaData.class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public void after() {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test @Test
public void unwrap() throws SQLException { public void unwrap() throws SQLException {
...@@ -61,7 +33,7 @@ public class TSDBDatabaseMetaDataTest { ...@@ -61,7 +33,7 @@ public class TSDBDatabaseMetaDataTest {
@Test @Test
public void getURL() throws SQLException { public void getURL() throws SQLException {
Assert.assertEquals("jdbc:TAOS://localhost:6030/?user=root&password=taosdata", metaData.getURL()); Assert.assertEquals("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata", metaData.getURL());
} }
@Test @Test
...@@ -975,4 +947,32 @@ public class TSDBDatabaseMetaDataTest { ...@@ -975,4 +947,32 @@ public class TSDBDatabaseMetaDataTest {
public void generatedKeyAlwaysReturned() throws SQLException { public void generatedKeyAlwaysReturned() throws SQLException {
Assert.assertFalse(metaData.generatedKeyAlwaysReturned()); Assert.assertFalse(metaData.generatedKeyAlwaysReturned());
} }
@BeforeClass
public static void beforeClass() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata", properties);
metaData = connection.getMetaData().unwrap(TSDBDatabaseMetaData.class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
\ No newline at end of file
package com.taosdata.jdbc.lib;
import com.taosdata.jdbc.TSDBDriver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class TSDBCommon {
public static Connection getConn(String host) throws SQLException, ClassNotFoundException {
Class.forName("com.taosdata.jdbc.TSDBDriver");
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
return DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
}
public static void createDatabase(Connection connection, String dbName) throws SQLException {
Statement statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("use " + dbName);
statement.close();
}
public static void createStable(Connection connection, String stbName) throws SQLException {
Statement statement = connection.createStatement();
String createTableSql = "create table " + stbName + "(ts timestamp, f1 int, f2 int, f3 int) tags(areaid int, loc binary(20))";
statement.executeUpdate(createTableSql);
statement.close();
}
public static void createTables(Connection connection, int numOfTables, String stbName,String tablePrefix) throws SQLException {
Statement statement = connection.createStatement();
for(int i = 0; i < numOfTables; i++) {
String loc = i % 2 == 0 ? "beijing" : "shanghai";
String createSubTalbesSql = "create table " + tablePrefix + i + " using " + stbName + " tags(" + i + ", '" + loc + "')";
statement.executeUpdate(createSubTalbesSql);
}
statement.close();
}
}
...@@ -8,6 +8,7 @@ import java.sql.*; ...@@ -8,6 +8,7 @@ import java.sql.*;
public class AuthenticationTest { public class AuthenticationTest {
private static final String host = "127.0.0.1"; private static final String host = "127.0.0.1";
// private static final String host = "master";
private static final String user = "root"; private static final String user = "root";
private static final String password = "123456"; private static final String password = "123456";
private Connection conn; private Connection conn;
......
...@@ -16,10 +16,6 @@ public class SqlSyntaxValidatorTest { ...@@ -16,10 +16,6 @@ public class SqlSyntaxValidatorTest {
@Test @Test
public void isUseSQL() { public void isUseSQL() {
Assert.assertTrue(SqlSyntaxValidator.isUseSql("use database test")); Assert.assertTrue(SqlSyntaxValidator.isUseSql("use database test"));
Assert.assertTrue(SqlSyntaxValidator.isUseSql("create database test"));
Assert.assertTrue(SqlSyntaxValidator.isUseSql("create database if not exist test"));
Assert.assertTrue(SqlSyntaxValidator.isUseSql("drop database test"));
Assert.assertTrue(SqlSyntaxValidator.isUseSql("drop database if exist test"));
} }
} }
\ No newline at end of file
...@@ -163,6 +163,11 @@ do { \ ...@@ -163,6 +163,11 @@ do { \
#define TSDB_BINARY_OP_MULTIPLY 32 #define TSDB_BINARY_OP_MULTIPLY 32
#define TSDB_BINARY_OP_DIVIDE 33 #define TSDB_BINARY_OP_DIVIDE 33
#define TSDB_BINARY_OP_REMAINDER 34 #define TSDB_BINARY_OP_REMAINDER 34
#define IS_RELATION_OPTR(op) (((op) >= TSDB_RELATION_LESS) && ((op) <= TSDB_RELATION_IN))
#define IS_ARITHMETIC_OPTR(op) (((op) >= TSDB_BINARY_OP_ADD) && ((op) <= TSDB_BINARY_OP_REMAINDER))
#define TS_PATH_DELIMITER_LEN 1 #define TS_PATH_DELIMITER_LEN 1
#define TSDB_UNI_LEN 24 #define TSDB_UNI_LEN 24
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
...@@ -134,7 +134,7 @@ int tsem_init(tsem_t *sem, int pshared, unsigned int value) { ...@@ -134,7 +134,7 @@ int tsem_init(tsem_t *sem, int pshared, unsigned int value) {
errno = ENOMEM; errno = ENOMEM;
return -1; return -1;
} }
kern_return_t ret = semaphore_create(sem_port, &p->sem, SYNC_POLICY_FIFO, 0); kern_return_t ret = semaphore_create(sem_port, &p->sem, SYNC_POLICY_FIFO, value);
if (ret != KERN_SUCCESS) { if (ret != KERN_SUCCESS) {
fprintf(stderr, "==%s[%d]%s():[%p]==semophore_create failed\n", basename(__FILE__), __LINE__, __func__, sem); fprintf(stderr, "==%s[%d]%s():[%p]==semophore_create failed\n", basename(__FILE__), __LINE__, __func__, sem);
// we fail-fast here, because we have less-doc about semaphore_create for the moment // we fail-fast here, because we have less-doc about semaphore_create for the moment
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册