Merge branch 'develop' into feature/query

This commit is contained in:
Haojun Liao 2021-01-28 14:14:50 +08:00
commit 3163eff6af
264 changed files with 7977 additions and 4059 deletions

View File

@ -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

View File

@ -13,7 +13,7 @@ ENDIF ()
SET(TD_ACCOUNT FALSE) SET(TD_ACCOUNT FALSE)
SET(TD_ADMIN FALSE) SET(TD_ADMIN FALSE)
SET(TD_GRANT FALSE) SET(TD_GRANT FALSE)
SET(TD_MQTT TRUE) SET(TD_MQTT FALSE)
SET(TD_TSDB_PLUGINS FALSE) SET(TD_TSDB_PLUGINS FALSE)
SET(TD_COVER FALSE) SET(TD_COVER FALSE)
@ -29,6 +29,11 @@ MESSAGE(STATUS "Community directory: " ${TD_COMMUNITY_DIR})
INCLUDE(cmake/input.inc) INCLUDE(cmake/input.inc)
INCLUDE(cmake/platform.inc) INCLUDE(cmake/platform.inc)
IF (TD_WINDOWS OR TD_DARWIN)
SET(TD_SOMODE_STATIC TRUE)
ENDIF ()
INCLUDE(cmake/define.inc) INCLUDE(cmake/define.inc)
INCLUDE(cmake/env.inc) INCLUDE(cmake/env.inc)
INCLUDE(cmake/version.inc) INCLUDE(cmake/version.inc)

79
Jenkinsfile vendored
View File

@ -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"
)
}
}
} }

View File

@ -126,44 +126,57 @@ 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"
nmake nmake
``` ```
If you use the Visual Studio 2019, please open a command window by executing "cmd.exe". If you use the Visual Studio 2019 or 2017:
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"
nmake nmake
``` ```
Or, you can open a command window by clicking Visual Studio 2019 menu "Tools -> Command Line -> Developer Command Prompt" or "Tools -> Command Line -> Developer PowerShell" 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.

View File

@ -128,6 +128,8 @@ IF (TD_DARWIN_64)
SET(COMMON_FLAGS "-std=gnu99 -Wall -Werror -Wno-missing-braces -fPIC -msse4.2 -D_FILE_OFFSET_BITS=64 -D_LARGE_FILE") SET(COMMON_FLAGS "-std=gnu99 -Wall -Werror -Wno-missing-braces -fPIC -msse4.2 -D_FILE_OFFSET_BITS=64 -D_LARGE_FILE")
SET(DEBUG_FLAGS "-O0 -g3 -DDEBUG") SET(DEBUG_FLAGS "-O0 -g3 -DDEBUG")
SET(RELEASE_FLAGS "-Og") SET(RELEASE_FLAGS "-Og")
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/cJson/inc)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/lz4/inc)
ENDIF () ENDIF ()
IF (TD_WINDOWS) IF (TD_WINDOWS)
@ -139,6 +141,9 @@ IF (TD_WINDOWS)
SET(CMAKE_GENERATOR "NMake Makefiles" CACHE INTERNAL "" FORCE) SET(CMAKE_GENERATOR "NMake Makefiles" CACHE INTERNAL "" FORCE)
IF (NOT TD_GODLL) IF (NOT TD_GODLL)
SET(COMMON_FLAGS "/nologo /WX /wd4018 /wd2220 /Oi /Oy- /Gm- /EHsc /MT /GS /Gy /fp:precise /Zc:wchar_t /Zc:forScope /Gd /errorReport:prompt /analyze-") SET(COMMON_FLAGS "/nologo /WX /wd4018 /wd2220 /Oi /Oy- /Gm- /EHsc /MT /GS /Gy /fp:precise /Zc:wchar_t /Zc:forScope /Gd /errorReport:prompt /analyze-")
IF (MSVC AND (MSVC_VERSION GREATER_EQUAL 1900))
SET(COMMON_FLAGS "${COMMON_FLAGS} /Wv:18")
ENDIF ()
SET(DEBUG_FLAGS "/Zi /W3 /GL") SET(DEBUG_FLAGS "/Zi /W3 /GL")
SET(RELEASE_FLAGS "/W0 /O3 /GL") SET(RELEASE_FLAGS "/W0 /O3 /GL")
ENDIF () ENDIF ()

View File

@ -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")

4
deps/CMakeLists.txt vendored
View File

@ -13,3 +13,7 @@ ADD_SUBDIRECTORY(MsvcLibX)
IF (TD_LINUX AND TD_MQTT) IF (TD_LINUX AND TD_MQTT)
ADD_SUBDIRECTORY(MQTT-C) ADD_SUBDIRECTORY(MQTT-C)
ENDIF () ENDIF ()
IF (TD_DARWIN AND TD_MQTT)
ADD_SUBDIRECTORY(MQTT-C)
ENDIF ()

View File

@ -5,6 +5,10 @@
#include <stdint.h> #include <stdint.h>
#include "gzguts.h" #include "gzguts.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__) #if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__)
# define LSEEK _lseeki64 # define LSEEK _lseeki64
#else #else
@ -240,9 +244,9 @@ local gzFile gz_open(path, fd, mode)
/* open the file with the appropriate flags (or just use fd) */ /* open the file with the appropriate flags (or just use fd) */
state->fd = fd > -1 ? fd : ( state->fd = fd > -1 ? fd : (
#ifdef WIDECHAR #ifdef WIDECHAR
fd == -2 ? _wopen(path, oflag, 0666) : fd == -2 ? _wopen(path, oflag | O_BINARY, 0666) :
#endif #endif
open((const char *)path, oflag, 0666)); open((const char *)path, oflag | O_BINARY, 0666));
if (state->fd == -1) { if (state->fd == -1) {
free(state->path); free(state->path);
free(state); free(state);

View File

@ -213,12 +213,15 @@ TDengine缺省的时间戳是毫秒精度但通过修改配置参数enableMic
如果表是通过[超级表](../super-table/)创建,更改表结构的操作只能对超级表进行。同时针对超级表的结构更改对所有通过该结构创建的表生效。对于不是通过超级表创建的表,可以直接修改表结构 如果表是通过[超级表](../super-table/)创建,更改表结构的操作只能对超级表进行。同时针对超级表的结构更改对所有通过该结构创建的表生效。对于不是通过超级表创建的表,可以直接修改表结构
## 超级表STable管理 ## 超级表STable管理
注意:在 2.0.15 以前的版本中,并不支持 STABLE 保留字,而是写作 TABLE。也即在本节后文的指令说明中CREATE、DROP、ALTER 三个指令在老版本中保留字需写作 TABLE 而不是 STABLE。
- **创建超级表** - **创建超级表**
```mysql ```mysql
CREATE TABLE [IF NOT EXISTS] stb_name (timestamp_field_name TIMESTAMP, field1_name data_type1 [, field2_name data_type2 ...]) TAGS (tag1_name tag_type1, tag2_name tag_type2 [, tag3_name tag_type3]); CREATE STABLE [IF NOT EXISTS] stb_name (timestamp_field_name TIMESTAMP, field1_name data_type1 [, field2_name data_type2 ...]) TAGS (tag1_name tag_type1, tag2_name tag_type2 [, tag3_name tag_type3]);
``` ```
创建STable, 与创建表的SQL语法相似但需指定TAGS字段的名称和类型 创建 STable与创建表的 SQL 语法相似,但需指定 TAGS 字段的名称和类型
说明: 说明:
@ -233,7 +236,7 @@ TDengine缺省的时间戳是毫秒精度但通过修改配置参数enableMic
- **删除超级表** - **删除超级表**
```mysql ```mysql
DROP TABLE [IF EXISTS] stb_name; DROP STABLE [IF EXISTS] stb_name;
``` ```
删除 STable 会自动删除通过 STable 创建的子表。 删除 STable 会自动删除通过 STable 创建的子表。
@ -253,41 +256,41 @@ TDengine缺省的时间戳是毫秒精度但通过修改配置参数enableMic
- **超级表增加列** - **超级表增加列**
```mysql ```mysql
ALTER TABLE stb_name ADD COLUMN field_name data_type; ALTER STABLE stb_name ADD COLUMN field_name data_type;
``` ```
- **超级表删除列** - **超级表删除列**
```mysql ```mysql
ALTER TABLE stb_name DROP COLUMN field_name; ALTER STABLE stb_name DROP COLUMN field_name;
``` ```
## 超级表 STable 中 TAG 管理 ## 超级表 STable 中 TAG 管理
- **添加标签** - **添加标签**
```mysql ```mysql
ALTER TABLE stb_name ADD TAG new_tag_name tag_type; ALTER STABLE stb_name ADD TAG new_tag_name tag_type;
``` ```
为 STable 增加一个新的标签,并指定新标签的类型。标签总数不能超过 128 个,总长度不超过 16k 个字符。 为 STable 增加一个新的标签,并指定新标签的类型。标签总数不能超过 128 个,总长度不超过 16k 个字符。
- **删除标签** - **删除标签**
```mysql ```mysql
ALTER TABLE stb_name DROP TAG tag_name; ALTER STABLE stb_name DROP TAG tag_name;
``` ```
删除超级表的一个标签,从超级表删除某个标签后,该超级表下的所有子表也会自动删除该标签。 删除超级表的一个标签,从超级表删除某个标签后,该超级表下的所有子表也会自动删除该标签。
- **修改标签名** - **修改标签名**
```mysql ```mysql
ALTER TABLE stb_name CHANGE TAG old_tag_name new_tag_name; ALTER STABLE stb_name CHANGE TAG old_tag_name new_tag_name;
``` ```
修改超级表的标签名,从超级表修改某个标签名后,该超级表下的所有子表也会自动更新该标签名。 修改超级表的标签名,从超级表修改某个标签名后,该超级表下的所有子表也会自动更新该标签名。
- **修改子表标签值** - **修改子表标签值**
```mysql ```mysql
ALTER TABLE tb_name SET TAG tag_name=new_tag_value; ALTER STABLE tb_name SET TAG tag_name=new_tag_value;
``` ```
说明:除了更新标签的值的操作是针对子表进行,其他所有的标签操作(添加标签、删除标签等)均只能作用于 STable不能对单个子表操作。对 STable 添加标签以后,依托于该 STable 建立的所有表将自动增加了一个标签,所有新增标签的默认值都是 NULL。 说明:除了更新标签的值的操作是针对子表进行,其他所有的标签操作(添加标签、删除标签等)均只能作用于 STable不能对单个子表操作。对 STable 添加标签以后,依托于该 STable 建立的所有表将自动增加了一个标签,所有新增标签的默认值都是 NULL。
@ -467,6 +470,17 @@ Query OK, 2 row(s) in set (0.003112s)
注意:普通表的通配符 * 中并不包含 _标签列_ 注意:普通表的通配符 * 中并不包含 _标签列_
##### 获取标签列的去重取值
从 2.0.15 版本开始,支持在超级表查询标签列时,指定 distinct 关键字,这样将返回指定标签列的所有不重复取值。
```mysql
SELECT DISTINCT tag_name FROM stb_name;
```
注意:目前 distinct 关键字只支持对超级表的标签列进行去重,而不能用于普通列。
#### 结果集列名 #### 结果集列名
```SELECT```子句中,如果不指定返回结果集合的列名,结果集列名称默认使用```SELECT```子句中的表达式名称作为列名称。此外,用户可使用```AS```来重命名返回结果集合中列的名称。例如: ```SELECT```子句中,如果不指定返回结果集合的列名,结果集列名称默认使用```SELECT```子句中的表达式名称作为列名称。此外,用户可使用```AS```来重命名返回结果集合中列的名称。例如:

View File

@ -12,7 +12,7 @@
Memory Size = maxVgroupsPerDb * (blocks * cache + 10Mb) + numOfTables * (tagSizePerTable + 0.5Kb) Memory Size = maxVgroupsPerDb * (blocks * cache + 10Mb) + numOfTables * (tagSizePerTable + 0.5Kb)
``` ```
示例假设是4核机器cache是缺省大小16M, blocks是缺省值6假设有10万张表标签总长度是256字节则总的内存需求为4\*(16\*6+10) + 100000*(0.25+0.5)/1000 = 499M。 示例假设是4核机器cache是缺省大小16M, blocks是缺省值6假设有10万张表标签总长度是256字节则总的内存需求为4\*(16\*6+10) + 100000\*(0.25+0.5)/1000 = 499M。
实际运行的系统往往会根据数据特点的不同将数据存放在不同的DB里。因此做规划时也需要考虑。 实际运行的系统往往会根据数据特点的不同将数据存放在不同的DB里。因此做规划时也需要考虑。
@ -35,7 +35,7 @@ TDengine相对于通用数据库有超高的压缩比在绝大多数场景
Raw DataSize = numOfTables * rowSizePerTable * rowsPerTable Raw DataSize = numOfTables * rowSizePerTable * rowsPerTable
``` ```
示例1000万台智能电表每台电表每15分钟采集一次数据每次采集的数据128字节那么一年的原始数据量是10000000\*128\*24\*60/15*365 = 44.8512T。TDengine大概需要消耗44.851/5=8.97024T空间。 示例1000万台智能电表每台电表每15分钟采集一次数据每次采集的数据128字节那么一年的原始数据量是10000000\*128\*24\*60/15\*365 = 44.8512T。TDengine大概需要消耗44.851/5=8.97024T空间。
用户可以通过参数keep设置数据在磁盘中的最大保存时长。为进一步减少存储成本TDengine还提供多级存储最冷的数据可以存放在最廉价的存储介质上应用的访问不用做任何调整只是读取速度降低了。 用户可以通过参数keep设置数据在磁盘中的最大保存时长。为进一步减少存储成本TDengine还提供多级存储最冷的数据可以存放在最廉价的存储介质上应用的访问不用做任何调整只是读取速度降低了。
@ -181,7 +181,7 @@ taos -C 或 taos --dump-config
客户端的输入的字符均采用操作系统当前默认的编码格式在Linux系统上多为UTF-8部分中文系统编码则可能是GB18030或GBK等。在docker环境中默认的编码是POSIX。在中文版Windows系统中编码则是CP936。客户端需要确保正确设置自己所使用的字符集即客户端运行的操作系统当前编码字符集才能保证nchar中的数据正确转换为UCS4-LE编码格式。 客户端的输入的字符均采用操作系统当前默认的编码格式在Linux系统上多为UTF-8部分中文系统编码则可能是GB18030或GBK等。在docker环境中默认的编码是POSIX。在中文版Windows系统中编码则是CP936。客户端需要确保正确设置自己所使用的字符集即客户端运行的操作系统当前编码字符集才能保证nchar中的数据正确转换为UCS4-LE编码格式。
在 Linux 中 locale 的命名规则为: <语言>_<地区>.<字符集编码>zh_CN.UTF-8zh代表中文CN代表大陆地区UTF-8表示字符集。字符集编码为客户端正确解析本地字符串提供编码转换的说明。Linux系统与 Mac OSX 系统可以通过设置locale来确定系统的字符编码由于Windows使用的locale中不是POSIX标准的locale格式因此在Windows下需要采用另一个配置参数charset来指定字符编码。在Linux 系统中也可以使用charset来指定字符编码。 在 Linux 中 locale 的命名规则为: <语言>\_<地区>.<字符集编码>zh_CN.UTF-8zh代表中文CN代表大陆地区UTF-8表示字符集。字符集编码为客户端正确解析本地字符串提供编码转换的说明。Linux系统与 Mac OSX 系统可以通过设置locale来确定系统的字符编码由于Windows使用的locale中不是POSIX标准的locale格式因此在Windows下需要采用另一个配置参数charset来指定字符编码。在Linux 系统中也可以使用charset来指定字符编码。
- charset - charset
@ -452,39 +452,39 @@ TDengine的所有可执行文件默认存放在 _/usr/local/taos/bin_ 目录下
| 关键字列表 | | | | | | 关键字列表 | | | | |
| ---------- | ----------- | ------------ | ---------- | --------- | | ---------- | ----------- | ------------ | ---------- | --------- |
| ABLOCKS | CONNECTION | GT | MINUS | SHOW | | ABLOCKS | CONNECTION | GROUP | MINUS | SLASH |
| ABORT | CONNECTIONS | ID | MNODES | SLASH | | ABORT | CONNECTIONS | GT | MNODES | SLIDING |
| ACCOUNT | COPY | IF | MODULES | SLIDING | | ACCOUNT | COPY | ID | MODULES | SMALLINT |
| ACCOUNTS | COUNT | IGNORE | NCHAR | SMALLINT | | ACCOUNTS | COUNT | IF | NCHAR | SPREAD |
| ADD | CREATE | IMMEDIATE | NE | SPREAD | | ADD | CREATE | IGNORE | NE | STABLE |
| AFTER | CTIME | IMPORT | NONE | STAR | | AFTER | CTIME | IMMEDIATE | NONE | STABLES |
| ALL | DATABASE | IN | NOT | STATEMENT | | ALL | DATABASE | IMPORT | NOT | STAR |
| ALTER | DATABASES | INITIALLY | NOTNULL | STDDEV | | ALTER | DATABASES | IN | NOTNULL | STATEMENT |
| AND | DAYS | INSERT | NOW | STREAM | | AND | DAYS | INITIALLY | NOW | STDDEV |
| AS | DEFERRED | INSTEAD | OF | STREAMS | | AS | DEFERRED | INSERT | OF | STREAM |
| ASC | DELIMITERS | INTEGER | OFFSET | STRING | | ASC | DELIMITERS | INSTEAD | OFFSET | STREAMS |
| ATTACH | DESC | INTERVAL | OR | SUM | | ATTACH | DESC | INTEGER | OR | STRING |
| AVG | DESCRIBE | INTO | ORDER | TABLE | | AVG | DESCRIBE | INTERVAL | ORDER | SUM |
| BEFORE | DETACH | IP | PASS | TABLES | | BEFORE | DETACH | INTO | PASS | TABLE |
| BEGIN | DIFF | IS | PERCENTILE | TAG | | BEGIN | DIFF | IP | PERCENTILE | TABLES |
| BETWEEN | DIVIDE | ISNULL | PLUS | TAGS | | BETWEEN | DISTINCT | IS | PLUS | TAG |
| BIGINT | DNODE | JOIN | PRAGMA | TBLOCKS | | BIGINT | DIVIDE | ISNULL | PRAGMA | TAGS |
| BINARY | DNODES | KEEP | PREV | TBNAME | | BINARY | DNODE | JOIN | PREV | TBLOCKS |
| BITAND | DOT | KEY | PRIVILEGE | TIMES | | BITAND | DNODES | KEEP | PRIVILEGE | TBNAME |
| BITNOT | DOUBLE | KILL | QUERIES | TIMESTAMP | | BITNOT | DOT | KEY | QUERIES | TIMES |
| BITOR | DROP | LAST | QUERY | TINYINT | | BITOR | DOUBLE | KILL | QUERY | TIMESTAMP |
| BOOL | EACH | LE | RAISE | TOP | | BOOL | DROP | LAST | RAISE | TINYINT |
| BOTTOM | END | LEASTSQUARES | REM | TRIGGER | | BOTTOM | EACH | LE | REM | TOP |
| BY | EQ | LIKE | REPLACE | UMINUS | | BY | END | LEASTSQUARES | REPLACE | TRIGGER |
| CACHE | EXISTS | LIMIT | REPLICA | UPLUS | | CACHE | EQ | LIKE | REPLICA | UMINUS |
| CASCADE | EXPLAIN | LINEAR | RESET | USE | | CASCADE | EXISTS | LIMIT | RESET | UPLUS |
| CHANGE | FAIL | LOCAL | RESTRICT | USER | | CHANGE | EXPLAIN | LINEAR | RESTRICT | USE |
| CLOG | FILL | LP | ROW | USERS | | CLOG | FAIL | LOCAL | ROW | USER |
| CLUSTER | FIRST | LSHIFT | ROWS | USING | | CLUSTER | FILL | LP | ROWS | USERS |
| COLON | FLOAT | LT | RP | VALUES | | COLON | FIRST | LSHIFT | RP | USING |
| COLUMN | FOR | MATCH | RSHIFT | VARIABLE | | COLUMN | FLOAT | LT | RSHIFT | VALUES |
| COMMA | FROM | MAX | SCORES | VGROUPS | | COMMA | FOR | MATCH | SCORES | VARIABLE |
| COMP | GE | METRIC | SELECT | VIEW | | COMP | FROM | MAX | SELECT | VGROUPS |
| CONCAT | GLOB | METRICS | SEMI | WAVG | | CONCAT | GE | METRIC | SEMI | VIEW |
| CONFIGS | GRANTS | MIN | SET | WHERE | | CONFIGS | GLOB | METRICS | SET | WAVG |
| CONFLICT | GROUP | | | | | CONFLICT | GRANTS | MIN | SHOW | WHERE |

View File

@ -344,7 +344,6 @@ dataDir /mnt/disk6/taos 2
挂载的盘也可以是非本地的网络盘,只要系统能访问即可。 挂载的盘也可以是非本地的网络盘,只要系统能访问即可。
注:多级存储功能仅企业版支持 注:多级存储功能仅企业版支持
**提示:该功能暂未提供**
## 数据查询 ## 数据查询
TDengine提供了多种多样针对表和超级表的查询处理功能除了常规的聚合查询之外还提供针对时序数据的窗口查询、统计聚合等功能。TDengine的查询处理需要客户端、vnode, mnode节点协同完成。 TDengine提供了多种多样针对表和超级表的查询处理功能除了常规的聚合查询之外还提供针对时序数据的窗口查询、统计聚合等功能。TDengine的查询处理需要客户端、vnode, mnode节点协同完成。

View File

@ -2,7 +2,7 @@
TDengine 提供了遵循 JDBC 标准3.0API 规范的 `taos-jdbcdriver` 实现,可在 maven 的中央仓库 [Sonatype Repository][1] 搜索下载。 TDengine 提供了遵循 JDBC 标准3.0API 规范的 `taos-jdbcdriver` 实现,可在 maven 的中央仓库 [Sonatype Repository][1] 搜索下载。
`taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTfultaos-jdbcdriver-2.0.17 开始支持 JDBC-RESTful。 JDBC-JNI 通过调用客户端 libtaos.so或 taos.dll )的本地方法实现, JDBC-RESTful 则在内部封装了 RESTful 接口实现。 `taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTfultaos-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 配置即可:
<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,17 @@ 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(10); //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.setMaxLifetime(0); // maximum life time for each connection
config.setConnectionTestQuery("describe log.dn"); //validation query config.setIdleTimeout(0); // max idle time for recycle idle connection
config.setValidationTimeout(3000); //validation query timeout config.setConnectionTestQuery("select server_status()"); //validation query
HikariDataSource ds = new HikariDataSource(config); //create datasource HikariDataSource ds = new HikariDataSource(config); //create datasource
@ -375,32 +376,22 @@ 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.put("driverClassName","com.taosdata.jdbc.TSDBDriver");
properties.put("url","jdbc:TAOS://127.0.0.1:6030/log");
properties.put("username","root");
properties.put("password","taosdata");
properties.put("maxActive","10"); //maximum number of connection in the pool DruidDataSource dataSource = new DruidDataSource();
properties.put("initialSize","3");//initial number of connection // jdbc properties
properties.put("maxWait","10000");//maximum wait milliseconds for get connection from pool dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver");
properties.put("minIdle","3");//minimum number of connection in the pool dataSource.setUrl(url);
dataSource.setUsername("root");
dataSource.setPassword("taosdata");
// pool configurations
dataSource.setInitialSize(10);
dataSource.setMinIdle(10);
dataSource.setMaxActive(10);
dataSource.setMaxWait(30000);
dataSource.setValidationQuery("select server_status()");
properties.put("timeBetweenEvictionRunsMillis","3000");// the interval milliseconds to test connection Connection connection = dataSource.getConnection(); // get 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
DataSource ds = DruidDataSourceFactory.createDataSource(properties);
Connection connection = ds.getConnection(); // get connection
Statement statement = connection.createStatement(); // get statement Statement statement = connection.createStatement(); // get statement
//query or insert //query or insert
// ... // ...
@ -427,7 +418,7 @@ Query OK, 1 row(s) in set (0.000141s)
## 与框架使用 ## 与框架使用
* Spring JdbcTemplate 中使用 taos-jdbcdriver可参考 [SpringJdbcTemplate][11] * Spring JdbcTemplate 中使用 taos-jdbcdriver可参考 [SpringJdbcTemplate][11]
* Springboot + Mybatis 中使用,可参考 [springbootdemo * Springboot + Mybatis 中使用,可参考 [springbootdemo][12]

View File

@ -21,7 +21,7 @@ else
cd ${script_dir} cd ${script_dir}
script_dir="$(pwd)" script_dir="$(pwd)"
data_dir="/var/lib/taos" data_dir="/var/lib/taos"
log_dir="~/TDengineLog" log_dir=~/TDengine/log
fi fi
log_link_dir="/usr/local/taos/log" log_link_dir="/usr/local/taos/log"

View File

@ -24,7 +24,7 @@ data_dir="/var/lib/taos"
if [ "$osType" != "Darwin" ]; then if [ "$osType" != "Darwin" ]; then
log_dir="/var/log/taos" log_dir="/var/log/taos"
else else
log_dir="~/TDengineLog" log_dir=~/TDengine/log
fi fi
data_link_dir="/usr/local/taos/data" data_link_dir="/usr/local/taos/data"
@ -178,7 +178,9 @@ function install_bin() {
function install_lib() { function install_lib() {
# Remove links # Remove links
${csudo} rm -f ${lib_link_dir}/libtaos.* || : ${csudo} rm -f ${lib_link_dir}/libtaos.* || :
if [ "$osType" != "Darwin" ]; then
${csudo} rm -f ${lib64_link_dir}/libtaos.* || : ${csudo} rm -f ${lib64_link_dir}/libtaos.* || :
fi
if [ "$osType" != "Darwin" ]; then if [ "$osType" != "Darwin" ]; then
${csudo} cp ${binary_dir}/build/lib/libtaos.so.${verNumber} ${install_main_dir}/driver && ${csudo} chmod 777 ${install_main_dir}/driver/* ${csudo} cp ${binary_dir}/build/lib/libtaos.so.${verNumber} ${install_main_dir}/driver && ${csudo} chmod 777 ${install_main_dir}/driver/*
@ -190,12 +192,14 @@ function install_lib() {
${csudo} ln -sf ${lib64_link_dir}/libtaos.so.1 ${lib64_link_dir}/libtaos.so ${csudo} ln -sf ${lib64_link_dir}/libtaos.so.1 ${lib64_link_dir}/libtaos.so
fi fi
else else
${csudo} cp ${binary_dir}/build/lib/libtaos.* ${install_main_dir}/driver && ${csudo} chmod 777 ${install_main_dir}/driver/* ${csudo} cp -Rf ${binary_dir}/build/lib/libtaos.* ${install_main_dir}/driver && ${csudo} chmod 777 ${install_main_dir}/driver/*
${csudo} ln -sf ${install_main_dir}/driver/libtaos.* ${lib_link_dir}/libtaos.1.dylib ${csudo} ln -sf ${install_main_dir}/driver/libtaos.1.dylib ${lib_link_dir}/libtaos.1.dylib
${csudo} ln -sf ${lib_link_dir}/libtaos.1.dylib ${lib_link_dir}/libtaos.dylib ${csudo} ln -sf ${lib_link_dir}/libtaos.1.dylib ${lib_link_dir}/libtaos.dylib
fi fi
if [ "$osType" != "Darwin" ]; then
${csudo} ldconfig ${csudo} ldconfig
fi
} }
function install_header() { function install_header() {

View File

@ -8,6 +8,4 @@ INCLUDE_DIRECTORIES(${TD_ENTERPRISE_DIR}/src/inc)
INCLUDE_DIRECTORIES(inc) INCLUDE_DIRECTORIES(inc)
AUX_SOURCE_DIRECTORY(src SRC) AUX_SOURCE_DIRECTORY(src SRC)
IF (TD_LINUX)
ADD_LIBRARY(balance ${SRC}) ADD_LIBRARY(balance ${SRC})
ENDIF ()

View File

@ -24,7 +24,7 @@ extern "C" {
int32_t bnInitThread(); int32_t bnInitThread();
void bnCleanupThread(); void bnCleanupThread();
void bnNotify(); void bnNotify();
void bnStartTimer(int64_t mseconds); void bnStartTimer(int32_t mseconds);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -30,7 +30,7 @@
#include "mnodeVgroup.h" #include "mnodeVgroup.h"
extern int64_t tsDnodeRid; extern int64_t tsDnodeRid;
extern int64_t tsSdbRid; extern int32_t tsSdbRid;
static SBnMgmt tsBnMgmt; static SBnMgmt tsBnMgmt;
static void bnMonitorDnodeModule(); static void bnMonitorDnodeModule();

View File

@ -271,23 +271,23 @@ static int32_t bnRetrieveScores(SShowObj *pShow, char *data, int32_t rows, void
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
*(float *)pWrite = systemScore; *(float *)pWrite = (float)systemScore;
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
*(float *)pWrite = pDnode->customScore; *(float *)pWrite = (float)pDnode->customScore;
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
*(float *)pWrite = (int32_t)moduleScore; *(float *)pWrite = (float)moduleScore;
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
*(float *)pWrite = (int32_t)vnodeScore; *(float *)pWrite = (float)vnodeScore;
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
*(float *)pWrite = (int32_t)(vnodeScore + moduleScore + pDnode->customScore + systemScore); *(float *)pWrite = (float)(vnodeScore + moduleScore + pDnode->customScore + systemScore);
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;

View File

@ -119,13 +119,13 @@ static void bnProcessTimer(void *handle, void *tmrId) {
} }
} }
void bnStartTimer(int64_t mseconds) { void bnStartTimer(int32_t mseconds) {
if (tsBnThread.stop) return; if (tsBnThread.stop) return;
bool updateSoon = (mseconds != -1); bool updateSoon = (mseconds != -1);
if (updateSoon) { if (updateSoon) {
mTrace("balance function will be called after %" PRId64 " ms", mseconds); mTrace("balance function will be called after %d ms", mseconds);
taosTmrReset(bnProcessTimer, mseconds, (void *)mseconds, tsMnodeTmr, &tsBnThread.timer); taosTmrReset(bnProcessTimer, mseconds, (void *)(int64_t)mseconds, tsMnodeTmr, &tsBnThread.timer);
} else { } else {
taosTmrReset(bnProcessTimer, tsStatusInterval * 1000, NULL, tsMnodeTmr, &tsBnThread.timer); taosTmrReset(bnProcessTimer, tsStatusInterval * 1000, NULL, tsMnodeTmr, &tsBnThread.timer);
} }

View File

@ -28,6 +28,28 @@ IF (TD_LINUX)
ADD_SUBDIRECTORY(tests) ADD_SUBDIRECTORY(tests)
ELSEIF (TD_DARWIN)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/linux)
# set the static lib name
ADD_LIBRARY(taos_static STATIC ${SRC})
TARGET_LINK_LIBRARIES(taos_static common query trpc tutil pthread m)
SET_TARGET_PROPERTIES(taos_static PROPERTIES OUTPUT_NAME "taos_static")
SET_TARGET_PROPERTIES(taos_static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
# generate dynamic library (*.dylib)
ADD_LIBRARY(taos SHARED ${SRC})
TARGET_LINK_LIBRARIES(taos common query trpc tutil pthread m)
SET_TARGET_PROPERTIES(taos PROPERTIES CLEAN_DIRECT_OUTPUT 1)
#set version of .dylib
#VERSION dylib version
#SOVERSION dylib version
#MESSAGE(STATUS "build version ${TD_VER_NUMBER}")
SET_TARGET_PROPERTIES(taos PROPERTIES VERSION ${TD_VER_NUMBER} SOVERSION 1)
ADD_SUBDIRECTORY(tests)
ELSEIF (TD_WINDOWS) ELSEIF (TD_WINDOWS)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/windows) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/windows)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/windows/win32) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/windows/win32)
@ -49,12 +71,12 @@ ELSEIF (TD_DARWIN)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/linux) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/jni/linux)
ADD_LIBRARY(taos_static STATIC ${SRC}) ADD_LIBRARY(taos_static STATIC ${SRC})
TARGET_LINK_LIBRARIES(taos_static trpc tutil pthread m) TARGET_LINK_LIBRARIES(taos_static query trpc tutil pthread m)
SET_TARGET_PROPERTIES(taos_static PROPERTIES OUTPUT_NAME "taos_static") SET_TARGET_PROPERTIES(taos_static PROPERTIES OUTPUT_NAME "taos_static")
# generate dynamic library (*.dylib) # generate dynamic library (*.dylib)
ADD_LIBRARY(taos SHARED ${SRC}) ADD_LIBRARY(taos SHARED ${SRC})
TARGET_LINK_LIBRARIES(taos trpc tutil pthread m) TARGET_LINK_LIBRARIES(taos query trpc tutil pthread m)
SET_TARGET_PROPERTIES(taos PROPERTIES CLEAN_DIRECT_OUTPUT 1) SET_TARGET_PROPERTIES(taos PROPERTIES CLEAN_DIRECT_OUTPUT 1)

View File

@ -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);

View File

@ -905,6 +905,13 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
return tscInvalidSQLErrMsg(pCmd->payload, "keyword TAGS expected", sToken.z); return tscInvalidSQLErrMsg(pCmd->payload, "keyword TAGS expected", sToken.z);
} }
index = 0;
sToken = tStrGetToken(sql, &index, false, 0, NULL);
sql += index;
if (sToken.type != TK_LP) {
return tscInvalidSQLErrMsg(pCmd->payload, NULL, sToken.z);
}
SKVRowBuilder kvRowBuilder = {0}; SKVRowBuilder kvRowBuilder = {0};
if (tdInitKVRowBuilder(&kvRowBuilder) < 0) { if (tdInitKVRowBuilder(&kvRowBuilder) < 0) {
return TSDB_CODE_TSC_OUT_OF_MEMORY; return TSDB_CODE_TSC_OUT_OF_MEMORY;
@ -1548,12 +1555,13 @@ void tscImportDataFromFile(SSqlObj *pSql) {
SSqlObj *pNew = createSubqueryObj(pSql, 0, parseFileSendDataBlock, pSupporter, TSDB_SQL_INSERT, NULL); SSqlObj *pNew = createSubqueryObj(pSql, 0, parseFileSendDataBlock, pSupporter, TSDB_SQL_INSERT, NULL);
pCmd->count = 1; pCmd->count = 1;
FILE *fp = fopen(pCmd->payload, "r"); FILE *fp = fopen(pCmd->payload, "rb");
if (fp == NULL) { if (fp == NULL) {
pSql->res.code = TAOS_SYSTEM_ERROR(errno); pSql->res.code = TAOS_SYSTEM_ERROR(errno);
tscError("%p failed to open file %s to load data from file, code:%s", pSql, pCmd->payload, tstrerror(pSql->res.code)); tscError("%p failed to open file %s to load data from file, code:%s", pSql, pCmd->payload, tstrerror(pSql->res.code));
tfree(pSupporter); tfree(pSupporter);
taos_free_result(pNew);
tscAsyncResultOnError(pSql); tscAsyncResultOnError(pSql);
return; return;
} }

View File

@ -13,10 +13,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef __APPLE__
#define _BSD_SOURCE #define _BSD_SOURCE
#define _XOPEN_SOURCE 500 #define _XOPEN_SOURCE 500
#define _DEFAULT_SOURCE #define _DEFAULT_SOURCE
#define _GNU_SOURCE #define _GNU_SOURCE
#endif // __APPLE__
#include "os.h" #include "os.h"
#include "ttype.h" #include "ttype.h"
@ -60,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);
@ -921,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);
} }
@ -1244,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 */
@ -4300,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;
@ -4342,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);
@ -4349,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;

View File

@ -1251,7 +1251,9 @@ 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)) {
pthread_mutex_lock(&pObj->mutex);
tstrncpy(pShowMsg->db, pObj->db, sizeof(pShowMsg->db)); 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) {
// 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) {
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) {
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;
} }

View File

@ -295,6 +295,10 @@ void taos_close(TAOS *taos) {
tscDebug("%p HB is freed", pHb); tscDebug("%p HB is freed", pHb);
taosReleaseRef(tscObjRef, pHb->self); taosReleaseRef(tscObjRef, pHb->self);
#ifdef __APPLE__
// to satisfy later tsem_destroy in taos_free_result
tsem_init(&pHb->rspSem, 0, 0);
#endif // __APPLE__
taos_free_result(pHb); taos_free_result(pHb);
} }
} }

View File

@ -313,7 +313,7 @@ static int tscLoadSubscriptionProgress(SSub* pSub) {
char buf[TSDB_MAX_SQL_LEN]; char buf[TSDB_MAX_SQL_LEN];
sprintf(buf, "%s/subscribe/%s", tsDataDir, pSub->topic); sprintf(buf, "%s/subscribe/%s", tsDataDir, pSub->topic);
FILE* fp = fopen(buf, "r"); FILE* fp = fopen(buf, "rb");
if (fp == NULL) { if (fp == NULL) {
tscDebug("subscription progress file does not exist: %s", pSub->topic); tscDebug("subscription progress file does not exist: %s", pSub->topic);
return 1; return 1;
@ -368,7 +368,7 @@ void tscSaveSubscriptionProgress(void* sub) {
} }
sprintf(path, "%s/subscribe/%s", tsDataDir, pSub->topic); sprintf(path, "%s/subscribe/%s", tsDataDir, pSub->topic);
FILE* fp = fopen(path, "w+"); FILE* fp = fopen(path, "wb+");
if (fp == NULL) { if (fp == NULL) {
tscError("failed to create progress file for subscription: %s", pSub->topic); tscError("failed to create progress file for subscription: %s", pSub->topic);
return; return;

View File

@ -1018,7 +1018,7 @@ static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRow
if (numOfRows > 0) { // write the compressed timestamp to disk file if (numOfRows > 0) { // write the compressed timestamp to disk file
if(pSupporter->f == NULL) { if(pSupporter->f == NULL) {
pSupporter->f = fopen(pSupporter->path, "w"); pSupporter->f = fopen(pSupporter->path, "wb");
if (pSupporter->f == NULL) { if (pSupporter->f == NULL) {
tscError("%p failed to create tmp file:%s, reason:%s", pSql, pSupporter->path, strerror(errno)); tscError("%p failed to create tmp file:%s, reason:%s", pSql, pSupporter->path, strerror(errno));
@ -1066,7 +1066,7 @@ static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRow
// continue to retrieve ts-comp data from vnode // continue to retrieve ts-comp data from vnode
if (!pRes->completed) { if (!pRes->completed) {
taosGetTmpfilePath("ts-join", pSupporter->path); taosGetTmpfilePath("ts-join", pSupporter->path);
pSupporter->f = fopen(pSupporter->path, "w"); pSupporter->f = fopen(pSupporter->path, "wb");
pRes->row = pRes->numOfRows; pRes->row = pRes->numOfRows;
taos_fetch_rows_a(tres, tsCompRetrieveCallback, param); taos_fetch_rows_a(tres, tsCompRetrieveCallback, param);
@ -1092,7 +1092,7 @@ static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRow
taosGetTmpfilePath("ts-join", pSupporter->path); taosGetTmpfilePath("ts-join", pSupporter->path);
// TODO check for failure // TODO check for failure
pSupporter->f = fopen(pSupporter->path, "w"); pSupporter->f = fopen(pSupporter->path, "wb");
pRes->row = pRes->numOfRows; pRes->row = pRes->numOfRows;
// set the callback function // set the callback function
@ -1991,7 +1991,22 @@ static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES
* current query failed, and the retry count is less than the available * current query failed, and the retry count is less than the available
* count, retry query clear previous retrieved data, then launch a new sub query * count, retry query clear previous retrieved data, then launch a new sub query
*/ */
static int32_t tscReissueSubquery(SRetrieveSupport *trsupport, SSqlObj *pSql, int32_t code) { static int32_t tscReissueSubquery(SRetrieveSupport *oriTrs, SSqlObj *pSql, int32_t code) {
SRetrieveSupport *trsupport = malloc(sizeof(SRetrieveSupport));
if (trsupport == NULL) {
return TSDB_CODE_TSC_OUT_OF_MEMORY;
}
memcpy(trsupport, oriTrs, sizeof(*trsupport));
const uint32_t nBufferSize = (1u << 16u); // 64KB
trsupport->localBuffer = (tFilePage *)calloc(1, nBufferSize + sizeof(tFilePage));
if (trsupport->localBuffer == NULL) {
tscError("%p failed to malloc buffer for local buffer, reason:%s", pSql, strerror(errno));
tfree(trsupport);
return TSDB_CODE_TSC_OUT_OF_MEMORY;
}
SSqlObj *pParentSql = trsupport->pParentSql; SSqlObj *pParentSql = trsupport->pParentSql;
int32_t subqueryIndex = trsupport->subqueryIndex; int32_t subqueryIndex = trsupport->subqueryIndex;

View File

@ -1942,6 +1942,10 @@ SSqlObj* createSimpleSubObj(SSqlObj* pSql, __async_cb_func_t fp, void* param, in
} }
if (tscAddSubqueryInfo(pCmd) != TSDB_CODE_SUCCESS) { if (tscAddSubqueryInfo(pCmd) != TSDB_CODE_SUCCESS) {
#ifdef __APPLE__
// to satisfy later tsem_destroy in taos_free_result
tsem_init(&pNew->rspSem, 0, 0);
#endif // __APPLE__
tscFreeSqlObj(pNew); tscFreeSqlObj(pNew);
return NULL; return NULL;
} }
@ -2123,6 +2127,10 @@ SSqlObj* createSubqueryObj(SSqlObj* pSql, int16_t tableIndex, __async_cb_func_t
pTableMetaInfo->tagColList, pTableMetaInfo->pVgroupTables); pTableMetaInfo->tagColList, pTableMetaInfo->pVgroupTables);
} else { // transfer the ownership of pTableMeta to the newly create sql object. } else { // transfer the ownership of pTableMeta to the newly create sql object.
STableMetaInfo* pPrevInfo = tscGetTableMetaInfoFromCmd(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex, 0); STableMetaInfo* pPrevInfo = tscGetTableMetaInfoFromCmd(&pPrevSql->cmd, pPrevSql->cmd.clauseIndex, 0);
if (pPrevInfo->pTableMeta && pPrevInfo->pTableMeta->tableType < 0) {
terrno = TSDB_CODE_TSC_APP_ERROR;
goto _error;
}
STableMeta* pPrevTableMeta = tscTableMetaDup(pPrevInfo->pTableMeta); STableMeta* pPrevTableMeta = tscTableMetaDup(pPrevInfo->pTableMeta);
SVgroupsInfo* pVgroupsInfo = pPrevInfo->vgroupList; SVgroupsInfo* pVgroupsInfo = pPrevInfo->vgroupList;
@ -2508,7 +2516,11 @@ bool tscSetSqlOwner(SSqlObj* pSql) {
SSqlRes* pRes = &pSql->res; SSqlRes* pRes = &pSql->res;
// set the sql object owner // set the sql object owner
#ifdef __APPLE__
pthread_t threadId = (pthread_t)taosGetSelfPthreadId();
#else // __APPLE__
uint64_t threadId = taosGetSelfPthreadId(); uint64_t threadId = taosGetSelfPthreadId();
#endif // __APPLE__
if (atomic_val_compare_exchange_64(&pSql->owner, 0, threadId) != 0) { if (atomic_val_compare_exchange_64(&pSql->owner, 0, threadId) != 0) {
pRes->code = TSDB_CODE_QRY_IN_EXEC; pRes->code = TSDB_CODE_QRY_IN_EXEC;
return false; return false;

View File

@ -29,7 +29,7 @@ extern "C" {
#define STR_TO_VARSTR(x, str) \ #define STR_TO_VARSTR(x, str) \
do { \ do { \
VarDataLenT __len = strlen(str); \ VarDataLenT __len = (VarDataLenT)strlen(str); \
*(VarDataLenT *)(x) = __len; \ *(VarDataLenT *)(x) = __len; \
memcpy(varDataVal(x), (str), __len); \ memcpy(varDataVal(x), (str), __len); \
} while (0); } while (0);
@ -42,7 +42,7 @@ extern "C" {
#define STR_WITH_SIZE_TO_VARSTR(x, str, _size) \ #define STR_WITH_SIZE_TO_VARSTR(x, str, _size) \
do { \ do { \
*(VarDataLenT *)(x) = (_size); \ *(VarDataLenT *)(x) = (VarDataLenT)(_size); \
memcpy(varDataVal(x), (str), (_size)); \ memcpy(varDataVal(x), (str), (_size)); \
} while (0); } while (0);

View File

@ -88,8 +88,8 @@ extern int32_t tsMinRowsInFileBlock;
extern int32_t tsMaxRowsInFileBlock; extern int32_t tsMaxRowsInFileBlock;
extern int16_t tsCommitTime; // seconds extern int16_t tsCommitTime; // seconds
extern int32_t tsTimePrecision; extern int32_t tsTimePrecision;
extern int16_t tsCompression; extern int8_t tsCompression;
extern int16_t tsWAL; extern int8_t tsWAL;
extern int32_t tsFsyncPeriod; extern int32_t tsFsyncPeriod;
extern int32_t tsReplications; extern int32_t tsReplications;
extern int32_t tsQuorum; extern int32_t tsQuorum;

View File

@ -121,8 +121,8 @@ int32_t tsMinRowsInFileBlock = TSDB_DEFAULT_MIN_ROW_FBLOCK;
int32_t tsMaxRowsInFileBlock = TSDB_DEFAULT_MAX_ROW_FBLOCK; int32_t tsMaxRowsInFileBlock = TSDB_DEFAULT_MAX_ROW_FBLOCK;
int16_t tsCommitTime = TSDB_DEFAULT_COMMIT_TIME; // seconds int16_t tsCommitTime = TSDB_DEFAULT_COMMIT_TIME; // seconds
int32_t tsTimePrecision = TSDB_DEFAULT_PRECISION; int32_t tsTimePrecision = TSDB_DEFAULT_PRECISION;
int16_t tsCompression = TSDB_DEFAULT_COMP_LEVEL; int8_t tsCompression = TSDB_DEFAULT_COMP_LEVEL;
int16_t tsWAL = TSDB_DEFAULT_WAL_LEVEL; int8_t tsWAL = TSDB_DEFAULT_WAL_LEVEL;
int32_t tsFsyncPeriod = TSDB_DEFAULT_FSYNC_PERIOD; int32_t tsFsyncPeriod = TSDB_DEFAULT_FSYNC_PERIOD;
int32_t tsReplications = TSDB_DEFAULT_DB_REPLICA_OPTION; int32_t tsReplications = TSDB_DEFAULT_DB_REPLICA_OPTION;
int32_t tsQuorum = TSDB_DEFAULT_DB_QUORUM_OPTION; int32_t tsQuorum = TSDB_DEFAULT_DB_QUORUM_OPTION;
@ -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;
@ -550,7 +550,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);
@ -758,7 +758,7 @@ static void doInitGlobalConfig(void) {
cfg.option = "comp"; cfg.option = "comp";
cfg.ptr = &tsCompression; cfg.ptr = &tsCompression;
cfg.valType = TAOS_CFG_VTYPE_INT16; cfg.valType = TAOS_CFG_VTYPE_INT8;
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 = TSDB_MIN_COMP_LEVEL; cfg.minValue = TSDB_MIN_COMP_LEVEL;
cfg.maxValue = TSDB_MAX_COMP_LEVEL; cfg.maxValue = TSDB_MAX_COMP_LEVEL;
@ -768,7 +768,7 @@ static void doInitGlobalConfig(void) {
cfg.option = "walLevel"; cfg.option = "walLevel";
cfg.ptr = &tsWAL; cfg.ptr = &tsWAL;
cfg.valType = TAOS_CFG_VTYPE_INT16; cfg.valType = TAOS_CFG_VTYPE_INT8;
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 = TSDB_MIN_WAL_LEVEL; cfg.minValue = TSDB_MIN_WAL_LEVEL;
cfg.maxValue = TSDB_MAX_WAL_LEVEL; cfg.maxValue = TSDB_MAX_WAL_LEVEL;

View File

@ -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;
@ -775,7 +775,7 @@ int32_t tVariantDump(tVariant *pVariant, char *payload, int16_t type, bool inclu
return -1; return -1;
} }
} else { } else {
wcsncpy((wchar_t *)p, pVariant->wpz, pVariant->nLen); memcpy(p, pVariant->wpz, pVariant->nLen);
newlen = pVariant->nLen; newlen = pVariant->nLen;
} }

View File

@ -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})

View File

@ -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>

View File

@ -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 @@
<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>

View File

@ -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 {
} }
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");

View File

@ -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
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
@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

View File

@ -123,11 +123,21 @@ public class TSDBResultSet implements ResultSet {
} }
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); if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw new SQLException("Unable to unwrap to " + iface.toString());
}
} }
public boolean isWrapperFor(Class<?> iface) throws SQLException { public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return iface.isInstance(this);
} }
public boolean next() throws SQLException { public boolean next() throws SQLException {

View File

@ -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 {
} }
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;
} }

View File

@ -15,28 +15,28 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class RestfulResultSet implements ResultSet { public class RestfulResultSet implements ResultSet {
private static final String RESULT_SET_IS_CLOSED = "resultSet is closed.";
private volatile boolean isClosed; private volatile boolean isClosed;
private int pos = -1; private int pos = -1;
private final String database; private final String database;
private final Statement statement; private final Statement statement;
// data // data
private ArrayList<ArrayList<Object>> resultSet; private ArrayList<ArrayList<Object>> resultSet = new ArrayList<>();
// meta // meta
private ArrayList<String> columnNames; private ArrayList<String> columnNames = new ArrayList<>();
private ArrayList<Field> columns; private ArrayList<Field> columns = new ArrayList<>();
private RestfulResultSetMetaData metaData; private RestfulResultSetMetaData metaData;
/** /**
* 由一个result的Json构造结果集对应执行show databases, show tables等这些语句返回结果集但无法获取结果集对应的meta统一当成String处理 * 由一个result的Json构造结果集对应执行show databases, show tables等这些语句返回结果集但无法获取结果集对应的meta统一当成String处理
*
* @param resultJson: 包含data信息的结果集有sql返回的结果集
***/ ***/
public RestfulResultSet(String database, Statement statement, JSONObject resultJson) { public RestfulResultSet(String database, Statement statement, JSONObject resultJson) {
this.database = database; this.database = database;
this.statement = statement; this.statement = statement;
// row data // row data
JSONArray data = resultJson.getJSONArray("data"); JSONArray data = resultJson.getJSONArray("data");
resultSet = new ArrayList<>();
int columnIndex = 0; int columnIndex = 0;
for (; columnIndex < data.size(); columnIndex++) { for (; columnIndex < data.size(); columnIndex++) {
ArrayList oneRow = new ArrayList<>(); ArrayList oneRow = new ArrayList<>();
@ -48,15 +48,13 @@ public class RestfulResultSet implements ResultSet {
} }
// column only names // column only names
columnNames = new ArrayList<>();
columns = new ArrayList<>();
JSONArray head = resultJson.getJSONArray("head"); JSONArray head = resultJson.getJSONArray("head");
for (int i = 0; i < head.size(); i++) { for (int i = 0; i < head.size(); i++) {
String name = head.getString(i); String name = head.getString(i);
columnNames.add(name); columnNames.add(name);
columns.add(new Field(name, "", 0, "")); columns.add(new Field(name, "", 0, ""));
} }
this.metaData = new RestfulResultSetMetaData(this.database, columns); this.metaData = new RestfulResultSetMetaData(this.database, columns, this);
} }
/** /**
@ -78,7 +76,7 @@ public class RestfulResultSet implements ResultSet {
} }
} }
this.columns = newColumns; this.columns = newColumns;
this.metaData = new RestfulResultSetMetaData(this.database, this.columns); this.metaData = new RestfulResultSetMetaData(this.database, this.columns, this);
} }
public Field findField(String columnName, List<JSONObject> fieldJsonList) { public Field findField(String columnName, List<JSONObject> fieldJsonList) {
@ -91,7 +89,6 @@ public class RestfulResultSet implements ResultSet {
} }
} }
} }
return null; return null;
} }
@ -112,10 +109,9 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public boolean next() throws SQLException { public boolean next() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
if (pos < resultSet.size() - 1) {
pos++; pos++;
if (pos <= resultSet.size() - 1) {
return true; return true;
} }
return false; return false;
@ -131,37 +127,38 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public boolean wasNull() throws SQLException { public boolean wasNull() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return resultSet.isEmpty(); return resultSet.isEmpty();
} }
@Override @Override
public String getString(int columnIndex) throws SQLException { public String getString(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
if (columnIndex > resultSet.get(pos).size()) { if (columnIndex > resultSet.get(pos).size()) {
throw new SQLException(TSDBConstants.WrapErrMsg("Column Index out of range, " + columnIndex + " > " + resultSet.get(pos).size())); throw new SQLException(TSDBConstants.WrapErrMsg("Column Index out of range, " + columnIndex + " > " + resultSet.get(pos).size()));
} }
return resultSet.get(pos).get(columnIndex - 1).toString();
columnIndex = getTrueColumnIndex(columnIndex);
return resultSet.get(pos).get(columnIndex).toString();
} }
@Override @Override
public boolean getBoolean(int columnIndex) throws SQLException { public boolean getBoolean(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
String result = getString(columnIndex); columnIndex = getTrueColumnIndex(columnIndex);
if (!(result.equals("true") || result.equals("false"))) { int result = getInt(columnIndex);
throw new SQLException("not boolean value"); return result == 0 ? false : true;
}
return result.equals("true");
} }
@Override @Override
public byte getByte(int columnIndex) throws SQLException { public byte getByte(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -169,40 +166,55 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public short getShort(int columnIndex) throws SQLException { public short getShort(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
columnIndex = getTrueColumnIndex(columnIndex);
return Short.parseShort(getString(columnIndex)); return Short.parseShort(resultSet.get(pos).get(columnIndex).toString());
} }
@Override @Override
public int getInt(int columnIndex) throws SQLException { public int getInt(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return Integer.parseInt(getString(columnIndex)); columnIndex = getTrueColumnIndex(columnIndex);
return Integer.parseInt(resultSet.get(pos).get(columnIndex).toString());
} }
@Override @Override
public long getLong(int columnIndex) throws SQLException { public long getLong(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
columnIndex = getTrueColumnIndex(columnIndex);
return Long.parseLong(getString(columnIndex)); return Long.parseLong(resultSet.get(pos).get(columnIndex).toString());
} }
@Override @Override
public float getFloat(int columnIndex) throws SQLException { public float getFloat(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
columnIndex = getTrueColumnIndex(columnIndex);
return Float.parseFloat(getString(columnIndex)); return Float.parseFloat(resultSet.get(pos).get(columnIndex).toString());
} }
@Override @Override
public double getDouble(int columnIndex) throws SQLException { public double getDouble(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return Double.parseDouble(getString(columnIndex)); columnIndex = getTrueColumnIndex(columnIndex);
return Double.parseDouble(resultSet.get(pos).get(columnIndex).toString());
}
private int getTrueColumnIndex(int columnIndex) throws SQLException {
if (columnIndex < 1) {
throw new SQLException("Column Index out of range, " + columnIndex + " < 1");
}
int numOfCols = resultSet.get(pos).size();
if (columnIndex > numOfCols) {
throw new SQLException("Column Index out of range, " + columnIndex + " > " + numOfCols);
}
return columnIndex - 1;
} }
/*******************************************************************************************************************/ /*******************************************************************************************************************/
@ -210,7 +222,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -218,7 +230,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public byte[] getBytes(int columnIndex) throws SQLException { public byte[] getBytes(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -226,7 +238,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Date getDate(int columnIndex) throws SQLException { public Date getDate(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -234,7 +246,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Time getTime(int columnIndex) throws SQLException { public Time getTime(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -242,17 +254,18 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Timestamp getTimestamp(int columnIndex) throws SQLException { public Timestamp getTimestamp(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
String strDate = getString(columnIndex); columnIndex = getTrueColumnIndex(columnIndex);
strDate = strDate.substring(1, strDate.length() - 1); String strDate = resultSet.get(pos).get(columnIndex).toString();
// strDate = strDate.substring(1, strDate.length() - 1);
return Timestamp.valueOf(strDate); return Timestamp.valueOf(strDate);
} }
@Override @Override
public InputStream getAsciiStream(int columnIndex) throws SQLException { public InputStream getAsciiStream(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -260,7 +273,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public InputStream getUnicodeStream(int columnIndex) throws SQLException { public InputStream getUnicodeStream(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -268,17 +281,16 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public InputStream getBinaryStream(int columnIndex) throws SQLException { public InputStream getBinaryStream(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
/*************************************************************************************************************/
@Override @Override
public String getString(String columnLabel) throws SQLException { public String getString(String columnLabel) throws SQLException {
if (isClosed()) return getString(findColumn(columnLabel));
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED));
return getString(findColumn(columnLabel) + 1);
} }
@Override @Override
@ -338,53 +350,44 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Timestamp getTimestamp(String columnLabel) throws SQLException { public Timestamp getTimestamp(String columnLabel) throws SQLException {
if (isClosed()) return getTimestamp(findColumn(columnLabel));
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED));
return Timestamp.valueOf(getString(findColumn(columnLabel)));
} }
@Override @Override
public InputStream getAsciiStream(String columnLabel) throws SQLException { public InputStream getAsciiStream(String columnLabel) throws SQLException {
if (isClosed()) return getAsciiStream(findColumn(columnLabel));
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public InputStream getUnicodeStream(String columnLabel) throws SQLException { public InputStream getUnicodeStream(String columnLabel) throws SQLException {
if (isClosed()) return getUnicodeStream(findColumn(columnLabel));
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public InputStream getBinaryStream(String columnLabel) throws SQLException { public InputStream getBinaryStream(String columnLabel) throws SQLException {
if (isClosed()) return getBinaryStream(findColumn(columnLabel));
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
/*************************************************************************************************************/
@Override @Override
public SQLWarning getWarnings() throws SQLException { public SQLWarning getWarnings() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return null; return null;
} }
@Override @Override
public void clearWarnings() throws SQLException { public void clearWarnings() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return; return;
} }
@Override @Override
public String getCursorName() throws SQLException { public String getCursorName() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -392,7 +395,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public ResultSetMetaData getMetaData() throws SQLException { public ResultSetMetaData getMetaData() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return this.metaData; return this.metaData;
} }
@ -400,7 +403,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Object getObject(int columnIndex) throws SQLException { public Object getObject(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -413,15 +416,18 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public int findColumn(String columnLabel) throws SQLException { public int findColumn(String columnLabel) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return columnNames.indexOf(columnLabel); int columnIndex = columnNames.indexOf(columnLabel);
if (columnIndex == -1)
throw new SQLException("cannot find Column in resultSet");
return columnIndex + 1;
} }
@Override @Override
public Reader getCharacterStream(int columnIndex) throws SQLException { public Reader getCharacterStream(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -429,7 +435,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Reader getCharacterStream(String columnLabel) throws SQLException { public Reader getCharacterStream(String columnLabel) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -437,7 +443,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public BigDecimal getBigDecimal(int columnIndex) throws SQLException { public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -445,7 +451,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public BigDecimal getBigDecimal(String columnLabel) throws SQLException { public BigDecimal getBigDecimal(String columnLabel) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -453,78 +459,132 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public boolean isBeforeFirst() throws SQLException { public boolean isBeforeFirst() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return this.pos == -1 && this.resultSet.size() != 0;
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public boolean isAfterLast() throws SQLException { public boolean isAfterLast() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
return this.pos >= resultSet.size() && this.resultSet.size() != 0;
} }
@Override @Override
public boolean isFirst() throws SQLException { public boolean isFirst() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); return this.pos == 0;
} }
@Override @Override
public boolean isLast() throws SQLException { public boolean isLast() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
if (this.resultSet.size() == 0)
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); return false;
return this.pos == (this.resultSet.size() - 1);
} }
@Override @Override
public void beforeFirst() throws SQLException { public void beforeFirst() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); synchronized (this) {
if (this.resultSet.size() > 0) {
this.pos = -1;
}
}
} }
@Override @Override
public void afterLast() throws SQLException { public void afterLast() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
synchronized (this) {
if (this.resultSet.size() > 0) {
this.pos = this.resultSet.size();
}
}
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public boolean first() throws SQLException { public boolean first() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); if (this.resultSet.size() == 0)
return false;
synchronized (this) {
this.pos = 0;
}
return true;
} }
@Override @Override
public boolean last() throws SQLException { public boolean last() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
if (this.resultSet.size() == 0)
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); return false;
synchronized (this) {
this.pos = this.resultSet.size() - 1;
}
return true;
} }
@Override @Override
public int getRow() throws SQLException { public int getRow() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
int row;
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); synchronized (this) {
if (this.pos < 0 || this.pos >= this.resultSet.size())
return 0;
row = this.pos + 1;
}
return row;
} }
@Override @Override
public boolean absolute(int row) throws SQLException { public boolean absolute(int row) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
// if (this.resultSet.size() == 0)
// return false;
//
// if (row == 0) {
// beforeFirst();
// return false;
// } else if (row == 1) {
// return first();
// } else if (row == -1) {
// return last();
// } else if (row > this.resultSet.size()) {
// afterLast();
// return false;
// } else {
// if (row < 0) {
// // adjust to reflect after end of result set
// int newRowPosition = this.resultSet.size() + row + 1;
// if (newRowPosition <= 0) {
// beforeFirst();
// return false;
// } else {
// return absolute(newRowPosition);
// }
// } else {
// row--; // adjust for index difference
// this.pos = row;
// return true;
// }
// }
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -532,7 +592,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public boolean relative(int rows) throws SQLException { public boolean relative(int rows) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -540,7 +600,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public boolean previous() throws SQLException { public boolean previous() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@ -548,17 +608,18 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public void setFetchDirection(int direction) throws SQLException { public void setFetchDirection(int direction) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
if (direction != ResultSet.FETCH_REVERSE || direction != ResultSet.FETCH_REVERSE || direction != ResultSet.FETCH_UNKNOWN) if ((direction != ResultSet.FETCH_FORWARD) && (direction != ResultSet.FETCH_REVERSE) && (direction != ResultSet.FETCH_UNKNOWN))
throw new SQLException(TSDBConstants.INVALID_VARIABLES); throw new SQLException(TSDBConstants.INVALID_VARIABLES);
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); if (!(getType() == ResultSet.TYPE_FORWARD_ONLY && direction == ResultSet.FETCH_FORWARD))
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public int getFetchDirection() throws SQLException { public int getFetchDirection() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return ResultSet.FETCH_FORWARD; return ResultSet.FETCH_FORWARD;
} }
@ -566,17 +627,17 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public void setFetchSize(int rows) throws SQLException { public void setFetchSize(int rows) throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
if (rows < 0) if (rows < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES); throw new SQLException(TSDBConstants.INVALID_VARIABLES);
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
public int getFetchSize() throws SQLException { public int getFetchSize() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return this.resultSet.size(); return this.resultSet.size();
} }
@ -834,7 +895,7 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public Statement getStatement() throws SQLException { public Statement getStatement() throws SQLException {
if (isClosed()) if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(RESULT_SET_IS_CLOSED)); throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return this.statement; return this.statement;
} }
@ -992,14 +1053,15 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public int getHoldability() throws SQLException { public int getHoldability() throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return ResultSet.HOLD_CURSORS_OVER_COMMIT; return ResultSet.HOLD_CURSORS_OVER_COMMIT;
} }
@Override @Override
public boolean isClosed() throws SQLException { public boolean isClosed() throws SQLException {
return false; return isClosed;
//TODO: SQLFeature Not Supported
// throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
} }
@Override @Override
@ -1224,11 +1286,21 @@ public class RestfulResultSet implements ResultSet {
@Override @Override
public <T> T unwrap(Class<T> iface) throws SQLException { public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
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 {
throw new SQLFeatureNotSupportedException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG); if (isClosed())
throw new SQLException(TSDBConstants.WrapErrMsg(TSDBConstants.RESULT_SET_IS_CLOSED));
return iface.isInstance(this);
} }
} }

View File

@ -1,17 +1,22 @@
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 {
@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 {
@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 {
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; 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 {
@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 {
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; return 0;
} }
}
@Override @Override
public int getScale(int column) throws SQLException { public int getScale(int column) throws SQLException {
String type = this.fields.get(column - 1).type.toUpperCase();
switch (type) {
case "FLOAT":
return 5;
case "DOUBLE":
return 9;
default:
return 0; 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 {
@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 {
@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);
} }
} }

View File

@ -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,17 +64,163 @@ 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";
if (SqlSyntaxValidator.isDatabaseUnspecifiedQuery(sql)) {
return executeOneQuery(url, sql);
}
if (this.database == null || this.database.isEmpty())
throw new SQLException("Database not specified or available");
HttpClientPoolUtil.execute(url, "use " + this.database);
return executeOneQuery(url, sql);
}
@Override
public int executeUpdate(String sql) throws SQLException {
if (isClosed())
throw new SQLException("statement already closed");
if (!SqlSyntaxValidator.isValidForExecuteUpdate(sql))
throw new SQLException("not a valid sql for executeUpdate: " + sql);
final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql";
if (SqlSyntaxValidator.isDatabaseUnspecifiedUpdate(sql)) {
return executeOneUpdate(url, sql);
}
if (this.database == null || this.database.isEmpty())
throw new SQLException("Database not specified or available");
HttpClientPoolUtil.execute(url, "use " + this.database);
return executeOneUpdate(url, sql);
}
@Override
public void close() throws SQLException {
synchronized (RestfulStatement.class) {
if (!isClosed())
this.closed = true;
}
}
@Override
public int getMaxFieldSize() throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return TSDBConstants.maxFieldSize;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (max < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
// nothing to do
}
@Override
public int getMaxRows() throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return 0;
}
@Override
public void setMaxRows(int max) throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (max < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
// nothing to do
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
}
@Override
public int getQueryTimeout() throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return 0;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
if (seconds < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
}
@Override
public void cancel() throws SQLException {
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
}
@Override
public SQLWarning getWarnings() throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
return null;
}
@Override
public void clearWarnings() throws SQLException {
// nothing to do
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
}
@Override
public void setCursorName(String name) throws SQLException {
if (isClosed())
throw new SQLException(TSDBConstants.STATEMENT_CLOSED);
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
}
@Override
public boolean execute(String sql) throws SQLException {
if (isClosed())
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
final String url = "http://" + conn.getHost() + ":" + conn.getPort() + "/rest/sql";
if (SqlSyntaxValidator.isUseSql(sql)) {
HttpClientPoolUtil.execute(url, sql);
this.database = sql.trim().replace("use", "").trim();
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);
}
}
return true;
}
private ResultSet executeOneQuery(String url, String sql) throws SQLException {
if (!SqlSyntaxValidator.isValidForExecuteQuery(sql))
throw new SQLException("not a select sql for executeQuery: " + sql);
// row data // row data
String result = HttpClientPoolUtil.execute(url, sql); String result = HttpClientPoolUtil.execute(url, sql);
JSONObject resultJson = JSON.parseObject(result); JSONObject resultJson = JSON.parseObject(result);
if (resultJson.getString("status").equals("error")) { if (resultJson.getString("status").equals("error")) {
throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + resultJson.getString("desc") + "\n" + "error code: " + resultJson.getString("code"))); throw new SQLException(TSDBConstants.WrapErrMsg("SQL execution error: " + resultJson.getString("desc") + "\n" + "error code: " + resultJson.getString("code")));
} }
// parse table name from sql // parse table name from sql
String[] tableIdentifiers = parseTableIdentifier(sql); String[] tableIdentifiers = parseTableIdentifier(sql);
if (tableIdentifiers != null) { if (tableIdentifiers != null) {
@ -93,23 +238,14 @@ public class RestfulStatement implements Statement {
} else { } else {
this.resultSet = new RestfulResultSet(database, this, resultJson); this.resultSet = new RestfulResultSet(database, this, resultJson);
} }
this.affectedRows = 0; this.affectedRows = 0;
return resultSet; return resultSet;
} }
@Override private int executeOneUpdate(String url, String sql) throws SQLException {
public int executeUpdate(String sql) throws SQLException {
if (isClosed())
throw new SQLException("statement already closed");
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)
throw new SQLException("Database not specified or available");
final String url = "http://" + conn.getHost().trim() + ":" + conn.getPort() + "/rest/sql";
// HttpClientPoolUtil.execute(url, "use " + conn.getDatabase());
String result = HttpClientPoolUtil.execute(url, sql); String result = HttpClientPoolUtil.execute(url, sql);
JSONObject jsonObject = JSON.parseObject(result); JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject.getString("status").equals("error")) { if (jsonObject.getString("status").equals("error")) {
@ -120,130 +256,10 @@ public class RestfulStatement implements Statement {
return this.affectedRows; return this.affectedRows;
} }
@Override
public void close() throws SQLException {
synchronized (RestfulStatement.class) {
if (!isClosed())
this.closed = true;
}
}
@Override
public int getMaxFieldSize() throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
return TSDBConstants.maxFieldSize;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
if (max < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
// nothing to do
}
@Override
public int getMaxRows() throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
return 0;
}
@Override
public void setMaxRows(int max) throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
if (max < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
// nothing to do
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
if (isClosed())
throw new SQLException(RestfulStatement.STATEMENT_CLOSED);
}
@Override
public int getQueryTimeout() throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
return 0;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
if (seconds < 0)
throw new SQLException(TSDBConstants.INVALID_VARIABLES);
}
@Override
public void cancel() throws SQLException {
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
}
@Override
public SQLWarning getWarnings() throws SQLException {
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
return null;
}
@Override
public void clearWarnings() throws SQLException {
// nothing to do
if (isClosed())
throw new SQLException(STATEMENT_CLOSED);
}
@Override
public void setCursorName(String name) throws SQLException {
if (isClosed())
throw new SQLException(RestfulStatement.STATEMENT_CLOSED);
throw new SQLException(TSDBConstants.UNSUPPORT_METHOD_EXCEPTIONZ_MSG);
}
@Override
public boolean execute(String sql) throws SQLException {
if (isClosed()) {
throw new SQLException("Invalid method call on a closed statement.");
}
//如果执行了use操作应该将当前Statement的catalog设置为新的database
if (SqlSyntaxValidator.isUseSql(sql)) {
this.database = sql.trim().replace("use", "").trim();
this.conn.setCatalog(this.database);
}
if (this.database == null)
throw new SQLException("Database not specified or available");
if (SqlSyntaxValidator.isSelectSql(sql)) {
executeQuery(sql);
} else if (SqlSyntaxValidator.isShowSql(sql) || SqlSyntaxValidator.isDescribeSql(sql)) {
final String url = "http://" + conn.getHost().trim() + ":" + conn.getPort() + "/rest/sql";
if (!SqlSyntaxValidator.isShowDatabaseSql(sql)) {
HttpClientPoolUtil.execute(url, "use " + conn.getDatabase());
}
String result = HttpClientPoolUtil.execute(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")));
}
this.resultSet = new RestfulResultSet(database, this, resultJson);
} else {
executeUpdate(sql);
}
return true;
}
@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 {
@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 {
@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 {
@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 {
@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 {
@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;
} }

View File

@ -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 {
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 {
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");
} }
} }

View File

@ -1,33 +0,0 @@
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);
}
}

View File

@ -1,115 +0,0 @@
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();
}
}
}

View File

@ -1,9 +1,7 @@
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;
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 {
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 {
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 { try {
tsdbStatement.unwrap(null); statement.getMaxFieldSize();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.isWrapperFor(null); statement.setMaxFieldSize(0);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getMaxFieldSize(); statement.setEscapeProcessing(true);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setMaxFieldSize(0); statement.cancel();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setEscapeProcessing(true); statement.getWarnings();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.cancel(); statement.clearWarnings();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getWarnings(); statement.setCursorName(null);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.clearWarnings(); statement.getMoreResults();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setCursorName(null); statement.setFetchDirection(0);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getMoreResults(); statement.getFetchDirection();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setFetchDirection(0); statement.getResultSetConcurrency();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getFetchDirection(); statement.getResultSetType();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getResultSetConcurrency(); statement.getConnection();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getResultSetType(); statement.getMoreResults();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getConnection(); statement.getGeneratedKeys();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getMoreResults(); statement.executeUpdate(null, 0);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getGeneratedKeys(); statement.executeUpdate(null, new int[]{0});
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.executeUpdate(null, 0); statement.executeUpdate(null, new String[]{"str1", "str2"});
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.executeUpdate(null, new int[]{0}); statement.getResultSetHoldability();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.executeUpdate(null, new String[]{"str1", "str2"}); statement.setPoolable(true);
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.getResultSetHoldability(); statement.isPoolable();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.setPoolable(true); statement.closeOnCompletion();
} catch (SQLException e) { } catch (SQLException e) {
} }
try { try {
tsdbStatement.isPoolable(); statement.isCloseOnCompletion();
} catch (SQLException e) {
}
try {
tsdbStatement.closeOnCompletion();
} catch (SQLException e) {
}
try {
tsdbStatement.isCloseOnCompletion();
} catch (SQLException e) { } catch (SQLException e) {
} }
} }

View File

@ -6,37 +6,22 @@ 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 {
public class QueryDataTest extends BaseTest { static Connection connection;
static Statement statement;
static Connection connection = null;
static Statement statement = null;
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) {
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");
@ -47,35 +32,41 @@ public class QueryDataTest extends BaseTest {
statement.executeUpdate("create database if not exists " + dbName); statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("use " + dbName); statement.executeUpdate("use " + dbName);
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(6))"; String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))";
statement.executeUpdate(createTableSql); statement.executeUpdate(createTableSql);
} catch (ClassNotFoundException | SQLException e) {
return;
}
} }
@Test @Test
public void testQueryBinaryData() throws SQLException { public void testQueryBinaryData() throws SQLException {
String insertSql = "insert into " + stbName + " values(now, 'taosdata')";
String insertSql = "insert into " + stbName + " values(now, 'taosda')";
System.out.println(insertSql); 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() {
try {
if (statement != null)
statement.close(); statement.close();
if (connection != null)
connection.close(); connection.close();
Thread.sleep(10); } catch (SQLException e) {
e.printStackTrace();
}
} }
} }

View File

@ -1,6 +1,7 @@
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;
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) {
return;
}
Properties properties = new Properties(); 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_TIME_ZONE, "UTC-8");
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");
connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/", properties);
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName); statement.executeUpdate("drop database if exists " + dbName);
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 + statement.execute("use " + dbName);
" (ts timestamp, k1 int, k2 bigint, k3 float, k4 double, k5 binary(30), k6 smallint, k7 bool, k8 nchar(20))"); 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;
}
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 {
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 {
assertEquals(res.length, 2); assertEquals(res.length, 2);
statement.clearBatch(); statement.clearBatch();
} }
@AfterClass @AfterClass
public static void close() throws Exception { public static void close() {
try {
statement.executeUpdate("drop database " + dbName); statement.executeUpdate("drop database " + dbName);
if (statement != null)
statement.close(); statement.close();
if (connection != null)
connection.close(); connection.close();
Thread.sleep(10); } catch (SQLException e) {
e.printStackTrace();
}
} }
} }

View File

@ -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();

View File

@ -1,6 +1,7 @@
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 {
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");
} catch (ClassNotFoundException e) {
return;
}
Properties properties = new Properties(); Properties properties = new Properties();
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/?user=root&password=taosdata", properties); connection = DriverManager.getConnection("jdbc:TAOS://" + host + ":0/?user=root&password=taosdata", properties);
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName); statement.executeUpdate("drop database if exists " + dbName);
} catch (ClassNotFoundException e) {
return;
}
} }
@Test @Test
@ -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 {
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);
if (statement != null)
statement.close(); statement.close();
if (connection != null)
connection.close(); connection.close();
Thread.sleep(10); } catch (SQLException e) {
e.printStackTrace();
} }
} }
} }

View File

@ -10,21 +10,18 @@ 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) {
return;
}
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host); properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
@ -41,6 +38,10 @@ public class SubscribeTest extends BaseTest {
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;
}
} }
@Test @Test
@ -79,10 +80,16 @@ public class SubscribeTest extends BaseTest {
} }
@After @After
public void close() throws Exception { public void close() {
try {
statement.executeQuery("drop database " + dbName); statement.executeQuery("drop database " + dbName);
if (statement != null)
statement.close(); statement.close();
if (connection != null)
connection.close(); connection.close();
Thread.sleep(10); } catch (SQLException e) {
e.printStackTrace();
}
} }
} }

View File

@ -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 {
@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 {
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();
}
}
} }

View File

@ -3,9 +3,6 @@ package com.taosdata.jdbc;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
@ -27,54 +24,15 @@ public class TSDBDriverTest {
"jdbc:TAOS://:/test", "jdbc:TAOS://:/test",
"jdbc:TAOS://localhost:0/?user=root&password=taosdata" "jdbc:TAOS://localhost:0/?user=root&password=taosdata"
}; };
private static boolean islibLoaded = false;
private static boolean isTaosdActived;
private Connection conn; private Connection conn;
@BeforeClass
public static void before() {
String osName = System.getProperty("os.name").toLowerCase();
if (!osName.equals("linux"))
return;
// try to load taos lib
try {
System.loadLibrary("taos");
islibLoaded = true;
} catch (UnsatisfiedLinkError error) {
System.out.println("load tdengine lib failed.");
error.printStackTrace();
}
// check taosd is activated
try {
String[] cmd = {"/bin/bash", "-c", "ps -ef | grep taosd | grep -v \"grep\""};
Process exec = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
int lineCnt = 0;
while (reader.readLine() != null) {
lineCnt++;
}
if (lineCnt > 0)
isTaosdActived = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Test @Test
public void testConnectWithJdbcURL() { public void testConnectWithJdbcURL() {
final String url = "jdbc:TAOS://localhost:6030/log?user=root&password=taosdata"; final String url = "jdbc:TAOS://localhost:6030/log?user=root&password=taosdata";
try { try {
if (islibLoaded && isTaosdActived) {
conn = DriverManager.getConnection(url); conn = DriverManager.getConnection(url);
assertNotNull("failure - connection should not be null", conn); assertNotNull("failure - connection should not be null", conn);
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
@ -89,10 +47,8 @@ public class TSDBDriverTest {
connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
try { try {
if (islibLoaded && isTaosdActived) {
conn = DriverManager.getConnection(jdbcUrl, connProps); conn = DriverManager.getConnection(jdbcUrl, connProps);
assertNotNull("failure - connection should not be null", conn); assertNotNull("failure - connection should not be null", conn);
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
@ -107,10 +63,8 @@ public class TSDBDriverTest {
connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
try { try {
if (islibLoaded && isTaosdActived) {
conn = DriverManager.getConnection(jdbcUrl, connProps); conn = DriverManager.getConnection(jdbcUrl, connProps);
assertNotNull("failure - connection should not be null", conn); assertNotNull("failure - connection should not be null", conn);
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
@ -207,4 +161,14 @@ public class TSDBDriverTest {
assertNull("failure - getParentLogger should be be null", new TSDBDriver().getParentLogger()); assertNull("failure - getParentLogger should be be null", new TSDBDriver().getParentLogger());
} }
@BeforeClass
public static void before() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} }

View File

@ -0,0 +1,186 @@
package com.taosdata.jdbc;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TSDBPreparedStatementTest {
private static final String host = "127.0.0.1";
private static Connection conn;
@Test
public void executeQuery() {
}
@Test
public void executeUpdate() {
}
@Test
public void setNull() {
}
@Test
public void setBoolean() {
}
@Test
public void setByte() {
}
@Test
public void setShort() {
}
@Test
public void setInt() {
}
@Test
public void setLong() {
}
@Test
public void setFloat() {
}
@Test
public void setDouble() {
}
@Test
public void setBigDecimal() {
}
@Test
public void setString() {
}
@Test
public void setBytes() {
}
@Test
public void setDate() {
}
@Test
public void setTime() {
}
@Test
public void setTimestamp() {
}
@Test
public void setAsciiStream() {
}
@Test
public void setUnicodeStream() {
}
@Test
public void setBinaryStream() {
}
@Test
public void clearParameters() {
}
@Test
public void setObject() {
}
@Test
public void execute() {
}
@Test
public void addBatch() {
}
@Test
public void setCharacterStream() {
}
@Test
public void setRef() {
}
@Test
public void setBlob() {
}
@Test
public void setClob() {
}
@Test
public void setArray() {
}
@Test
public void getMetaData() {
}
@Test
public void setURL() {
}
@Test
public void getParameterMetaData() {
}
@Test
public void setRowId() {
}
@Test
public void setNString() {
}
@Test
public void setNCharacterStream() {
}
@Test
public void setNClob() {
}
@Test
public void setSQLXML() {
}
@BeforeClass
public static void beforeClass() {
try {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -1,14 +1,12 @@
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import com.taosdata.jdbc.lib.TSDBCommon; import com.taosdata.jdbc.TSDBDriver;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.sql.Connection; import java.sql.*;
import java.sql.ResultSet; import java.util.Properties;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -18,23 +16,40 @@ import static org.junit.Assert.assertEquals;
public class BatchInsertTest { public class BatchInsertTest {
static String host = "localhost"; static String host = "127.0.0.1";
static String dbName = "test"; static String dbName = "test";
static String stbName = "meters"; static String stbName = "meters";
static int numOfTables = 30; static int numOfTables = 30;
final static int numOfRecordsPerTable = 1000; final static int numOfRecordsPerTable = 1000;
static long ts = 1496732686000l; static long ts = 1496732686000l;
final static String tablePrefix = "t"; final static String tablePrefix = "t";
private Connection connection; private Connection connection;
@Before @Before
public void before() { public void before() {
try { try {
connection = TSDBCommon.getConn(host); Class.forName("com.taosdata.jdbc.TSDBDriver");
TSDBCommon.createDatabase(connection, dbName); Properties properties = new Properties();
TSDBCommon.createStable(connection, stbName); properties.setProperty(TSDBDriver.PROPERTY_KEY_HOST, host);
TSDBCommon.createTables(connection, numOfTables, stbName, tablePrefix); 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 statement = connection.createStatement();
statement.executeUpdate("drop database if exists " + dbName);
statement.executeUpdate("create database if not exists " + dbName);
statement.executeUpdate("use " + dbName);
// create stable
String createTableSql = "create table " + stbName + "(ts timestamp, f1 int, f2 int, f3 int) tags(areaid int, loc binary(20))";
statement.executeUpdate(createTableSql);
// create tables
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();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -45,9 +60,7 @@ public class BatchInsertTest {
ExecutorService executorService = Executors.newFixedThreadPool(numOfTables); ExecutorService executorService = Executors.newFixedThreadPool(numOfTables);
for (int i = 0; i < numOfTables; i++) { for (int i = 0; i < numOfTables; i++) {
final int index = i; final int index = i;
executorService.execute(new Runnable() { executorService.execute(() -> {
@Override
public void run() {
try { try {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
Statement statement = connection.createStatement(); // get statement Statement statement = connection.createStatement(); // get statement
@ -69,7 +82,6 @@ public class BatchInsertTest {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }
@ -102,7 +114,6 @@ public class BatchInsertTest {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -1,47 +0,0 @@
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();
}
}

View File

@ -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;

View File

@ -10,23 +10,12 @@ import java.util.Random;
public class RestfulJDBCTest { public class RestfulJDBCTest {
private static final String host = "127.0.0.1"; private static final String host = "127.0.0.1";
private Connection connection; // private static final String host = "master";
private static Connection connection;
@Before private Random random = new Random(System.currentTimeMillis());
public void before() throws ClassNotFoundException, SQLException {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
}
@After
public void after() throws SQLException {
if (connection != null)
connection.close();
}
/** /**
* 查询所有log.log * select * from log.log
**/ **/
@Test @Test
public void testCase001() { public void testCase001() {
@ -85,7 +74,6 @@ public class RestfulJDBCTest {
} }
} }
private Random random = new Random(System.currentTimeMillis());
@Test @Test
public void testCase005() { public void testCase005() {
@ -105,5 +93,50 @@ public class RestfulJDBCTest {
} }
} }
@Test
public void testCase006() {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
System.out.print("ts: " + rs.getTimestamp("ts"));
System.out.print(", temperature: " + rs.getString("temperature"));
System.out.print(", humidity: " + rs.getString("humidity"));
System.out.println(", location: " + rs.getString("location"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testCase007() {
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnLabel = meta.getColumnLabel(i);
String value = rs.getString(i);
System.out.print(columnLabel + ": " + value + "\t");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@BeforeClass
public static void before() throws ClassNotFoundException, SQLException {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
}
@AfterClass
public static void after() throws SQLException {
if (connection != null)
connection.close();
}
} }

View File

@ -0,0 +1,221 @@
package com.taosdata.jdbc.rs;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.*;
public class RestfulResultSetMetaDataTest {
private static final String host = "127.0.0.1";
// private static final String host = "master";
private static Connection conn;
private static Statement stmt;
private static ResultSet rs;
private static ResultSetMetaData meta;
@Test
public void getColumnCount() throws SQLException {
Assert.assertEquals(10, meta.getColumnCount());
}
@Test
public void isAutoIncrement() throws SQLException {
Assert.assertFalse(meta.isAutoIncrement(1));
Assert.assertFalse(meta.isAutoIncrement(2));
Assert.assertFalse(meta.isAutoIncrement(3));
Assert.assertFalse(meta.isAutoIncrement(4));
Assert.assertFalse(meta.isAutoIncrement(5));
Assert.assertFalse(meta.isAutoIncrement(6));
Assert.assertFalse(meta.isAutoIncrement(7));
Assert.assertFalse(meta.isAutoIncrement(8));
Assert.assertFalse(meta.isAutoIncrement(9));
Assert.assertFalse(meta.isAutoIncrement(10));
}
@Test
public void isCaseSensitive() throws SQLException {
Assert.assertFalse(meta.isCaseSensitive(1));
}
@Test
public void isSearchable() throws SQLException {
Assert.assertTrue(meta.isSearchable(1));
}
@Test
public void isCurrency() throws SQLException {
Assert.assertFalse(meta.isCurrency(1));
}
@Test
public void isNullable() throws SQLException {
Assert.assertEquals(ResultSetMetaData.columnNoNulls, meta.isNullable(1));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(2));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(3));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(4));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(5));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(6));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(7));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(8));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(9));
Assert.assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(10));
}
@Test
public void isSigned() throws SQLException {
Assert.assertFalse(meta.isSigned(1));
}
@Test
public void getColumnDisplaySize() throws SQLException {
Assert.assertEquals(64, meta.getColumnDisplaySize(10));
}
@Test
public void getColumnLabel() throws SQLException {
Assert.assertEquals("f1", meta.getColumnLabel(1));
}
@Test
public void getColumnName() throws SQLException {
Assert.assertEquals("f1", meta.getColumnName(1));
}
@Test
public void getSchemaName() throws SQLException {
Assert.assertEquals("", meta.getSchemaName(1));
}
@Test
public void getPrecision() throws SQLException {
Assert.assertEquals(0, meta.getPrecision(1));
}
@Test
public void getScale() throws SQLException {
Assert.assertEquals(0, meta.getScale(1));
}
@Test
public void getTableName() throws SQLException {
Assert.assertEquals("", meta.getTableName(1));
}
@Test
public void getCatalogName() throws SQLException {
Assert.assertEquals("restful_test", meta.getCatalogName(1));
Assert.assertEquals("restful_test", meta.getCatalogName(2));
Assert.assertEquals("restful_test", meta.getCatalogName(3));
Assert.assertEquals("restful_test", meta.getCatalogName(4));
Assert.assertEquals("restful_test", meta.getCatalogName(5));
Assert.assertEquals("restful_test", meta.getCatalogName(6));
Assert.assertEquals("restful_test", meta.getCatalogName(7));
Assert.assertEquals("restful_test", meta.getCatalogName(8));
Assert.assertEquals("restful_test", meta.getCatalogName(9));
Assert.assertEquals("restful_test", meta.getCatalogName(10));
}
@Test
public void getColumnType() throws SQLException {
Assert.assertEquals(Types.TIMESTAMP, meta.getColumnType(1));
Assert.assertEquals(Types.INTEGER, meta.getColumnType(2));
Assert.assertEquals(Types.BIGINT, meta.getColumnType(3));
Assert.assertEquals(Types.FLOAT, meta.getColumnType(4));
Assert.assertEquals(Types.DOUBLE, meta.getColumnType(5));
Assert.assertEquals(Types.BINARY, meta.getColumnType(6));
Assert.assertEquals(Types.SMALLINT, meta.getColumnType(7));
Assert.assertEquals(Types.TINYINT, meta.getColumnType(8));
Assert.assertEquals(Types.BOOLEAN, meta.getColumnType(9));
Assert.assertEquals(Types.NCHAR, meta.getColumnType(10));
}
@Test
public void getColumnTypeName() throws SQLException {
Assert.assertEquals("TIMESTAMP", meta.getColumnTypeName(1));
Assert.assertEquals("INT", meta.getColumnTypeName(2));
Assert.assertEquals("BIGINT", meta.getColumnTypeName(3));
Assert.assertEquals("FLOAT", meta.getColumnTypeName(4));
Assert.assertEquals("DOUBLE", meta.getColumnTypeName(5));
Assert.assertEquals("BINARY", meta.getColumnTypeName(6));
Assert.assertEquals("SMALLINT", meta.getColumnTypeName(7));
Assert.assertEquals("TINYINT", meta.getColumnTypeName(8));
Assert.assertEquals("BOOL", meta.getColumnTypeName(9));
Assert.assertEquals("NCHAR", meta.getColumnTypeName(10));
}
@Test
public void isReadOnly() throws SQLException {
Assert.assertTrue(meta.isReadOnly(1));
}
@Test
public void isWritable() throws SQLException {
Assert.assertFalse(meta.isWritable(1));
}
@Test
public void isDefinitelyWritable() throws SQLException {
Assert.assertFalse(meta.isDefinitelyWritable(1));
}
@Test
public void getColumnClassName() throws SQLException {
Assert.assertEquals(Timestamp.class.getName(), meta.getColumnClassName(1));
Assert.assertEquals(Integer.class.getName(), meta.getColumnClassName(2));
Assert.assertEquals(Long.class.getName(), meta.getColumnClassName(3));
Assert.assertEquals(Float.class.getName(), meta.getColumnClassName(4));
Assert.assertEquals(Double.class.getName(), meta.getColumnClassName(5));
Assert.assertEquals(String.class.getName(), meta.getColumnClassName(6));
Assert.assertEquals(Short.class.getName(), meta.getColumnClassName(7));
Assert.assertEquals(Short.class.getName(), meta.getColumnClassName(8));
Assert.assertEquals(Boolean.class.getName(), meta.getColumnClassName(9));
Assert.assertEquals(String.class.getName(), meta.getColumnClassName(10));
}
@Test
public void unwrap() throws SQLException {
Assert.assertNotNull(meta.unwrap(RestfulResultSetMetaData.class));
}
@Test
public void isWrapperFor() throws SQLException {
Assert.assertTrue(meta.isWrapperFor(RestfulResultSetMetaData.class));
}
@BeforeClass
public static void beforeClass() {
try {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
stmt = conn.createStatement();
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
stmt.execute("drop table if exists weather");
stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))");
stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')");
rs = stmt.executeQuery("select * from restful_test.weather");
rs.next();
meta = rs.getMetaData();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,588 @@
package com.taosdata.jdbc.rs;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.*;
public class RestfulResultSetTest {
private static final String host = "127.0.0.1";
// private static final String host = "master";
private static Connection conn;
private static Statement stmt;
private static ResultSet rs;
@Test
public void wasNull() throws SQLException {
Assert.assertFalse(rs.wasNull());
}
@Test
public void getString() throws SQLException {
String f10 = rs.getString("f10");
Assert.assertEquals("涛思数据", f10);
f10 = rs.getString(10);
Assert.assertEquals("涛思数据", f10);
}
@Test
public void getBoolean() throws SQLException {
Boolean f9 = rs.getBoolean("f9");
Assert.assertEquals(true, f9);
f9 = rs.getBoolean(9);
Assert.assertEquals(true, f9);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getByte() throws SQLException {
rs.getByte(1);
}
@Test
public void getShort() throws SQLException {
short f7 = rs.getShort("f7");
Assert.assertEquals(10, f7);
f7 = rs.getShort(7);
Assert.assertEquals(10, f7);
}
@Test
public void getInt() throws SQLException {
int f2 = rs.getInt("f2");
Assert.assertEquals(1, f2);
f2 = rs.getInt(2);
Assert.assertEquals(1, f2);
}
@Test
public void getLong() throws SQLException {
long f3 = rs.getLong("f3");
Assert.assertEquals(100, f3);
f3 = rs.getLong(3);
Assert.assertEquals(100, f3);
}
@Test
public void getFloat() throws SQLException {
float f4 = rs.getFloat("f4");
Assert.assertEquals(3.1415f, f4, 0f);
f4 = rs.getFloat(4);
Assert.assertEquals(3.1415f, f4, 0f);
}
@Test
public void getDouble() throws SQLException {
double f5 = rs.getDouble("f5");
Assert.assertEquals(3.1415926, f5, 0.0);
f5 = rs.getDouble(5);
Assert.assertEquals(3.1415926, f5, 0.0);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getBigDecimal() throws SQLException {
rs.getBigDecimal("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getBytes() throws SQLException {
rs.getBytes("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getDate() throws SQLException {
rs.getDate("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getTime() throws SQLException {
rs.getTime("f1");
}
@Test
public void getTimestamp() throws SQLException {
Timestamp f1 = rs.getTimestamp("f1");
Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString());
f1 = rs.getTimestamp(1);
Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getAsciiStream() throws SQLException {
rs.getAsciiStream("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getUnicodeStream() throws SQLException {
rs.getUnicodeStream("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getBinaryStream() throws SQLException {
rs.getBinaryStream("f1");
}
@Test
public void getWarnings() throws SQLException {
Assert.assertNull(rs.getWarnings());
}
@Test
public void clearWarnings() throws SQLException {
rs.clearWarnings();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getCursorName() throws SQLException {
rs.getCursorName();
}
@Test
public void getMetaData() throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
Assert.assertNotNull(meta);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getObject() throws SQLException {
rs.getObject("f1");
}
@Test(expected = SQLException.class)
public void findColumn() throws SQLException {
int columnIndex = rs.findColumn("f1");
Assert.assertEquals(1, columnIndex);
columnIndex = rs.findColumn("f2");
Assert.assertEquals(2, columnIndex);
columnIndex = rs.findColumn("f3");
Assert.assertEquals(3, columnIndex);
columnIndex = rs.findColumn("f4");
Assert.assertEquals(4, columnIndex);
columnIndex = rs.findColumn("f5");
Assert.assertEquals(5, columnIndex);
columnIndex = rs.findColumn("f6");
Assert.assertEquals(6, columnIndex);
columnIndex = rs.findColumn("f7");
Assert.assertEquals(7, columnIndex);
columnIndex = rs.findColumn("f8");
Assert.assertEquals(8, columnIndex);
columnIndex = rs.findColumn("f9");
Assert.assertEquals(9, columnIndex);
columnIndex = rs.findColumn("f10");
Assert.assertEquals(10, columnIndex);
rs.findColumn("f11");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getCharacterStream() throws SQLException {
rs.getCharacterStream(1);
}
@Test
public void isBeforeFirst() throws SQLException {
Assert.assertFalse(rs.isBeforeFirst());
rs.beforeFirst();
Assert.assertTrue(rs.isBeforeFirst());
rs.next();
}
@Test
public void isAfterLast() throws SQLException {
Assert.assertFalse(rs.isAfterLast());
}
@Test
public void isFirst() throws SQLException {
Assert.assertTrue(rs.isFirst());
}
@Test
public void isLast() throws SQLException {
Assert.assertTrue(rs.isLast());
}
@Test
public void beforeFirst() throws SQLException {
rs.beforeFirst();
Assert.assertTrue(rs.isBeforeFirst());
rs.next();
}
@Test
public void afterLast() throws SQLException {
rs.afterLast();
Assert.assertTrue(rs.isAfterLast());
rs.first();
}
@Test
public void first() throws SQLException {
rs.first();
Assert.assertEquals("2021-01-01 00:00:00.0", rs.getTimestamp("f1").toString());
}
@Test
public void last() throws SQLException {
rs.last();
Assert.assertEquals("2021-01-01 00:00:00.0", rs.getTimestamp("f1").toString());
}
@Test
public void getRow() throws SQLException {
int row = rs.getRow();
Assert.assertEquals(1, row);
rs.beforeFirst();
row = rs.getRow();
Assert.assertEquals(0, row);
rs.first();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void absolute() throws SQLException {
rs.absolute(-1);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void relative() throws SQLException {
rs.relative(-1);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void previous() throws SQLException {
rs.previous();
}
@Test(expected = SQLException.class)
public void setFetchDirection() throws SQLException {
rs.setFetchDirection(ResultSet.FETCH_FORWARD);
rs.setFetchDirection(ResultSet.FETCH_UNKNOWN);
}
@Test
public void getFetchDirection() throws SQLException {
Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection());
}
@Test(expected = SQLException.class)
public void setFetchSize() throws SQLException {
rs.setFetchSize(0);
}
@Test
public void getFetchSize() throws SQLException {
Assert.assertEquals(1, rs.getFetchSize());
}
@Test
public void getType() throws SQLException {
Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
}
@Test
public void getConcurrency() throws SQLException {
Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void rowUpdated() throws SQLException {
rs.rowUpdated();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void rowInserted() throws SQLException {
rs.rowInserted();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void rowDeleted() throws SQLException {
rs.rowDeleted();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateNull() throws SQLException {
rs.updateNull("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateBoolean() throws SQLException {
rs.updateBoolean(1, false);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateByte() throws SQLException {
rs.updateByte(1, new Byte("0"));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateShort() throws SQLException {
rs.updateShort(1, new Short("0"));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateInt() throws SQLException {
rs.updateInt(1, 1);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateLong() throws SQLException {
rs.updateLong(1, 1l);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateFloat() throws SQLException {
rs.updateFloat(1, 1f);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateDouble() throws SQLException {
rs.updateDouble(1, 1.0);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateBigDecimal() throws SQLException {
rs.updateBigDecimal(1, new BigDecimal(1));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateString() throws SQLException {
rs.updateString(1, "abc");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateBytes() throws SQLException {
rs.updateBytes(1, new byte[]{});
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateDate() throws SQLException {
rs.updateDate(1, new Date(System.currentTimeMillis()));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateTime() throws SQLException {
rs.updateTime(1, new Time(System.currentTimeMillis()));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateTimestamp() throws SQLException {
rs.updateTimestamp(1, new Timestamp(System.currentTimeMillis()));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateAsciiStream() throws SQLException {
rs.updateAsciiStream(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateBinaryStream() throws SQLException {
rs.updateBinaryStream(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateCharacterStream() throws SQLException {
rs.updateCharacterStream(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateObject() throws SQLException {
rs.updateObject(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void insertRow() throws SQLException {
rs.insertRow();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateRow() throws SQLException {
rs.updateRow();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void deleteRow() throws SQLException {
rs.deleteRow();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void refreshRow() throws SQLException {
rs.refreshRow();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void cancelRowUpdates() throws SQLException {
rs.cancelRowUpdates();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void moveToInsertRow() throws SQLException {
rs.moveToInsertRow();
}
@Test
public void getStatement() throws SQLException {
Statement stmt = rs.getStatement();
Assert.assertNotNull(stmt);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void moveToCurrentRow() throws SQLException {
rs.moveToCurrentRow();
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getRef() throws SQLException {
rs.getRef(1);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getBlob() throws SQLException {
rs.getBlob("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getClob() throws SQLException {
rs.getClob("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getArray() throws SQLException {
rs.getArray("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getURL() throws SQLException {
rs.getURL("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateRef() throws SQLException {
rs.updateRef("f1", null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateBlob() throws SQLException {
rs.updateBlob(1, (InputStream) null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateClob() throws SQLException {
rs.updateClob(1, (Reader) null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateArray() throws SQLException {
rs.updateArray(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getRowId() throws SQLException {
rs.getRowId("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateRowId() throws SQLException {
rs.updateRowId(1, null);
}
@Test
public void getHoldability() throws SQLException {
Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability());
}
@Test
public void isClosed() throws SQLException {
Assert.assertFalse(rs.isClosed());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateNString() throws SQLException {
rs.updateNString(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateNClob() throws SQLException {
rs.updateNClob(1, (Reader) null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getNClob() throws SQLException {
rs.getNClob("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getSQLXML() throws SQLException {
rs.getSQLXML("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateSQLXML() throws SQLException {
rs.updateSQLXML(1, null);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getNString() throws SQLException {
rs.getNString("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void getNCharacterStream() throws SQLException {
rs.getNCharacterStream("f1");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void updateNCharacterStream() throws SQLException {
rs.updateNCharacterStream(1, null);
}
@Test
public void unwrap() throws SQLException {
RestfulResultSet unwrap = rs.unwrap(RestfulResultSet.class);
Assert.assertNotNull(unwrap);
}
@Test
public void isWrapperFor() throws SQLException {
Assert.assertTrue(rs.isWrapperFor(RestfulResultSet.class));
}
@BeforeClass
public static void beforeClass() {
try {
Class.forName("com.taosdata.jdbc.rs.RestfulDriver");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
stmt = conn.createStatement();
stmt.execute("create database if not exists restful_test");
stmt.execute("use restful_test");
stmt.execute("drop table if exists weather");
stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))");
stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')");
rs = stmt.executeQuery("select * from restful_test.weather");
rs.next();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -1,5 +1,6 @@
package com.taosdata.jdbc.rs; package com.taosdata.jdbc.rs;
import com.taosdata.jdbc.utils.SQLExecutor;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.FixMethodOrder; import org.junit.FixMethodOrder;
@ -11,378 +12,315 @@ import java.sql.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SQLTest { public class SQLTest {
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 Connection connection; private static Connection connection;
@Test @Test
public void testCase001() { public void testCase001() {
String sql = "create database if not exists restful_test"; String sql = "create database if not exists restful_test";
execute(sql); SQLExecutor.execute(connection, sql);
} }
@Test @Test
public void testCase002() { public void testCase002() {
String sql = "use restful_test"; String sql = "use restful_test";
execute(sql); SQLExecutor.execute(connection, sql);
} }
@Test @Test
public void testCase003() { public void testCase003() {
String sql = "show databases"; String sql = "show databases";
executeWithResult(sql); SQLExecutor.executeWithResult(connection, sql);
} }
@Test @Test
public void testCase004() { public void testCase004() {
String sql = "show tables"; String sql = "show tables";
executeWithResult(sql); SQLExecutor.executeWithResult(connection, sql);
} }
@Test @Test
public void testCase005() { public void testCase005() {
String sql = "show stables"; String sql = "show stables";
executeWithResult(sql); SQLExecutor.executeWithResult(connection, sql);
} }
@Test @Test
public void testCase006() { public void testCase006() {
String sql = "show dnodes"; String sql = "show dnodes";
executeWithResult(sql); SQLExecutor.executeWithResult(connection, sql);
} }
@Test @Test
public void testCase007() { public void testCase007() {
String sql = "show vgroups"; String sql = "show vgroups";
executeWithResult(sql); SQLExecutor.executeWithResult(connection, sql);
} }
@Test @Test
public void testCase008() { public void testCase008() {
String sql = "drop table if exists restful_test.weather"; String sql = "drop table if exists restful_test.weather";
execute(sql); SQLExecutor.execute(connection, sql);
} }
@Test @Test
public void testCase009() { public void testCase009() {
String sql = "create table if not exists restful_test.weather(ts timestamp, temperature float) tags(location nchar(64))"; String sql = "create table if not exists restful_test.weather(ts timestamp, temperature float) tags(location nchar(64))";
execute(sql); SQLExecutor.execute(connection, sql);
} }
@Test @Test
public void testCase010() { public void testCase010() {
String sql = "create table t1 using restful_test.weather tags('北京')"; String sql = "create table t1 using restful_test.weather tags('北京')";
execute(sql); SQLExecutor.execute(connection, sql);
} }
@Test @Test
public void testCase011() { public void testCase011() {
String sql = "insert into restful_test.t1 values(now, 22.22)"; String sql = "insert into restful_test.t1 values(now, 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase012() { public void testCase012() {
String sql = "insert into restful_test.t1 values('2020-01-01 00:00:00.000', 22.22)"; String sql = "insert into restful_test.t1 values('2020-01-01 00:00:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase013() { public void testCase013() {
String sql = "insert into restful_test.t1 values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)"; String sql = "insert into restful_test.t1 values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase014() { public void testCase014() {
String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:03:00.000', 22.22)"; String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:03:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase015() { public void testCase015() {
String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)"; String sql = "insert into restful_test.t2 using weather tags('上海') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase016() { public void testCase016() {
String sql = "insert into t1 values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t2 values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)"; String sql = "insert into t1 values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t2 values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase017() { public void testCase017() {
String sql = "Insert into t3 using weather tags('广东') values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t4 using weather tags('天津') values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)"; String sql = "Insert into t3 using weather tags('广东') values('2020-01-01 01:0:00.000', 22.22),('2020-01-01 02:00:00.000', 22.22) t4 using weather tags('天津') values('2020-01-01 01:0:00.000', 33.33),('2020-01-01 02:00:00.000', 33.33)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase018() { public void testCase018() {
String sql = "select * from restful_test.t1"; String sql = "select * from restful_test.t1";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase019() { public void testCase019() {
String sql = "select * from restful_test.weather"; String sql = "select * from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase020() { public void testCase020() {
String sql = "select ts, temperature from restful_test.t1"; String sql = "select ts, temperature from restful_test.t1";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase021() { public void testCase021() {
String sql = "select ts, temperature from restful_test.weather"; String sql = "select ts, temperature from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase022() { public void testCase022() {
String sql = "select temperature, ts from restful_test.t1"; String sql = "select temperature, ts from restful_test.t1";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase023() { public void testCase023() {
String sql = "select temperature, ts from restful_test.weather"; String sql = "select temperature, ts from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase024() { public void testCase024() {
String sql = "import into restful_test.t5 using weather tags('石家庄') values('2020-01-01 00:01:00.000', 22.22)"; String sql = "import into restful_test.t5 using weather tags('石家庄') values('2020-01-01 00:01:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase025() { public void testCase025() {
String sql = "import into restful_test.t6 using weather tags('沈阳') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)"; String sql = "import into restful_test.t6 using weather tags('沈阳') values('2020-01-01 00:01:00.000', 22.22),('2020-01-01 00:02:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase026() { public void testCase026() {
String sql = "import into restful_test.t7 using weather tags('长沙') values('2020-01-01 00:01:00.000', 22.22) restful_test.t8 using weather tags('吉林') values('2020-01-01 00:01:00.000', 22.22)"; String sql = "import into restful_test.t7 using weather tags('长沙') values('2020-01-01 00:01:00.000', 22.22) restful_test.t8 using weather tags('吉林') values('2020-01-01 00:01:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase027() { public void testCase027() {
String sql = "import into restful_test.t9 using weather tags('武汉') values('2020-01-01 00:01:00.000', 22.22) ,('2020-01-02 00:01:00.000', 22.22) restful_test.t10 using weather tags('哈尔滨') values('2020-01-01 00:01:00.000', 22.22),('2020-01-02 00:01:00.000', 22.22)"; String sql = "import into restful_test.t9 using weather tags('武汉') values('2020-01-01 00:01:00.000', 22.22) ,('2020-01-02 00:01:00.000', 22.22) restful_test.t10 using weather tags('哈尔滨') values('2020-01-01 00:01:00.000', 22.22),('2020-01-02 00:01:00.000', 22.22)";
executeUpdate(sql); SQLExecutor.executeUpdate(connection, sql);
} }
@Test @Test
public void testCase028() { public void testCase028() {
String sql = "select location, temperature, ts from restful_test.weather where temperature > 1"; String sql = "select location, temperature, ts from restful_test.weather where temperature > 1";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase029() { public void testCase029() {
String sql = "select location, temperature, ts from restful_test.weather where temperature < 1"; String sql = "select location, temperature, ts from restful_test.weather where temperature < 1";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase030() { public void testCase030() {
String sql = "select location, temperature, ts from restful_test.weather where ts > now"; String sql = "select location, temperature, ts from restful_test.weather where ts > now";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase031() { public void testCase031() {
String sql = "select location, temperature, ts from restful_test.weather where ts < now"; String sql = "select location, temperature, ts from restful_test.weather where ts < now";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase032() { public void testCase032() {
String sql = "select count(*) from restful_test.weather"; String sql = "select count(*) from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase033() { public void testCase033() {
String sql = "select first(*) from restful_test.weather"; String sql = "select first(*) from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase034() { public void testCase034() {
String sql = "select last(*) from restful_test.weather"; String sql = "select last(*) from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase035() { public void testCase035() {
String sql = "select last_row(*) from restful_test.weather"; String sql = "select last_row(*) from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase036() { public void testCase036() {
String sql = "select ts, ts as primary_key from restful_test.weather"; String sql = "select ts, ts as primary_key from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase037() { public void testCase037() {
String sql = "select database()"; String sql = "select database()";
execute("use restful_test"); SQLExecutor.execute(connection, "use restful_test");
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase038() { public void testCase038() {
String sql = "select client_version()"; String sql = "select client_version()";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase039() { public void testCase039() {
String sql = "select server_status()"; String sql = "select server_status()";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase040() { public void testCase040() {
String sql = "select server_status() as status"; String sql = "select server_status() as status";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase041() { public void testCase041() {
String sql = "select tbname, location from restful_test.weather"; String sql = "select tbname, location from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase042() { public void testCase042() {
String sql = "select count(tbname) from restful_test.weather"; String sql = "select count(tbname) from restful_test.weather";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase043() { public void testCase043() {
String sql = "select * from restful_test.weather where ts < now - 1h"; String sql = "select * from restful_test.weather where ts < now - 1h";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase044() { public void testCase044() {
String sql = "select * from restful_test.weather where ts < now - 1h and location like '%'"; String sql = "select * from restful_test.weather where ts < now - 1h and location like '%'";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase045() { public void testCase045() {
String sql = "select * from restful_test.weather where ts < now - 1h order by ts"; String sql = "select * from restful_test.weather where ts < now - 1h order by ts";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase046() { public void testCase046() {
String sql = "select last(*) from restful_test.weather where ts < now - 1h group by tbname order by tbname"; String sql = "select last(*) from restful_test.weather where ts < now - 1h group by tbname order by tbname";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase047() { public void testCase047() {
String sql = "select * from restful_test.weather limit 2"; String sql = "select * from restful_test.weather limit 2";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase048() { public void testCase048() {
String sql = "select * from restful_test.weather limit 2 offset 5"; String sql = "select * from restful_test.weather limit 2 offset 5";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase049() { public void testCase049() {
String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts "; String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts ";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase050() { public void testCase050() {
String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts and t1.location = t3.location"; String sql = "select * from restful_test.t1, restful_test.t3 where t1.ts = t3.ts and t1.location = t3.location";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
} }
@Test @Test
public void testCase051() { public void testCase051() {
String sql = "select * from restful_test.t1 tt, restful_test.t3 yy where tt.ts = yy.ts"; String sql = "select * from restful_test.t1 tt, restful_test.t3 yy where tt.ts = yy.ts";
executeQuery(sql); SQLExecutor.executeQuery(connection, sql);
}
private void executeUpdate(String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
int affectedRows = statement.executeUpdate(sql);
long end = System.currentTimeMillis();
System.out.println("[ affected rows : " + affectedRows + " ] time cost: " + (end - start) + " ms, execute statement ====> " + sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void executeWithResult(String sql) {
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
ResultSet resultSet = statement.getResultSet();
printResult(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void execute(String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
boolean execute = statement.execute(sql);
long end = System.currentTimeMillis();
printSql(sql, execute, (end - start));
} catch (SQLException e) {
System.out.println("ERROR execute SQL ===> " + sql);
e.printStackTrace();
}
}
private static void printSql(String sql, boolean succeed, long cost) {
System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql);
}
private void executeQuery(String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
ResultSet resultSet = statement.executeQuery(sql);
long end = System.currentTimeMillis();
printSql(sql, true, (end - start));
printResult(resultSet);
} catch (SQLException e) {
System.out.println("ERROR execute SQL ===> " + sql);
e.printStackTrace();
}
}
private static void printResult(ResultSet resultSet) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String columnLabel = metaData.getColumnLabel(i);
String value = resultSet.getString(i);
sb.append(columnLabel + ": " + value + "\t");
}
System.out.println(sb.toString());
}
} }
@BeforeClass @BeforeClass

View File

@ -0,0 +1,74 @@
package com.taosdata.jdbc.utils;
import java.sql.*;
public class SQLExecutor {
// insert, import
public static void executeUpdate(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
int affectedRows = statement.executeUpdate(sql);
long end = System.currentTimeMillis();
System.out.println("[ affected rows : " + affectedRows + " ] time cost: " + (end - start) + " ms, execute statement ====> " + sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// show databases, show tables, show stables
public static void executeWithResult(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
ResultSet resultSet = statement.getResultSet();
printResult(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
}
// use database, create database, create table, drop table...
public static void execute(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
boolean execute = statement.execute(sql);
long end = System.currentTimeMillis();
printSql(sql, execute, (end - start));
} catch (SQLException e) {
System.out.println("ERROR execute SQL ===> " + sql);
e.printStackTrace();
}
}
// select
public static void executeQuery(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) {
long start = System.currentTimeMillis();
ResultSet resultSet = statement.executeQuery(sql);
long end = System.currentTimeMillis();
printSql(sql, true, (end - start));
printResult(resultSet);
} catch (SQLException e) {
System.out.println("ERROR execute SQL ===> " + sql);
e.printStackTrace();
}
}
private static void printSql(String sql, boolean succeed, long cost) {
System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql);
}
private static void printResult(ResultSet resultSet) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String columnLabel = metaData.getColumnLabel(i);
String value = resultSet.getString(i);
sb.append(columnLabel + ": " + value + "\t");
}
System.out.println(sb.toString());
}
}
}

View File

@ -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"));
} }
} }

View File

@ -6,7 +6,6 @@ INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/client/inc)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/query/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/query/inc)
AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/src SRC) AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/src SRC)
IF (TD_LINUX)
ADD_LIBRARY(tcq ${SRC}) ADD_LIBRARY(tcq ${SRC})
IF (TD_SOMODE_STATIC) IF (TD_SOMODE_STATIC)
TARGET_LINK_LIBRARIES(tcq tutil common taos_static) TARGET_LINK_LIBRARIES(tcq tutil common taos_static)
@ -14,4 +13,3 @@ IF (TD_LINUX)
TARGET_LINK_LIBRARIES(tcq tutil common taos) TARGET_LINK_LIBRARIES(tcq tutil common taos)
ENDIF () ENDIF ()
ADD_SUBDIRECTORY(test) ADD_SUBDIRECTORY(test)
ENDIF ()

View File

@ -343,7 +343,7 @@ static void cqProcessStreamRes(void *param, TAOS_RES *tres, TAOS_ROW row) {
char buf[TSDB_MAX_NCHAR_LEN]; char buf[TSDB_MAX_NCHAR_LEN];
int32_t len = taos_fetch_lengths(tres)[i]; int32_t len = taos_fetch_lengths(tres)[i];
taosMbsToUcs4(val, len, buf, sizeof(buf), &len); taosMbsToUcs4(val, len, buf, sizeof(buf), &len);
memcpy(val + sizeof(VarDataLenT), buf, len); memcpy((char *)val + sizeof(VarDataLenT), buf, len);
varDataLen(val) = len; varDataLen(val) = len;
} }
tdAppendColVal(trow, val, c->type, c->bytes, c->offset); tdAppendColVal(trow, val, c->type, c->bytes, c->offset);

View File

@ -3,4 +3,4 @@ PROJECT(TDengine)
LIST(APPEND CQTEST_SRC ./cqtest.c) LIST(APPEND CQTEST_SRC ./cqtest.c)
ADD_EXECUTABLE(cqtest ${CQTEST_SRC}) ADD_EXECUTABLE(cqtest ${CQTEST_SRC})
TARGET_LINK_LIBRARIES(cqtest tcq) TARGET_LINK_LIBRARIES(cqtest tcq taos_static)

View File

@ -10,7 +10,6 @@ INCLUDE_DIRECTORIES(${TD_ENTERPRISE_DIR}/src/inc)
INCLUDE_DIRECTORIES(inc) INCLUDE_DIRECTORIES(inc)
AUX_SOURCE_DIRECTORY(src SRC) AUX_SOURCE_DIRECTORY(src SRC)
IF (TD_LINUX)
ADD_EXECUTABLE(taosd ${SRC}) ADD_EXECUTABLE(taosd ${SRC})
TARGET_LINK_LIBRARIES(taosd mnode monitor http tsdb twal vnode cJson lz4 balance sync) TARGET_LINK_LIBRARIES(taosd mnode monitor http tsdb twal vnode cJson lz4 balance sync)
@ -28,7 +27,7 @@ IF (TD_LINUX)
TARGET_LINK_LIBRARIES(taosd grant) TARGET_LINK_LIBRARIES(taosd grant)
ENDIF () ENDIF ()
IF (TD_MQTT) IF ((TD_LINUX OR TD_WINDOWS) AND TD_MQTT)
TARGET_LINK_LIBRARIES(taosd mqtt) TARGET_LINK_LIBRARIES(taosd mqtt)
ENDIF () ENDIF ()
@ -46,4 +45,3 @@ IF (TD_LINUX)
COMMAND ${CMAKE_COMMAND} -E echo charset UTF-8 >> ${TD_TESTS_OUTPUT_DIR}/cfg/taos.cfg COMMAND ${CMAKE_COMMAND} -E echo charset UTF-8 >> ${TD_TESTS_OUTPUT_DIR}/cfg/taos.cfg
COMMENT "prepare taosd environment") COMMENT "prepare taosd environment")
ADD_CUSTOM_TARGET(${PREPARE_ENV_TARGET} ALL WORKING_DIRECTORY ${TD_EXECUTABLE_OUTPUT_PATH} DEPENDS ${PREPARE_ENV_CMD}) ADD_CUSTOM_TARGET(${PREPARE_ENV_TARGET} ALL WORKING_DIRECTORY ${TD_EXECUTABLE_OUTPUT_PATH} DEPENDS ${PREPARE_ENV_CMD})
ENDIF ()

View File

@ -97,7 +97,7 @@ static int32_t dnodeReadCfg() {
goto PARSE_CFG_OVER; goto PARSE_CFG_OVER;
} }
len = fread(content, 1, maxLen, fp); len = (int32_t)fread(content, 1, maxLen, fp);
if (len <= 0) { if (len <= 0) {
dError("failed to read %s, content is null", file); dError("failed to read %s, content is null", file);
goto PARSE_CFG_OVER; goto PARSE_CFG_OVER;
@ -115,7 +115,7 @@ static int32_t dnodeReadCfg() {
dError("failed to read %s, dnodeId not found", file); dError("failed to read %s, dnodeId not found", file);
goto PARSE_CFG_OVER; goto PARSE_CFG_OVER;
} }
cfg.dnodeId = dnodeId->valueint; cfg.dnodeId = (int32_t)dnodeId->valueint;
cJSON *clusterId = cJSON_GetObjectItem(root, "clusterId"); cJSON *clusterId = cJSON_GetObjectItem(root, "clusterId");
if (!clusterId || clusterId->type != cJSON_String) { if (!clusterId || clusterId->type != cJSON_String) {

View File

@ -29,8 +29,8 @@ typedef struct {
static SCheckItem tsCheckItem[TSDB_CHECK_ITEM_MAX] = {{0}}; static SCheckItem tsCheckItem[TSDB_CHECK_ITEM_MAX] = {{0}};
int64_t tsMinFreeMemSizeForStart = 0; int64_t tsMinFreeMemSizeForStart = 0;
static int bindTcpPort(int port) { static int32_t bindTcpPort(int16_t port) {
int serverSocket; SOCKET serverSocket;
struct sockaddr_in server_addr; struct sockaddr_in server_addr;
if ((serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { if ((serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
@ -45,22 +45,22 @@ static int bindTcpPort(int port) {
if (bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { if (bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
dError("port:%d tcp bind() fail: %s", port, strerror(errno)); dError("port:%d tcp bind() fail: %s", port, strerror(errno));
close(serverSocket); taosCloseSocket(serverSocket);
return -1; return -1;
} }
if (listen(serverSocket, 5) < 0) { if (listen(serverSocket, 5) < 0) {
dError("port:%d listen() fail: %s", port, strerror(errno)); dError("port:%d listen() fail: %s", port, strerror(errno));
close(serverSocket); taosCloseSocket(serverSocket);
return -1; return -1;
} }
close(serverSocket); taosCloseSocket(serverSocket);
return 0; return 0;
} }
static int bindUdpPort(int port) { static int32_t bindUdpPort(int16_t port) {
int serverSocket; SOCKET serverSocket;
struct sockaddr_in server_addr; struct sockaddr_in server_addr;
if ((serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { if ((serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
@ -75,19 +75,19 @@ static int bindUdpPort(int port) {
if (bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { if (bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
dError("port:%d udp bind() fail: %s", port, strerror(errno)); dError("port:%d udp bind() fail: %s", port, strerror(errno));
close(serverSocket); taosCloseSocket(serverSocket);
return -1; return -1;
} }
close(serverSocket); taosCloseSocket(serverSocket);
return 0; return 0;
} }
static int dnodeCheckNetwork() { static int32_t dnodeCheckNetwork() {
int ret; int32_t ret;
int startPort = tsServerPort; int16_t startPort = tsServerPort;
for (int port = startPort; port < startPort + 12; port++) { for (int16_t port = startPort; port < startPort + 12; port++) {
ret = bindTcpPort(port); ret = bindTcpPort(port);
if (0 != ret) { if (0 != ret) {
dError("failed to tcp bind port %d, quit", port); dError("failed to tcp bind port %d, quit", port);
@ -103,7 +103,7 @@ static int dnodeCheckNetwork() {
return 0; return 0;
} }
static int dnodeCheckMem() { static int32_t dnodeCheckMem() {
float memoryUsedMB; float memoryUsedMB;
float memoryAvailMB; float memoryAvailMB;
if (true != taosGetSysMemory(&memoryUsedMB)) { if (true != taosGetSysMemory(&memoryUsedMB)) {
@ -121,12 +121,12 @@ static int dnodeCheckMem() {
return 0; return 0;
} }
static int dnodeCheckCpu() { static int32_t dnodeCheckCpu() {
// TODO: // TODO:
return 0; return 0;
} }
static int dnodeCheckDisk() { static int32_t dnodeCheckDisk() {
taosGetDisk(); taosGetDisk();
if (tsAvailDataDirGB < tsMinimalDataDirGB) { if (tsAvailDataDirGB < tsMinimalDataDirGB) {
@ -147,24 +147,24 @@ static int dnodeCheckDisk() {
return 0; return 0;
} }
static int dnodeCheckOs() { static int32_t dnodeCheckOs() {
// TODO: // TODO:
return 0; return 0;
} }
static int dnodeCheckAccess() { static int32_t dnodeCheckAccess() {
// TODO: // TODO:
return 0; return 0;
} }
static int dnodeCheckVersion() { static int32_t dnodeCheckVersion() {
// TODO: // TODO:
return 0; return 0;
} }
static int dnodeCheckDatafile() { static int32_t dnodeCheckDatafile() {
// TODO: // TODO:
return 0; return 0;

View File

@ -152,7 +152,7 @@ static int32_t dnodeReadEps() {
goto PRASE_EPS_OVER; goto PRASE_EPS_OVER;
} }
len = fread(content, 1, maxLen, fp); len = (int32_t)fread(content, 1, maxLen, fp);
if (len <= 0) { if (len <= 0) {
dError("failed to read %s, content is null", file); dError("failed to read %s, content is null", file);
goto PRASE_EPS_OVER; goto PRASE_EPS_OVER;
@ -199,7 +199,7 @@ static int32_t dnodeReadEps() {
dError("failed to read %s, dnodeId not found", file); dError("failed to read %s, dnodeId not found", file);
goto PRASE_EPS_OVER; goto PRASE_EPS_OVER;
} }
ep->dnodeId = dnodeId->valueint; ep->dnodeId = (int32_t)dnodeId->valueint;
cJSON *dnodeFqdn = cJSON_GetObjectItem(dnodeInfo, "dnodeFqdn"); cJSON *dnodeFqdn = cJSON_GetObjectItem(dnodeInfo, "dnodeFqdn");
if (!dnodeFqdn || dnodeFqdn->type != cJSON_String || dnodeFqdn->valuestring == NULL) { if (!dnodeFqdn || dnodeFqdn->type != cJSON_String || dnodeFqdn->valuestring == NULL) {

View File

@ -80,7 +80,7 @@ void dnodeUpdateEpSetForPeer(SRpcEpSet *ep) {
pthread_mutex_lock(&tsMInfosMutex); pthread_mutex_lock(&tsMInfosMutex);
dInfo("minfos is changed, numOfEps:%d inUse:%d", ep->numOfEps, ep->inUse); dInfo("minfos is changed, numOfEps:%d inUse:%d", ep->numOfEps, ep->inUse);
for (int i = 0; i < ep->numOfEps; ++i) { for (int32_t i = 0; i < ep->numOfEps; ++i) {
ep->port[i] -= TSDB_PORT_DNODEDNODE; ep->port[i] -= TSDB_PORT_DNODEDNODE;
dInfo("minfo:%d %s:%u", i, ep->fqdn[i], ep->port[i]); dInfo("minfo:%d %s:%u", i, ep->fqdn[i], ep->port[i]);
} }
@ -108,7 +108,7 @@ void dnodeGetMInfos(SMInfos *pMinfos) {
void dnodeGetEpSetForPeer(SRpcEpSet *epSet) { void dnodeGetEpSetForPeer(SRpcEpSet *epSet) {
pthread_mutex_lock(&tsMInfosMutex); pthread_mutex_lock(&tsMInfosMutex);
*epSet = tsMEpSet; *epSet = tsMEpSet;
for (int i = 0; i < epSet->numOfEps; ++i) { for (int32_t i = 0; i < epSet->numOfEps; ++i) {
epSet->port[i] += TSDB_PORT_DNODEDNODE; epSet->port[i] += TSDB_PORT_DNODEDNODE;
} }
pthread_mutex_unlock(&tsMInfosMutex); pthread_mutex_unlock(&tsMInfosMutex);
@ -171,7 +171,7 @@ static int32_t dnodeReadMInfos() {
goto PARSE_MINFOS_OVER; goto PARSE_MINFOS_OVER;
} }
len = fread(content, 1, maxLen, fp); len = (int32_t)fread(content, 1, maxLen, fp);
if (len <= 0) { if (len <= 0) {
dError("failed to read %s, content is null", file); dError("failed to read %s, content is null", file);
goto PARSE_MINFOS_OVER; goto PARSE_MINFOS_OVER;
@ -189,14 +189,14 @@ static int32_t dnodeReadMInfos() {
dError("failed to read mnodeEpSet.json, inUse not found"); dError("failed to read mnodeEpSet.json, inUse not found");
goto PARSE_MINFOS_OVER; goto PARSE_MINFOS_OVER;
} }
tsMInfos.inUse = inUse->valueint; tsMInfos.inUse = (int8_t)inUse->valueint;
cJSON *nodeNum = cJSON_GetObjectItem(root, "nodeNum"); cJSON *nodeNum = cJSON_GetObjectItem(root, "nodeNum");
if (!nodeNum || nodeNum->type != cJSON_Number) { if (!nodeNum || nodeNum->type != cJSON_Number) {
dError("failed to read mnodeEpSet.json, nodeNum not found"); dError("failed to read mnodeEpSet.json, nodeNum not found");
goto PARSE_MINFOS_OVER; goto PARSE_MINFOS_OVER;
} }
minfos.mnodeNum = nodeNum->valueint; minfos.mnodeNum = (int8_t)nodeNum->valueint;
cJSON *nodeInfos = cJSON_GetObjectItem(root, "nodeInfos"); cJSON *nodeInfos = cJSON_GetObjectItem(root, "nodeInfos");
if (!nodeInfos || nodeInfos->type != cJSON_Array) { if (!nodeInfos || nodeInfos->type != cJSON_Array) {
@ -204,13 +204,13 @@ static int32_t dnodeReadMInfos() {
goto PARSE_MINFOS_OVER; goto PARSE_MINFOS_OVER;
} }
int size = cJSON_GetArraySize(nodeInfos); int32_t size = cJSON_GetArraySize(nodeInfos);
if (size != minfos.mnodeNum) { if (size != minfos.mnodeNum) {
dError("failed to read mnodeEpSet.json, nodeInfos size not matched"); dError("failed to read mnodeEpSet.json, nodeInfos size not matched");
goto PARSE_MINFOS_OVER; goto PARSE_MINFOS_OVER;
} }
for (int i = 0; i < size; ++i) { for (int32_t i = 0; i < size; ++i) {
cJSON *nodeInfo = cJSON_GetArrayItem(nodeInfos, i); cJSON *nodeInfo = cJSON_GetArrayItem(nodeInfos, i);
if (nodeInfo == NULL) continue; if (nodeInfo == NULL) continue;
@ -227,7 +227,7 @@ static int32_t dnodeReadMInfos() {
} }
SMInfo *pMinfo = &minfos.mnodeInfos[i]; SMInfo *pMinfo = &minfos.mnodeInfos[i];
pMinfo->mnodeId = nodeId->valueint; pMinfo->mnodeId = (int32_t)nodeId->valueint;
tstrncpy(pMinfo->mnodeEp, nodeEp->valuestring, TSDB_EP_LEN); tstrncpy(pMinfo->mnodeEp, nodeEp->valuestring, TSDB_EP_LEN);
bool changed = dnodeCheckEpChanged(pMinfo->mnodeId, pMinfo->mnodeEp); bool changed = dnodeCheckEpChanged(pMinfo->mnodeId, pMinfo->mnodeEp);

View File

@ -60,7 +60,7 @@ int32_t dnodeInitMPeer() {
void dnodeCleanupMPeer() { void dnodeCleanupMPeer() {
for (int32_t i = 0; i < tsMPeerWP.maxNum; ++i) { for (int32_t i = 0; i < tsMPeerWP.maxNum; ++i) {
SMPeerWorker *pWorker = tsMPeerWP.worker + i; SMPeerWorker *pWorker = tsMPeerWP.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
taosQsetThreadResume(tsMPeerQset); taosQsetThreadResume(tsMPeerQset);
} }
dDebug("dnode mpeer worker:%d is closed", i); dDebug("dnode mpeer worker:%d is closed", i);
@ -69,7 +69,7 @@ void dnodeCleanupMPeer() {
for (int32_t i = 0; i < tsMPeerWP.maxNum; ++i) { for (int32_t i = 0; i < tsMPeerWP.maxNum; ++i) {
SMPeerWorker *pWorker = tsMPeerWP.worker + i; SMPeerWorker *pWorker = tsMPeerWP.worker + i;
dDebug("dnode mpeer worker:%d start to join", i); dDebug("dnode mpeer worker:%d start to join", i);
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
pthread_join(pWorker->thread, NULL); pthread_join(pWorker->thread, NULL);
} }
dDebug("dnode mpeer worker:%d join success", i); dDebug("dnode mpeer worker:%d join success", i);

View File

@ -40,7 +40,7 @@ static void *dnodeProcessMReadQueue(void *param);
int32_t dnodeInitMRead() { int32_t dnodeInitMRead() {
tsMReadQset = taosOpenQset(); tsMReadQset = taosOpenQset();
tsMReadWP.maxNum = tsNumOfCores * tsNumOfThreadsPerCore / 2; tsMReadWP.maxNum = (int32_t)(tsNumOfCores * tsNumOfThreadsPerCore / 2);
tsMReadWP.maxNum = MAX(2, tsMReadWP.maxNum); tsMReadWP.maxNum = MAX(2, tsMReadWP.maxNum);
tsMReadWP.maxNum = MIN(4, tsMReadWP.maxNum); tsMReadWP.maxNum = MIN(4, tsMReadWP.maxNum);
tsMReadWP.curNum = 0; tsMReadWP.curNum = 0;
@ -60,7 +60,7 @@ int32_t dnodeInitMRead() {
void dnodeCleanupMRead() { void dnodeCleanupMRead() {
for (int32_t i = 0; i < tsMReadWP.maxNum; ++i) { for (int32_t i = 0; i < tsMReadWP.maxNum; ++i) {
SMReadWorker *pWorker = tsMReadWP.worker + i; SMReadWorker *pWorker = tsMReadWP.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
taosQsetThreadResume(tsMReadQset); taosQsetThreadResume(tsMReadQset);
} }
dDebug("dnode mread worker:%d is closed", i); dDebug("dnode mread worker:%d is closed", i);
@ -69,7 +69,7 @@ void dnodeCleanupMRead() {
for (int32_t i = 0; i < tsMReadWP.maxNum; ++i) { for (int32_t i = 0; i < tsMReadWP.maxNum; ++i) {
SMReadWorker *pWorker = tsMReadWP.worker + i; SMReadWorker *pWorker = tsMReadWP.worker + i;
dDebug("dnode mread worker:%d start to join", i); dDebug("dnode mread worker:%d start to join", i);
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
pthread_join(pWorker->thread, NULL); pthread_join(pWorker->thread, NULL);
} }
dDebug("dnode mread worker:%d start to join", i); dDebug("dnode mread worker:%d start to join", i);

View File

@ -60,7 +60,7 @@ int32_t dnodeInitMWrite() {
void dnodeCleanupMWrite() { void dnodeCleanupMWrite() {
for (int32_t i = 0; i < tsMWriteWP.maxNum; ++i) { for (int32_t i = 0; i < tsMWriteWP.maxNum; ++i) {
SMWriteWorker *pWorker = tsMWriteWP.worker + i; SMWriteWorker *pWorker = tsMWriteWP.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
taosQsetThreadResume(tsMWriteQset); taosQsetThreadResume(tsMWriteQset);
} }
dDebug("dnode mwrite worker:%d is closed", i); dDebug("dnode mwrite worker:%d is closed", i);
@ -69,7 +69,7 @@ void dnodeCleanupMWrite() {
for (int32_t i = 0; i < tsMWriteWP.maxNum; ++i) { for (int32_t i = 0; i < tsMWriteWP.maxNum; ++i) {
SMWriteWorker *pWorker = tsMWriteWP.worker + i; SMWriteWorker *pWorker = tsMWriteWP.worker + i;
dDebug("dnode mwrite worker:%d start to join", i); dDebug("dnode mwrite worker:%d start to join", i);
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
pthread_join(pWorker->thread, NULL); pthread_join(pWorker->thread, NULL);
} }
dDebug("dnode mwrite worker:%d join success", i); dDebug("dnode mwrite worker:%d join success", i);

View File

@ -90,7 +90,10 @@ static void dnodeProcessReqMsgFromDnode(SRpcMsg *pMsg, SRpcEpSet *pEpSet) {
}; };
if (pMsg->pCont == NULL) return; if (pMsg->pCont == NULL) return;
if (pMsg->msgType == TSDB_MSG_TYPE_NETWORK_TEST) return dnodeSendStartupStep(pMsg); if (pMsg->msgType == TSDB_MSG_TYPE_NETWORK_TEST) {
dnodeSendStartupStep(pMsg);
return;
}
if (dnodeGetRunStatus() != TSDB_RUN_STATUS_RUNING) { if (dnodeGetRunStatus() != TSDB_RUN_STATUS_RUNING) {
rspMsg.code = TSDB_CODE_APP_NOT_READY; rspMsg.code = TSDB_CODE_APP_NOT_READY;

View File

@ -70,7 +70,7 @@ int32_t dnodeInitShell() {
dnodeProcessShellMsgFp[TSDB_MSG_TYPE_NETWORK_TEST] = dnodeSendStartupStep; dnodeProcessShellMsgFp[TSDB_MSG_TYPE_NETWORK_TEST] = dnodeSendStartupStep;
int32_t numOfThreads = (tsNumOfCores * tsNumOfThreadsPerCore) / 2.0; int32_t numOfThreads = (int32_t)((tsNumOfCores * tsNumOfThreadsPerCore) / 2.0);
if (numOfThreads < 1) { if (numOfThreads < 1) {
numOfThreads = 1; numOfThreads = 1;
} }

View File

@ -70,5 +70,5 @@ int32_t dnodeStepInit(SStep *pSteps, int32_t stepSize) {
} }
void dnodeStepCleanup(SStep *pSteps, int32_t stepSize) { void dnodeStepCleanup(SStep *pSteps, int32_t stepSize) {
return taosStepCleanupImp(pSteps, stepSize - 1); taosStepCleanupImp(pSteps, stepSize - 1);
} }

View File

@ -19,8 +19,10 @@
#include "tconfig.h" #include "tconfig.h"
#include "dnodeMain.h" #include "dnodeMain.h"
static void signal_handler(int32_t signum, siginfo_t *sigInfo, void *context);
static tsem_t exitSem; static tsem_t exitSem;
static void siguser1Handler(int32_t signum, void *sigInfo, void *context);
static void siguser2Handler(int32_t signum, void *sigInfo, void *context);
static void sigintHandler(int32_t signum, void *sigInfo, void *context);
int32_t main(int32_t argc, char *argv[]) { int32_t main(int32_t argc, char *argv[]) {
int dump_config = 0; int dump_config = 0;
@ -112,14 +114,13 @@ int32_t main(int32_t argc, char *argv[]) {
} }
/* Set termination handler. */ /* Set termination handler. */
struct sigaction act = {{0}}; taosSetSignal(SIGUSR1, siguser1Handler);
act.sa_flags = SA_SIGINFO; taosSetSignal(SIGUSR2, siguser2Handler);
act.sa_sigaction = signal_handler; taosSetSignal(SIGTERM, sigintHandler);
sigaction(SIGTERM, &act, NULL); taosSetSignal(SIGHUP, sigintHandler);
sigaction(SIGHUP, &act, NULL); taosSetSignal(SIGINT, sigintHandler);
sigaction(SIGINT, &act, NULL); taosSetSignal(SIGABRT, sigintHandler);
sigaction(SIGUSR1, &act, NULL); taosSetSignal(SIGBREAK, sigintHandler);
sigaction(SIGUSR2, &act, NULL);
// Open /var/log/syslog file to record information. // Open /var/log/syslog file to record information.
openlog("TDengine:", LOG_PID | LOG_CONS | LOG_NDELAY, LOG_LOCAL1); openlog("TDengine:", LOG_PID | LOG_CONS | LOG_NDELAY, LOG_LOCAL1);
@ -144,33 +145,40 @@ int32_t main(int32_t argc, char *argv[]) {
syslog(LOG_INFO, "Shut down TDengine service successfully"); syslog(LOG_INFO, "Shut down TDengine service successfully");
dInfo("TDengine is shut down!"); dInfo("TDengine is shut down!");
closelog(); closelog();
#ifdef WINDOWS
tsem_post(&exitSem);
#endif
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
static void signal_handler(int32_t signum, siginfo_t *sigInfo, void *context) { static void siguser1Handler(int32_t signum, void *sigInfo, void *context) { taosCfgDynamicOptions("debugFlag 143"); }
if (signum == SIGUSR1) {
taosCfgDynamicOptions("debugFlag 143"); static void siguser2Handler(int32_t signum, void *sigInfo, void *context) { taosCfgDynamicOptions("resetlog"); }
return;
} static void sigintHandler(int32_t signum, void *sigInfo, void *context) {
if (signum == SIGUSR2) { // protect the application from receive another signal
taosCfgDynamicOptions("resetlog"); taosIgnSignal(SIGUSR1);
return; taosIgnSignal(SIGUSR2);
} taosIgnSignal(SIGTERM);
taosIgnSignal(SIGHUP);
taosIgnSignal(SIGINT);
taosIgnSignal(SIGABRT);
taosIgnSignal(SIGBREAK);
// clean the system.
dInfo("shut down signal is %d", signum);
#ifndef WINDOWS
dInfo("sender PID:%d cmdline:%s", ((siginfo_t *)sigInfo)->si_pid, taosGetCmdlineByPID(((siginfo_t *)sigInfo)->si_pid));
#endif
syslog(LOG_INFO, "Shut down signal is %d", signum); syslog(LOG_INFO, "Shut down signal is %d", signum);
syslog(LOG_INFO, "Shutting down TDengine service..."); syslog(LOG_INFO, "Shutting down TDengine service...");
// clean the system.
dInfo("shut down signal is %d, sender PID:%d cmdline:%s", signum, sigInfo->si_pid, taosGetCmdlineByPID(sigInfo->si_pid));
// protect the application from receive another signal
struct sigaction act = {{0}};
act.sa_handler = SIG_IGN;
sigaction(SIGTERM, &act, NULL);
sigaction(SIGHUP, &act, NULL);
sigaction(SIGINT, &act, NULL);
sigaction(SIGUSR1, &act, NULL);
sigaction(SIGUSR2, &act, NULL);
// inform main thread to exit // inform main thread to exit
tsem_post(&exitSem); tsem_post(&exitSem);
#ifdef WINDOWS
tsem_wait(&exitSem);
#endif
} }

View File

@ -31,7 +31,11 @@
#include "mnodeAcct.h" #include "mnodeAcct.h"
#include "dnodeTelemetry.h" #include "dnodeTelemetry.h"
static tsem_t tsExitSem; // sem_timedwait is NOT implemented on MacOSX
// thus, we use pthread_mutex_t/pthread_cond_t to simulate
static pthread_mutex_t tsExitLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t tsExitCond = PTHREAD_COND_INITIALIZER;
static volatile int tsExit = 0;
static pthread_t tsTelemetryThread; static pthread_t tsTelemetryThread;
#define TELEMETRY_SERVER "telemetry.taosdata.com" #define TELEMETRY_SERVER "telemetry.taosdata.com"
@ -93,14 +97,14 @@ static void addStringField(SBufferWriter* bw, const char* k, const char* v) {
static void addCpuInfo(SBufferWriter* bw) { static void addCpuInfo(SBufferWriter* bw) {
char * line = NULL; char * line = NULL;
size_t size = 0; size_t size = 0;
int done = 0; int32_t done = 0;
FILE* fp = fopen("/proc/cpuinfo", "r"); FILE* fp = fopen("/proc/cpuinfo", "r");
if (fp == NULL) { if (fp == NULL) {
return; return;
} }
while (done != 3 && (size = getline(&line, &size, fp)) != -1) { while (done != 3 && (size = tgetline(&line, &size, fp)) != -1) {
line[size - 1] = '\0'; line[size - 1] = '\0';
if (((done&1) == 0) && strncmp(line, "model name", 10) == 0) { if (((done&1) == 0) && strncmp(line, "model name", 10) == 0) {
const char* v = strchr(line, ':') + 2; const char* v = strchr(line, ':') + 2;
@ -129,7 +133,7 @@ static void addOsInfo(SBufferWriter* bw) {
return; return;
} }
while ((size = getline(&line, &size, fp)) != -1) { while ((size = tgetline(&line, &size, fp)) != -1) {
line[size - 1] = '\0'; line[size - 1] = '\0';
if (strncmp(line, "PRETTY_NAME", 11) == 0) { if (strncmp(line, "PRETTY_NAME", 11) == 0) {
const char* p = strchr(line, '=') + 1; const char* p = strchr(line, '=') + 1;
@ -155,7 +159,7 @@ static void addMemoryInfo(SBufferWriter* bw) {
return; return;
} }
while ((size = getline(&line, &size, fp)) != -1) { while ((size = tgetline(&line, &size, fp)) != -1) {
line[size - 1] = '\0'; line[size - 1] = '\0';
if (strncmp(line, "MemTotal", 8) == 0) { if (strncmp(line, "MemTotal", 8) == 0) {
const char* p = strchr(line, ':') + 1; const char* p = strchr(line, ':') + 1;
@ -200,7 +204,7 @@ static void sendTelemetryReport() {
dTrace("failed to get IP address of " TELEMETRY_SERVER ", reason:%s", strerror(errno)); dTrace("failed to get IP address of " TELEMETRY_SERVER ", reason:%s", strerror(errno));
return; return;
} }
int fd = taosOpenTcpClientSocket(ip, TELEMETRY_PORT, 0); SOCKET fd = taosOpenTcpClientSocket(ip, TELEMETRY_PORT, 0);
if (fd < 0) { if (fd < 0) {
dTrace("failed to create socket for telemetry, reason:%s", strerror(errno)); dTrace("failed to create socket for telemetry, reason:%s", strerror(errno));
return; return;
@ -222,10 +226,10 @@ static void sendTelemetryReport() {
"Content-Type: application/json\n" "Content-Type: application/json\n"
"Content-Length: "; "Content-Length: ";
taosWriteSocket(fd, header, strlen(header)); taosWriteSocket(fd, header, (int32_t)strlen(header));
int contLen = tbufTell(&bw) - 1; int32_t contLen = (int32_t)(tbufTell(&bw) - 1);
sprintf(buf, "%d\n\n", contLen); sprintf(buf, "%d\n\n", contLen);
taosWriteSocket(fd, buf, strlen(buf)); taosWriteSocket(fd, buf, (int32_t)strlen(buf));
taosWriteSocket(fd, tbufGetData(&bw, false), contLen); taosWriteSocket(fd, tbufGetData(&bw, false), contLen);
tbufCloseWriter(&bw); tbufCloseWriter(&bw);
@ -241,12 +245,14 @@ static void* telemetryThread(void* param) {
clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_REALTIME, &end);
end.tv_sec += 300; // wait 5 minutes before send first report end.tv_sec += 300; // wait 5 minutes before send first report
while (1) { while (!tsExit) {
if (sem_timedwait(&tsExitSem, &end) == 0) { int r = 0;
break; struct timespec ts = end;
} else if (errno != ETIMEDOUT) { pthread_mutex_lock(&tsExitLock);
continue; r = pthread_cond_timedwait(&tsExitCond, &tsExitLock, &ts);
} pthread_mutex_unlock(&tsExitLock);
if (r==0) break;
if (r!=ETIMEDOUT) continue;
if (sdbIsMaster()) { if (sdbIsMaster()) {
sendTelemetryReport(); sendTelemetryReport();
@ -258,7 +264,7 @@ static void* telemetryThread(void* param) {
} }
static void dnodeGetEmail(char* filepath) { static void dnodeGetEmail(char* filepath) {
int fd = open(filepath, O_RDONLY); int32_t fd = open(filepath, O_RDONLY);
if (fd < 0) { if (fd < 0) {
return; return;
} }
@ -267,10 +273,9 @@ static void dnodeGetEmail(char* filepath) {
dError("failed to read %d bytes from file %s since %s", TSDB_FQDN_LEN, filepath, strerror(errno)); dError("failed to read %d bytes from file %s since %s", TSDB_FQDN_LEN, filepath, strerror(errno));
} }
close(fd); taosClose(fd);
} }
int32_t dnodeInitTelemetry() { int32_t dnodeInitTelemetry() {
if (!tsEnableTelemetryReporting) { if (!tsEnableTelemetryReporting) {
return 0; return 0;
@ -278,12 +283,6 @@ int32_t dnodeInitTelemetry() {
dnodeGetEmail("/usr/local/taos/email"); dnodeGetEmail("/usr/local/taos/email");
if (tsem_init(&tsExitSem, 0, 0) == -1) {
// just log the error, it is ok for telemetry to fail
dTrace("failed to create semaphore for telemetry, reason:%s", strerror(errno));
return 0;
}
pthread_attr_t attr; pthread_attr_t attr;
pthread_attr_init(&attr); pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
@ -303,9 +302,12 @@ void dnodeCleanupTelemetry() {
return; return;
} }
if (tsTelemetryThread) { if (taosCheckPthreadValid(tsTelemetryThread)) {
tsem_post(&tsExitSem); pthread_mutex_lock(&tsExitLock);
tsExit = 1;
pthread_cond_signal(&tsExitCond);
pthread_mutex_unlock(&tsExitLock);
pthread_join(tsTelemetryThread, NULL); pthread_join(tsTelemetryThread, NULL);
tsem_destroy(&tsExitSem);
} }
} }

View File

@ -52,14 +52,14 @@ int32_t dnodeInitVWrite() {
void dnodeCleanupVWrite() { void dnodeCleanupVWrite() {
for (int32_t i = 0; i < tsVWriteWP.max; ++i) { for (int32_t i = 0; i < tsVWriteWP.max; ++i) {
SVWriteWorker *pWorker = tsVWriteWP.worker + i; SVWriteWorker *pWorker = tsVWriteWP.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
taosQsetThreadResume(pWorker->qset); taosQsetThreadResume(pWorker->qset);
} }
} }
for (int32_t i = 0; i < tsVWriteWP.max; ++i) { for (int32_t i = 0; i < tsVWriteWP.max; ++i) {
SVWriteWorker *pWorker = tsVWriteWP.worker + i; SVWriteWorker *pWorker = tsVWriteWP.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
pthread_join(pWorker->thread, NULL); pthread_join(pWorker->thread, NULL);
taosFreeQall(pWorker->qall); taosFreeQall(pWorker->qall);
taosCloseQset(pWorker->qset); taosCloseQset(pWorker->qset);

View File

@ -157,7 +157,7 @@ int32_t dnodeInitVnodes() {
int32_t failedVnodes = 0; int32_t failedVnodes = 0;
for (int32_t t = 0; t < threadNum; ++t) { for (int32_t t = 0; t < threadNum; ++t) {
SOpenVnodeThread *pThread = &threads[t]; SOpenVnodeThread *pThread = &threads[t];
if (pThread->vnodeNum > 0 && pThread->thread) { if (pThread->vnodeNum > 0 && taosCheckPthreadValid(pThread->thread)) {
pthread_join(pThread->thread, NULL); pthread_join(pThread->thread, NULL);
} }
openVnodes += pThread->opened; openVnodes += pThread->opened;
@ -260,7 +260,7 @@ static void dnodeSendStatusMsg(void *handle, void *tmrId) {
tstrncpy(pStatus->clusterCfg.timezone, tsTimezone, 64); tstrncpy(pStatus->clusterCfg.timezone, tsTimezone, 64);
pStatus->clusterCfg.checkTime = 0; pStatus->clusterCfg.checkTime = 0;
char timestr[32] = "1970-01-01 00:00:00.00"; char timestr[32] = "1970-01-01 00:00:00.00";
(void)taosParseTime(timestr, &pStatus->clusterCfg.checkTime, strlen(timestr), TSDB_TIME_PRECISION_MILLI, 0); (void)taosParseTime(timestr, &pStatus->clusterCfg.checkTime, (int32_t)strlen(timestr), TSDB_TIME_PRECISION_MILLI, 0);
tstrncpy(pStatus->clusterCfg.locale, tsLocale, TSDB_LOCALE_LEN); tstrncpy(pStatus->clusterCfg.locale, tsLocale, TSDB_LOCALE_LEN);
tstrncpy(pStatus->clusterCfg.charset, tsCharset, TSDB_LOCALE_LEN); tstrncpy(pStatus->clusterCfg.charset, tsCharset, TSDB_LOCALE_LEN);

View File

@ -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

View File

@ -256,6 +256,8 @@ TAOS_DEFINE_ERROR(TSDB_CODE_QRY_HAS_RSP, 0, 0x0708, "Query shou
TAOS_DEFINE_ERROR(TSDB_CODE_QRY_IN_EXEC, 0, 0x0709, "Multiple retrieval of this query") TAOS_DEFINE_ERROR(TSDB_CODE_QRY_IN_EXEC, 0, 0x0709, "Multiple retrieval of this query")
TAOS_DEFINE_ERROR(TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW, 0, 0x070A, "Too many time window in query") TAOS_DEFINE_ERROR(TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW, 0, 0x070A, "Too many time window in query")
TAOS_DEFINE_ERROR(TSDB_CODE_QRY_NOT_ENOUGH_BUFFER, 0, 0x070B, "Query buffer limit has reached") TAOS_DEFINE_ERROR(TSDB_CODE_QRY_NOT_ENOUGH_BUFFER, 0, 0x070B, "Query buffer limit has reached")
TAOS_DEFINE_ERROR(TSDB_CODE_QRY_INCONSISTAN, 0, 0x070C, "File inconsistance in replica")
// grant // grant
TAOS_DEFINE_ERROR(TSDB_CODE_GRANT_EXPIRED, 0, 0x0800, "License expired") TAOS_DEFINE_ERROR(TSDB_CODE_GRANT_EXPIRED, 0, 0x0800, "License expired")

View File

@ -37,7 +37,10 @@ ELSEIF (TD_DARWIN)
LIST(APPEND SRC ./src/shellCommand.c) LIST(APPEND SRC ./src/shellCommand.c)
LIST(APPEND SRC ./src/shellImport.c) LIST(APPEND SRC ./src/shellImport.c)
ADD_EXECUTABLE(shell ${SRC}) ADD_EXECUTABLE(shell ${SRC})
TARGET_LINK_LIBRARIES(shell taos_static) # linking with dylib
TARGET_LINK_LIBRARIES(shell taos)
# linking taos statically
# TARGET_LINK_LIBRARIES(shell taos_static)
SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME taos) SET_TARGET_PROPERTIES(shell PROPERTIES OUTPUT_NAME taos)
ENDIF () ENDIF ()

View File

@ -21,6 +21,8 @@
#include "shellCommand.h" #include "shellCommand.h"
#include "tkey.h" #include "tkey.h"
#include "tscLog.h"
#define OPT_ABORT 1 /* <20>Cabort */ #define OPT_ABORT 1 /* <20>Cabort */
int indicator = 1; int indicator = 1;
@ -348,6 +350,9 @@ void *shellLoopQuery(void *arg) {
reset_terminal_mode(); reset_terminal_mode();
} while (shellRunCommand(con, command) == 0); } while (shellRunCommand(con, command) == 0);
tfree(command);
exitShell();
pthread_cleanup_pop(1); pthread_cleanup_pop(1);
return NULL; return NULL;

View File

@ -47,7 +47,7 @@ static struct argp_option options[] = {
{"thread", 'T', "THREADNUM", 0, "Number of threads when using multi-thread to import data."}, {"thread", 'T', "THREADNUM", 0, "Number of threads when using multi-thread to import data."},
{"database", 'd', "DATABASE", 0, "Database to use when connecting to the server."}, {"database", 'd', "DATABASE", 0, "Database to use when connecting to the server."},
{"timezone", 't', "TIMEZONE", 0, "Time zone of the shell, default is local."}, {"timezone", 't', "TIMEZONE", 0, "Time zone of the shell, default is local."},
{"netrole", 'n', "NETROLE", 0, "Net role when network connectivity test, default is startup, options: client|server|rpc|startup."}, {"netrole", 'n', "NETROLE", 0, "Net role when network connectivity test, default is startup, options: client|server|rpc|startup|sync."},
{"pktlen", 'l', "PKTLEN", 0, "Packet length used for net test, default is 1000 bytes."}, {"pktlen", 'l', "PKTLEN", 0, "Packet length used for net test, default is 1000 bytes."},
{0}}; {0}};

View File

@ -21,7 +21,7 @@
pthread_t pid; pthread_t pid;
static tsem_t cancelSem; static tsem_t cancelSem;
void shellQueryInterruptHandler(int signum) { void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) {
tsem_post(&cancelSem); tsem_post(&cancelSem);
} }
@ -130,12 +130,10 @@ int main(int argc, char* argv[]) {
pthread_create(&spid, NULL, cancelHandler, NULL); pthread_create(&spid, NULL, cancelHandler, NULL);
/* Interrupt handler. */ /* Interrupt handler. */
struct sigaction act; taosSetSignal(SIGTERM, shellQueryInterruptHandler);
memset(&act, 0, sizeof(struct sigaction)); taosSetSignal(SIGINT, shellQueryInterruptHandler);
taosSetSignal(SIGHUP, shellQueryInterruptHandler);
act.sa_handler = shellQueryInterruptHandler; taosSetSignal(SIGABRT, shellQueryInterruptHandler);
sigaction(SIGTERM, &act, NULL);
sigaction(SIGINT, &act, NULL);
/* Get grant information */ /* Get grant information */
shellGetGrantInfo(con); shellGetGrantInfo(con);

View File

@ -19,6 +19,10 @@
extern char configDir[]; extern char configDir[];
void printVersion() {
printf("version: %s\n", version);
}
void printHelp() { void printHelp() {
char indent[10] = " "; char indent[10] = " ";
printf("taos shell is used to test the TDengine database\n"); printf("taos shell is used to test the TDengine database\n");
@ -48,9 +52,11 @@ void printHelp() {
printf("%s%s\n", indent, "-t"); printf("%s%s\n", indent, "-t");
printf("%s%s%s\n", indent, indent, "Time zone of the shell, default is local."); printf("%s%s%s\n", indent, indent, "Time zone of the shell, default is local.");
printf("%s%s\n", indent, "-n"); printf("%s%s\n", indent, "-n");
printf("%s%s%s\n", indent, indent, "Net role when network connectivity test, default is startup, options: client|server|rpc|startup."); printf("%s%s%s\n", indent, indent, "Net role when network connectivity test, default is startup, options: client|server|rpc|startup|sync.");
printf("%s%s\n", indent, "-l"); printf("%s%s\n", indent, "-l");
printf("%s%s%s\n", indent, indent, "Packet length used for net test, default is 1000 bytes."); printf("%s%s%s\n", indent, indent, "Packet length used for net test, default is 1000 bytes.");
printf("%s%s\n", indent, "-V");
printf("%s%s%s\n", indent, indent, "Print program version.");
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
@ -69,6 +75,9 @@ void shellParseArgument(int argc, char *argv[], SShellArguments *arguments) {
// for password // for password
else if (strcmp(argv[i], "-p") == 0) { else if (strcmp(argv[i], "-p") == 0) {
arguments->is_use_passwd = true; arguments->is_use_passwd = true;
if (i < argc - 1 && argv[i + 1][0] != '-') {
arguments->password = argv[++i];
}
} }
// for management port // for management port
else if (strcmp(argv[i], "-P") == 0) { else if (strcmp(argv[i], "-P") == 0) {
@ -145,7 +154,6 @@ void shellParseArgument(int argc, char *argv[], SShellArguments *arguments) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
// For time zone
else if (strcmp(argv[i], "-n") == 0) { else if (strcmp(argv[i], "-n") == 0) {
if (i < argc - 1) { if (i < argc - 1) {
arguments->netTestRole = argv[++i]; arguments->netTestRole = argv[++i];
@ -154,7 +162,6 @@ void shellParseArgument(int argc, char *argv[], SShellArguments *arguments) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
// For time zone
else if (strcmp(argv[i], "-l") == 0) { else if (strcmp(argv[i], "-l") == 0) {
if (i < argc - 1) { if (i < argc - 1) {
arguments->pktLen = atoi(argv[++i]); arguments->pktLen = atoi(argv[++i]);
@ -163,10 +170,14 @@ void shellParseArgument(int argc, char *argv[], SShellArguments *arguments) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
else if (strcmp(argv[i], "-V") == 0) {
printVersion();
exit(EXIT_SUCCESS);
}
// For temperory command TODO // For temperory command TODO
else if (strcmp(argv[i], "--help") == 0) { else if (strcmp(argv[i], "--help") == 0) {
printHelp(); printHelp();
exit(EXIT_FAILURE); exit(EXIT_SUCCESS);
} else { } else {
fprintf(stderr, "wrong options\n"); fprintf(stderr, "wrong options\n");
printHelp(); printHelp();

View File

@ -17,4 +17,13 @@ ELSEIF (TD_WINDOWS)
AUX_SOURCE_DIRECTORY(. SRC) AUX_SOURCE_DIRECTORY(. SRC)
ADD_EXECUTABLE(taosdemo ${SRC}) ADD_EXECUTABLE(taosdemo ${SRC})
TARGET_LINK_LIBRARIES(taosdemo taos_static) TARGET_LINK_LIBRARIES(taosdemo taos_static)
ELSEIF (TD_DARWIN)
AUX_SOURCE_DIRECTORY(. SRC)
ADD_EXECUTABLE(taosdemo ${SRC})
IF (TD_SOMODE_STATIC)
TARGET_LINK_LIBRARIES(taosdemo taos_static)
ELSE ()
TARGET_LINK_LIBRARIES(taosdemo taos)
ENDIF ()
ENDIF () ENDIF ()

View File

@ -23,3 +23,25 @@ IF (TD_LINUX)
TARGET_LINK_LIBRARIES(taosdemox taos cJson) TARGET_LINK_LIBRARIES(taosdemox taos cJson)
ENDIF () ENDIF ()
ENDIF () ENDIF ()
IF (TD_DARWIN)
# missing a few dependencies, such as <argp.h>
# AUX_SOURCE_DIRECTORY(. SRC)
# ADD_EXECUTABLE(taosdemox ${SRC})
#
# #find_program(HAVE_CURL NAMES curl)
# IF ((NOT TD_ARM_64) AND (NOT TD_ARM_32))
# ADD_DEFINITIONS(-DTD_LOWA_CURL)
# LINK_DIRECTORIES(${TD_COMMUNITY_DIR}/deps/libcurl/lib)
# ADD_LIBRARY(curl STATIC IMPORTED)
# SET_PROPERTY(TARGET curl PROPERTY IMPORTED_LOCATION ${TD_COMMUNITY_DIR}/deps/libcurl/lib/libcurl.a)
# TARGET_LINK_LIBRARIES(taosdemox curl)
# ENDIF ()
#
# IF (TD_SOMODE_STATIC)
# TARGET_LINK_LIBRARIES(taosdemox taos_static cJson)
# ELSE ()
# TARGET_LINK_LIBRARIES(taosdemox taos cJson)
# ENDIF ()
ENDIF ()

View File

@ -14,3 +14,13 @@ IF (TD_LINUX)
TARGET_LINK_LIBRARIES(taosdump taos) TARGET_LINK_LIBRARIES(taosdump taos)
ENDIF () ENDIF ()
ENDIF () ENDIF ()
IF (TD_DARWIN)
# missing <argp.h> for macosx
# ADD_EXECUTABLE(taosdump ${SRC})
# IF (TD_SOMODE_STATIC)
# TARGET_LINK_LIBRARIES(taosdump taos_static)
# ELSE ()
# TARGET_LINK_LIBRARIES(taosdump taos)
# ENDIF ()
ENDIF ()

View File

@ -1,7 +1,6 @@
CMAKE_MINIMUM_REQUIRED(VERSION 3.5) CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
PROJECT(TDengine) PROJECT(TDengine)
IF (TD_LINUX)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/query/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/query/inc)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/dnode/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/dnode/inc)
@ -9,4 +8,3 @@ IF (TD_LINUX)
AUX_SOURCE_DIRECTORY(src SRC) AUX_SOURCE_DIRECTORY(src SRC)
ADD_LIBRARY(mnode ${SRC}) ADD_LIBRARY(mnode ${SRC})
ENDIF ()

View File

@ -81,7 +81,7 @@ static int32_t mnodeAcctActionDecode(SSdbRow *pRow) {
} }
static int32_t mnodeAcctActionRestored() { static int32_t mnodeAcctActionRestored() {
int32_t numOfRows = sdbGetNumOfRows(tsAcctSdb); int64_t numOfRows = sdbGetNumOfRows(tsAcctSdb);
if (numOfRows <= 0 && dnodeIsFirstDeploy()) { if (numOfRows <= 0 && dnodeIsFirstDeploy()) {
mInfo("dnode first deploy, create root acct"); mInfo("dnode first deploy, create root acct");
int32_t code = mnodeCreateRootAcct(); int32_t code = mnodeCreateRootAcct();
@ -97,14 +97,14 @@ static int32_t mnodeAcctActionRestored() {
int32_t mnodeInitAccts() { int32_t mnodeInitAccts() {
SAcctObj tObj; SAcctObj tObj;
tsAcctUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj; tsAcctUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj);
SSdbTableDesc desc = { SSdbTableDesc desc = {
.id = SDB_TABLE_ACCOUNT, .id = SDB_TABLE_ACCOUNT,
.name = "accounts", .name = "accounts",
.hashSessions = TSDB_DEFAULT_ACCOUNTS_HASH_SIZE, .hashSessions = TSDB_DEFAULT_ACCOUNTS_HASH_SIZE,
.maxRowSize = tsAcctUpdateSize, .maxRowSize = tsAcctUpdateSize,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_STRING, .keyType = SDB_KEY_STRING,
.fpInsert = mnodeAcctActionInsert, .fpInsert = mnodeAcctActionInsert,
.fpDelete = mnodeAcctActionDelete, .fpDelete = mnodeAcctActionDelete,
@ -206,7 +206,7 @@ void mnodeDropUserFromAcct(SAcctObj *pAcct, SUserObj *pUser) {
} }
static int32_t mnodeCreateRootAcct() { static int32_t mnodeCreateRootAcct() {
int32_t numOfAccts = sdbGetNumOfRows(tsAcctSdb); int64_t numOfAccts = sdbGetNumOfRows(tsAcctSdb);
if (numOfAccts != 0) return TSDB_CODE_SUCCESS; if (numOfAccts != 0) return TSDB_CODE_SUCCESS;
SAcctObj *pAcct = malloc(sizeof(SAcctObj)); SAcctObj *pAcct = malloc(sizeof(SAcctObj));

View File

@ -68,7 +68,7 @@ static int32_t mnodeClusterActionDecode(SSdbRow *pRow) {
} }
static int32_t mnodeClusterActionRestored() { static int32_t mnodeClusterActionRestored() {
int32_t numOfRows = sdbGetNumOfRows(tsClusterSdb); int64_t numOfRows = sdbGetNumOfRows(tsClusterSdb);
if (numOfRows <= 0 && dnodeIsFirstDeploy()) { if (numOfRows <= 0 && dnodeIsFirstDeploy()) {
mInfo("dnode first deploy, create cluster"); mInfo("dnode first deploy, create cluster");
int32_t code = mnodeCreateCluster(); int32_t code = mnodeCreateCluster();
@ -84,14 +84,14 @@ static int32_t mnodeClusterActionRestored() {
int32_t mnodeInitCluster() { int32_t mnodeInitCluster() {
SClusterObj tObj; SClusterObj tObj;
tsClusterUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj; tsClusterUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj);
SSdbTableDesc desc = { SSdbTableDesc desc = {
.id = SDB_TABLE_CLUSTER, .id = SDB_TABLE_CLUSTER,
.name = "cluster", .name = "cluster",
.hashSessions = TSDB_DEFAULT_CLUSTER_HASH_SIZE, .hashSessions = TSDB_DEFAULT_CLUSTER_HASH_SIZE,
.maxRowSize = tsClusterUpdateSize, .maxRowSize = tsClusterUpdateSize,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_STRING, .keyType = SDB_KEY_STRING,
.fpInsert = mnodeClusterActionInsert, .fpInsert = mnodeClusterActionInsert,
.fpDelete = mnodeClusterActionDelete, .fpDelete = mnodeClusterActionDelete,
@ -139,7 +139,7 @@ void mnodeDecClusterRef(SClusterObj *pCluster) {
} }
static int32_t mnodeCreateCluster() { static int32_t mnodeCreateCluster() {
int32_t numOfClusters = sdbGetNumOfRows(tsClusterSdb); int64_t numOfClusters = sdbGetNumOfRows(tsClusterSdb);
if (numOfClusters != 0) return TSDB_CODE_SUCCESS; if (numOfClusters != 0) return TSDB_CODE_SUCCESS;
SClusterObj *pCluster = malloc(sizeof(SClusterObj)); SClusterObj *pCluster = malloc(sizeof(SClusterObj));
@ -226,7 +226,7 @@ static int32_t mnodeRetrieveClusters(SShowObj *pShow, char *data, int32_t rows,
cols++; cols++;
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
*(int32_t *) pWrite = pCluster->createdTime; *(int64_t *) pWrite = pCluster->createdTime;
cols++; cols++;
mnodeDecClusterRef(pCluster); mnodeDecClusterRef(pCluster);

View File

@ -143,14 +143,14 @@ static int32_t mnodeDbActionRestored() {
int32_t mnodeInitDbs() { int32_t mnodeInitDbs() {
SDbObj tObj; SDbObj tObj;
tsDbUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj; tsDbUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj);
SSdbTableDesc desc = { SSdbTableDesc desc = {
.id = SDB_TABLE_DB, .id = SDB_TABLE_DB,
.name = "dbs", .name = "dbs",
.hashSessions = TSDB_DEFAULT_DBS_HASH_SIZE, .hashSessions = TSDB_DEFAULT_DBS_HASH_SIZE,
.maxRowSize = tsDbUpdateSize, .maxRowSize = tsDbUpdateSize,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_STRING, .keyType = SDB_KEY_STRING,
.fpInsert = mnodeDbActionInsert, .fpInsert = mnodeDbActionInsert,
.fpDelete = mnodeDbActionDelete, .fpDelete = mnodeDbActionDelete,
@ -192,11 +192,11 @@ SDbObj *mnodeGetDb(char *db) {
} }
void mnodeIncDbRef(SDbObj *pDb) { void mnodeIncDbRef(SDbObj *pDb) {
return sdbIncRef(tsDbSdb, pDb); sdbIncRef(tsDbSdb, pDb);
} }
void mnodeDecDbRef(SDbObj *pDb) { void mnodeDecDbRef(SDbObj *pDb) {
return sdbDecRef(tsDbSdb, pDb); sdbDecRef(tsDbSdb, pDb);
} }
SDbObj *mnodeGetDbByTableName(char *tableName) { SDbObj *mnodeGetDbByTableName(char *tableName) {

View File

@ -148,7 +148,7 @@ static int32_t mnodeDnodeActionDecode(SSdbRow *pRow) {
} }
static int32_t mnodeDnodeActionRestored() { static int32_t mnodeDnodeActionRestored() {
int32_t numOfRows = sdbGetNumOfRows(tsDnodeSdb); int64_t numOfRows = sdbGetNumOfRows(tsDnodeSdb);
if (numOfRows <= 0 && dnodeIsFirstDeploy()) { if (numOfRows <= 0 && dnodeIsFirstDeploy()) {
mInfo("dnode first deploy, create dnode:%s", tsLocalEp); mInfo("dnode first deploy, create dnode:%s", tsLocalEp);
mnodeCreateDnode(tsLocalEp, NULL); mnodeCreateDnode(tsLocalEp, NULL);
@ -165,7 +165,7 @@ static int32_t mnodeDnodeActionRestored() {
int32_t mnodeInitDnodes() { int32_t mnodeInitDnodes() {
SDnodeObj tObj; SDnodeObj tObj;
tsDnodeUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj; tsDnodeUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj);
pthread_mutex_init(&tsDnodeEpsMutex, NULL); pthread_mutex_init(&tsDnodeEpsMutex, NULL);
SSdbTableDesc desc = { SSdbTableDesc desc = {
@ -173,7 +173,7 @@ int32_t mnodeInitDnodes() {
.name = "dnodes", .name = "dnodes",
.hashSessions = TSDB_DEFAULT_DNODES_HASH_SIZE, .hashSessions = TSDB_DEFAULT_DNODES_HASH_SIZE,
.maxRowSize = tsDnodeUpdateSize, .maxRowSize = tsDnodeUpdateSize,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_AUTO, .keyType = SDB_KEY_AUTO,
.fpInsert = mnodeDnodeActionInsert, .fpInsert = mnodeDnodeActionInsert,
.fpDelete = mnodeDnodeActionDelete, .fpDelete = mnodeDnodeActionDelete,
@ -227,7 +227,7 @@ void mnodeCancelGetNextDnode(void *pIter) {
} }
int32_t mnodeGetDnodesNum() { int32_t mnodeGetDnodesNum() {
return sdbGetNumOfRows(tsDnodeSdb); return (int32_t)sdbGetNumOfRows(tsDnodeSdb);
} }
int32_t mnodeGetOnlinDnodesCpuCoreNum() { int32_t mnodeGetOnlinDnodesCpuCoreNum() {
@ -407,7 +407,7 @@ static int32_t mnodeCheckClusterCfgPara(const SClusterCfg *clusterCfg) {
int64_t checkTime = 0; int64_t checkTime = 0;
char timestr[32] = "1970-01-01 00:00:00.00"; char timestr[32] = "1970-01-01 00:00:00.00";
(void)taosParseTime(timestr, &checkTime, strlen(timestr), TSDB_TIME_PRECISION_MILLI, 0); (void)taosParseTime(timestr, &checkTime, (int32_t)strlen(timestr), TSDB_TIME_PRECISION_MILLI, 0);
if ((0 != strncasecmp(clusterCfg->timezone, tsTimezone, strlen(tsTimezone))) && if ((0 != strncasecmp(clusterCfg->timezone, tsTimezone, strlen(tsTimezone))) &&
(checkTime != clusterCfg->checkTime)) { (checkTime != clusterCfg->checkTime)) {
mError("\"timezone\"[%s - %s] [%" PRId64 " - %" PRId64 "] cfg parameters inconsistent", clusterCfg->timezone, mError("\"timezone\"[%s - %s] [%" PRId64 " - %" PRId64 "] cfg parameters inconsistent", clusterCfg->timezone,
@ -638,9 +638,9 @@ static int32_t mnodeCreateDnode(char *ep, SMnodeMsg *pMsg) {
char *temp = strchr(dnodeEp, ':'); char *temp = strchr(dnodeEp, ':');
if (!temp) { if (!temp) {
int len = strlen(dnodeEp); int32_t len = (int32_t)strlen(dnodeEp);
if (dnodeEp[len - 1] == ';') dnodeEp[len - 1] = 0; if (dnodeEp[len - 1] == ';') dnodeEp[len - 1] = 0;
len = strlen(dnodeEp); len = (int32_t)strlen(dnodeEp);
snprintf(dnodeEp + len, TSDB_EP_LEN - len, ":%d", tsServerPort); snprintf(dnodeEp + len, TSDB_EP_LEN - len, ":%d", tsServerPort);
} }
ep = dnodeEp; ep = dnodeEp;

View File

@ -136,14 +136,14 @@ int32_t mnodeInitMnodes() {
mnodeMnodeInitLock(); mnodeMnodeInitLock();
SMnodeObj tObj; SMnodeObj tObj;
tsMnodeUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj; tsMnodeUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj);
SSdbTableDesc desc = { SSdbTableDesc desc = {
.id = SDB_TABLE_MNODE, .id = SDB_TABLE_MNODE,
.name = "mnodes", .name = "mnodes",
.hashSessions = TSDB_DEFAULT_MNODES_HASH_SIZE, .hashSessions = TSDB_DEFAULT_MNODES_HASH_SIZE,
.maxRowSize = tsMnodeUpdateSize, .maxRowSize = tsMnodeUpdateSize,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_INT, .keyType = SDB_KEY_INT,
.fpInsert = mnodeMnodeActionInsert, .fpInsert = mnodeMnodeActionInsert,
.fpDelete = mnodeMnodeActionDelete, .fpDelete = mnodeMnodeActionDelete,
@ -176,7 +176,7 @@ void mnodeCleanupMnodes() {
} }
int32_t mnodeGetMnodesNum() { int32_t mnodeGetMnodesNum() {
return sdbGetNumOfRows(tsMnodeSdb); return (int32_t)sdbGetNumOfRows(tsMnodeSdb);
} }
void *mnodeGetMnode(int32_t mnodeId) { void *mnodeGetMnode(int32_t mnodeId) {

View File

@ -207,7 +207,7 @@ static void sdbRestoreTables() {
(*pTable->fpRestored)(); (*pTable->fpRestored)();
} }
totalRows += pTable->numOfRows; totalRows += (int32_t)pTable->numOfRows;
numOfTables++; numOfTables++;
sdbInfo("vgId:1, sdb:%s is checked, rows:%" PRId64, pTable->name, pTable->numOfRows); sdbInfo("vgId:1, sdb:%s is checked, rows:%" PRId64, pTable->name, pTable->numOfRows);
} }
@ -475,7 +475,7 @@ void sdbIncRef(void *tparam, void *pRow) {
if (pRow == NULL || tparam == NULL) return; if (pRow == NULL || tparam == NULL) return;
SSdbTable *pTable = tparam; SSdbTable *pTable = tparam;
int32_t * pRefCount = (int32_t *)(pRow + pTable->refCountPos); int32_t * pRefCount = (int32_t *)((char *)pRow + pTable->refCountPos);
int32_t refCount = atomic_add_fetch_32(pRefCount, 1); int32_t refCount = atomic_add_fetch_32(pRefCount, 1);
sdbTrace("vgId:1, sdb:%s, inc ref to row:%p:%s:%d", pTable->name, pRow, sdbGetRowStr(pTable, pRow), refCount); sdbTrace("vgId:1, sdb:%s, inc ref to row:%p:%s:%d", pTable->name, pRow, sdbGetRowStr(pTable, pRow), refCount);
} }
@ -484,11 +484,11 @@ void sdbDecRef(void *tparam, void *pRow) {
if (pRow == NULL || tparam == NULL) return; if (pRow == NULL || tparam == NULL) return;
SSdbTable *pTable = tparam; SSdbTable *pTable = tparam;
int32_t * pRefCount = (int32_t *)(pRow + pTable->refCountPos); int32_t * pRefCount = (int32_t *)((char *)pRow + pTable->refCountPos);
int32_t refCount = atomic_sub_fetch_32(pRefCount, 1); int32_t refCount = atomic_sub_fetch_32(pRefCount, 1);
sdbTrace("vgId:1, sdb:%s, dec ref to row:%p:%s:%d", pTable->name, pRow, sdbGetRowStr(pTable, pRow), refCount); sdbTrace("vgId:1, sdb:%s, dec ref to row:%p:%s:%d", pTable->name, pRow, sdbGetRowStr(pTable, pRow), refCount);
int32_t *updateEnd = pRow + pTable->refCountPos - 4; int32_t *updateEnd = (int32_t *)((char *)pRow + pTable->refCountPos - 4);
if (refCount <= 0 && *updateEnd) { if (refCount <= 0 && *updateEnd) {
sdbTrace("vgId:1, sdb:%s, row:%p:%s:%d destroyed", pTable->name, pRow, sdbGetRowStr(pTable, pRow), refCount); sdbTrace("vgId:1, sdb:%s, row:%p:%s:%d destroyed", pTable->name, pRow, sdbGetRowStr(pTable, pRow), refCount);
SSdbRow row = {.pObj = pRow}; SSdbRow row = {.pObj = pRow};
@ -501,7 +501,7 @@ static void *sdbGetRowMeta(SSdbTable *pTable, void *key) {
int32_t keySize = sizeof(int32_t); int32_t keySize = sizeof(int32_t);
if (pTable->keyType == SDB_KEY_STRING || pTable->keyType == SDB_KEY_VAR_STRING) { if (pTable->keyType == SDB_KEY_STRING || pTable->keyType == SDB_KEY_VAR_STRING) {
keySize = strlen((char *)key); keySize = (int32_t)strlen((char *)key);
} }
void **ppRow = (void **)taosHashGet(pTable->iHandle, key, keySize); void **ppRow = (void **)taosHashGet(pTable->iHandle, key, keySize);
@ -534,7 +534,7 @@ static int32_t sdbInsertHash(SSdbTable *pTable, SSdbRow *pRow) {
int32_t keySize = sizeof(int32_t); int32_t keySize = sizeof(int32_t);
if (pTable->keyType == SDB_KEY_STRING || pTable->keyType == SDB_KEY_VAR_STRING) { if (pTable->keyType == SDB_KEY_STRING || pTable->keyType == SDB_KEY_VAR_STRING) {
keySize = strlen((char *)key); keySize = (int32_t)strlen((char *)key);
} }
pthread_mutex_lock(&pTable->mutex); pthread_mutex_lock(&pTable->mutex);
@ -564,7 +564,7 @@ static int32_t sdbInsertHash(SSdbTable *pTable, SSdbRow *pRow) {
} }
static int32_t sdbDeleteHash(SSdbTable *pTable, SSdbRow *pRow) { static int32_t sdbDeleteHash(SSdbTable *pTable, SSdbRow *pRow) {
int32_t *updateEnd = pRow->pObj + pTable->refCountPos - 4; int32_t *updateEnd = (int32_t *)((char*)pRow->pObj + pTable->refCountPos - 4);
bool set = atomic_val_compare_exchange_32(updateEnd, 0, 1) == 0; bool set = atomic_val_compare_exchange_32(updateEnd, 0, 1) == 0;
if (!set) { if (!set) {
sdbError("vgId:1, sdb:%s, failed to delete key:%s from hash, for it already removed", pTable->name, sdbError("vgId:1, sdb:%s, failed to delete key:%s from hash, for it already removed", pTable->name,
@ -577,7 +577,7 @@ static int32_t sdbDeleteHash(SSdbTable *pTable, SSdbRow *pRow) {
void * key = sdbGetObjKey(pTable, pRow->pObj); void * key = sdbGetObjKey(pTable, pRow->pObj);
int32_t keySize = sizeof(int32_t); int32_t keySize = sizeof(int32_t);
if (pTable->keyType == SDB_KEY_STRING || pTable->keyType == SDB_KEY_VAR_STRING) { if (pTable->keyType == SDB_KEY_STRING || pTable->keyType == SDB_KEY_VAR_STRING) {
keySize = strlen((char *)key); keySize = (int32_t)strlen((char *)key);
} }
pthread_mutex_lock(&pTable->mutex); pthread_mutex_lock(&pTable->mutex);
@ -764,7 +764,7 @@ bool sdbCheckRowDeleted(void *tparam, void *pRow) {
SSdbTable *pTable = tparam; SSdbTable *pTable = tparam;
if (pTable == NULL) return false; if (pTable == NULL) return false;
int32_t *updateEnd = pRow + pTable->refCountPos - 4; int32_t *updateEnd = (int32_t *)((char*)pRow + pTable->refCountPos - 4);
return atomic_val_compare_exchange_32(updateEnd, 1, 1) == 1; return atomic_val_compare_exchange_32(updateEnd, 1, 1) == 1;
} }
@ -942,14 +942,14 @@ static int32_t sdbInitWorker() {
static void sdbCleanupWorker() { static void sdbCleanupWorker() {
for (int32_t i = 0; i < tsSdbPool.num; ++i) { for (int32_t i = 0; i < tsSdbPool.num; ++i) {
SSdbWorker *pWorker = tsSdbPool.worker + i; SSdbWorker *pWorker = tsSdbPool.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
taosQsetThreadResume(tsSdbWQset); taosQsetThreadResume(tsSdbWQset);
} }
} }
for (int32_t i = 0; i < tsSdbPool.num; ++i) { for (int32_t i = 0; i < tsSdbPool.num; ++i) {
SSdbWorker *pWorker = tsSdbPool.worker + i; SSdbWorker *pWorker = tsSdbPool.worker + i;
if (pWorker->thread) { if (taosCheckPthreadValid(pWorker->thread)) {
pthread_join(pWorker->thread, NULL); pthread_join(pWorker->thread, NULL);
} }
} }

View File

@ -218,7 +218,7 @@ static int32_t mnodeProcessRetrieveMsg(SMnodeMsg *pMsg) {
} }
pRsp->numOfRows = htonl(rowsRead); pRsp->numOfRows = htonl(rowsRead);
pRsp->precision = htonl(TSDB_TIME_PRECISION_MILLI); // millisecond time precision pRsp->precision = (int16_t)htonl(TSDB_TIME_PRECISION_MILLI); // millisecond time precision
pMsg->rpcRsp.rsp = pRsp; pMsg->rpcRsp.rsp = pRsp;
pMsg->rpcRsp.len = size; pMsg->rpcRsp.len = size;

View File

@ -222,23 +222,23 @@ static int32_t mnodeChildTableActionEncode(SSdbRow *pRow) {
SCTableObj *pTable = pRow->pObj; SCTableObj *pTable = pRow->pObj;
assert(pTable != NULL && pRow->rowData != NULL); assert(pTable != NULL && pRow->rowData != NULL);
int32_t len = strlen(pTable->info.tableId); int32_t len = (int32_t)strlen(pTable->info.tableId);
if (len >= TSDB_TABLE_FNAME_LEN) return TSDB_CODE_MND_INVALID_TABLE_ID; if (len >= TSDB_TABLE_FNAME_LEN) return TSDB_CODE_MND_INVALID_TABLE_ID;
memcpy(pRow->rowData, pTable->info.tableId, len); memcpy(pRow->rowData, pTable->info.tableId, len);
memset(pRow->rowData + len, 0, 1); memset((char *)pRow->rowData + len, 0, 1);
len++; len++;
memcpy(pRow->rowData + len, (char*)pTable + sizeof(char *), tsChildTableUpdateSize); memcpy((char *)pRow->rowData + len, (char *)pTable + sizeof(char *), tsChildTableUpdateSize);
len += tsChildTableUpdateSize; len += tsChildTableUpdateSize;
if (pTable->info.type != TSDB_CHILD_TABLE) { if (pTable->info.type != TSDB_CHILD_TABLE) {
int32_t schemaSize = pTable->numOfColumns * sizeof(SSchema); int32_t schemaSize = pTable->numOfColumns * sizeof(SSchema);
memcpy(pRow->rowData + len, pTable->schema, schemaSize); memcpy((char *)pRow->rowData + len, pTable->schema, schemaSize);
len += schemaSize; len += schemaSize;
if (pTable->sqlLen != 0) { if (pTable->sqlLen != 0) {
memcpy(pRow->rowData + len, pTable->sql, pTable->sqlLen); memcpy((char *)pRow->rowData + len, pTable->sql, pTable->sqlLen);
len += pTable->sqlLen; len += pTable->sqlLen;
} }
} }
@ -253,7 +253,7 @@ static int32_t mnodeChildTableActionDecode(SSdbRow *pRow) {
SCTableObj *pTable = calloc(1, sizeof(SCTableObj)); SCTableObj *pTable = calloc(1, sizeof(SCTableObj));
if (pTable == NULL) return TSDB_CODE_MND_OUT_OF_MEMORY; if (pTable == NULL) return TSDB_CODE_MND_OUT_OF_MEMORY;
int32_t len = strlen(pRow->rowData); int32_t len = (int32_t)strlen(pRow->rowData);
if (len >= TSDB_TABLE_FNAME_LEN) { if (len >= TSDB_TABLE_FNAME_LEN) {
free(pTable); free(pTable);
return TSDB_CODE_MND_INVALID_TABLE_ID; return TSDB_CODE_MND_INVALID_TABLE_ID;
@ -261,7 +261,7 @@ static int32_t mnodeChildTableActionDecode(SSdbRow *pRow) {
pTable->info.tableId = strdup(pRow->rowData); pTable->info.tableId = strdup(pRow->rowData);
len++; len++;
memcpy((char*)pTable + sizeof(char *), pRow->rowData + len, tsChildTableUpdateSize); memcpy((char *)pTable + sizeof(char *), (char *)pRow->rowData + len, tsChildTableUpdateSize);
len += tsChildTableUpdateSize; len += tsChildTableUpdateSize;
if (pTable->info.type != TSDB_CHILD_TABLE) { if (pTable->info.type != TSDB_CHILD_TABLE) {
@ -271,7 +271,7 @@ static int32_t mnodeChildTableActionDecode(SSdbRow *pRow) {
mnodeDestroyChildTable(pTable); mnodeDestroyChildTable(pTable);
return TSDB_CODE_MND_INVALID_TABLE_TYPE; return TSDB_CODE_MND_INVALID_TABLE_TYPE;
} }
memcpy(pTable->schema, pRow->rowData + len, schemaSize); memcpy(pTable->schema, (char *)pRow->rowData + len, schemaSize);
len += schemaSize; len += schemaSize;
if (pTable->sqlLen != 0) { if (pTable->sqlLen != 0) {
@ -280,7 +280,7 @@ static int32_t mnodeChildTableActionDecode(SSdbRow *pRow) {
mnodeDestroyChildTable(pTable); mnodeDestroyChildTable(pTable);
return TSDB_CODE_MND_OUT_OF_MEMORY; return TSDB_CODE_MND_OUT_OF_MEMORY;
} }
memcpy(pTable->sql, pRow->rowData + len, pTable->sqlLen); memcpy(pTable->sql, (char *)pRow->rowData + len, pTable->sqlLen);
} }
} }
@ -352,14 +352,14 @@ static int32_t mnodeChildTableActionRestored() {
static int32_t mnodeInitChildTables() { static int32_t mnodeInitChildTables() {
SCTableObj tObj; SCTableObj tObj;
tsChildTableUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj.info.type; tsChildTableUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj.info.type);
SSdbTableDesc desc = { SSdbTableDesc desc = {
.id = SDB_TABLE_CTABLE, .id = SDB_TABLE_CTABLE,
.name = "ctables", .name = "ctables",
.hashSessions = TSDB_DEFAULT_CTABLES_HASH_SIZE, .hashSessions = TSDB_DEFAULT_CTABLES_HASH_SIZE,
.maxRowSize = sizeof(SCTableObj) + sizeof(SSchema) * (TSDB_MAX_TAGS + TSDB_MAX_COLUMNS + 16) + TSDB_TABLE_FNAME_LEN + TSDB_CQ_SQL_SIZE, .maxRowSize = sizeof(SCTableObj) + sizeof(SSchema) * (TSDB_MAX_TAGS + TSDB_MAX_COLUMNS + 16) + TSDB_TABLE_FNAME_LEN + TSDB_CQ_SQL_SIZE,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_VAR_STRING, .keyType = SDB_KEY_VAR_STRING,
.fpInsert = mnodeChildTableActionInsert, .fpInsert = mnodeChildTableActionInsert,
.fpDelete = mnodeChildTableActionDelete, .fpDelete = mnodeChildTableActionDelete,
@ -501,18 +501,18 @@ static int32_t mnodeSuperTableActionEncode(SSdbRow *pRow) {
SSTableObj *pStable = pRow->pObj; SSTableObj *pStable = pRow->pObj;
assert(pRow->pObj != NULL && pRow->rowData != NULL); assert(pRow->pObj != NULL && pRow->rowData != NULL);
int32_t len = strlen(pStable->info.tableId); int32_t len = (int32_t)strlen(pStable->info.tableId);
if (len >= TSDB_TABLE_FNAME_LEN) len = TSDB_CODE_MND_INVALID_TABLE_ID; if (len >= TSDB_TABLE_FNAME_LEN) len = TSDB_CODE_MND_INVALID_TABLE_ID;
memcpy(pRow->rowData, pStable->info.tableId, len); memcpy(pRow->rowData, pStable->info.tableId, len);
memset(pRow->rowData + len, 0, 1); memset((char *)pRow->rowData + len, 0, 1);
len++; len++;
memcpy(pRow->rowData + len, (char*)pStable + sizeof(char *), tsSuperTableUpdateSize); memcpy((char *)pRow->rowData + len, (char *)pStable + sizeof(char *), tsSuperTableUpdateSize);
len += tsSuperTableUpdateSize; len += tsSuperTableUpdateSize;
int32_t schemaSize = sizeof(SSchema) * (pStable->numOfColumns + pStable->numOfTags); int32_t schemaSize = sizeof(SSchema) * (pStable->numOfColumns + pStable->numOfTags);
memcpy(pRow->rowData + len, pStable->schema, schemaSize); memcpy((char *)pRow->rowData + len, pStable->schema, schemaSize);
len += schemaSize; len += schemaSize;
pRow->rowSize = len; pRow->rowSize = len;
@ -525,7 +525,7 @@ static int32_t mnodeSuperTableActionDecode(SSdbRow *pRow) {
SSTableObj *pStable = (SSTableObj *) calloc(1, sizeof(SSTableObj)); SSTableObj *pStable = (SSTableObj *) calloc(1, sizeof(SSTableObj));
if (pStable == NULL) return TSDB_CODE_MND_OUT_OF_MEMORY; if (pStable == NULL) return TSDB_CODE_MND_OUT_OF_MEMORY;
int32_t len = strlen(pRow->rowData); int32_t len = (int32_t)strlen(pRow->rowData);
if (len >= TSDB_TABLE_FNAME_LEN){ if (len >= TSDB_TABLE_FNAME_LEN){
free(pStable); free(pStable);
return TSDB_CODE_MND_INVALID_TABLE_ID; return TSDB_CODE_MND_INVALID_TABLE_ID;
@ -533,7 +533,7 @@ static int32_t mnodeSuperTableActionDecode(SSdbRow *pRow) {
pStable->info.tableId = strdup(pRow->rowData); pStable->info.tableId = strdup(pRow->rowData);
len++; len++;
memcpy((char*)pStable + sizeof(char *), pRow->rowData + len, tsSuperTableUpdateSize); memcpy((char *)pStable + sizeof(char *), (char *)pRow->rowData + len, tsSuperTableUpdateSize);
len += tsSuperTableUpdateSize; len += tsSuperTableUpdateSize;
int32_t schemaSize = sizeof(SSchema) * (pStable->numOfColumns + pStable->numOfTags); int32_t schemaSize = sizeof(SSchema) * (pStable->numOfColumns + pStable->numOfTags);
@ -543,8 +543,7 @@ static int32_t mnodeSuperTableActionDecode(SSdbRow *pRow) {
return TSDB_CODE_MND_NOT_SUPER_TABLE; return TSDB_CODE_MND_NOT_SUPER_TABLE;
} }
memcpy(pStable->schema, pRow->rowData + len, schemaSize); memcpy(pStable->schema, (char *)pRow->rowData + len, schemaSize);
pRow->pObj = pStable; pRow->pObj = pStable;
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
@ -556,14 +555,14 @@ static int32_t mnodeSuperTableActionRestored() {
static int32_t mnodeInitSuperTables() { static int32_t mnodeInitSuperTables() {
SSTableObj tObj; SSTableObj tObj;
tsSuperTableUpdateSize = (int8_t *)tObj.updateEnd - (int8_t *)&tObj.info.type; tsSuperTableUpdateSize = (int32_t)((int8_t *)tObj.updateEnd - (int8_t *)&tObj.info.type);
SSdbTableDesc desc = { SSdbTableDesc desc = {
.id = SDB_TABLE_STABLE, .id = SDB_TABLE_STABLE,
.name = "stables", .name = "stables",
.hashSessions = TSDB_DEFAULT_STABLES_HASH_SIZE, .hashSessions = TSDB_DEFAULT_STABLES_HASH_SIZE,
.maxRowSize = sizeof(SSTableObj) + sizeof(SSchema) * (TSDB_MAX_TAGS + TSDB_MAX_COLUMNS + 16) + TSDB_TABLE_FNAME_LEN, .maxRowSize = sizeof(SSTableObj) + sizeof(SSchema) * (TSDB_MAX_TAGS + TSDB_MAX_COLUMNS + 16) + TSDB_TABLE_FNAME_LEN,
.refCountPos = (int8_t *)(&tObj.refCount) - (int8_t *)&tObj, .refCountPos = (int32_t)((int8_t *)(&tObj.refCount) - (int8_t *)&tObj),
.keyType = SDB_KEY_VAR_STRING, .keyType = SDB_KEY_VAR_STRING,
.fpInsert = mnodeSuperTableActionInsert, .fpInsert = mnodeSuperTableActionInsert,
.fpDelete = mnodeSuperTableActionDelete, .fpDelete = mnodeSuperTableActionDelete,
@ -844,6 +843,7 @@ static int32_t mnodeProcessBatchCreateTableMsg(SMnodeMsg *pMsg) {
return TSDB_CODE_MND_ACTION_IN_PROGRESS; return TSDB_CODE_MND_ACTION_IN_PROGRESS;
} else { // batch master replay, reprocess the whole batch } else { // batch master replay, reprocess the whole batch
assert(0); assert(0);
return TSDB_CODE_MND_MSG_NOT_PROCESSED;
} }
} }
} }
@ -1257,7 +1257,7 @@ static int32_t mnodeModifySuperTableTagName(SMnodeMsg *pMsg, char *oldTagName, c
} }
// int32_t rowSize = 0; // int32_t rowSize = 0;
uint32_t len = strlen(newTagName); uint32_t len = (int32_t)strlen(newTagName);
if (len >= TSDB_COL_NAME_LEN) { if (len >= TSDB_COL_NAME_LEN) {
return TSDB_CODE_MND_COL_NAME_TOO_LONG; return TSDB_CODE_MND_COL_NAME_TOO_LONG;
} }
@ -1420,7 +1420,7 @@ static int32_t mnodeChangeSuperTableColumn(SMnodeMsg *pMsg, char *oldName, char
} }
// int32_t rowSize = 0; // int32_t rowSize = 0;
uint32_t len = strlen(newName); uint32_t len = (uint32_t)strlen(newName);
if (len >= TSDB_COL_NAME_LEN) { if (len >= TSDB_COL_NAME_LEN) {
return TSDB_CODE_MND_COL_NAME_TOO_LONG; return TSDB_CODE_MND_COL_NAME_TOO_LONG;
} }
@ -1525,7 +1525,7 @@ int32_t mnodeRetrieveShowSuperTables(SShowObj *pShow, char *data, int32_t rows,
tstrncpy(prefix, pDb->name, 64); tstrncpy(prefix, pDb->name, 64);
strcat(prefix, TS_PATH_DELIMITER); strcat(prefix, TS_PATH_DELIMITER);
prefixLen = strlen(prefix); prefixLen = (int32_t)strlen(prefix);
SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER; SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER;
char stableName[TSDB_TABLE_NAME_LEN] = {0}; char stableName[TSDB_TABLE_NAME_LEN] = {0};
@ -1550,7 +1550,7 @@ int32_t mnodeRetrieveShowSuperTables(SShowObj *pShow, char *data, int32_t rows,
pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows; pWrite = data + pShow->offset[cols] * rows + pShow->bytes[cols] * numOfRows;
int16_t len = strnlen(stableName, TSDB_TABLE_NAME_LEN - 1); int16_t len = (int16_t)strnlen(stableName, TSDB_TABLE_NAME_LEN - 1);
*(int16_t*) pWrite = len; *(int16_t*) pWrite = len;
pWrite += sizeof(int16_t); // todo refactor pWrite += sizeof(int16_t); // todo refactor
@ -1593,7 +1593,7 @@ void mnodeDropAllSuperTables(SDbObj *pDropDb) {
char prefix[64] = {0}; char prefix[64] = {0};
tstrncpy(prefix, pDropDb->name, 64); tstrncpy(prefix, pDropDb->name, 64);
strcat(prefix, TS_PATH_DELIMITER); strcat(prefix, TS_PATH_DELIMITER);
int32_t prefixLen = strlen(prefix); int32_t prefixLen = (int32_t)strlen(prefix);
mInfo("db:%s, all super tables will be dropped from sdb", pDropDb->name); mInfo("db:%s, all super tables will be dropped from sdb", pDropDb->name);
@ -1746,9 +1746,9 @@ static int32_t mnodeProcessSuperTableVgroupMsg(SMnodeMsg *pMsg) {
rpcFreeCont(pRsp); rpcFreeCont(pRsp);
return TSDB_CODE_MND_INVALID_TABLE_NAME; return TSDB_CODE_MND_INVALID_TABLE_NAME;
} else { } else {
pRsp->numOfTables = htonl(pRsp->numOfTables); pRsp->numOfTables = (int32_t)htonl(pRsp->numOfTables);
pMsg->rpcRsp.rsp = pRsp; pMsg->rpcRsp.rsp = pRsp;
pMsg->rpcRsp.len = msg - (char *)pRsp; pMsg->rpcRsp.len = (int32_t)((char *)msg - (char *)pRsp);
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
} }
@ -2021,7 +2021,7 @@ static int32_t mnodeDoCreateChildTable(SMnodeMsg *pMsg, int32_t tid) {
static int32_t mnodeProcessCreateChildTableMsg(SMnodeMsg *pMsg) { static int32_t mnodeProcessCreateChildTableMsg(SMnodeMsg *pMsg) {
//SCMCreateTableMsg* p1 = pMsg->rpcMsg.pCont; // there are several tables here. //SCMCreateTableMsg* p1 = pMsg->rpcMsg.pCont; // there are several tables here.
SCreateTableMsg* pCreate = (SCreateTableMsg*)(pMsg->rpcMsg.pCont + sizeof(SCMCreateTableMsg)); SCreateTableMsg* pCreate = (SCreateTableMsg*)((char *)pMsg->rpcMsg.pCont + sizeof(SCMCreateTableMsg));
int32_t code = grantCheck(TSDB_GRANT_TIMESERIES); int32_t code = grantCheck(TSDB_GRANT_TIMESERIES);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
@ -2278,7 +2278,7 @@ static int32_t mnodeChangeNormalTableColumn(SMnodeMsg *pMsg, char *oldName, char
} }
// int32_t rowSize = 0; // int32_t rowSize = 0;
uint32_t len = strlen(newName); uint32_t len = (uint32_t)strlen(newName);
if (len >= TSDB_COL_NAME_LEN) { if (len >= TSDB_COL_NAME_LEN) {
return TSDB_CODE_MND_COL_NAME_TOO_LONG; return TSDB_CODE_MND_COL_NAME_TOO_LONG;
} }
@ -2481,7 +2481,7 @@ void mnodeDropAllChildTables(SDbObj *pDropDb) {
char prefix[64] = {0}; char prefix[64] = {0};
tstrncpy(prefix, pDropDb->name, 64); tstrncpy(prefix, pDropDb->name, 64);
strcat(prefix, TS_PATH_DELIMITER); strcat(prefix, TS_PATH_DELIMITER);
int32_t prefixLen = strlen(prefix); int32_t prefixLen = (int32_t)strlen(prefix);
mInfo("db:%s, all child tables will be dropped from sdb", pDropDb->name); mInfo("db:%s, all child tables will be dropped from sdb", pDropDb->name);
@ -2897,7 +2897,7 @@ static int32_t mnodeRetrieveShowTables(SShowObj *pShow, char *data, int32_t rows
SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER; SPatternCompareInfo info = PATTERN_COMPARE_INFO_INITIALIZER;
char prefix[64] = {0}; char prefix[64] = {0};
int32_t prefixLen = tableIdPrefix(pDb->name, prefix, 64); int32_t prefixLen = (int32_t)tableIdPrefix(pDb->name, prefix, 64);
char* pattern = NULL; char* pattern = NULL;
if (pShow->payloadLen > 0) { if (pShow->payloadLen > 0) {
@ -3133,7 +3133,7 @@ static int32_t mnodeRetrieveStreamTables(SShowObj *pShow, char *data, int32_t ro
char prefix[64] = {0}; char prefix[64] = {0};
tstrncpy(prefix, pDb->name, 64); tstrncpy(prefix, pDb->name, 64);
strcat(prefix, TS_PATH_DELIMITER); strcat(prefix, TS_PATH_DELIMITER);
int32_t prefixLen = strlen(prefix); int32_t prefixLen = (int32_t)strlen(prefix);
while (numOfRows < rows) { while (numOfRows < rows) {
pShow->pIter = mnodeGetNextChildTable(pShow->pIter, &pTable); pShow->pIter = mnodeGetNextChildTable(pShow->pIter, &pTable);

Some files were not shown because too many files have changed in this diff Show More