提交 b7e585ba 编写于 作者: G Ganlin Zhao

Merge branch 'develop' into fix/TD-10897

...@@ -82,6 +82,10 @@ tests/comparisonTest/opentsdb/opentsdbtest/.settings/ ...@@ -82,6 +82,10 @@ tests/comparisonTest/opentsdb/opentsdbtest/.settings/
tests/examples/JDBC/JDBCDemo/.classpath tests/examples/JDBC/JDBCDemo/.classpath
tests/examples/JDBC/JDBCDemo/.project tests/examples/JDBC/JDBCDemo/.project
tests/examples/JDBC/JDBCDemo/.settings/ tests/examples/JDBC/JDBCDemo/.settings/
tests/script/api/batchprepare
tests/script/api/stmt
tests/script/api/stmtBatchTest
tests/script/api/stmtTest
# Emacs # Emacs
# -*- mode: gitignore; -*- # -*- mode: gitignore; -*-
......
...@@ -455,17 +455,18 @@ pipeline { ...@@ -455,17 +455,18 @@ pipeline {
npm install td2.0-connector > /dev/null 2>&1 npm install td2.0-connector > /dev/null 2>&1
node nodejsChecker.js host=localhost node nodejsChecker.js host=localhost
node test1970.js node test1970.js
cd ${WKC}/tests/connectorTest/nodejsTest/nanosupport cd ${WKC}/tests/connectorTest/nodejsTest/nanosupport
npm install td2.0-connector > /dev/null 2>&1 npm install td2.0-connector > /dev/null 2>&1
node nanosecondTest.js node nanosecondTest.js
''' '''
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
sh ''' sh '''
cd ${WKC}/tests/examples/C#/taosdemo cd ${WKC}/tests/examples/C#/taosdemo
mcs -out:taosdemo *.cs > /dev/null 2>&1 mcs -out:taosdemo *.cs > /dev/null 2>&1
echo '' |./taosdemo -c /etc/taos echo '' |./taosdemo -c /etc/taos
''' '''
}
sh ''' sh '''
cd ${WKC}/tests/gotest cd ${WKC}/tests/gotest
bash batchtest.sh bash batchtest.sh
......
...@@ -135,6 +135,8 @@ IF ("${BUILD_HTTP}" STREQUAL "") ...@@ -135,6 +135,8 @@ IF ("${BUILD_HTTP}" STREQUAL "")
ELSE () ELSE ()
SET(BUILD_HTTP "false") SET(BUILD_HTTP "false")
ENDIF () ENDIF ()
ELSEIF (TD_DARWIN)
SET(BUILD_HTTP "false")
ELSE () ELSE ()
SET(BUILD_HTTP "true") SET(BUILD_HTTP "true")
ENDIF () ENDIF ()
......
...@@ -36,7 +36,13 @@ IF (${CMAKE_SYSTEM_NAME} MATCHES "Linux") ...@@ -36,7 +36,13 @@ IF (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
# Get OS information and store in variable TD_OS_INFO. # Get OS information and store in variable TD_OS_INFO.
# #
execute_process(COMMAND chmod 777 ${TD_COMMUNITY_DIR}/packaging/tools/get_os.sh) execute_process(COMMAND chmod 777 ${TD_COMMUNITY_DIR}/packaging/tools/get_os.sh)
execute_process(COMMAND sh ${TD_COMMUNITY_DIR}/packaging/tools/get_os.sh "" OUTPUT_VARIABLE TD_OS_INFO) execute_process(COMMAND readlink /bin/sh OUTPUT_VARIABLE SHELL_LINK)
MESSAGE(STATUS "The shell is: " ${SHELL_LINK})
IF (${SHELL_LINK} MATCHES "dash")
execute_process(COMMAND ${TD_COMMUNITY_DIR}/packaging/tools/get_os.sh "" OUTPUT_VARIABLE TD_OS_INFO)
ELSE ()
execute_process(COMMAND sh ${TD_COMMUNITY_DIR}/packaging/tools/get_os.sh "" OUTPUT_VARIABLE TD_OS_INFO)
ENDIF()
MESSAGE(STATUS "The current os is " ${TD_OS_INFO}) MESSAGE(STATUS "The current os is " ${TD_OS_INFO})
SET(TD_LINUX TRUE) SET(TD_LINUX TRUE)
......
...@@ -55,6 +55,7 @@ IF (TD_LINUX_64 AND JEMALLOC_ENABLED) ...@@ -55,6 +55,7 @@ IF (TD_LINUX_64 AND JEMALLOC_ENABLED)
MESSAGE("") MESSAGE("")
MESSAGE("setup deps/jemalloc, current source dir:" ${CMAKE_CURRENT_SOURCE_DIR}) MESSAGE("setup deps/jemalloc, current source dir:" ${CMAKE_CURRENT_SOURCE_DIR})
MESSAGE("binary dir:" ${CMAKE_BINARY_DIR}) MESSAGE("binary dir:" ${CMAKE_BINARY_DIR})
include(ExternalProject)
ExternalProject_Add(jemalloc ExternalProject_Add(jemalloc
PREFIX "jemalloc" PREFIX "jemalloc"
SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/jemalloc SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/jemalloc
...@@ -62,6 +63,7 @@ IF (TD_LINUX_64 AND JEMALLOC_ENABLED) ...@@ -62,6 +63,7 @@ IF (TD_LINUX_64 AND JEMALLOC_ENABLED)
CONFIGURE_COMMAND ./autogen.sh COMMAND ./configure --prefix=${CMAKE_BINARY_DIR}/build/ CONFIGURE_COMMAND ./autogen.sh COMMAND ./configure --prefix=${CMAKE_BINARY_DIR}/build/
BUILD_COMMAND ${MAKE} BUILD_COMMAND ${MAKE}
) )
INCLUDE_DIRECTORIES(${CMAKE_BINARY_DIR}/build/include)
ENDIF () ENDIF ()
IF (${TSZ_ENABLED} MATCHES "true") IF (${TSZ_ENABLED} MATCHES "true")
......
...@@ -121,10 +121,11 @@ TDengine是一个高效的存储、查询、分析时序大数据的平台,专 ...@@ -121,10 +121,11 @@ TDengine是一个高效的存储、查询、分析时序大数据的平台,专
* [数据复制](/architecture/replica):支持实时同步、异步复制,保证系统的High Availibility * [数据复制](/architecture/replica):支持实时同步、异步复制,保证系统的High Availibility
* [技术博客](https://www.taosdata.com/cn/blog/?categories=3):更多的技术分析和架构设计文章 * [技术博客](https://www.taosdata.com/cn/blog/?categories=3):更多的技术分析和架构设计文章
## [应用 TDengine 快速搭建 IT 运维系统](/devops) ## 应用 TDengine 快速搭建 IT 运维系统
* [devops](/devops/telegraf):使用 TDengine + Telegraf + Grafana 快速搭建 IT 运维系统 * [devops](/devops/telegraf):使用 TDengine + Telegraf + Grafana 快速搭建 IT 运维系统
* [devops](/devops/collectd):使用 TDengine + collectd_statsd + Grafana 快速搭建 IT 运维系统 * [devops](/devops/collectd):使用 TDengine + collectd_statsd + Grafana 快速搭建 IT 运维系统
* [最佳实践](/devops/immigrate):OpenTSDB 应用迁移到 TDengine 的最佳实践
## 常用工具 ## 常用工具
......
...@@ -145,7 +145,7 @@ insert delay, avg: 8.31ms, max: 860.12ms, min: 2.00ms ...@@ -145,7 +145,7 @@ insert delay, avg: 8.31ms, max: 860.12ms, min: 2.00ms
``` ```
$ taosdemo --help $ taosdemo --help
-f, --file=FILE The meta file to the execution procedure. -f, --file=FILE The meta file to the execution procedure. Currently, we support standard UTF-8 (without BOM) encoded files only.
-u, --user=USER The user name to use when connecting to the server. -u, --user=USER The user name to use when connecting to the server.
-p, --password The password to use when connecting to the server. -p, --password The password to use when connecting to the server.
-c, --config-dir=CONFIG_DIR Configuration directory. -c, --config-dir=CONFIG_DIR Configuration directory.
...@@ -442,7 +442,7 @@ TDengine是涛思数据专为物联网、车联网、工业互联网、IT运维 ...@@ -442,7 +442,7 @@ TDengine是涛思数据专为物联网、车联网、工业互联网、IT运维
taosdemo支持两种配置参数的模式,一种是命令行参数,一种是使用json格式的配置文件。 taosdemo支持两种配置参数的模式,一种是命令行参数,一种是使用json格式的配置文件。
一、命令行参数 一、命令行参数
-f:指定taosdemo所需参数的meta文件。当使用该参数时,其他所有命令行参数都失效。可选项,缺省是NULL。 -f:指定taosdemo所需参数的meta文件。当使用该参数时,其他所有命令行参数都失效。可选项,缺省是NULL。目前仅支持不含 BOM(byte-order mark)的标准 UTF-8 编码文件。
-u: 用户名。可选项,缺省是“root“。 -u: 用户名。可选项,缺省是“root“。
......
...@@ -145,27 +145,27 @@ st,t1=3,t2=4,t3=t3 c1=3i64,c6="passit" 1626006833640000000 ...@@ -145,27 +145,27 @@ st,t1=3,t2=4,t3=t3 c1=3i64,c6="passit" 1626006833640000000
<br/>如果是无模式写入过程中的数据本身错误,应用会得到 TSDB_CODE_TSC_LINE_SYNTAX_ERROR 错误信息,该错误信息表明错误发生在写入文本中。其他的错误码与原系统一致,可以通过 taos_errstr 获取具体的错误原因。 <br/>如果是无模式写入过程中的数据本身错误,应用会得到 TSDB_CODE_TSC_LINE_SYNTAX_ERROR 错误信息,该错误信息表明错误发生在写入文本中。其他的错误码与原系统一致,可以通过 taos_errstr 获取具体的错误原因。
**后续升级计划** **后续升级计划**
<br/>当前版本只提供了 C 版本的 API,后续将提供 其他高级语言的 API,例如 Java/Go/Python/C# 等。此外,在TDengine v2.3及后续版本中,您还可以通过 BLM v3 采用 REST 的方式直接写入无模式数据。 <br/>当前版本只提供了 C 版本的 API,后续将提供 其他高级语言的 API,例如 Java/Go/Python/C# 等。此外,在TDengine v2.3及后续版本中,您还可以通过 Taos Adapter 采用 REST 的方式直接写入无模式数据。
## <a class="anchor" id="prometheus"></a>Prometheus 直接写入 ## <a class="anchor" id="prometheus"></a>Prometheus 直接写入
[Prometheus](https://www.prometheus.io/)作为Cloud Native Computing Fundation毕业的项目,在性能监控以及K8S性能监控领域有着非常广泛的应用。TDengine提供一个小工具[Bailongma](https://github.com/taosdata/Bailongma),只需对Prometheus做简单配置,无需任何代码,就可将Prometheus采集的数据直接写入TDengine,并按规则在TDengine自动创建库和相关表项。博文[用Docker容器快速搭建一个Devops监控Demo](https://www.taosdata.com/blog/2020/02/03/1189.html)即是采用Bailongma将Prometheus和Telegraf的数据写入TDengine中的示例,可以参考。 [Prometheus](https://www.prometheus.io/)作为Cloud Native Computing Fundation毕业的项目,在性能监控以及K8S性能监控领域有着非常广泛的应用。TDengine提供一个小工具[Bailongma](https://github.com/taosdata/Bailongma),只需对Prometheus做简单配置,无需任何代码,就可将Prometheus采集的数据直接写入TDengine,并按规则在TDengine自动创建库和相关表项。博文[用Docker容器快速搭建一个Devops监控Demo](https://www.taosdata.com/blog/2020/02/03/1189.html)即是采用Bailongma将Prometheus和Telegraf的数据写入TDengine中的示例,可以参考。
### 从源代码编译 taosadapter_prometheus ### 从源代码编译 blm_prometheus
用户需要从github下载[Bailongma](https://github.com/taosdata/Bailongma)的源码,使用Golang语言编译器编译生成可执行文件。在开始编译前,需要准备好以下条件: 用户需要从github下载[Bailongma](https://github.com/taosdata/Bailongma)的源码,使用Golang语言编译器编译生成可执行文件。在开始编译前,需要准备好以下条件:
- Linux操作系统的服务器 - Linux操作系统的服务器
- 安装好Golang,1.14版本以上 - 安装好Golang,1.14版本以上
- 对应的TDengine版本。因为用到了TDengine的客户端动态链接库,因此需要安装好和服务端相同版本的TDengine程序;比如服务端版本是TDengine 2.0.0, 则在Bailongma所在的Linux服务器(可以与TDengine在同一台服务器,或者不同服务器) - 对应的TDengine版本。因为用到了TDengine的客户端动态链接库,因此需要安装好和服务端相同版本的TDengine程序;比如服务端版本是TDengine 2.0.0, 则在Bailongma所在的Linux服务器(可以与TDengine在同一台服务器,或者不同服务器)
Bailongma项目中有一个文件夹taosadapter_prometheus,存放了prometheus的写入API程序。编译过程如下: Bailongma项目中有一个文件夹blm_prometheus,存放了prometheus的写入API程序。编译过程如下:
```bash ```bash
cd taosadapter_prometheus cd blm_prometheus
go build go build
``` ```
一切正常的情况下,就会在对应的目录下生成一个taosadapter_prometheus的可执行程序。 一切正常的情况下,就会在对应的目录下生成一个blm_prometheus的可执行程序。
### 安装 Prometheus ### 安装 Prometheus
...@@ -176,23 +176,23 @@ go build ...@@ -176,23 +176,23 @@ go build
参考Prometheus的[配置文档](https://prometheus.io/docs/prometheus/latest/configuration/configuration/),在Prometheus的配置文件中的<remote_write>部分,增加以下配置: 参考Prometheus的[配置文档](https://prometheus.io/docs/prometheus/latest/configuration/configuration/),在Prometheus的配置文件中的<remote_write>部分,增加以下配置:
``` ```
- url: "bailongma API服务提供的URL"(参考下面的taosadapter_prometheus启动示例章节) - url: "bailongma API服务提供的URL"(参考下面的blm_prometheus启动示例章节)
``` ```
启动Prometheus后,可以通过taos客户端查询确认数据是否成功写入。 启动Prometheus后,可以通过taos客户端查询确认数据是否成功写入。
### 启动 taosadapter_prometheus 程序 ### 启动 blm_prometheus 程序
taosadapter_prometheus程序有以下选项,在启动taosadapter_prometheus程序时可以通过设定这些选项来设定taosadapter_prometheus的配置。 blm_prometheus程序有以下选项,在启动blm_prometheus程序时可以通过设定这些选项来设定blm_prometheus的配置。
```bash ```bash
--tdengine-name --tdengine-name
如果TDengine安装在一台具备域名的服务器上,也可以通过配置TDengine的域名来访问TDengine。在K8S环境下,可以配置成TDengine所运行的service name。 如果TDengine安装在一台具备域名的服务器上,也可以通过配置TDengine的域名来访问TDengine。在K8S环境下,可以配置成TDengine所运行的service name。
--batch-size --batch-size
taosadapter_prometheus会将收到的prometheus的数据拼装成TDengine的写入请求,这个参数控制一次发给TDengine的写入请求中携带的数据条数。 blm_prometheus会将收到的prometheus的数据拼装成TDengine的写入请求,这个参数控制一次发给TDengine的写入请求中携带的数据条数。
--dbname --dbname
设置在TDengine中创建的数据库名称,taosadapter_prometheus会自动在TDengine中创建一个以dbname为名称的数据库,缺省值是prometheus。 设置在TDengine中创建的数据库名称,blm_prometheus会自动在TDengine中创建一个以dbname为名称的数据库,缺省值是prometheus。
--dbuser --dbuser
设置访问TDengine的用户名,缺省值是'root' 设置访问TDengine的用户名,缺省值是'root'
...@@ -201,16 +201,16 @@ taosadapter_prometheus会将收到的prometheus的数据拼装成TDengine的写 ...@@ -201,16 +201,16 @@ taosadapter_prometheus会将收到的prometheus的数据拼装成TDengine的写
设置访问TDengine的密码,缺省值是'taosdata' 设置访问TDengine的密码,缺省值是'taosdata'
--port --port
taosadapter_prometheus对prometheus提供服务的端口号。 blm_prometheus对prometheus提供服务的端口号。
``` ```
### 启动示例 ### 启动示例
通过以下命令启动一个taosadapter_prometheus的API服务 通过以下命令启动一个blm_prometheus的API服务
```bash ```bash
./taosadapter_prometheus -port 8088 ./blm_prometheus -port 8088
``` ```
假设taosadapter_prometheus所在服务器的IP地址为"10.1.2.3",则在prometheus的配置文件中<remote_write>部分增加url为 假设blm_prometheus所在服务器的IP地址为"10.1.2.3",则在prometheus的配置文件中<remote_write>部分增加url为
```yaml ```yaml
remote_write: remote_write:
- url: "http://10.1.2.3:8088/receive" - url: "http://10.1.2.3:8088/receive"
...@@ -235,7 +235,7 @@ prometheus产生的数据格式如下: ...@@ -235,7 +235,7 @@ prometheus产生的数据格式如下:
} }
} }
``` ```
其中,apiserver_request_latencies_bucket为prometheus采集的时序数据的名称,后面{}中的为该时序数据的标签。taosadapter_prometheus会以时序数据的名称在TDengine中自动创建一个超级表,并将{}中的标签转换成TDengine的tag值,Timestamp作为时间戳,value作为该时序数据的值。因此在TDengine的客户端中,可以通过以下指令查到这个数据是否成功写入。 其中,apiserver_request_latencies_bucket为prometheus采集的时序数据的名称,后面{}中的为该时序数据的标签。blm_prometheus会以时序数据的名称在TDengine中自动创建一个超级表,并将{}中的标签转换成TDengine的tag值,Timestamp作为时间戳,value作为该时序数据的值。因此在TDengine的客户端中,可以通过以下指令查到这个数据是否成功写入。
```mysql ```mysql
use prometheus; use prometheus;
select * from apiserver_request_latencies_bucket; select * from apiserver_request_latencies_bucket;
...@@ -314,7 +314,7 @@ taosadapter 相关配置参数请参考 taosadapter --help 命令输出以及相 ...@@ -314,7 +314,7 @@ taosadapter 相关配置参数请参考 taosadapter --help 命令输出以及相
[Telegraf](https://www.influxdata.com/time-series-platform/telegraf/)是一流行的IT运维数据采集开源工具,TDengine提供一个小工具[Bailongma](https://github.com/taosdata/Bailongma),只需在Telegraf做简单配置,无需任何代码,就可将Telegraf采集的数据直接写入TDengine,并按规则在TDengine自动创建库和相关表项。博文[用Docker容器快速搭建一个Devops监控Demo](https://www.taosdata.com/blog/2020/02/03/1189.html)即是采用bailongma将Prometheus和Telegraf的数据写入TDengine中的示例,可以参考。 [Telegraf](https://www.influxdata.com/time-series-platform/telegraf/)是一流行的IT运维数据采集开源工具,TDengine提供一个小工具[Bailongma](https://github.com/taosdata/Bailongma),只需在Telegraf做简单配置,无需任何代码,就可将Telegraf采集的数据直接写入TDengine,并按规则在TDengine自动创建库和相关表项。博文[用Docker容器快速搭建一个Devops监控Demo](https://www.taosdata.com/blog/2020/02/03/1189.html)即是采用bailongma将Prometheus和Telegraf的数据写入TDengine中的示例,可以参考。
### 从源代码编译 taosadapter_telegraf ### 从源代码编译 blm_telegraf
用户需要从github下载[Bailongma](https://github.com/taosdata/Bailongma)的源码,使用Golang语言编译器编译生成可执行文件。在开始编译前,需要准备好以下条件: 用户需要从github下载[Bailongma](https://github.com/taosdata/Bailongma)的源码,使用Golang语言编译器编译生成可执行文件。在开始编译前,需要准备好以下条件:
...@@ -322,14 +322,14 @@ taosadapter 相关配置参数请参考 taosadapter --help 命令输出以及相 ...@@ -322,14 +322,14 @@ taosadapter 相关配置参数请参考 taosadapter --help 命令输出以及相
- 安装好Golang,1.10版本以上 - 安装好Golang,1.10版本以上
- 对应的TDengine版本。因为用到了TDengine的客户端动态链接库,因此需要安装好和服务端相同版本的TDengine程序;比如服务端版本是TDengine 2.0.0, 则在Bailongma所在的Linux服务器(可以与TDengine在同一台服务器,或者不同服务器) - 对应的TDengine版本。因为用到了TDengine的客户端动态链接库,因此需要安装好和服务端相同版本的TDengine程序;比如服务端版本是TDengine 2.0.0, 则在Bailongma所在的Linux服务器(可以与TDengine在同一台服务器,或者不同服务器)
Bailongma项目中有一个文件夹taosadapter_telegraf,存放了Telegraf的写入API程序。编译过程如下: Bailongma项目中有一个文件夹blm_telegraf,存放了Telegraf的写入API程序。编译过程如下:
```bash ```bash
cd taosadapter_telegraf cd blm_telegraf
go build go build
``` ```
一切正常的情况下,就会在对应的目录下生成一个taosadapter_telegraf的可执行程序。 一切正常的情况下,就会在对应的目录下生成一个blm_telegraf的可执行程序。
### 安装 Telegraf ### 安装 Telegraf
...@@ -352,19 +352,19 @@ go build ...@@ -352,19 +352,19 @@ go build
关于如何使用Telegraf采集数据以及更多有关使用Telegraf的信息,请参考Telegraf官方的[文档](https://docs.influxdata.com/telegraf/v1.11/) 关于如何使用Telegraf采集数据以及更多有关使用Telegraf的信息,请参考Telegraf官方的[文档](https://docs.influxdata.com/telegraf/v1.11/)
### 启动 taosadapter_telegraf 程序 ### 启动 blm_telegraf 程序
taosadapter_telegraf程序有以下选项,在启动taosadapter_telegraf程序时可以通过设定这些选项来设定taosadapter_telegraf的配置。 blm_telegraf程序有以下选项,在启动blm_telegraf程序时可以通过设定这些选项来设定blm_telegraf的配置。
```bash ```bash
--host --host
TDengine服务端的IP地址,缺省值为空。 TDengine服务端的IP地址,缺省值为空。
--batch-size --batch-size
taosadapter_telegraf会将收到的telegraf的数据拼装成TDengine的写入请求,这个参数控制一次发给TDengine的写入请求中携带的数据条数。 blm_telegraf会将收到的telegraf的数据拼装成TDengine的写入请求,这个参数控制一次发给TDengine的写入请求中携带的数据条数。
--dbname --dbname
设置在TDengine中创建的数据库名称,taosadapter_telegraf会自动在TDengine中创建一个以dbname为名称的数据库,缺省值是prometheus。 设置在TDengine中创建的数据库名称,blm_telegraf会自动在TDengine中创建一个以dbname为名称的数据库,缺省值是prometheus。
--dbuser --dbuser
设置访问TDengine的用户名,缺省值是'root' 设置访问TDengine的用户名,缺省值是'root'
...@@ -373,17 +373,17 @@ taosadapter_telegraf会将收到的telegraf的数据拼装成TDengine的写入 ...@@ -373,17 +373,17 @@ taosadapter_telegraf会将收到的telegraf的数据拼装成TDengine的写入
设置访问TDengine的密码,缺省值是'taosdata' 设置访问TDengine的密码,缺省值是'taosdata'
--port --port
taosadapter_telegraf对telegraf提供服务的端口号。 blm_telegraf对telegraf提供服务的端口号。
``` ```
### 启动示例 ### 启动示例
通过以下命令启动一个taosadapter_telegraf的API服务: 通过以下命令启动一个blm_telegraf的API服务:
```bash ```bash
./taosadapter_telegraf -host 127.0.0.1 -port 8089 ./blm_telegraf -host 127.0.0.1 -port 8089
``` ```
假设taosadapter_telegraf所在服务器的IP地址为"10.1.2.3",则在telegraf的配置文件中, 在output plugins部分,增加[[outputs.http]]配置项: 假设blm_telegraf所在服务器的IP地址为"10.1.2.3",则在telegraf的配置文件中, 在output plugins部分,增加[[outputs.http]]配置项:
```yaml ```yaml
url = "http://10.1.2.3:8089/telegraf" url = "http://10.1.2.3:8089/telegraf"
...@@ -416,7 +416,7 @@ telegraf产生的数据格式如下: ...@@ -416,7 +416,7 @@ telegraf产生的数据格式如下:
} }
``` ```
其中,name字段为telegraf采集的时序数据的名称,tags字段为该时序数据的标签。taosadapter_telegraf会以时序数据的名称在TDengine中自动创建一个超级表,并将tags字段中的标签转换成TDengine的tag值,timestamp作为时间戳,fields字段中的值作为该时序数据的值。因此在TDengine的客户端中,可以通过以下指令查到这个数据是否成功写入。 其中,name字段为telegraf采集的时序数据的名称,tags字段为该时序数据的标签。blm_telegraf会以时序数据的名称在TDengine中自动创建一个超级表,并将tags字段中的标签转换成TDengine的tag值,timestamp作为时间戳,fields字段中的值作为该时序数据的值。因此在TDengine的客户端中,可以通过以下指令查到这个数据是否成功写入。
```mysql ```mysql
use telegraf; use telegraf;
......
# TDengine的运营与运维 # TDengine的运营与维护
## <a class="anchor" id="planning"></a>容量规划 ## <a class="anchor" id="planning"></a>容量规划
...@@ -157,7 +157,7 @@ taosd -C ...@@ -157,7 +157,7 @@ taosd -C
| 39 | keep | | **S** | 天 | 数据保留的天数 | | 3650 | | | 39 | keep | | **S** | 天 | 数据保留的天数 | | 3650 | |
| 40 | minRows | | **S** | | 文件块中记录的最小条数 | | 100 | | | 40 | minRows | | **S** | | 文件块中记录的最小条数 | | 100 | |
| 41 | maxRows | | **S** | | 文件块中记录的最大条数 | | 4096 | | | 41 | maxRows | | **S** | | 文件块中记录的最大条数 | | 4096 | |
| 42 | quorum | | **S** | | 异步写入成功所需应答之法定数 | 1-3 | 1 | | | 42 | quorum | | **S** | | 多副本环境下指令执行的确认数要求 | 1,2 | 1 | |
| 43 | comp | | **S** | | 文件压缩标志位 | 0:关闭,1:一阶段压缩,2:两阶段压缩 | 2 | | | 43 | comp | | **S** | | 文件压缩标志位 | 0:关闭,1:一阶段压缩,2:两阶段压缩 | 2 | |
| 44 | walLevel | | **S** | | WAL级别 | 1:写wal, 但不执行fsync; 2:写wal, 而且执行fsync | 1 | | | 44 | walLevel | | **S** | | WAL级别 | 1:写wal, 但不执行fsync; 2:写wal, 而且执行fsync | 1 | |
| 45 | fsync | | **S** | 毫秒 | 当wal设置为2时,执行fsync的周期 | 最小为0,表示每次写入,立即执行fsync;最大为180000(三分钟) | 3000 | | | 45 | fsync | | **S** | 毫秒 | 当wal设置为2时,执行fsync的周期 | 最小为0,表示每次写入,立即执行fsync;最大为180000(三分钟) | 3000 | |
......
...@@ -124,7 +124,7 @@ TDengine 缺省的时间戳是毫秒精度,但通过在 CREATE DATABASE 时传 ...@@ -124,7 +124,7 @@ TDengine 缺省的时间戳是毫秒精度,但通过在 CREATE DATABASE 时传
```mysql ```mysql
ALTER DATABASE db_name QUORUM 2; ALTER DATABASE db_name QUORUM 2;
``` ```
QUORUM 参数是指数据写入成功所需要的确认数,取值范围 [1, 2]。对于异步复制,quorum 设为 1,具有 master 角色的虚拟节点自己确认即可。对于同步复制,需要至少大于等于 2。原则上,Quorum >= 1 并且 Quorum <= replica(副本数),这个参数在启动一个同步模块实例时需要提供。 QUORUM 参数是指数据写入成功所需要的确认数,取值范围 [1, 2]。对于异步复制,quorum 设为 1,具有 master 角色的虚拟节点自己确认即可。对于同步复制,quorum 设为 2。原则上,Quorum >= 1 并且 Quorum <= replica(副本数),这个参数在启动一个同步模块实例时需要提供。
```mysql ```mysql
ALTER DATABASE db_name BLOCKS 100; ALTER DATABASE db_name BLOCKS 100;
...@@ -719,7 +719,7 @@ Query OK, 1 row(s) in set (0.001091s) ...@@ -719,7 +719,7 @@ Query OK, 1 row(s) in set (0.001091s)
* 暂不支持含列名的四则运算表达式用于条件过滤算子(例如,不支持 `where a*2>6;`,但可以写 `where a>6/2;`)。 * 暂不支持含列名的四则运算表达式用于条件过滤算子(例如,不支持 `where a*2>6;`,但可以写 `where a>6/2;`)。
* 暂不支持含列名的四则运算表达式作为 SQL 函数的应用对象(例如,不支持 `select min(2*a) from t;`,但可以写 `select 2*min(a) from t;`)。 * 暂不支持含列名的四则运算表达式作为 SQL 函数的应用对象(例如,不支持 `select min(2*a) from t;`,但可以写 `select 2*min(a) from t;`)。
- WHERE 语句可以使用各种逻辑判断来过滤数字值,或使用通配符来过滤字符串。 - WHERE 语句可以使用各种逻辑判断来过滤数字值,或使用通配符来过滤字符串。
- 输出结果缺省按首列时间戳升序排序,但可以指定按降序排序( _c0 指首列时间戳)。使用 ORDER BY 对其他字段进行排序为非法操作 - 输出结果缺省按首列时间戳升序排序,但可以指定按降序排序( _c0 指首列时间戳)。使用 ORDER BY 对其他字段进行排序,排序结果顺序不确定
- 参数 LIMIT 控制输出条数,OFFSET 指定从第几条开始输出。LIMIT/OFFSET 对结果集的执行顺序在 ORDER BY 之后。且 `LIMIT 5 OFFSET 2` 可以简写为 `LIMIT 2, 5`。 - 参数 LIMIT 控制输出条数,OFFSET 指定从第几条开始输出。LIMIT/OFFSET 对结果集的执行顺序在 ORDER BY 之后。且 `LIMIT 5 OFFSET 2` 可以简写为 `LIMIT 2, 5`。
* 在有 GROUP BY 子句的情况下,LIMIT 参数控制的是每个分组中至多允许输出的条数。 * 在有 GROUP BY 子句的情况下,LIMIT 参数控制的是每个分组中至多允许输出的条数。
- 参数 SLIMIT 控制由 GROUP BY 指令划分的分组中,至多允许输出几个分组的数据。且 `SLIMIT 5 SOFFSET 2` 可以简写为 `SLIMIT 2, 5`。 - 参数 SLIMIT 控制由 GROUP BY 指令划分的分组中,至多允许输出几个分组的数据。且 `SLIMIT 5 SOFFSET 2` 可以简写为 `SLIMIT 2, 5`。
...@@ -743,7 +743,7 @@ Query OK, 1 row(s) in set (0.001091s) ...@@ -743,7 +743,7 @@ Query OK, 1 row(s) in set (0.001091s)
1. <> 算子也可以写为 != ,请注意,这个算子不能用于数据表第一列的 timestamp 字段。 1. <> 算子也可以写为 != ,请注意,这个算子不能用于数据表第一列的 timestamp 字段。
2. like 算子使用通配符字符串进行匹配检查。 2. like 算子使用通配符字符串进行匹配检查。
* 在通配符字符串中:'%'(百分号)匹配 0 到任意个字符;'\_'(下划线)匹配单个任意字符。 * 在通配符字符串中:'%'(百分号)匹配 0 到任意个字符;'\_'(下划线)匹配单个任意ASCII字符。
* 如果希望匹配字符串中原本就带有的 \_(下划线)字符,那么可以在通配符字符串中写作 `\_`,也即加一个反斜线来进行转义。(从 2.2.0.0 版本开始支持) * 如果希望匹配字符串中原本就带有的 \_(下划线)字符,那么可以在通配符字符串中写作 `\_`,也即加一个反斜线来进行转义。(从 2.2.0.0 版本开始支持)
* 通配符字符串最长不能超过 20 字节。(从 2.1.6.1 版本开始,通配符字符串的长度放宽到了 100 字节,并可以通过 taos.cfg 中的 maxWildCardsLength 参数来配置这一长度限制。但不建议使用太长的通配符字符串,将有可能严重影响 LIKE 操作的执行性能。) * 通配符字符串最长不能超过 20 字节。(从 2.1.6.1 版本开始,通配符字符串的长度放宽到了 100 字节,并可以通过 taos.cfg 中的 maxWildCardsLength 参数来配置这一长度限制。但不建议使用太长的通配符字符串,将有可能严重影响 LIKE 操作的执行性能。)
3. 同时进行多个字段的范围过滤,需要使用关键词 AND 来连接不同的查询条件,暂不支持 OR 连接的不同列之间的查询过滤条件。 3. 同时进行多个字段的范围过滤,需要使用关键词 AND 来连接不同的查询条件,暂不支持 OR 连接的不同列之间的查询过滤条件。
......
...@@ -40,7 +40,7 @@ IT 运维监测数据通常都是对时间特性比较敏感的数据,例如 ...@@ -40,7 +40,7 @@ IT 运维监测数据通常都是对时间特性比较敏感的数据,例如
``` ```
### 配置 collectd ### 配置 collectd
在 /etc/collectd/collectd.conf 文件中增加如下内容,其中 host 和 port 请填写 TDengine 和 BLM3 配置的实际值: 在 /etc/collectd/collectd.conf 文件中增加如下内容,其中 host 和 port 请填写 TDengine 和 Taos Adapter 配置的实际值:
``` ```
LoadPlugin network LoadPlugin network
<Plugin network> <Plugin network>
...@@ -51,7 +51,7 @@ sudo systemctl start collectd ...@@ -51,7 +51,7 @@ sudo systemctl start collectd
``` ```
### 配置 StatsD ### 配置 StatsD
在 config.js 文件中增加如下内容后启动 StatsD,其中 host 和 port 请填写 TDengine 和 BLM3 配置的实际值: 在 config.js 文件中增加如下内容后启动 StatsD,其中 host 和 port 请填写 TDengine 和 Taos Adapter 配置的实际值:
``` ```
backends 部分添加 "./backends/repeater" backends 部分添加 "./backends/repeater"
repeater 部分添加 { host:'<TDengine server/cluster host>', port: <port for StatsD>} repeater 部分添加 { host:'<TDengine server/cluster host>', port: <port for StatsD>}
......
此差异已折叠。
...@@ -154,7 +154,7 @@ The complete list of taosdemo command-line arguments can be displayed via taosde ...@@ -154,7 +154,7 @@ The complete list of taosdemo command-line arguments can be displayed via taosde
``` ```
$ taosdemo --help $ taosdemo --help
-f, --file=FILE The meta file to the execution procedure. -f, --file=FILE The meta file to the execution procedure. Currently, we support standard UTF-8 (without BOM) encoded files only.
-u, --user=USER The user name to use when connecting to the server. -u, --user=USER The user name to use when connecting to the server.
-p, --password The password to use when connecting to the server. -p, --password The password to use when connecting to the server.
-c, --config-dir=CONFIG_DIR Configuration directory. -c, --config-dir=CONFIG_DIR Configuration directory.
......
...@@ -299,8 +299,8 @@ keepColumnName 1 ...@@ -299,8 +299,8 @@ keepColumnName 1
# percent of redundant data in tsdb meta will compact meta data,0 means donot compact # percent of redundant data in tsdb meta will compact meta data,0 means donot compact
# tsdbMetaCompactRatio 0 # tsdbMetaCompactRatio 0
# default string type used for storing JSON String, options can be binary/nchar, default is binary # default string type used for storing JSON String, options can be binary/nchar, default is nchar
# defaultJSONStrType binary # defaultJSONStrType nchar
# force TCP transmission # force TCP transmission
# rpcForceTcp 0 # rpcForceTcp 0
......
...@@ -45,10 +45,10 @@ mkdir -p ${pkg_dir}${install_home_path}/script ...@@ -45,10 +45,10 @@ mkdir -p ${pkg_dir}${install_home_path}/script
cp ${compile_dir}/../packaging/cfg/taos.cfg ${pkg_dir}${install_home_path}/cfg cp ${compile_dir}/../packaging/cfg/taos.cfg ${pkg_dir}${install_home_path}/cfg
if [ -f "${compile_dir}/test/cfg/taosadapter.toml" ]; then if [ -f "${compile_dir}/test/cfg/taosadapter.toml" ]; then
cp ${compile_dir}/test/cfg/taosadapter.toml ${pkg_dir}${install_home_path}/cfg cp ${compile_dir}/test/cfg/taosadapter.toml ${pkg_dir}${install_home_path}/cfg || :
fi fi
if [ -f "${compile_dir}/test/cfg/taosadapter.service" ]; then if [ -f "${compile_dir}/test/cfg/taosadapter.service" ]; then
cp ${compile_dir}/test/cfg/taosadapter.service ${pkg_dir}${install_home_path}/cfg ||: cp ${compile_dir}/test/cfg/taosadapter.service ${pkg_dir}${install_home_path}/cfg || :
fi fi
cp ${compile_dir}/../packaging/deb/taosd ${pkg_dir}${install_home_path}/init.d cp ${compile_dir}/../packaging/deb/taosd ${pkg_dir}${install_home_path}/init.d
......
...@@ -194,6 +194,7 @@ fi ...@@ -194,6 +194,7 @@ fi
if [[ "$dbName" == "pro" ]]; then if [[ "$dbName" == "pro" ]]; then
sed -i "s/taos config/prodb config/g" ${top_dir}/src/util/src/tconfig.c sed -i "s/taos config/prodb config/g" ${top_dir}/src/util/src/tconfig.c
sed -i "s/TDengine/ProDB/g" ${top_dir}/src/dnode/src/dnodeSystem.c
fi fi
echo "build ${pagMode} package ..." echo "build ${pagMode} package ..."
...@@ -213,7 +214,12 @@ else ...@@ -213,7 +214,12 @@ else
exit 1 exit 1
fi fi
make -j8 && ${csudo} make install if [[ "$allocator" == "jemalloc" ]]; then
# jemalloc need compile first, so disable parallel build
make V=1 && ${csudo} make install
else
make -j8 && ${csudo} make install
fi
cd ${curr_dir} cd ${curr_dir}
......
...@@ -757,8 +757,12 @@ function install_service_on_systemd() { ...@@ -757,8 +757,12 @@ function install_service_on_systemd() {
} }
function install_taosadapter_service() { function install_taosadapter_service() {
[ -f ${script_dir}/cfg/taosadapter.service ] &&\ if ((${service_mod}==0)); then
${csudo} cp ${script_dir}/cfg/taosadapter.service ${service_config_dir}/ [ -f ${script_dir}/cfg/taosadapter.service ] &&\
${csudo} cp ${script_dir}/cfg/taosadapter.service \
${service_config_dir}/ || :
${csudo} systemctl daemon-reload
fi
} }
function install_service() { function install_service() {
......
...@@ -62,12 +62,14 @@ NC='\033[0m' ...@@ -62,12 +62,14 @@ NC='\033[0m'
csudo="" csudo=""
service_mod=2
os_type=0
if [ "$osType" != "Darwin" ]; then if [ "$osType" != "Darwin" ]; then
if command -v sudo > /dev/null; then if command -v sudo > /dev/null; then
csudo="sudo" csudo="sudo"
fi fi
initd_mod=0 initd_mod=0
service_mod=2
if pidof systemd &> /dev/null; then if pidof systemd &> /dev/null; then
service_mod=0 service_mod=0
elif $(which service &> /dev/null); then elif $(which service &> /dev/null); then
...@@ -91,7 +93,6 @@ if [ "$osType" != "Darwin" ]; then ...@@ -91,7 +93,6 @@ if [ "$osType" != "Darwin" ]; then
#osinfo=$(awk -F= '/^NAME/{print $2}' /etc/os-release) #osinfo=$(awk -F= '/^NAME/{print $2}' /etc/os-release)
osinfo=$(cat /etc/os-release | grep "NAME" | cut -d '"' -f2) osinfo=$(cat /etc/os-release | grep "NAME" | cut -d '"' -f2)
#echo "osinfo: ${osinfo}" #echo "osinfo: ${osinfo}"
os_type=0
if echo $osinfo | grep -qwi "ubuntu" ; then if echo $osinfo | grep -qwi "ubuntu" ; then
echo "this is ubuntu system" echo "this is ubuntu system"
os_type=1 os_type=1
...@@ -122,7 +123,8 @@ function kill_taosadapter() { ...@@ -122,7 +123,8 @@ function kill_taosadapter() {
} }
function kill_taosd() { function kill_taosd() {
pid=$(ps -ef | grep "taosd" | grep -v "grep" | awk '{print $2}') ps -ef | grep "taosd"
pid=$(ps -ef | grep -w "taosd" | grep -v "grep" | awk '{print $2}')
if [ -n "$pid" ]; then if [ -n "$pid" ]; then
${csudo} kill -9 $pid || : ${csudo} kill -9 $pid || :
fi fi
...@@ -202,31 +204,31 @@ function install_jemalloc() { ...@@ -202,31 +204,31 @@ function install_jemalloc() {
/usr/bin/install -c -d /usr/local/bin /usr/bin/install -c -d /usr/local/bin
if [ -f "${binary_dir}/build/bin/jemalloc-config" ]; then if [ -f "${binary_dir}/build/bin/jemalloc-config" ]; then
/usr/bin/install -c -m 755 ${binary_dir}/build/bin/jemalloc-config /usr/local/bin ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/bin/jemalloc-config /usr/local/bin
fi fi
if [ -f "${binary_dir}/build/bin/jemalloc.sh" ]; then if [ -f "${binary_dir}/build/bin/jemalloc.sh" ]; then
/usr/bin/install -c -m 755 ${binary_dir}/build/bin/jemalloc.sh /usr/local/bin ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/bin/jemalloc.sh /usr/local/bin
fi fi
if [ -f "${binary_dir}/build/bin/jeprof" ]; then if [ -f "${binary_dir}/build/bin/jeprof" ]; then
/usr/bin/install -c -m 755 ${binary_dir}/build/bin/jeprof /usr/local/bin ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/bin/jeprof /usr/local/bin
fi fi
if [ -f "${binary_dir}/build/include/jemalloc/jemalloc.h" ]; then if [ -f "${binary_dir}/build/include/jemalloc/jemalloc.h" ]; then
/usr/bin/install -c -d /usr/local/include/jemalloc ${csudo} /usr/bin/install -c -d /usr/local/include/jemalloc
/usr/bin/install -c -m 644 ${binary_dir}/build/include/jemalloc/jemalloc.h\ ${csudo} /usr/bin/install -c -m 644 ${binary_dir}/build/include/jemalloc/jemalloc.h\
/usr/local/include/jemalloc /usr/local/include/jemalloc
fi fi
if [ -f "${binary_dir}/build/lib/libjemalloc.so.2" ]; then if [ -f "${binary_dir}/build/lib/libjemalloc.so.2" ]; then
/usr/bin/install -c -d /usr/local/lib ${csudo} /usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 755 ${binary_dir}/build/lib/libjemalloc.so.2 /usr/local/lib ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/lib/libjemalloc.so.2 /usr/local/lib
ln -sf libjemalloc.so.2 /usr/local/lib/libjemalloc.so ${csudo} ln -sf libjemalloc.so.2 /usr/local/lib/libjemalloc.so
/usr/bin/install -c -d /usr/local/lib ${csudo} /usr/bin/install -c -d /usr/local/lib
[ -f ${binary_dir}/build/lib/libjemalloc.a ] && [ -f ${binary_dir}/build/lib/libjemalloc.a ] &&
/usr/bin/install -c -m 755 ${binary_dir}/build/lib/libjemalloc.a /usr/local/lib ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/lib/libjemalloc.a /usr/local/lib
[ -f ${binary_dir}/build/lib/libjemalloc_pic.a ] && [ -f ${binary_dir}/build/lib/libjemalloc_pic.a ] &&
/usr/bin/install -c -m 755 ${binary_dir}/build/lib/libjemalloc_pic.a /usr/local/lib ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/lib/libjemalloc_pic.a /usr/local/lib
if [ -f "${binary_dir}/build/lib/pkgconfig/jemalloc.pc" ]; then if [ -f "${binary_dir}/build/lib/pkgconfig/jemalloc.pc" ]; then
/usr/bin/install -c -d /usr/local/lib/pkgconfig ${csudo} /usr/bin/install -c -d /usr/local/lib/pkgconfig
/usr/bin/install -c -m 644 ${binary_dir}/build/lib/pkgconfig/jemalloc.pc\ ${csudo} /usr/bin/install -c -m 644 ${binary_dir}/build/lib/pkgconfig/jemalloc.pc\
/usr/local/lib/pkgconfig /usr/local/lib/pkgconfig
fi fi
if [ -d /etc/ld.so.conf.d ]; then if [ -d /etc/ld.so.conf.d ]; then
...@@ -237,29 +239,28 @@ function install_jemalloc() { ...@@ -237,29 +239,28 @@ function install_jemalloc() {
fi fi
fi fi
if [ -f "${binary_dir}/build/share/doc/jemalloc/jemalloc.html" ]; then if [ -f "${binary_dir}/build/share/doc/jemalloc/jemalloc.html" ]; then
/usr/bin/install -c -d /usr/local/share/doc/jemalloc ${csudo} /usr/bin/install -c -d /usr/local/share/doc/jemalloc
/usr/bin/install -c -m 644 ${binary_dir}/build/share/doc/jemalloc/jemalloc.html\ ${csudo} /usr/bin/install -c -m 644 ${binary_dir}/build/share/doc/jemalloc/jemalloc.html\
/usr/local/share/doc/jemalloc /usr/local/share/doc/jemalloc
fi fi
if [ -f "${binary_dir}/build/share/man/man3/jemalloc.3" ]; then if [ -f "${binary_dir}/build/share/man/man3/jemalloc.3" ]; then
/usr/bin/install -c -d /usr/local/share/man/man3 ${csudo} /usr/bin/install -c -d /usr/local/share/man/man3
/usr/bin/install -c -m 644 ${binary_dir}/build/share/man/man3/jemalloc.3\ ${csudo} /usr/bin/install -c -m 644 ${binary_dir}/build/share/man/man3/jemalloc.3\
/usr/local/share/man/man3 /usr/local/share/man/man3
fi fi
fi fi
} }
function install_avro() { function install_avro() {
if [ "$osType" != "Darwin" ]; then if [ "$osType" != "Darwin" ]; then
if [ -f "${binary_dir}/build/$1/libavro.so.23.0.0" ]; then if [ -f "${binary_dir}/build/$1/libavro.so.23.0.0" ]; then
/usr/bin/install -c -d /usr/local/$1 ${csudo} /usr/bin/install -c -d /usr/local/$1
/usr/bin/install -c -m 755 ${binary_dir}/build/$1/libavro.so.23.0.0 /usr/local/$1 ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/$1/libavro.so.23.0.0 /usr/local/$1
ln -sf libavro.so.23.0.0 /usr/local/$1/libavro.so.23 ${csudo} ln -sf libavro.so.23.0.0 /usr/local/$1/libavro.so.23
ln -sf libavro.so.23 /usr/local/$1/libavro.so ${csudo} ln -sf libavro.so.23 /usr/local/$1/libavro.so
/usr/bin/install -c -d /usr/local/$1 ${csudo} /usr/bin/install -c -d /usr/local/$1
[ -f ${binary_dir}/build/$1/libavro.a ] && [ -f ${binary_dir}/build/$1/libavro.a ] &&
/usr/bin/install -c -m 755 ${binary_dir}/build/$1/libavro.a /usr/local/$1 ${csudo} /usr/bin/install -c -m 755 ${binary_dir}/build/$1/libavro.a /usr/local/$1
if [ -d /etc/ld.so.conf.d ]; then if [ -d /etc/ld.so.conf.d ]; then
echo "/usr/local/$1" | ${csudo} tee /etc/ld.so.conf.d/libavro.conf echo "/usr/local/$1" | ${csudo} tee /etc/ld.so.conf.d/libavro.conf
...@@ -455,11 +456,11 @@ function install_service_on_sysvinit() { ...@@ -455,11 +456,11 @@ function install_service_on_sysvinit() {
# Install taosd service # Install taosd service
if ((${os_type}==1)); then if ((${os_type}==1)); then
${csudo} cp -f ${script_dir}/../deb/taosd ${install_main_dir}/init.d ${csudo} cp -f ${script_dir}/../deb/taosd ${install_main_dir}/init.d
${csudo} cp ${script_dir}/../deb/taosd ${service_config_dir} && ${csudo} chmod a+x ${service_config_dir}/taosd ${csudo} cp ${script_dir}/../deb/taosd ${service_config_dir} && ${csudo} chmod a+x ${service_config_dir}/taosd
elif ((${os_type}==2)); then elif ((${os_type}==2)); then
${csudo} cp -f ${script_dir}/../rpm/taosd ${install_main_dir}/init.d ${csudo} cp -f ${script_dir}/../rpm/taosd ${install_main_dir}/init.d
${csudo} cp ${script_dir}/../rpm/taosd ${service_config_dir} && ${csudo} chmod a+x ${service_config_dir}/taosd ${csudo} cp ${script_dir}/../rpm/taosd ${service_config_dir} && ${csudo} chmod a+x ${service_config_dir}/taosd
fi fi
#restart_config_str="taos:2345:respawn:${service_config_dir}/taosd start" #restart_config_str="taos:2345:respawn:${service_config_dir}/taosd start"
...@@ -523,9 +524,8 @@ function install_taosadapter_service() { ...@@ -523,9 +524,8 @@ function install_taosadapter_service() {
if ((${service_mod}==0)); then if ((${service_mod}==0)); then
[ -f ${binary_dir}/test/cfg/taosadapter.service ] &&\ [ -f ${binary_dir}/test/cfg/taosadapter.service ] &&\
${csudo} cp ${binary_dir}/test/cfg/taosadapter.service\ ${csudo} cp ${binary_dir}/test/cfg/taosadapter.service\
${service_config_dir}/ || : ${service_config_dir}/ || :
else ${csudo} systemctl daemon-reload
kill_taosadapter
fi fi
} }
...@@ -544,7 +544,6 @@ function update_TDengine() { ...@@ -544,7 +544,6 @@ function update_TDengine() {
echo -e "${GREEN}Start to update TDengine...${NC}" echo -e "${GREEN}Start to update TDengine...${NC}"
# Stop the service if running # Stop the service if running
if [ "$osType" != "Darwin" ]; then
if pidof taosd &> /dev/null; then if pidof taosd &> /dev/null; then
if ((${service_mod}==0)); then if ((${service_mod}==0)); then
${csudo} systemctl stop taosd || : ${csudo} systemctl stop taosd || :
...@@ -556,7 +555,6 @@ function update_TDengine() { ...@@ -556,7 +555,6 @@ function update_TDengine() {
fi fi
sleep 1 sleep 1
fi fi
fi
install_main_path install_main_path
...@@ -567,50 +565,35 @@ function update_TDengine() { ...@@ -567,50 +565,35 @@ function update_TDengine() {
install_examples install_examples
install_bin install_bin
if [ "$osType" != "Darwin" ]; then install_service
install_service install_taosadapter_service
install_taosadapter_service
fi
install_config install_config
install_taosadapter_config install_taosadapter_config
if [ "$osType" != "Darwin" ]; then echo
echo echo -e "\033[44;32;1mTDengine is updated successfully!${NC}"
echo -e "\033[44;32;1mTDengine is updated successfully!${NC}" echo
echo
echo -e "${GREEN_DARK}To configure TDengine ${NC}: edit /etc/taos/taos.cfg"
echo -e "${GREEN_DARK}To configure taosadapter (if has) ${NC}: edit /etc/taos/taosadapter.toml"
if ((${service_mod}==0)); then
echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} systemctl start taosd${NC}"
elif ((${service_mod}==1)); then
echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} service taosd start${NC}"
else
echo -e "${GREEN_DARK}To start TDengine ${NC}: ./taosd${NC}"
fi
echo -e "${GREEN_DARK}To access TDengine ${NC}: use ${GREEN_UNDERLINE}taos${NC} in shell${NC}" echo -e "${GREEN_DARK}To configure TDengine ${NC}: edit /etc/taos/taos.cfg"
echo echo -e "${GREEN_DARK}To configure Taos Adapter (if has) ${NC}: edit /etc/taos/taosadapter.toml"
echo -e "\033[44;32;1mTDengine is updated successfully!${NC}" if ((${service_mod}==0)); then
echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} systemctl start taosd${NC}"
elif ((${service_mod}==1)); then
echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} service taosd start${NC}"
else else
echo echo -e "${GREEN_DARK}To start Taos Adapter (if has)${NC}: taosadapter &${NC}"
echo -e "\033[44;32;1mTDengine Client is updated successfully!${NC}" echo -e "${GREEN_DARK}To start TDengine ${NC}: taosd${NC}"
echo
echo -e "${GREEN_DARK}To access TDengine Client ${NC}: use ${GREEN_UNDERLINE}taos${NC} in shell${NC}"
echo
echo -e "\033[44;32;1mTDengine Client is updated successfully!${NC}"
fi fi
echo -e "${GREEN_DARK}To access TDengine ${NC}: use ${GREEN_UNDERLINE}taos${NC} in shell${NC}"
echo
echo -e "\033[44;32;1mTDengine is updated successfully!${NC}"
} }
function install_TDengine() { function install_TDengine() {
# Start to install # Start to install
if [ "$osType" != "Darwin" ]; then echo -e "${GREEN}Start to install TDengine...${NC}"
echo -e "${GREEN}Start to install TDEngine...${NC}"
else
echo -e "${GREEN}Start to install TDEngine Client ...${NC}"
fi
install_main_path install_main_path
...@@ -622,37 +605,29 @@ function install_TDengine() { ...@@ -622,37 +605,29 @@ function install_TDengine() {
install_examples install_examples
install_bin install_bin
if [ "$osType" != "Darwin" ]; then install_service
install_service install_taosadapter_service
install_taosadapter_service
fi
install_config install_config
install_taosadapter_config install_taosadapter_config
if [ "$osType" != "Darwin" ]; then # Ask if to start the service
# Ask if to start the service echo
echo echo -e "\033[44;32;1mTDengine is installed successfully!${NC}"
echo -e "\033[44;32;1mTDengine is installed successfully!${NC}" echo
echo echo -e "${GREEN_DARK}To configure TDengine ${NC}: edit /etc/taos/taos.cfg"
echo -e "${GREEN_DARK}To configure TDengine ${NC}: edit /etc/taos/taos.cfg" echo -e "${GREEN_DARK}To configure taosadapter (if has) ${NC}: edit /etc/taos/taosadapter.toml"
echo -e "${GREEN_DARK}To configure taosadapter (if has) ${NC}: edit /etc/taos/taosadapter.toml" if ((${service_mod}==0)); then
if ((${service_mod}==0)); then echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} systemctl start taosd${NC}"
echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} systemctl start taosd${NC}" elif ((${service_mod}==1)); then
elif ((${service_mod}==1)); then echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} service taosd start${NC}"
echo -e "${GREEN_DARK}To start TDengine ${NC}: ${csudo} service taosd start${NC}"
else
echo -e "${GREEN_DARK}To start TDengine ${NC}: ./taosd${NC}"
fi
echo -e "${GREEN_DARK}To access TDengine ${NC}: use ${GREEN_UNDERLINE}taos${NC} in shell${NC}"
echo
echo -e "\033[44;32;1mTDengine is installed successfully!${NC}"
else else
echo -e "${GREEN_DARK}To access TDengine ${NC}: use ${GREEN_UNDERLINE}taos${NC} in shell${NC}" echo -e "${GREEN_DARK}To start TDengine ${NC}: ./taosd${NC}"
echo
echo -e "\033[44;32;1mTDengine Client is installed successfully!${NC}"
fi fi
echo -e "${GREEN_DARK}To access TDengine ${NC}: use ${GREEN_UNDERLINE}taos${NC} in shell${NC}"
echo
echo -e "\033[44;32;1mTDengine is installed successfully!${NC}"
} }
## ==============================Main program starts from here============================ ## ==============================Main program starts from here============================
......
...@@ -78,7 +78,13 @@ mkdir -p ${install_dir} ...@@ -78,7 +78,13 @@ mkdir -p ${install_dir}
mkdir -p ${install_dir}/inc && cp ${header_files} ${install_dir}/inc mkdir -p ${install_dir}/inc && cp ${header_files} ${install_dir}/inc
mkdir -p ${install_dir}/cfg && cp ${cfg_dir}/taos.cfg ${install_dir}/cfg/taos.cfg mkdir -p ${install_dir}/cfg && cp ${cfg_dir}/taos.cfg ${install_dir}/cfg/taos.cfg
[ -f ${cfg_dir}/taosadapter.toml ] && cp ${cfg_dir}/taosadapter.toml ${install_dir}/cfg/taosadapter.toml if [ -f "${compile_dir}/test/cfg/taosadapter.toml" ]; then
cp ${compile_dir}/test/cfg/taosadapter.toml ${install_dir}/cfg || :
fi
if [ -f "${compile_dir}/test/cfg/taosadapter.service" ]; then
cp ${compile_dir}/test/cfg/taosadapter.service ${install_dir}/cfg || :
fi
mkdir -p ${install_dir}/bin && cp ${bin_files} ${install_dir}/bin && chmod a+x ${install_dir}/bin/* || : mkdir -p ${install_dir}/bin && cp ${bin_files} ${install_dir}/bin && chmod a+x ${install_dir}/bin/* || :
mkdir -p ${install_dir}/init.d && cp ${init_file_deb} ${install_dir}/init.d/taosd.deb mkdir -p ${install_dir}/init.d && cp ${init_file_deb} ${install_dir}/init.d/taosd.deb
......
...@@ -467,7 +467,12 @@ function install_service_on_systemd() { ...@@ -467,7 +467,12 @@ function install_service_on_systemd() {
} }
function install_taosadapter_service() { function install_taosadapter_service() {
[ -f ${cfg_dir}/taosadapter.service ] && ${csudo} cp ${cfg_dir}/taosadapter.service ${service_config_dir} if ((${service_mod}==0)); then
[ -f ${script_dir}/cfg/taosadapter.service ] &&\
${csudo} cp ${script_dir}/cfg/taosadapter.service \
${service_config_dir}/ || :
${csudo} systemctl daemon-reload
fi
} }
function install_service() { function install_service() {
......
...@@ -119,7 +119,8 @@ typedef struct SBlockKeyInfo { ...@@ -119,7 +119,8 @@ typedef struct SBlockKeyInfo {
int32_t converToStr(char *str, int type, void *buf, int32_t bufSize, int32_t *len); int32_t converToStr(char *str, int type, void *buf, int32_t bufSize, int32_t *len);
int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, SName* name, STableMeta* pTableMeta, STableDataBlocks** dataBlocks); int32_t tscCreateDataBlock(size_t initialSize, int32_t rowSize, int32_t startOffset, SName* name, STableMeta* pTableMeta, STableDataBlocks** dataBlocks);
void tscDestroyDataBlock(SSqlObj *pSql, STableDataBlocks* pDataBlock, bool removeMeta); int32_t tscCreateDataBlockData(STableDataBlocks* dataBuf, size_t defaultSize, int32_t rowSize, int32_t startOffset);
void tscDestroyDataBlock(SSqlObj *pSql, STableDataBlocks* pDataBlock, bool removeMeta);
void tscSortRemoveDataBlockDupRowsRaw(STableDataBlocks* dataBuf); void tscSortRemoveDataBlockDupRowsRaw(STableDataBlocks* dataBuf);
int tscSortRemoveDataBlockDupRows(STableDataBlocks* dataBuf, SBlockKeyInfo* pBlkKeyInfo); int tscSortRemoveDataBlockDupRows(STableDataBlocks* dataBuf, SBlockKeyInfo* pBlkKeyInfo);
int32_t tsSetBlockInfo(SSubmitBlk *pBlocks, const STableMeta *pTableMeta, int32_t numOfRows); int32_t tsSetBlockInfo(SSubmitBlk *pBlocks, const STableMeta *pTableMeta, int32_t numOfRows);
......
...@@ -237,7 +237,7 @@ void taos_fetch_rows_a(TAOS_RES *tres, __async_cb_func_t fp, void *param) { ...@@ -237,7 +237,7 @@ void taos_fetch_rows_a(TAOS_RES *tres, __async_cb_func_t fp, void *param) {
return; return;
} }
if (pRes->qId == 0) { if (pRes->qId == 0 && pSql->cmd.command != TSDB_SQL_RETRIEVE_EMPTY_RESULT) {
tscError("qhandle is invalid"); tscError("qhandle is invalid");
pRes->code = TSDB_CODE_TSC_INVALID_QHANDLE; pRes->code = TSDB_CODE_TSC_INVALID_QHANDLE;
tscAsyncResultOnError(pSql); tscAsyncResultOnError(pSql);
......
...@@ -967,7 +967,6 @@ SSDataBlock* doGlobalAggregate(void* param, bool* newgroup) { ...@@ -967,7 +967,6 @@ SSDataBlock* doGlobalAggregate(void* param, bool* newgroup) {
if (pOperator->pRuntimeEnv->pQueryAttr->order.order == TSDB_ORDER_DESC) { if (pOperator->pRuntimeEnv->pQueryAttr->order.order == TSDB_ORDER_DESC) {
SWAP(w->skey, w->ekey, TSKEY); SWAP(w->skey, w->ekey, TSKEY);
assert(w->skey <= w->ekey);
} }
} }
} }
......
...@@ -314,8 +314,6 @@ int32_t tsParseOneColumn(SSchema *pSchema, SStrToken *pToken, char *payload, cha ...@@ -314,8 +314,6 @@ int32_t tsParseOneColumn(SSchema *pSchema, SStrToken *pToken, char *payload, cha
ret = tStrToInteger(pToken->z, pToken->type, pToken->n, &iv, false); ret = tStrToInteger(pToken->z, pToken->type, pToken->n, &iv, false);
if (ret != TSDB_CODE_SUCCESS) { if (ret != TSDB_CODE_SUCCESS) {
return tscInvalidOperationMsg(msg, "invalid unsigned bigint data", pToken->z); return tscInvalidOperationMsg(msg, "invalid unsigned bigint data", pToken->z);
} else if (!IS_VALID_UBIGINT((uint64_t)iv)) {
return tscInvalidOperationMsg(msg, "unsigned bigint data overflow", pToken->z);
} }
*((uint64_t *)payload) = iv; *((uint64_t *)payload) = iv;
...@@ -1419,6 +1417,11 @@ int tsParseInsertSql(SSqlObj *pSql) { ...@@ -1419,6 +1417,11 @@ int tsParseInsertSql(SSqlObj *pSql) {
goto _clean; goto _clean;
} }
if (sToken.type == TK_ILLEGAL) { // ,,,, like => insert into t values(now,1),,,,(now+1s,2);
code = tscSQLSyntaxErrMsg(pInsertParam->msg, NULL, str);
goto _clean;
}
/* /*
* if no data has been generated during parsing the sql string, error msg will return * if no data has been generated during parsing the sql string, error msg will return
* Otherwise, create the first submit block and submit to virtual node. * Otherwise, create the first submit block and submit to virtual node.
......
...@@ -195,8 +195,9 @@ static int32_t parseTelnetMetricValue(TAOS_SML_KV **pKVs, int *num_kvs, const ch ...@@ -195,8 +195,9 @@ static int32_t parseTelnetMetricValue(TAOS_SML_KV **pKVs, int *num_kvs, const ch
} }
tfree(value); tfree(value);
pVal->key = tcalloc(sizeof(key), 1); pVal->key = tcalloc(sizeof(key) + TS_ESCAPE_CHAR_SIZE, 1);
memcpy(pVal->key, key, sizeof(key)); memcpy(pVal->key, key, sizeof(key));
addEscapeCharToString(pVal->key, (int32_t)strlen(pVal->key));
*num_kvs += 1; *num_kvs += 1;
*index = cur + 1; *index = cur + 1;
...@@ -877,8 +878,9 @@ static int32_t parseMetricValueFromJSON(cJSON *root, TAOS_SML_KV **pKVs, int *nu ...@@ -877,8 +878,9 @@ static int32_t parseMetricValueFromJSON(cJSON *root, TAOS_SML_KV **pKVs, int *nu
return ret; return ret;
} }
pVal->key = tcalloc(sizeof(key), 1); pVal->key = tcalloc(sizeof(key) + TS_ESCAPE_CHAR_SIZE, 1);
memcpy(pVal->key, key, sizeof(key)); memcpy(pVal->key, key, sizeof(key));
addEscapeCharToString(pVal->key, (int32_t)strlen(pVal->key));
*num_kvs += 1; *num_kvs += 1;
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
......
...@@ -48,12 +48,14 @@ typedef struct SMultiTbStmt { ...@@ -48,12 +48,14 @@ typedef struct SMultiTbStmt {
bool nameSet; bool nameSet;
bool tagSet; bool tagSet;
bool subSet; bool subSet;
bool tagColSet;
uint64_t currentUid; uint64_t currentUid;
char *sqlstr; char *sqlstr;
uint32_t tbNum; uint32_t tbNum;
SStrToken tbname; SStrToken tbname;
SStrToken stbname; SStrToken stbname;
SStrToken values; SStrToken values;
SStrToken tagCols;
SArray *tags; SArray *tags;
STableDataBlocks *lastBlock; STableDataBlocks *lastBlock;
SHashObj *pTableHash; SHashObj *pTableHash;
...@@ -1250,6 +1252,12 @@ static void insertBatchClean(STscStmt* pStmt) { ...@@ -1250,6 +1252,12 @@ static void insertBatchClean(STscStmt* pStmt) {
pCmd->insertParam.pDataBlocks = tscDestroyBlockArrayList(pSql, pCmd->insertParam.pDataBlocks); pCmd->insertParam.pDataBlocks = tscDestroyBlockArrayList(pSql, pCmd->insertParam.pDataBlocks);
pCmd->insertParam.numOfTables = 0; pCmd->insertParam.numOfTables = 0;
STableDataBlocks** p = taosHashIterate(pCmd->insertParam.pTableBlockHashList, NULL);
while(p) {
tfree((*p)->pData);
p = taosHashIterate(pCmd->insertParam.pTableBlockHashList, p);
}
taosHashClear(pCmd->insertParam.pTableBlockHashList); taosHashClear(pCmd->insertParam.pTableBlockHashList);
tscFreeSqlResult(pSql); tscFreeSqlResult(pSql);
tscFreeSubobj(pSql); tscFreeSubobj(pSql);
...@@ -1343,9 +1351,40 @@ int stmtParseInsertTbTags(SSqlObj* pSql, STscStmt* pStmt) { ...@@ -1343,9 +1351,40 @@ int stmtParseInsertTbTags(SSqlObj* pSql, STscStmt* pStmt) {
pStmt->mtb.stbname = sToken; pStmt->mtb.stbname = sToken;
sToken = tStrGetToken(pCmd->insertParam.sql, &index, false); sToken = tStrGetToken(pCmd->insertParam.sql, &index, false);
if (sToken.n <= 0 || sToken.type != TK_TAGS) { if (sToken.n <= 0 || ((sToken.type != TK_TAGS) && (sToken.type != TK_LP))) {
tscError("keyword TAGS expected, sql:%s", pCmd->insertParam.sql); tscError("invalid token, sql:%s", pCmd->insertParam.sql);
return tscSQLSyntaxErrMsg(pCmd->payload, "keyword TAGS expected", sToken.z ? sToken.z : pCmd->insertParam.sql); return tscSQLSyntaxErrMsg(pCmd->payload, "invalid token", sToken.z ? sToken.z : pCmd->insertParam.sql);
}
// ... (tag_col_list) TAGS(tag_val_list) ...
int32_t tagColsCnt = 0;
if (sToken.type == TK_LP) {
pStmt->mtb.tagColSet = true;
pStmt->mtb.tagCols = sToken;
int32_t tagColsStart = index;
while (1) {
sToken = tStrGetToken(pCmd->insertParam.sql, &index, false);
if (sToken.type == TK_ILLEGAL) {
return tscSQLSyntaxErrMsg(pCmd->payload, "unrecognized token", sToken.z);
}
if (sToken.type == TK_ID) {
++tagColsCnt;
}
if (sToken.type == TK_RP) {
break;
}
}
if (tagColsCnt == 0) {
tscError("tag column list expected, sql:%s", pCmd->insertParam.sql);
return tscSQLSyntaxErrMsg(pCmd->payload, "tag column list expected", pCmd->insertParam.sql);
}
pStmt->mtb.tagCols.n = index - tagColsStart + 1;
sToken = tStrGetToken(pCmd->insertParam.sql, &index, false);
if (sToken.n <= 0 || sToken.type != TK_TAGS) {
tscError("keyword TAGS expected, sql:%s", pCmd->insertParam.sql);
return tscSQLSyntaxErrMsg(pCmd->payload, "keyword TAGS expected", sToken.z ? sToken.z : pCmd->insertParam.sql);
}
} }
sToken = tStrGetToken(pCmd->insertParam.sql, &index, false); sToken = tStrGetToken(pCmd->insertParam.sql, &index, false);
...@@ -1385,6 +1424,11 @@ int stmtParseInsertTbTags(SSqlObj* pSql, STscStmt* pStmt) { ...@@ -1385,6 +1424,11 @@ int stmtParseInsertTbTags(SSqlObj* pSql, STscStmt* pStmt) {
return tscSQLSyntaxErrMsg(pCmd->payload, "no tags", pCmd->insertParam.sql); return tscSQLSyntaxErrMsg(pCmd->payload, "no tags", pCmd->insertParam.sql);
} }
if (tagColsCnt > 0 && taosArrayGetSize(pStmt->mtb.tags) != tagColsCnt) {
tscError("not match tags, sql:%s", pCmd->insertParam.sql);
return tscSQLSyntaxErrMsg(pCmd->payload, "not match tags", pCmd->insertParam.sql);
}
sToken = tStrGetToken(pCmd->insertParam.sql, &index, false); sToken = tStrGetToken(pCmd->insertParam.sql, &index, false);
if (sToken.n <= 0 || (sToken.type != TK_VALUES && sToken.type != TK_LP)) { if (sToken.n <= 0 || (sToken.type != TK_VALUES && sToken.type != TK_LP)) {
tscError("sql error, sql:%s", pCmd->insertParam.sql); tscError("sql error, sql:%s", pCmd->insertParam.sql);
...@@ -1407,7 +1451,13 @@ int stmtGenInsertStatement(SSqlObj* pSql, STscStmt* pStmt, const char* name, TAO ...@@ -1407,7 +1451,13 @@ int stmtGenInsertStatement(SSqlObj* pSql, STscStmt* pStmt, const char* name, TAO
int32_t j = 0; int32_t j = 0;
while (1) { while (1) {
len = (size_t)snprintf(str, size - 1, "insert into %s using %.*s tags(", name, pStmt->mtb.stbname.n, pStmt->mtb.stbname.z); if (pStmt->mtb.tagColSet) {
len = (size_t)snprintf(str, size - 1, "insert into %s using %.*s %.*s tags(",
name, pStmt->mtb.stbname.n, pStmt->mtb.stbname.z, pStmt->mtb.tagCols.n, pStmt->mtb.tagCols.z);
} else {
len = (size_t)snprintf(str, size - 1, "insert into %s using %.*s tags(", name, pStmt->mtb.stbname.n, pStmt->mtb.stbname.z);
}
if (len >= (size -1)) { if (len >= (size -1)) {
size *= 2; size *= 2;
free(str); free(str);
...@@ -1659,6 +1709,13 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1659,6 +1709,13 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
STMT_RET(TSDB_CODE_TSC_APP_ERROR); STMT_RET(TSDB_CODE_TSC_APP_ERROR);
} }
if ((*t1)->pData == NULL) {
code = tscCreateDataBlockData(*t1, TSDB_PAYLOAD_SIZE, (*t1)->pTableMeta->tableInfo.rowSize, sizeof(SSubmitBlk));
if (code != TSDB_CODE_SUCCESS) {
STMT_RET(code);
}
}
SSubmitBlk* pBlk = (SSubmitBlk*) (*t1)->pData; SSubmitBlk* pBlk = (SSubmitBlk*) (*t1)->pData;
pCmd->batchSize = pBlk->numOfRows; pCmd->batchSize = pBlk->numOfRows;
if (pBlk->numOfRows == 0) { if (pBlk->numOfRows == 0) {
...@@ -1784,7 +1841,6 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags ...@@ -1784,7 +1841,6 @@ int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags
STMT_RET(code); STMT_RET(code);
} }
int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) { int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
STMT_CHECK STMT_CHECK
...@@ -1792,8 +1848,6 @@ int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) { ...@@ -1792,8 +1848,6 @@ int taos_stmt_set_sub_tbname(TAOS_STMT* stmt, const char* name) {
return taos_stmt_set_tbname_tags(stmt, name, NULL); return taos_stmt_set_tbname_tags(stmt, name, NULL);
} }
int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) { int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
STMT_CHECK STMT_CHECK
...@@ -1801,7 +1855,6 @@ int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) { ...@@ -1801,7 +1855,6 @@ int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name) {
return taos_stmt_set_tbname_tags(stmt, name, NULL); return taos_stmt_set_tbname_tags(stmt, name, NULL);
} }
int taos_stmt_close(TAOS_STMT* stmt) { int taos_stmt_close(TAOS_STMT* stmt) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
if (pStmt == NULL || pStmt->taos == NULL) { if (pStmt == NULL || pStmt->taos == NULL) {
...@@ -1868,7 +1921,6 @@ int taos_stmt_bind_param(TAOS_STMT* stmt, TAOS_BIND* bind) { ...@@ -1868,7 +1921,6 @@ int taos_stmt_bind_param(TAOS_STMT* stmt, TAOS_BIND* bind) {
} }
} }
int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind) { int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
...@@ -1932,8 +1984,6 @@ int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, in ...@@ -1932,8 +1984,6 @@ int taos_stmt_bind_single_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind, in
STMT_RET(insertStmtBindParamBatch(pStmt, bind, colIdx)); STMT_RET(insertStmtBindParamBatch(pStmt, bind, colIdx));
} }
int taos_stmt_add_batch(TAOS_STMT* stmt) { int taos_stmt_add_batch(TAOS_STMT* stmt) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
STMT_CHECK STMT_CHECK
...@@ -2086,7 +2136,6 @@ int taos_stmt_get_param(TAOS_STMT *stmt, int idx, int *type, int *bytes) { ...@@ -2086,7 +2136,6 @@ int taos_stmt_get_param(TAOS_STMT *stmt, int idx, int *type, int *bytes) {
} }
} }
char *taos_stmt_errstr(TAOS_STMT *stmt) { char *taos_stmt_errstr(TAOS_STMT *stmt) {
STscStmt* pStmt = (STscStmt*)stmt; STscStmt* pStmt = (STscStmt*)stmt;
...@@ -2097,8 +2146,6 @@ char *taos_stmt_errstr(TAOS_STMT *stmt) { ...@@ -2097,8 +2146,6 @@ char *taos_stmt_errstr(TAOS_STMT *stmt) {
return taos_errstr(pStmt->pSql); return taos_errstr(pStmt->pSql);
} }
const char *taos_data_type(int type) { const char *taos_data_type(int type) {
switch (type) { switch (type) {
case TSDB_DATA_TYPE_NULL: return "TSDB_DATA_TYPE_NULL"; case TSDB_DATA_TYPE_NULL: return "TSDB_DATA_TYPE_NULL";
...@@ -2115,4 +2162,3 @@ const char *taos_data_type(int type) { ...@@ -2115,4 +2162,3 @@ const char *taos_data_type(int type) {
default: return "UNKNOWN"; default: return "UNKNOWN";
} }
} }
...@@ -2019,6 +2019,7 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS ...@@ -2019,6 +2019,7 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS
const char* msg8 = "not support distinct in nest query"; const char* msg8 = "not support distinct in nest query";
const char* msg9 = "_block_dist not support subquery, only support stable/table"; const char* msg9 = "_block_dist not support subquery, only support stable/table";
const char* msg10 = "not support group by in block func"; const char* msg10 = "not support group by in block func";
const char* msg11 = "invalid alias name";
// too many result columns not support order by in query // too many result columns not support order by in query
if (taosArrayGetSize(pSelNodeList) > TSDB_MAX_COLUMNS) { if (taosArrayGetSize(pSelNodeList) > TSDB_MAX_COLUMNS) {
...@@ -2038,9 +2039,12 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS ...@@ -2038,9 +2039,12 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS
int32_t outputIndex = (int32_t)tscNumOfExprs(pQueryInfo); int32_t outputIndex = (int32_t)tscNumOfExprs(pQueryInfo);
tSqlExprItem* pItem = taosArrayGet(pSelNodeList, i); tSqlExprItem* pItem = taosArrayGet(pSelNodeList, i);
if (hasDistinct == false) { if (hasDistinct == false) {
hasDistinct = (pItem->distinct == true); hasDistinct = (pItem->distinct == true);
distIdx = hasDistinct ? i : -1; distIdx = hasDistinct ? i : -1;
} }
if(pItem->aliasName != NULL && validateColumnName(pItem->aliasName) != TSDB_CODE_SUCCESS){
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg11);
}
int32_t type = pItem->pNode->type; int32_t type = pItem->pNode->type;
if (type == SQL_NODE_SQLFUNCTION) { if (type == SQL_NODE_SQLFUNCTION) {
...@@ -3705,6 +3709,10 @@ int32_t validateGroupbyNode(SQueryInfo* pQueryInfo, SArray* pList, SSqlCmd* pCmd ...@@ -3705,6 +3709,10 @@ int32_t validateGroupbyNode(SQueryInfo* pQueryInfo, SArray* pList, SSqlCmd* pCmd
SStrToken token = {pVar->nLen, pVar->nType, pVar->pz}; SStrToken token = {pVar->nLen, pVar->nType, pVar->pz};
if (pVar->nType != TSDB_DATA_TYPE_BINARY){
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2);
}
SColumnIndex index = COLUMN_INDEX_INITIALIZER; SColumnIndex index = COLUMN_INDEX_INITIALIZER;
if (getColumnIndexByName(&token, pQueryInfo, &index, tscGetErrorMsgPayload(pCmd)) != TSDB_CODE_SUCCESS) { if (getColumnIndexByName(&token, pQueryInfo, &index, tscGetErrorMsgPayload(pCmd)) != TSDB_CODE_SUCCESS) {
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2);
...@@ -4023,7 +4031,7 @@ static int32_t getColQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, tSqlEx ...@@ -4023,7 +4031,7 @@ static int32_t getColQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, tSqlEx
UNUSED(code); UNUSED(code);
// TODO: more error handling // TODO: more error handling
} END_TRY } END_TRY
// add to required table column list // add to required table column list
STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i); STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
int64_t uid = pTableMetaInfo->pTableMeta->id.uid; int64_t uid = pTableMetaInfo->pTableMeta->id.uid;
...@@ -5208,7 +5216,7 @@ static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondE ...@@ -5208,7 +5216,7 @@ static int32_t getTagQueryCondExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SCondE
UNUSED(code); UNUSED(code);
// TODO: more error handling // TODO: more error handling
} END_TRY } END_TRY
// add to required table column list // add to required table column list
STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i); STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
int64_t uid = pTableMetaInfo->pTableMeta->id.uid; int64_t uid = pTableMetaInfo->pTableMeta->id.uid;
...@@ -5417,7 +5425,7 @@ int32_t validateWhereNode(SQueryInfo* pQueryInfo, tSqlExpr** pExpr, SSqlObj* pSq ...@@ -5417,7 +5425,7 @@ int32_t validateWhereNode(SQueryInfo* pQueryInfo, tSqlExpr** pExpr, SSqlObj* pSq
if (taosArrayGetSize(pQueryInfo->pUpstream) > 0 && condExpr.pTimewindow != NULL) { if (taosArrayGetSize(pQueryInfo->pUpstream) > 0 && condExpr.pTimewindow != NULL) {
setNormalExprToCond(&condExpr.pColumnCond, condExpr.pTimewindow, TK_AND); setNormalExprToCond(&condExpr.pColumnCond, condExpr.pTimewindow, TK_AND);
condExpr.pTimewindow = NULL; condExpr.pTimewindow = tSqlExprClone(condExpr.pTimewindow);
} }
tSqlExprCompact(pExpr); tSqlExprCompact(pExpr);
...@@ -6070,14 +6078,19 @@ int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) { ...@@ -6070,14 +6078,19 @@ int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, DEFAULT_TABLE_INDEX); STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, DEFAULT_TABLE_INDEX);
bool dbIncluded = false; bool dbIncluded = false;
if (tscValidateName(&(pAlterSQL->name), true, &dbIncluded) != TSDB_CODE_SUCCESS) { SStrToken tmpToken = pAlterSQL->name;
tmpToken.z= strndup(pAlterSQL->name.z, pAlterSQL->name.n);
if (tscValidateName(&tmpToken, true, &dbIncluded) != TSDB_CODE_SUCCESS) {
free(tmpToken.z);
return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1); return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1);
} }
code = tscSetTableFullName(&pTableMetaInfo->name, &(pAlterSQL->name), pSql, dbIncluded); code = tscSetTableFullName(&pTableMetaInfo->name, &tmpToken, pSql, dbIncluded);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
free(tmpToken.z);
return code; return code;
} }
free(tmpToken.z);
code = tscGetTableMeta(pSql, pTableMetaInfo); code = tscGetTableMeta(pSql, pTableMetaInfo);
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
......
...@@ -975,7 +975,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) { ...@@ -975,7 +975,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
if (pQueryInfo->colCond && taosArrayGetSize(pQueryInfo->colCond) > 0 && !onlyQueryTags(&query) ) { if (pQueryInfo->colCond && taosArrayGetSize(pQueryInfo->colCond) > 0 && !onlyQueryTags(&query) ) {
STblCond *pCond = tsGetTableFilter(pQueryInfo->colCond, pTableMeta->id.uid, 0); STblCond *pCond = tsGetTableFilter(pQueryInfo->colCond, pTableMeta->id.uid, 0);
if (pCond != NULL && pCond->cond != NULL) { if (pCond != NULL && pCond->cond != NULL) {
pQueryMsg->colCondLen = htons(pCond->len); pQueryMsg->colCondLen = htonl(pCond->len);
memcpy(pMsg, pCond->cond, pCond->len); memcpy(pMsg, pCond->cond, pCond->len);
pMsg += pCond->len; pMsg += pCond->len;
...@@ -1056,7 +1056,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) { ...@@ -1056,7 +1056,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
SCond *pCond = tsGetSTableQueryCond(pTagCond, pTableMeta->id.uid); SCond *pCond = tsGetSTableQueryCond(pTagCond, pTableMeta->id.uid);
if (pCond != NULL && pCond->cond != NULL) { if (pCond != NULL && pCond->cond != NULL) {
pQueryMsg->tagCondLen = htons(pCond->len); pQueryMsg->tagCondLen = htonl(pCond->len);
memcpy(pMsg, pCond->cond, pCond->len); memcpy(pMsg, pCond->cond, pCond->len);
pMsg += pCond->len; pMsg += pCond->len;
...@@ -2955,7 +2955,8 @@ int32_t tscGetTableMetaImpl(SSqlObj* pSql, STableMetaInfo *pTableMetaInfo, bool ...@@ -2955,7 +2955,8 @@ int32_t tscGetTableMetaImpl(SSqlObj* pSql, STableMetaInfo *pTableMetaInfo, bool
// in case of child table, here only get the // in case of child table, here only get the
if (pMeta->tableType == TSDB_CHILD_TABLE) { if (pMeta->tableType == TSDB_CHILD_TABLE) {
int32_t code = tscCreateTableMetaFromSTableMeta(pSql, &pTableMetaInfo->pTableMeta, name, &pTableMetaInfo->tableMetaCapacity, (STableMeta **)(&pSTMeta)); int32_t code = tscCreateTableMetaFromSTableMeta(pSql, &pTableMetaInfo->pTableMeta, name, &pTableMetaInfo->tableMetaCapacity, (STableMeta **)(&pSTMeta));
pSql->pBuf = (void *)(pSTMeta); pSql->pBuf = (void *)(pSTMeta);
pMeta = pTableMetaInfo->pTableMeta;
if (code != TSDB_CODE_SUCCESS) { if (code != TSDB_CODE_SUCCESS) {
return getTableMetaFromMnode(pSql, pTableMetaInfo, autocreate); return getTableMetaFromMnode(pSql, pTableMetaInfo, autocreate);
} }
......
...@@ -468,7 +468,7 @@ SSqlObj* recreateSqlObj(SSub* pSub) { ...@@ -468,7 +468,7 @@ SSqlObj* recreateSqlObj(SSub* pSub) {
} }
registerSqlObj(pSql); registerSqlObj(pSql);
pSql->rootObj = pSql;
code = tsParseSql(pSql, true); code = tsParseSql(pSql, true);
if (code == TSDB_CODE_TSC_ACTION_IN_PROGRESS) { if (code == TSDB_CODE_TSC_ACTION_IN_PROGRESS) {
tsem_wait(&pSub->sem); tsem_wait(&pSub->sem);
......
...@@ -187,7 +187,7 @@ bool tscQueryTags(SQueryInfo* pQueryInfo) { ...@@ -187,7 +187,7 @@ bool tscQueryTags(SQueryInfo* pQueryInfo) {
continue; continue;
} }
if (functId != TSDB_FUNC_TAGPRJ && functId != TSDB_FUNC_TID_TAG) { if (functId != TSDB_FUNC_TAGPRJ && functId != TSDB_FUNC_TID_TAG && functId != TSDB_FUNC_BLKINFO) {
return false; return false;
} }
} }
...@@ -942,23 +942,30 @@ SSDataBlock* doGetDataBlock(void* param, bool* newgroup) { ...@@ -942,23 +942,30 @@ SSDataBlock* doGetDataBlock(void* param, bool* newgroup) {
pBlock->info.rows = pRes->numOfRows; pBlock->info.rows = pRes->numOfRows;
if (pRes->numOfRows != 0) { if (pRes->numOfRows != 0) {
doSetupSDataBlock(pRes, pBlock, pInput->pFilterInfo); doSetupSDataBlock(pRes, pBlock, pInput->pFilterInfo);
*newgroup = false; if (pBlock->info.rows > 0) {
return pBlock; *newgroup = false;
return pBlock;
}
} }
// No data block exists. So retrieve and transfer it into to SSDataBlock SSDataBlock* result = NULL;
TAOS_ROW pRow = NULL; do {
taos_fetch_block(pSql, &pRow); // No data block exists. So retrieve and transfer it into to SSDataBlock
TAOS_ROW pRow = NULL;
taos_fetch_block(pSql, &pRow);
if (pRes->numOfRows == 0) { if (pRes->numOfRows == 0) {
pOperator->status = OP_EXEC_DONE; pOperator->status = OP_EXEC_DONE;
return NULL; result = NULL;
} break;
}
pBlock->info.rows = pRes->numOfRows;
doSetupSDataBlock(pRes, pBlock, pInput->pFilterInfo);
*newgroup = false;
result = pBlock;
} while (result->info.rows == 0);
pBlock->info.rows = pRes->numOfRows; return result;
doSetupSDataBlock(pRes, pBlock, pInput->pFilterInfo);
*newgroup = false;
return pBlock;
} }
static void fetchNextBlockIfCompleted(SOperatorInfo* pOperator, bool* newgroup) { static void fetchNextBlockIfCompleted(SOperatorInfo* pOperator, bool* newgroup) {
...@@ -1838,6 +1845,32 @@ int32_t tscCreateDataBlock(size_t defaultSize, int32_t rowSize, int32_t startOff ...@@ -1838,6 +1845,32 @@ int32_t tscCreateDataBlock(size_t defaultSize, int32_t rowSize, int32_t startOff
return TSDB_CODE_TSC_OUT_OF_MEMORY; return TSDB_CODE_TSC_OUT_OF_MEMORY;
} }
int32_t code = tscCreateDataBlockData(dataBuf, defaultSize, rowSize, startOffset);
if (code != TSDB_CODE_SUCCESS) {
tfree(dataBuf);
return code;
}
//Here we keep the tableMeta to avoid it to be remove by other threads.
dataBuf->pTableMeta = tscTableMetaDup(pTableMeta);
SParsedDataColInfo* pColInfo = &dataBuf->boundColumnInfo;
SSchema* pSchema = tscGetTableSchema(dataBuf->pTableMeta);
tscSetBoundColumnInfo(pColInfo, pSchema, dataBuf->pTableMeta->tableInfo.numOfColumns);
dataBuf->vgId = dataBuf->pTableMeta->vgId;
tNameAssign(&dataBuf->tableName, name);
assert(defaultSize > 0 && pTableMeta != NULL && dataBuf->pTableMeta != NULL);
*dataBlocks = dataBuf;
return TSDB_CODE_SUCCESS;
}
int32_t tscCreateDataBlockData(STableDataBlocks* dataBuf, size_t defaultSize, int32_t rowSize, int32_t startOffset) {
assert(dataBuf != NULL);
dataBuf->nAllocSize = (uint32_t)defaultSize; dataBuf->nAllocSize = (uint32_t)defaultSize;
dataBuf->headerSize = startOffset; dataBuf->headerSize = startOffset;
...@@ -1850,30 +1883,16 @@ int32_t tscCreateDataBlock(size_t defaultSize, int32_t rowSize, int32_t startOff ...@@ -1850,30 +1883,16 @@ int32_t tscCreateDataBlock(size_t defaultSize, int32_t rowSize, int32_t startOff
dataBuf->pData = malloc(dataBuf->nAllocSize); dataBuf->pData = malloc(dataBuf->nAllocSize);
if (dataBuf->pData == NULL) { if (dataBuf->pData == NULL) {
tscError("failed to allocated memory, reason:%s", strerror(errno)); tscError("failed to allocated memory, reason:%s", strerror(errno));
tfree(dataBuf);
return TSDB_CODE_TSC_OUT_OF_MEMORY; return TSDB_CODE_TSC_OUT_OF_MEMORY;
} }
memset(dataBuf->pData, 0, sizeof(SSubmitBlk)); memset(dataBuf->pData, 0, sizeof(SSubmitBlk));
//Here we keep the tableMeta to avoid it to be remove by other threads.
dataBuf->pTableMeta = tscTableMetaDup(pTableMeta);
SParsedDataColInfo* pColInfo = &dataBuf->boundColumnInfo;
SSchema* pSchema = tscGetTableSchema(dataBuf->pTableMeta);
tscSetBoundColumnInfo(pColInfo, pSchema, dataBuf->pTableMeta->tableInfo.numOfColumns);
dataBuf->ordered = true; dataBuf->ordered = true;
dataBuf->prevTS = INT64_MIN; dataBuf->prevTS = INT64_MIN;
dataBuf->rowSize = rowSize; dataBuf->rowSize = rowSize;
dataBuf->size = startOffset; dataBuf->size = startOffset;
dataBuf->tsSource = -1; dataBuf->tsSource = -1;
dataBuf->vgId = dataBuf->pTableMeta->vgId;
tNameAssign(&dataBuf->tableName, name);
assert(defaultSize > 0 && pTableMeta != NULL && dataBuf->pTableMeta != NULL);
*dataBlocks = dataBuf;
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
} }
...@@ -2953,6 +2972,11 @@ int32_t tscValidateName(SStrToken* pToken, bool escapeEnabled, bool *dbIncluded) ...@@ -2953,6 +2972,11 @@ int32_t tscValidateName(SStrToken* pToken, bool escapeEnabled, bool *dbIncluded)
} }
} else if (pToken->type == TK_ID) { } else if (pToken->type == TK_ID) {
tscRmEscapeAndTrimToken(pToken); tscRmEscapeAndTrimToken(pToken);
if (pToken->n == 0) {
return TSDB_CODE_TSC_INVALID_OPERATION;
}
return TSDB_CODE_SUCCESS; return TSDB_CODE_SUCCESS;
} else { } else {
if (isNumber(pToken)) { if (isNumber(pToken)) {
......
...@@ -253,9 +253,10 @@ int dataColAppendVal(SDataCol *pCol, const void *value, int numOfRows, int maxPo ...@@ -253,9 +253,10 @@ int dataColAppendVal(SDataCol *pCol, const void *value, int numOfRows, int maxPo
} }
if(tdAllocMemForCol(pCol, maxPoints) < 0) return -1; if(tdAllocMemForCol(pCol, maxPoints) < 0) return -1;
if (numOfRows > 0) {
if (((rowOffset == 0) && (numOfRows > 0)) || ((rowOffset == -1) && (numOfRows >= 0))) {
// Find the first not null value, fill all previouse values as NULL // Find the first not null value, fill all previouse values as NULL
dataColSetNEleNull(pCol, numOfRows); dataColSetNEleNull(pCol, numOfRows - rowOffset);
} }
} }
...@@ -463,9 +464,7 @@ static void tdAppendDataRowToDataCol(SDataRow row, STSchema *pSchema, SDataCols ...@@ -463,9 +464,7 @@ static void tdAppendDataRowToDataCol(SDataRow row, STSchema *pSchema, SDataCols
int rcol = 0; int rcol = 0;
int dcol = 0; int dcol = 0;
while (dcol < pCols->numOfCols) { while (dcol < pCols->numOfCols) {
bool setCol = 0;
SDataCol *pDataCol = &(pCols->cols[dcol]); SDataCol *pDataCol = &(pCols->cols[dcol]);
if (rcol >= schemaNCols(pSchema)) { if (rcol >= schemaNCols(pSchema)) {
dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset); dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset);
...@@ -476,14 +475,22 @@ static void tdAppendDataRowToDataCol(SDataRow row, STSchema *pSchema, SDataCols ...@@ -476,14 +475,22 @@ static void tdAppendDataRowToDataCol(SDataRow row, STSchema *pSchema, SDataCols
STColumn *pRowCol = schemaColAt(pSchema, rcol); STColumn *pRowCol = schemaColAt(pSchema, rcol);
if (pRowCol->colId == pDataCol->colId) { if (pRowCol->colId == pDataCol->colId) {
void *value = tdGetRowDataOfCol(row, pRowCol->type, pRowCol->offset + TD_DATA_ROW_HEAD_SIZE); void *value = tdGetRowDataOfCol(row, pRowCol->type, pRowCol->offset + TD_DATA_ROW_HEAD_SIZE);
if(!isNull(value, pDataCol->type)) setCol = 1; if (rowOffset == 0) {
dataColAppendVal(pDataCol, value, pCols->numOfRows, pCols->maxPoints, rowOffset); dataColAppendVal(pDataCol, value, pCols->numOfRows, pCols->maxPoints, rowOffset);
} else if (rowOffset == -1) {
// for update 2
if (!isNull(value, pDataCol->type)) {
dataColAppendVal(pDataCol, value, pCols->numOfRows, pCols->maxPoints, rowOffset);
}
} else {
ASSERT(0);
}
dcol++; dcol++;
rcol++; rcol++;
} else if (pRowCol->colId < pDataCol->colId) { } else if (pRowCol->colId < pDataCol->colId) {
rcol++; rcol++;
} else { } else {
if(forceSetNull || setCol) { if(forceSetNull) {
dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset); dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset);
} }
dcol++; dcol++;
...@@ -501,7 +508,6 @@ static void tdAppendKvRowToDataCol(SKVRow row, STSchema *pSchema, SDataCols *pCo ...@@ -501,7 +508,6 @@ static void tdAppendKvRowToDataCol(SKVRow row, STSchema *pSchema, SDataCols *pCo
int nRowCols = kvRowNCols(row); int nRowCols = kvRowNCols(row);
while (dcol < pCols->numOfCols) { while (dcol < pCols->numOfCols) {
bool setCol = 0;
SDataCol *pDataCol = &(pCols->cols[dcol]); SDataCol *pDataCol = &(pCols->cols[dcol]);
if (rcol >= nRowCols || rcol >= schemaNCols(pSchema)) { if (rcol >= nRowCols || rcol >= schemaNCols(pSchema)) {
dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset); dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset);
...@@ -513,14 +519,22 @@ static void tdAppendKvRowToDataCol(SKVRow row, STSchema *pSchema, SDataCols *pCo ...@@ -513,14 +519,22 @@ static void tdAppendKvRowToDataCol(SKVRow row, STSchema *pSchema, SDataCols *pCo
if (colIdx->colId == pDataCol->colId) { if (colIdx->colId == pDataCol->colId) {
void *value = tdGetKvRowDataOfCol(row, colIdx->offset); void *value = tdGetKvRowDataOfCol(row, colIdx->offset);
if(!isNull(value, pDataCol->type)) setCol = 1; if (rowOffset == 0) {
dataColAppendVal(pDataCol, value, pCols->numOfRows, pCols->maxPoints, rowOffset); dataColAppendVal(pDataCol, value, pCols->numOfRows, pCols->maxPoints, rowOffset);
} else if (rowOffset == -1) {
// for update 2
if (!isNull(value, pDataCol->type)) {
dataColAppendVal(pDataCol, value, pCols->numOfRows, pCols->maxPoints, rowOffset);
}
} else {
ASSERT(0);
}
++dcol; ++dcol;
++rcol; ++rcol;
} else if (colIdx->colId < pDataCol->colId) { } else if (colIdx->colId < pDataCol->colId) {
++rcol; ++rcol;
} else { } else {
if(forceSetNull || setCol) { if (forceSetNull) {
dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset); dataColAppendVal(pDataCol, getNullValue(pDataCol->type), pCols->numOfRows, pCols->maxPoints, rowOffset);
} }
++dcol; ++dcol;
......
...@@ -73,7 +73,7 @@ int32_t tsMaxBinaryDisplayWidth = 30; ...@@ -73,7 +73,7 @@ int32_t tsMaxBinaryDisplayWidth = 30;
* -1: all data are not compressed * -1: all data are not compressed
* other values: if the message payload size is greater than the tsCompressMsgSize, the message will be compressed. * other values: if the message payload size is greater than the tsCompressMsgSize, the message will be compressed.
*/ */
int32_t tsCompressMsgSize = -1; int32_t tsCompressMsgSize = 512 * 1024;
/* denote if server needs to compress the retrieved column data before adding to the rpc response message body. /* denote if server needs to compress the retrieved column data before adding to the rpc response message body.
* 0: all data are compressed * 0: all data are compressed
...@@ -289,7 +289,7 @@ char Compressor[32] = "ZSTD_COMPRESSOR"; // ZSTD_COMPRESSOR or GZIP_COMPRES ...@@ -289,7 +289,7 @@ char Compressor[32] = "ZSTD_COMPRESSOR"; // ZSTD_COMPRESSOR or GZIP_COMPRES
int8_t tsDeadLockKillQuery = 0; int8_t tsDeadLockKillQuery = 0;
// default JSON string type // default JSON string type
char tsDefaultJSONStrType[7] = "binary"; char tsDefaultJSONStrType[7] = "nchar";
char tsSmlChildTableName[TSDB_TABLE_NAME_LEN] = ""; //user defined child table name can be specified in tag value. If set to empty system will generate table name using MD5 hash. char tsSmlChildTableName[TSDB_TABLE_NAME_LEN] = ""; //user defined child table name can be specified in tag value. If set to empty system will generate table name using MD5 hash.
int32_t (*monStartSystemFp)() = NULL; int32_t (*monStartSystemFp)() = NULL;
......
...@@ -163,8 +163,12 @@ namespace TDengineDriver ...@@ -163,8 +163,12 @@ namespace TDengineDriver
[DllImport("taos", EntryPoint = "taos_close", CallingConvention = CallingConvention.Cdecl)] [DllImport("taos", EntryPoint = "taos_close", CallingConvention = CallingConvention.Cdecl)]
static extern public int Close(IntPtr taos); static extern public int Close(IntPtr taos);
//get precisionin parameter restultset //get precision in restultset
[DllImport("taos", EntryPoint = "taos_result_precision", CallingConvention = CallingConvention.Cdecl)] [DllImport("taos", EntryPoint = "taos_result_precision", CallingConvention = CallingConvention.Cdecl)]
static extern public int ResultPrecision(IntPtr taos); static extern public int ResultPrecision(IntPtr taos);
//schemaless API
[DllImport("taos",SetLastError = true, EntryPoint = "taos_schemaless_insert", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr SchemalessInsert(IntPtr taos, string[] lines, int numLines, int protocol, int precision);
} }
} }
...@@ -413,8 +413,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti ...@@ -413,8 +413,7 @@ public abstract class AbstractConnection extends WrapperImpl implements Connecti
status = future.get(); status = future.get();
else else
status = future.get(timeout, TimeUnit.SECONDS); status = future.get(timeout, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException ignored) {
e.printStackTrace();
} catch (TimeoutException e) { } catch (TimeoutException e) {
future.cancel(true); future.cancel(true);
status = false; status = false;
......
...@@ -597,7 +597,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -597,7 +597,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
return col4; return col4;
} }
public ResultSet getSchemas() throws SQLException { public ResultSet getSchemas() {
return getEmptyResultSet(); return getEmptyResultSet();
} }
...@@ -629,7 +629,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -629,7 +629,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
public abstract ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException; public abstract ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException;
protected ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern, Connection conn) { protected ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern, Connection conn) throws SQLException {
if (catalog == null || catalog.isEmpty()) if (catalog == null || catalog.isEmpty())
return null; return null;
if (!isAvailableCatalog(conn, catalog)) if (!isAvailableCatalog(conn, catalog))
...@@ -682,8 +682,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -682,8 +682,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
rowIndex++; rowIndex++;
} }
resultSet.setRowDataList(rowDataList); resultSet.setRowDataList(rowDataList);
} catch (SQLException e) {
e.printStackTrace();
} }
return resultSet; return resultSet;
} }
...@@ -1220,7 +1218,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -1220,7 +1218,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
return col6; return col6;
} }
private boolean isAvailableCatalog(Connection connection, String catalog) { private boolean isAvailableCatalog(Connection connection, String catalog) throws SQLException {
try (Statement stmt = connection.createStatement(); try (Statement stmt = connection.createStatement();
ResultSet databases = stmt.executeQuery("show databases")) { ResultSet databases = stmt.executeQuery("show databases")) {
while (databases.next()) { while (databases.next()) {
...@@ -1229,8 +1227,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da ...@@ -1229,8 +1227,6 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da
if (dbname.equalsIgnoreCase(catalog)) if (dbname.equalsIgnoreCase(catalog))
return true; return true;
} }
} catch (SQLException e) {
e.printStackTrace();
} }
return false; return false;
} }
......
...@@ -21,6 +21,7 @@ import com.taosdata.jdbc.enums.SchemalessProtocolType; ...@@ -21,6 +21,7 @@ import com.taosdata.jdbc.enums.SchemalessProtocolType;
import com.taosdata.jdbc.enums.SchemalessTimestampType; import com.taosdata.jdbc.enums.SchemalessTimestampType;
import com.taosdata.jdbc.utils.TaosInfo; import com.taosdata.jdbc.utils.TaosInfo;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.SQLWarning; import java.sql.SQLWarning;
...@@ -107,8 +108,7 @@ public class TSDBJNIConnector { ...@@ -107,8 +108,7 @@ public class TSDBJNIConnector {
try { try {
pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos); pSql = this.executeQueryImp(sql.getBytes(TaosGlobalConfig.getCharset()), this.taos);
taosInfo.stmt_count_increment(); taosInfo.stmt_count_increment();
} catch (Exception e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace();
this.freeResultSetImp(this.taos, pSql); this.freeResultSetImp(this.taos, pSql);
throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING); throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNSUPPORTED_ENCODING);
} }
......
...@@ -611,7 +611,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -611,7 +611,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
try { try {
this.tagValueLength += value.getBytes(charset).length; this.tagValueLength += value.getBytes(charset).length;
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
} }
...@@ -786,7 +786,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -786,7 +786,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
b = val.getBytes(charset); b = val.getBytes(charset);
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
tagDataList.put(b); tagDataList.put(b);
...@@ -921,7 +921,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -921,7 +921,7 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
b = val.getBytes(charset); b = val.getBytes(charset);
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
if (val.length() > col1.bytes) { if (val.length() > col1.bytes) {
...@@ -980,8 +980,10 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat ...@@ -980,8 +980,10 @@ public class TSDBPreparedStatement extends TSDBStatement implements PreparedStat
@Override @Override
public void close() throws SQLException { public void close() throws SQLException {
this.columnDataClearBatchInternal(); if (this.nativeStmtHandle != 0L) {
this.columnDataCloseBatch(); this.columnDataClearBatchInternal();
this.columnDataCloseBatch();
}
super.close(); super.close();
} }
} }
...@@ -92,75 +92,71 @@ public class TSDBResultSetBlockData { ...@@ -92,75 +92,71 @@ public class TSDBResultSetBlockData {
} }
public void setByteArray(int col, int length, byte[] value) { public void setByteArray(int col, int length, byte[] value) {
try { switch (this.columnMetaDataList.get(col).getColType()) {
switch (this.columnMetaDataList.get(col).getColType()) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: {
case TSDBConstants.TSDB_DATA_TYPE_BOOL: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer();
buf.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer(); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_UTINYINT:
case TSDBConstants.TSDB_DATA_TYPE_UTINYINT: case TSDBConstants.TSDB_DATA_TYPE_TINYINT: {
case TSDBConstants.TSDB_DATA_TYPE_TINYINT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN);
buf.order(ByteOrder.LITTLE_ENDIAN); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_USMALLINT:
case TSDBConstants.TSDB_DATA_TYPE_USMALLINT: case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: {
case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); ShortBuffer sb = buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
ShortBuffer sb = buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer(); this.colData.set(col, sb);
this.colData.set(col, sb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_UINT:
case TSDBConstants.TSDB_DATA_TYPE_UINT: case TSDBConstants.TSDB_DATA_TYPE_INT: {
case TSDBConstants.TSDB_DATA_TYPE_INT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); IntBuffer ib = buf.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
IntBuffer ib = buf.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); this.colData.set(col, ib);
this.colData.set(col, ib); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_UBIGINT:
case TSDBConstants.TSDB_DATA_TYPE_UBIGINT: case TSDBConstants.TSDB_DATA_TYPE_BIGINT: {
case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); this.colData.set(col, lb);
this.colData.set(col, lb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_FLOAT: {
case TSDBConstants.TSDB_DATA_TYPE_FLOAT: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); FloatBuffer fb = buf.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
FloatBuffer fb = buf.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer(); this.colData.set(col, fb);
this.colData.set(col, fb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: {
case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); DoubleBuffer db = buf.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
DoubleBuffer db = buf.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); this.colData.set(col, db);
this.colData.set(col, db); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_BINARY: {
case TSDBConstants.TSDB_DATA_TYPE_BINARY: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN);
buf.order(ByteOrder.LITTLE_ENDIAN); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: {
case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
LongBuffer lb = buf.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); this.colData.set(col, lb);
this.colData.set(col, lb); break;
break; }
} case TSDBConstants.TSDB_DATA_TYPE_NCHAR: {
case TSDBConstants.TSDB_DATA_TYPE_NCHAR: { ByteBuffer buf = ByteBuffer.wrap(value, 0, length);
ByteBuffer buf = ByteBuffer.wrap(value, 0, length); buf.order(ByteOrder.LITTLE_ENDIAN);
buf.order(ByteOrder.LITTLE_ENDIAN); this.colData.set(col, buf);
this.colData.set(col, buf); break;
break;
}
} }
} catch (Exception e) {
e.printStackTrace();
} }
} }
...@@ -283,14 +279,8 @@ public class TSDBResultSetBlockData { ...@@ -283,14 +279,8 @@ public class TSDBResultSetBlockData {
return 0; return 0;
} }
public Timestamp getTimestamp(int col) { public Timestamp getTimestamp(int col) throws SQLException {
try { return new Timestamp(getLong(col));
return new Timestamp(getLong(col));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
} }
public double getDouble(int col) { public double getDouble(int col) {
...@@ -429,7 +419,7 @@ public class TSDBResultSetBlockData { ...@@ -429,7 +419,7 @@ public class TSDBResultSetBlockData {
String charset = TaosGlobalConfig.getCharset(); String charset = TaosGlobalConfig.getCharset();
return new String(dest, charset); return new String(dest, charset);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
} }
} }
......
...@@ -16,6 +16,7 @@ package com.taosdata.jdbc; ...@@ -16,6 +16,7 @@ package com.taosdata.jdbc;
import com.taosdata.jdbc.utils.NullType; import com.taosdata.jdbc.utils.NullType;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
...@@ -378,8 +379,8 @@ public class TSDBResultSetRowData { ...@@ -378,8 +379,8 @@ public class TSDBResultSetRowData {
// this setByteArr(int, byte[]) to handle NCHAR value, we need to build a String with charsetEncoding by TaosGlobalConfig // this setByteArr(int, byte[]) to handle NCHAR value, we need to build a String with charsetEncoding by TaosGlobalConfig
try { try {
data.set(col, new String(value, TaosGlobalConfig.getCharset())); data.set(col, new String(value, TaosGlobalConfig.getCharset()));
} catch (Exception e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); throw new RuntimeException(e.getMessage());
} }
} }
......
...@@ -5,6 +5,7 @@ import com.taosdata.jdbc.TSDBErrorNumbers; ...@@ -5,6 +5,7 @@ import com.taosdata.jdbc.TSDBErrorNumbers;
import org.apache.http.HeaderElement; import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator; import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.*;
......
...@@ -16,8 +16,8 @@ public class TaosInfo implements TaosInfoMBean { ...@@ -16,8 +16,8 @@ public class TaosInfo implements TaosInfoMBean {
MBeanServer server = ManagementFactory.getPlatformMBeanServer(); MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("TaosInfoMBean:name=TaosInfo"); ObjectName name = new ObjectName("TaosInfoMBean:name=TaosInfo");
server.registerMBean(TaosInfo.getInstance(), name); server.registerMBean(TaosInfo.getInstance(), name);
} catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ignored) {
e.printStackTrace(); throw new RuntimeException("registerMBean failed");
} }
} }
......
...@@ -30,42 +30,6 @@ public class TSDBConnectionTest { ...@@ -30,42 +30,6 @@ public class TSDBConnectionTest {
} }
} }
@Test
public void runSubscribe() {
try {
// given
TSDBConnection unwrap = conn.unwrap(TSDBConnection.class);
TSDBSubscribe subscribe = unwrap.subscribe("topic1", "select * from log.log", false);
// when
TSDBResultSet rs = subscribe.consume();
ResultSetMetaData metaData = rs.getMetaData();
// then
Assert.assertNotNull(rs);
Assert.assertEquals(4, metaData.getColumnCount());
Assert.assertEquals("ts", metaData.getColumnLabel(1));
Assert.assertEquals("level", metaData.getColumnLabel(2));
Assert.assertEquals("content", metaData.getColumnLabel(3));
Assert.assertEquals("ipaddr", metaData.getColumnLabel(4));
rs.next();
// row 1
{
Assert.assertNotNull(rs.getTimestamp(1));
Assert.assertNotNull(rs.getTimestamp("ts"));
Assert.assertNotNull(rs.getByte(2));
Assert.assertNotNull(rs.getByte("level"));
Assert.assertNotNull(rs.getString(3));
Assert.assertNotNull(rs.getString("content"));
Assert.assertNotNull(rs.getString(4));
Assert.assertNotNull(rs.getString("ipaddr"));
}
subscribe.close(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test @Test
public void prepareStatement() throws SQLException { public void prepareStatement() throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("select server_status()"); PreparedStatement pstmt = conn.prepareStatement("select server_status()");
...@@ -391,13 +355,9 @@ public class TSDBConnectionTest { ...@@ -391,13 +355,9 @@ public class TSDBConnectionTest {
} }
@Test @Test
public void unwrap() { public void unwrap() throws SQLException {
try { TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class);
TSDBConnection tsdbConnection = conn.unwrap(TSDBConnection.class); Assert.assertNotNull(tsdbConnection);
Assert.assertNotNull(tsdbConnection);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -406,32 +366,22 @@ public class TSDBConnectionTest { ...@@ -406,32 +366,22 @@ public class TSDBConnectionTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { Properties properties = new Properties();
Class.forName("com.taosdata.jdbc.TSDBDriver"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/log?user=root&password=taosdata", properties);
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); // create test database for test cases
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/log?user=root&password=taosdata", properties); try (Statement stmt = conn.createStatement()) {
// create test database for test cases stmt.execute("create database if not exists test");
try (Statement stmt = conn.createStatement()) {
stmt.execute("create database if not exists test");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} }
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -33,7 +33,6 @@ public class TSDBDriverTest { ...@@ -33,7 +33,6 @@ public class TSDBDriverTest {
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();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
} }
} }
...@@ -49,7 +48,6 @@ public class TSDBDriverTest { ...@@ -49,7 +48,6 @@ public class TSDBDriverTest {
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();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
} }
} }
...@@ -65,7 +63,6 @@ public class TSDBDriverTest { ...@@ -65,7 +63,6 @@ public class TSDBDriverTest {
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();
fail("failure - should not throw Exception"); fail("failure - should not throw Exception");
} }
} }
...@@ -157,16 +154,8 @@ public class TSDBDriverTest { ...@@ -157,16 +154,8 @@ public class TSDBDriverTest {
} }
@Test @Test
public void getParentLogger() throws SQLFeatureNotSupportedException { public void getParentLogger() {
assertNull(new TSDBDriver().getParentLogger()); assertNull(new TSDBDriver().getParentLogger());
} }
@BeforeClass
public static void before() {
try {
Class.forName("com.taosdata.jdbc.TSDBDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} }
\ No newline at end of file
...@@ -57,44 +57,31 @@ public class AuthenticationTest { ...@@ -57,44 +57,31 @@ public class AuthenticationTest {
@Ignore @Ignore
@Test @Test
public void test() { public void test() throws SQLException {
// change password // change password
try { String url = "jdbc:TAOS-RS://" + host + ":6041/restful_test?user=" + user + "&password=taosdata";
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=" + user + "&password=taosdata"); try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();) {
stmt.execute("alter user " + user + " pass '" + password + "'"); stmt.execute("alter user " + user + " pass '" + password + "'");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
// use new to login and execute query // use new to login and execute query
try { url = "jdbc:TAOS-RS://" + host + ":6041/restful_test?user=" + user + "&password=" + password;
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=" + user + "&password=" + password); try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement()) {
stmt.execute("show databases"); stmt.execute("show databases");
ResultSet rs = stmt.getResultSet(); ResultSet rs = stmt.getResultSet();
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) { while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.print(meta.getColumnLabel(i) + ":" + rs.getString(i) + "\t");
}
System.out.println();
} }
} catch (SQLException e) {
e.printStackTrace();
} }
// change password back // change password back
try { url = "jdbc:TAOS-RS://" + host + ":6041/restful_test?user=" + user + "&password=" + password;
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=" + user + "&password=" + password); try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement()) {
stmt.execute("alter user " + user + " pass 'taosdata'"); stmt.execute("alter user " + user + " pass 'taosdata'");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Before @Before
......
...@@ -19,16 +19,14 @@ public class BatchErrorIgnoreTest { ...@@ -19,16 +19,14 @@ public class BatchErrorIgnoreTest {
IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("insert into t11 values(now, 11)"); stmt.addBatch("insert into t11 values(now, 11)");
IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> { IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("select count(*) from test.weather"); stmt.addBatch("select count(*) from test.weather");
...@@ -57,23 +55,19 @@ public class BatchErrorIgnoreTest { ...@@ -57,23 +55,19 @@ public class BatchErrorIgnoreTest {
IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> { IntStream.range(1, 6).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("insert into t11 values(now, 11)"); stmt.addBatch("insert into t11 values(now, 11)");
IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> { IntStream.range(6, 11).mapToObj(i -> "insert into test.t" + i + " values(now, " + i + "),(now + 1s, " + (10 * i) + ")").forEach(sql -> {
try { try {
stmt.addBatch(sql); stmt.addBatch(sql);
} catch (SQLException e) { } catch (SQLException ignored) {
e.printStackTrace();
} }
}); });
stmt.addBatch("select count(*) from test.weather"); stmt.addBatch("select count(*) from test.weather");
results = stmt.executeBatch(); results = stmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -94,10 +88,10 @@ public class BatchErrorIgnoreTest { ...@@ -94,10 +88,10 @@ public class BatchErrorIgnoreTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement();) {
Statement stmt = conn.createStatement();
stmt.execute("use test"); stmt.execute("use test");
stmt.execute("drop table if exists weather"); stmt.execute("drop table if exists weather");
stmt.execute("create table weather (ts timestamp, f1 float) tags(t1 int)"); stmt.execute("create table weather (ts timestamp, f1 float) tags(t1 int)");
...@@ -108,37 +102,25 @@ public class BatchErrorIgnoreTest { ...@@ -108,37 +102,25 @@ public class BatchErrorIgnoreTest {
e.printStackTrace(); e.printStackTrace();
} }
}); });
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test"); stmt.execute("create database if not exists test");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
Connection conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
...@@ -20,22 +20,20 @@ public class ConnectMultiTaosdByRestfulWithDifferentTokenTest { ...@@ -20,22 +20,20 @@ public class ConnectMultiTaosdByRestfulWithDifferentTokenTest {
private Connection conn2; private Connection conn2;
@Test @Test
public void test() { public void test() throws SQLException {
//when //when
executeSelectStatus(conn1); executeSelectStatus(conn1);
executeSelectStatus(conn2); executeSelectStatus(conn2);
executeSelectStatus(conn1); executeSelectStatus(conn1);
} }
private void executeSelectStatus(Connection connection) { private void executeSelectStatus(Connection connection) throws SQLException {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery("select server_status()"); ResultSet rs = stmt.executeQuery("select server_status()");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
Assert.assertNotNull(meta); Assert.assertNotNull(meta);
while (rs.next()) { while (rs.next()) {
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import com.taosdata.jdbc.TSDBErrorNumbers;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.sql.DriverManager; import java.sql.DriverManager;
...@@ -9,16 +7,9 @@ import java.sql.SQLException; ...@@ -9,16 +7,9 @@ import java.sql.SQLException;
public class ConnectWrongDatabaseTest { public class ConnectWrongDatabaseTest {
@Test @Test(expected = SQLException.class)
public void connect() { public void connect() throws SQLException {
try { DriverManager.getConnection("jdbc:TAOS://localhost:6030/wrong_db?user=root&password=taosdata");
Class.forName("com.taosdata.jdbc.TSDBDriver");
DriverManager.getConnection("jdbc:TAOS://localhost:6030/wrong_db?user=root&password=taosdata");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
Assert.assertEquals(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL, e.getErrorCode());
}
} }
} }
...@@ -11,7 +11,7 @@ public class DatetimeBefore1970Test { ...@@ -11,7 +11,7 @@ public class DatetimeBefore1970Test {
private Connection conn; private Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
// given // given
stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')"); stmt.executeUpdate("insert into weather(ts) values('1969-12-31 23:59:59.999')");
...@@ -45,36 +45,25 @@ public class DatetimeBefore1970Test { ...@@ -45,36 +45,25 @@ public class DatetimeBefore1970Test {
// then // then
ts = rs.getTimestamp("ts"); ts = rs.getTimestamp("ts");
Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime())); Assert.assertEquals("1970-01-01 07:59:59.999", TimestampUtil.longToDatetime(ts.getTime()));
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata");
conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists test_timestamp");
stmt.execute("drop database if exists test_timestamp"); stmt.execute("create database if not exists test_timestamp keep 36500");
stmt.execute("create database if not exists test_timestamp keep 36500"); stmt.execute("use test_timestamp");
stmt.execute("use test_timestamp"); stmt.execute("create table weather(ts timestamp,f1 float)");
stmt.execute("create table weather(ts timestamp,f1 float)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists test_timestamp");
stmt.execute("drop database if exists test_timestamp"); if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -17,29 +17,6 @@ public class ImportTest { ...@@ -17,29 +17,6 @@ public class ImportTest {
static String host = "127.0.0.1"; static String host = "127.0.0.1";
private static long ts; private static long ts;
@BeforeClass
public static void before() {
try {
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root");
properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata");
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("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
ts = System.currentTimeMillis();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test @Test
public void case001_insertData() throws Exception { public void case001_insertData() throws Exception {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
...@@ -52,28 +29,25 @@ public class ImportTest { ...@@ -52,28 +29,25 @@ public class ImportTest {
} }
@Test @Test
public void case002_checkSum() { public void case002_checkSum() throws SQLException {
Assert.assertEquals(50, select()); Assert.assertEquals(50, select());
} }
private int select() { private int select() throws SQLException {
int count = 0; int count = 0;
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
String sql = "select * from " + dbName + "." + tName; String sql = "select * from " + dbName + "." + tName;
ResultSet rs = stmt.executeQuery(sql); ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) { while (rs.next()) {
count++; count++;
} }
rs.close(); rs.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return count; return count;
} }
@Test @Test
public void case003_importData() { public void case003_importData() throws SQLException {
// 避免时间重复 // 避免时间重复
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
StringBuilder sqlBuilder = new StringBuilder("import into ").append(dbName).append(".").append(tName).append(" values "); StringBuilder sqlBuilder = new StringBuilder("import into ").append(dbName).append(".").append(tName).append(" values ");
...@@ -84,27 +58,40 @@ public class ImportTest { ...@@ -84,27 +58,40 @@ public class ImportTest {
} }
int rows = stmt.executeUpdate(sqlBuilder.toString()); int rows = stmt.executeUpdate(sqlBuilder.toString());
assertEquals(50, rows); assertEquals(50, rows);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void case004_checkSum() { public void case004_checkSum() throws SQLException {
Assert.assertEquals(100, select()); Assert.assertEquals(100, select());
} }
@BeforeClass
public static void before() throws SQLException {
Properties properties = new Properties();
properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root");
properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata");
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("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
ts = System.currentTimeMillis();
}
@AfterClass @AfterClass
public static void close() { public static void close() throws SQLException {
try { if (connection != null) {
if (connection != null) { Statement statement = connection.createStatement();
Statement statement = connection.createStatement(); statement.executeUpdate("drop database " + dbName);
statement.executeUpdate("drop database " + dbName); statement.close();
statement.close(); connection.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
...@@ -23,7 +23,7 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -23,7 +23,7 @@ public class MicroSecondPrecisionRestfulTest {
private static Connection conn3; private static Connection conn3;
@Test @Test
public void testCase1() { public void testCase1() throws SQLException {
try (Statement stmt = conn1.createStatement()) { try (Statement stmt = conn1.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -31,13 +31,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -31,13 +31,11 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase2() { public void testCase2() throws SQLException {
try (Statement stmt = conn1.createStatement()) { try (Statement stmt = conn1.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -50,13 +48,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -50,13 +48,11 @@ public class MicroSecondPrecisionRestfulTest {
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase3() { public void testCase3() throws SQLException {
try (Statement stmt = conn2.createStatement()) { try (Statement stmt = conn2.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -65,13 +61,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -65,13 +61,11 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase4() { public void testCase4() throws SQLException {
try (Statement stmt = conn2.createStatement()) { try (Statement stmt = conn2.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -84,13 +78,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -84,13 +78,11 @@ public class MicroSecondPrecisionRestfulTest {
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase5() { public void testCase5() throws SQLException {
try (Statement stmt = conn3.createStatement()) { try (Statement stmt = conn3.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + ms_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -99,13 +91,11 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -99,13 +91,11 @@ public class MicroSecondPrecisionRestfulTest {
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase6() { public void testCase6() throws SQLException {
try (Statement stmt = conn3.createStatement()) { try (Statement stmt = conn3.createStatement()) {
ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather"); ResultSet rs = stmt.executeQuery("select last_row(ts) from " + us_timestamp_db + ".weather");
rs.next(); rs.next();
...@@ -118,8 +108,6 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -118,8 +108,6 @@ public class MicroSecondPrecisionRestfulTest {
ts = rs.getLong(1); ts = rs.getLong(1);
Assert.assertEquals(timestamp1, ts); Assert.assertEquals(timestamp1, ts);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -154,16 +142,12 @@ public class MicroSecondPrecisionRestfulTest { ...@@ -154,16 +142,12 @@ public class MicroSecondPrecisionRestfulTest {
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn1 != null)
if (conn1 != null) conn1.close();
conn1.close(); if (conn2 != null)
if (conn2 != null) conn2.close();
conn2.close(); if (conn3 != null)
if (conn3 != null) conn3.close();
conn3.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -9,8 +9,7 @@ import java.util.concurrent.TimeUnit; ...@@ -9,8 +9,7 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
public class MultiConnectionWithDifferentDbTest { public class MultiConnectionWithDifferentDbTest {
...@@ -26,16 +25,17 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -26,16 +25,17 @@ public class MultiConnectionWithDifferentDbTest {
@Override @Override
public void run() { public void run() {
for (int j = 0; j < 10; j++) { for (int j = 0; j < 10; j++) {
queryDb();
try { try {
queryDb();
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException ignored) {
e.printStackTrace(); } catch (SQLException throwables) {
fail();
} }
} }
} }
private void queryDb() { private void queryDb() throws SQLException {
String url = "jdbc:TAOS-RS://" + host + ":6041/db" + i + "?user=root&password=taosdata"; String url = "jdbc:TAOS-RS://" + host + ":6041/db" + i + "?user=root&password=taosdata";
try (Connection connection = DriverManager.getConnection(url)) { try (Connection connection = DriverManager.getConnection(url)) {
Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement();
...@@ -54,8 +54,6 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -54,8 +54,6 @@ public class MultiConnectionWithDifferentDbTest {
assertEquals(loc, loc_actual); assertEquals(loc, loc_actual);
stmt.close(); stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
}, "thread-" + i)).collect(Collectors.toList()); }, "thread-" + i)).collect(Collectors.toList());
...@@ -73,12 +71,10 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -73,12 +71,10 @@ public class MultiConnectionWithDifferentDbTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
ts = System.currentTimeMillis(); ts = System.currentTimeMillis();
try { try (Connection conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata")) {
Connection conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + db1); stmt.execute("drop database if exists " + db1);
stmt.execute("create database if not exists " + db1); stmt.execute("create database if not exists " + db1);
...@@ -91,10 +87,6 @@ public class MultiConnectionWithDifferentDbTest { ...@@ -91,10 +87,6 @@ public class MultiConnectionWithDifferentDbTest {
stmt.execute("use " + db2); stmt.execute("use " + db2);
stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))"); stmt.execute("create table weather(ts timestamp, f1 int) tags(loc nchar(10))");
stmt.execute("insert into t1 using weather tags('shanghai') values(" + ts + ", 2)"); stmt.execute("insert into t1 using weather tags('shanghai') values(" + ts + ", 2)");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
package com.taosdata.jdbc.cases;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.*;
import java.util.concurrent.TimeUnit;
public class MultiThreadsWithSameStatementTest {
private static class Service {
public Connection conn;
public Statement stmt;
public Service() {
try {
conn = DriverManager.getConnection("jdbc:TAOS://localhost:6030/?user=root&password=taosdata");
stmt = conn.createStatement();
stmt.execute("create database if not exists jdbctest");
stmt.executeUpdate("create table if not exists jdbctest.weather (ts timestamp, f1 int)");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void release() {
try {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Before
public void before() {
}
@Test
public void test() {
Thread t1 = new Thread(() -> {
try {
Service service = new Service();
ResultSet resultSet = service.stmt.executeQuery("select * from jdbctest.weather");
while (resultSet.next()) {
ResultSetMetaData metaData = resultSet.getMetaData();
}
resultSet.close();
service.release();
} catch (SQLException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
while (true) {
try {
Service service = new Service();
service.stmt.executeUpdate("insert into jdbctest.weather values(now,1)");
service.release();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
t1.start();
sleep(1000);
t2.start();
}
private void sleep(long mills) {
try {
TimeUnit.MILLISECONDS.sleep(mills);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void after() {
}
}
...@@ -17,7 +17,7 @@ public class NanoSecondTimestampJNITest { ...@@ -17,7 +17,7 @@ public class NanoSecondTimestampJNITest {
private static Connection conn; private static Connection conn;
@Test @Test
public void insertUsingLongValue() { public void insertUsingLongValue() throws SQLException {
// given // given
long ms = System.currentTimeMillis(); long ms = System.currentTimeMillis();
long ns = ms * 1000_000 + random.nextInt(1000_000); long ns = ms * 1000_000 + random.nextInt(1000_000);
...@@ -26,8 +26,6 @@ public class NanoSecondTimestampJNITest { ...@@ -26,8 +26,6 @@ public class NanoSecondTimestampJNITest {
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -35,15 +33,13 @@ public class NanoSecondTimestampJNITest { ...@@ -35,15 +33,13 @@ public class NanoSecondTimestampJNITest {
} }
@Test @Test
public void insertUsingStringValue() { public void insertUsingStringValue() throws SQLException {
// given // given
// when // when
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('2021-01-01 12:00:00.123456789', 12.3, 4)"); ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('2021-01-01 12:00:00.123456789', 12.3, 4)");
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -51,7 +47,7 @@ public class NanoSecondTimestampJNITest { ...@@ -51,7 +47,7 @@ public class NanoSecondTimestampJNITest {
} }
@Test @Test
public void insertUsingTimestampValue() { public void insertUsingTimestampValue() throws SQLException {
// given // given
long epochSec = System.currentTimeMillis() / 1000; long epochSec = System.currentTimeMillis() / 1000;
long nanoAdjustment = random.nextInt(1000_000_000); long nanoAdjustment = random.nextInt(1000_000_000);
...@@ -65,8 +61,6 @@ public class NanoSecondTimestampJNITest { ...@@ -65,8 +61,6 @@ public class NanoSecondTimestampJNITest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
ret = pstmt.executeUpdate(); ret = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -85,8 +79,6 @@ public class NanoSecondTimestampJNITest { ...@@ -85,8 +79,6 @@ public class NanoSecondTimestampJNITest {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -102,13 +94,11 @@ public class NanoSecondTimestampJNITest { ...@@ -102,13 +94,11 @@ public class NanoSecondTimestampJNITest {
String timestampStr = "2021-01-01 12:00:00.123456789"; String timestampStr = "2021-01-01 12:00:00.123456789";
// when // when
ResultSet rs = null; ResultSet rs;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -133,8 +123,6 @@ public class NanoSecondTimestampJNITest { ...@@ -133,8 +123,6 @@ public class NanoSecondTimestampJNITest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
pstmt.executeUpdate(); pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// when // when
...@@ -142,8 +130,6 @@ public class NanoSecondTimestampJNITest { ...@@ -142,8 +130,6 @@ public class NanoSecondTimestampJNITest {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -156,26 +142,21 @@ public class NanoSecondTimestampJNITest { ...@@ -156,26 +142,21 @@ public class NanoSecondTimestampJNITest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists weather"); stmt.execute("drop table if exists weather");
stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); stmt.execute("create table weather(ts timestamp, temperature float, humidity int)");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
try { conn = DriverManager.getConnection(url);
conn = DriverManager.getConnection(url); try (Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + dbname); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists " + dbname + " precision 'ns'"); stmt.execute("create database if not exists " + dbname + " precision 'ns'");
stmt.execute("use " + dbname); stmt.execute("use " + dbname);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
...@@ -17,7 +17,7 @@ public class NanoSecondTimestampRestfulTest { ...@@ -17,7 +17,7 @@ public class NanoSecondTimestampRestfulTest {
private static Connection conn; private static Connection conn;
@Test @Test
public void insertUsingLongValue() { public void insertUsingLongValue() throws SQLException {
// given // given
long ms = System.currentTimeMillis(); long ms = System.currentTimeMillis();
long ns = ms * 1000_000 + random.nextInt(1000_000); long ns = ms * 1000_000 + random.nextInt(1000_000);
...@@ -26,8 +26,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -26,8 +26,6 @@ public class NanoSecondTimestampRestfulTest {
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -35,15 +33,13 @@ public class NanoSecondTimestampRestfulTest { ...@@ -35,15 +33,13 @@ public class NanoSecondTimestampRestfulTest {
} }
@Test @Test
public void insertUsingStringValue() { public void insertUsingStringValue() throws SQLException {
// given // given
// when // when
int ret = 0; int ret = 0;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('2021-01-01 12:00:00.123456789', 12.3, 4)"); ret = stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('2021-01-01 12:00:00.123456789', 12.3, 4)");
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -51,7 +47,7 @@ public class NanoSecondTimestampRestfulTest { ...@@ -51,7 +47,7 @@ public class NanoSecondTimestampRestfulTest {
} }
@Test @Test
public void insertUsingTimestampValue() { public void insertUsingTimestampValue() throws SQLException {
// given // given
long epochSec = System.currentTimeMillis() / 1000; long epochSec = System.currentTimeMillis() / 1000;
long nanoAdjustment = random.nextInt(1000_000_000); long nanoAdjustment = random.nextInt(1000_000_000);
...@@ -65,8 +61,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -65,8 +61,6 @@ public class NanoSecondTimestampRestfulTest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
ret = pstmt.executeUpdate(); ret = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -80,13 +74,11 @@ public class NanoSecondTimestampRestfulTest { ...@@ -80,13 +74,11 @@ public class NanoSecondTimestampRestfulTest {
long ns = ms * 1000_000L + random.nextInt(1000_000); long ns = ms * 1000_000L + random.nextInt(1000_000);
// when // when
ResultSet rs = null; ResultSet rs;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -102,13 +94,11 @@ public class NanoSecondTimestampRestfulTest { ...@@ -102,13 +94,11 @@ public class NanoSecondTimestampRestfulTest {
String timestampStr = "2021-01-01 12:00:00.123456789"; String timestampStr = "2021-01-01 12:00:00.123456789";
// when // when
ResultSet rs = null; ResultSet rs;
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)");
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -133,8 +123,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -133,8 +123,6 @@ public class NanoSecondTimestampRestfulTest {
pstmt.setFloat(2, 12.34f); pstmt.setFloat(2, 12.34f);
pstmt.setInt(3, 55); pstmt.setInt(3, 55);
pstmt.executeUpdate(); pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
// when // when
...@@ -142,8 +130,6 @@ public class NanoSecondTimestampRestfulTest { ...@@ -142,8 +130,6 @@ public class NanoSecondTimestampRestfulTest {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
rs = stmt.executeQuery("select * from weather"); rs = stmt.executeQuery("select * from weather");
rs.next(); rs.next();
} catch (SQLException e) {
e.printStackTrace();
} }
// then // then
...@@ -156,26 +142,21 @@ public class NanoSecondTimestampRestfulTest { ...@@ -156,26 +142,21 @@ public class NanoSecondTimestampRestfulTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
stmt.execute("drop table if exists weather"); stmt.execute("drop table if exists weather");
stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); stmt.execute("create table weather(ts timestamp, temperature float, humidity int)");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"; final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
try { conn = DriverManager.getConnection(url);
conn = DriverManager.getConnection(url); try (Statement stmt = conn.createStatement()) {
Statement stmt = conn.createStatement();
stmt.execute("drop database if exists " + dbname); stmt.execute("drop database if exists " + dbname);
stmt.execute("create database if not exists " + dbname + " precision 'ns'"); stmt.execute("create database if not exists " + dbname + " precision 'ns'");
stmt.execute("use " + dbname); stmt.execute("use " + dbname);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
...@@ -12,15 +12,13 @@ public class NullValueInResultSetJNITest { ...@@ -12,15 +12,13 @@ public class NullValueInResultSetJNITest {
Connection conn; Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather"); ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) { while (rs.next()) {
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -42,18 +40,12 @@ public class NullValueInResultSetJNITest { ...@@ -42,18 +40,12 @@ public class NullValueInResultSetJNITest {
stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)");
stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')"); stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')");
stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@After @After
public void after() { public void after() throws SQLException {
try { if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -12,7 +12,7 @@ public class NullValueInResultSetRestfulTest { ...@@ -12,7 +12,7 @@ public class NullValueInResultSetRestfulTest {
Connection conn; Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from weather"); ResultSet rs = stmt.executeQuery("select * from weather");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -21,9 +21,6 @@ public class NullValueInResultSetRestfulTest { ...@@ -21,9 +21,6 @@ public class NullValueInResultSetRestfulTest {
Object value = rs.getObject(i); Object value = rs.getObject(i);
} }
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -45,18 +42,12 @@ public class NullValueInResultSetRestfulTest { ...@@ -45,18 +42,12 @@ public class NullValueInResultSetRestfulTest {
stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)"); stmt.executeUpdate("insert into weather(ts, f7) values(now+7s, true)");
stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')"); stmt.executeUpdate("insert into weather(ts, f8) values(now+8s, 'hello')");
stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')"); stmt.executeUpdate("insert into weather(ts, f9) values(now+9s, '涛思数据')");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@After @After
public void after() { public void after() throws SQLException {
try { if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -20,7 +20,7 @@ public class PreparedStatementBatchInsertRestfulTest { ...@@ -20,7 +20,7 @@ public class PreparedStatementBatchInsertRestfulTest {
private Connection conn; private Connection conn;
@Test @Test
public void test() { public void test() throws SQLException {
// given // given
long ts = System.currentTimeMillis(); long ts = System.currentTimeMillis();
List<Object[]> rows = IntStream.range(0, 10).mapToObj(i -> { List<Object[]> rows = IntStream.range(0, 10).mapToObj(i -> {
...@@ -52,7 +52,6 @@ public class PreparedStatementBatchInsertRestfulTest { ...@@ -52,7 +52,6 @@ public class PreparedStatementBatchInsertRestfulTest {
} }
pstmt.executeBatch(); pstmt.executeBatch();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace();
Assert.fail(); Assert.fail();
} }
...@@ -64,35 +63,25 @@ public class PreparedStatementBatchInsertRestfulTest { ...@@ -64,35 +63,25 @@ public class PreparedStatementBatchInsertRestfulTest {
count++; count++;
} }
Assert.assertEquals(10, count); Assert.assertEquals(10, count);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.execute("create database if not exists " + dbname);
stmt.execute("create database if not exists " + dbname); stmt.execute("use " + dbname);
stmt.execute("use " + dbname); stmt.execute("create table meters(ts timestamp, current float, voltage int, phase int) tags(groupId int)");
stmt.execute("create table meters(ts timestamp, current float, voltage int, phase int) tags(groupId int)");
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.close();
stmt.close(); conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -19,26 +19,22 @@ public class QueryDataTest { ...@@ -19,26 +19,22 @@ public class QueryDataTest {
static String host = "127.0.0.1"; static String host = "127.0.0.1";
@Before @Before
public void createDatabase() { public void createDatabase() throws SQLException {
try { Properties properties = new Properties();
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root");
properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata");
properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); 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);
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("use " + dbName);
statement.executeUpdate("use " + dbName);
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))";
String createTableSql = "create table " + stbName + "(ts timestamp, name binary(64))"; statement.executeUpdate(createTableSql);
statement.executeUpdate(createTableSql);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -57,15 +53,11 @@ public class QueryDataTest { ...@@ -57,15 +53,11 @@ public class QueryDataTest {
} }
@After @After
public void close() { public void close() throws SQLException {
try { if (statement != null)
if (statement != null) statement.close();
statement.close(); if (connection != null)
if (connection != null) connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -15,19 +15,15 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { ...@@ -15,19 +15,15 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
private Connection connection; private Connection connection;
@Test @Test
public void testExecuteQuery() { public void testExecuteQuery() throws SQLException {
// given // given
ResultSetMetaData metaData = null; ResultSetMetaData metaData;
int columnCount = -1; int columnCount;
// when // when
try { Statement statement = connection.createStatement();
Statement statement = connection.createStatement(); metaData = statement.executeQuery("select * from weather").getMetaData();
metaData = statement.executeQuery("select * from weather").getMetaData(); columnCount = metaData.getColumnCount();
columnCount = metaData.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
// then // then
Assert.assertNotNull(metaData); Assert.assertNotNull(metaData);
...@@ -35,20 +31,17 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { ...@@ -35,20 +31,17 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
} }
@Test @Test
public void testExecute() { public void testExecute() throws SQLException {
// given // given
ResultSetMetaData metaData = null; ResultSetMetaData metaData;
int columnCount = -1; int columnCount;
boolean execute = false; boolean execute;
// when // when
try { Statement statement = connection.createStatement();
Statement statement = connection.createStatement(); execute = statement.execute("select * from weather");
execute = statement.execute("select * from weather"); metaData = statement.getResultSet().getMetaData();
metaData = statement.getResultSet().getMetaData(); columnCount = metaData.getColumnCount();
columnCount = metaData.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
// then // then
Assert.assertEquals(true, execute); Assert.assertEquals(true, execute);
...@@ -57,30 +50,22 @@ public class ResultSetMetaShouldNotBeNullRestfulTest { ...@@ -57,30 +50,22 @@ public class ResultSetMetaShouldNotBeNullRestfulTest {
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata");
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata"); Statement stmt = connection.createStatement();
Statement stmt = connection.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.execute("create database if not exists " + dbname);
stmt.execute("create database if not exists " + dbname); stmt.execute("use " + dbname);
stmt.execute("use " + dbname); stmt.execute("create table weather (ts timestamp, temperature float)");
stmt.execute("create table weather (ts timestamp, temperature float)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { Statement stmt = connection.createStatement();
Statement stmt = connection.createStatement(); stmt.execute("drop database if exists " + dbname);
stmt.execute("drop database if exists " + dbname); stmt.close();
stmt.close(); connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -17,25 +17,20 @@ public class SelectTest { ...@@ -17,25 +17,20 @@ public class SelectTest {
String host = "127.0.0.1"; String host = "127.0.0.1";
@Before @Before
public void createDatabaseAndTable() { public void createDatabaseAndTable() throws SQLException {
try { Properties properties = new Properties();
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root");
properties.setProperty(TSDBDriver.PROPERTY_KEY_USER, "root"); properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata");
properties.setProperty(TSDBDriver.PROPERTY_KEY_PASSWORD, "taosdata"); 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);
Statement stmt = connection.createStatement();
stmt.execute("drop database if exists " + dbName);
stmt.execute("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
Statement stmt = connection.createStatement();
stmt.execute("drop database if exists " + dbName);
stmt.execute("create database if not exists " + dbName);
stmt.execute("create table if not exists " + dbName + "." + tName + " (ts timestamp, k int, v int)");
stmt.close();
} }
@Test @Test
...@@ -65,16 +60,12 @@ public class SelectTest { ...@@ -65,16 +60,12 @@ public class SelectTest {
} }
@After @After
public void close() { public void close() throws SQLException {
try { if (connection != null) {
if (connection != null) { Statement stmt = connection.createStatement();
Statement stmt = connection.createStatement(); stmt.executeUpdate("drop database " + dbName);
stmt.executeUpdate("drop database " + dbName); stmt.close();
stmt.close(); connection.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
package com.taosdata.jdbc.cases;
import org.junit.Test;
import java.sql.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TaosInfoMonitorTest {
@Test
public void testCreateTooManyConnection() throws ClassNotFoundException {
Class.forName("com.taosdata.jdbc.TSDBDriver");
final String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata";
List<Connection> connectionList = IntStream.range(0, 100).mapToObj(i -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
return DriverManager.getConnection(url);
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
connectionList.forEach(conn -> {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("show databases");
while (rs.next()) {
}
TimeUnit.MILLISECONDS.sleep(100);
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
});
connectionList.forEach(conn -> {
try {
conn.close();
TimeUnit.MILLISECONDS.sleep(100);
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
});
}
}
...@@ -15,7 +15,7 @@ public class UnsignedNumberJniTest { ...@@ -15,7 +15,7 @@ public class UnsignedNumberJniTest {
private static long ts; private static long ts;
@Test @Test
public void testCase001() { public void testCase001() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -27,13 +27,11 @@ public class UnsignedNumberJniTest { ...@@ -27,13 +27,11 @@ public class UnsignedNumberJniTest {
Assert.assertEquals("2147483647", rs.getString(4)); Assert.assertEquals("2147483647", rs.getString(4));
Assert.assertEquals("9223372036854775807", rs.getString(5)); Assert.assertEquals("9223372036854775807", rs.getString(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase002() { public void testCase002() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -46,8 +44,6 @@ public class UnsignedNumberJniTest { ...@@ -46,8 +44,6 @@ public class UnsignedNumberJniTest {
Assert.assertEquals(2147483647, rs.getInt(4)); Assert.assertEquals(2147483647, rs.getInt(4));
Assert.assertEquals(9223372036854775807L, rs.getLong(5)); Assert.assertEquals(9223372036854775807L, rs.getLong(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -140,36 +136,28 @@ public class UnsignedNumberJniTest { ...@@ -140,36 +136,28 @@ public class UnsignedNumberJniTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
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");
ts = System.currentTimeMillis(); ts = System.currentTimeMillis();
try { final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; conn = DriverManager.getConnection(url, properties);
conn = DriverManager.getConnection(url, properties); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists unsign_jni");
stmt.execute("drop database if exists unsign_jni"); stmt.execute("create database if not exists unsign_jni");
stmt.execute("create database if not exists unsign_jni"); stmt.execute("use unsign_jni");
stmt.execute("use unsign_jni"); stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)");
stmt.execute("create table us_table(ts timestamp, f1 tinyint unsigned, f2 smallint unsigned, f3 int unsigned, f4 bigint unsigned)"); stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)");
stmt.executeUpdate("insert into us_table(ts,f1,f2,f3,f4) values(" + ts + ", 127, 32767,2147483647, 9223372036854775807)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -16,7 +16,7 @@ public class UnsignedNumberRestfulTest { ...@@ -16,7 +16,7 @@ public class UnsignedNumberRestfulTest {
private static long ts; private static long ts;
@Test @Test
public void testCase001() { public void testCase001() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -28,13 +28,11 @@ public class UnsignedNumberRestfulTest { ...@@ -28,13 +28,11 @@ public class UnsignedNumberRestfulTest {
Assert.assertEquals("2147483647", rs.getString(4)); Assert.assertEquals("2147483647", rs.getString(4));
Assert.assertEquals("9223372036854775807", rs.getString(5)); Assert.assertEquals("9223372036854775807", rs.getString(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void testCase002() { public void testCase002() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select * from us_table"); ResultSet rs = stmt.executeQuery("select * from us_table");
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -47,8 +45,6 @@ public class UnsignedNumberRestfulTest { ...@@ -47,8 +45,6 @@ public class UnsignedNumberRestfulTest {
Assert.assertEquals(2147483647, rs.getInt(4)); Assert.assertEquals(2147483647, rs.getInt(4));
Assert.assertEquals(9223372036854775807L, rs.getLong(5)); Assert.assertEquals(9223372036854775807L, rs.getLong(5));
} }
} catch (SQLException e) {
e.printStackTrace();
} }
} }
......
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.cases;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.sql.*; import java.sql.*;
...@@ -12,7 +11,7 @@ public class UseNowInsertTimestampTest { ...@@ -12,7 +11,7 @@ public class UseNowInsertTimestampTest {
String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; String url = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata";
@Test @Test
public void millisec() { public void millisec() throws SQLException {
try (Connection conn = DriverManager.getConnection(url)) { try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
...@@ -30,13 +29,11 @@ public class UseNowInsertTimestampTest { ...@@ -30,13 +29,11 @@ public class UseNowInsertTimestampTest {
assertEquals(0, nanos % 1000_000); assertEquals(0, nanos % 1000_000);
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void microsec() { public void microsec() throws SQLException {
try (Connection conn = DriverManager.getConnection(url)) { try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
...@@ -53,13 +50,11 @@ public class UseNowInsertTimestampTest { ...@@ -53,13 +50,11 @@ public class UseNowInsertTimestampTest {
assertEquals(0, nanos % 1000); assertEquals(0, nanos % 1000);
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
@Test @Test
public void nanosec() { public void nanosec() throws SQLException {
try (Connection conn = DriverManager.getConnection(url)) { try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
...@@ -77,8 +72,6 @@ public class UseNowInsertTimestampTest { ...@@ -77,8 +72,6 @@ public class UseNowInsertTimestampTest {
assertTrue(nanos % 1000 != 0); assertTrue(nanos % 1000 != 0);
stmt.execute("drop database if exists test"); stmt.execute("drop database if exists test");
} catch (SQLException e) {
e.printStackTrace();
} }
} }
} }
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver; import com.taosdata.jdbc.TSDBDriver;
...@@ -19,26 +19,22 @@ public class BadLocaleSettingTest { ...@@ -19,26 +19,22 @@ public class BadLocaleSettingTest {
private static Connection conn; private static Connection conn;
@Test @Test
public void canSetLocale() { public void canSetLocale() throws SQLException {
try { 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");
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; conn = DriverManager.getConnection(url, properties);
conn = DriverManager.getConnection(url, properties); Statement stmt = conn.createStatement();
Statement stmt = conn.createStatement(); stmt.execute("drop database if exists " + dbName);
stmt.execute("drop database if exists " + dbName); stmt.execute("create database if not exists " + dbName);
stmt.execute("create database if not exists " + dbName); stmt.execute("use " + dbName);
stmt.execute("use " + dbName); stmt.execute("drop table if exists weather");
stmt.execute("drop table if exists weather"); stmt.execute("create table weather(ts timestamp, temperature float, humidity int)");
stmt.execute("create table weather(ts timestamp, temperature float, humidity int)"); stmt.executeUpdate("insert into weather values(1624071506435, 12.3, 4)");
stmt.executeUpdate("insert into weather values(1624071506435, 12.3, 4)"); stmt.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
@BeforeClass @BeforeClass
...@@ -48,12 +44,8 @@ public class BadLocaleSettingTest { ...@@ -48,12 +44,8 @@ public class BadLocaleSettingTest {
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
package com.taosdata.jdbc.confprops;
import org.junit.*;
import org.junit.runners.MethodSorters;
import java.sql.*;
import java.util.Random;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BatchFetchTest {
private static String host = "127.0.0.1";
private long rowFetchCost, batchFetchCost;
@Test
public void case01_rowFetch() throws SQLException {
String url = "jdbc:TAOS://" + host + ":6030/test?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
boolean batchfetch = Boolean.parseBoolean(conn.getClientInfo("batchfetch"));
Assert.assertFalse(batchfetch);
long start = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
}
long end = System.currentTimeMillis();
rowFetchCost = end - start;
}
}
@Test
public void case02_batchFetch() throws SQLException {
String url = "jdbc:TAOS://" + host + ":6030/test?user=root&password=taosdata&batchfetch=true";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
boolean batchfetch = Boolean.parseBoolean(conn.getClientInfo("batchfetch"));
Assert.assertTrue(batchfetch);
long start = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
}
long end = System.currentTimeMillis();
batchFetchCost = end - start;
}
}
@Test
public void case03_batchFetchFastThanRowFetch() {
Assert.assertTrue(rowFetchCost - batchFetchCost >= 0);
}
@BeforeClass
public static void beforeClass() throws SQLException {
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, f int) tags(t int)");
for (int i = 0; i < 1000; i++) {
stmt.execute(generateSql(100, 100));
}
}
}
private static String generateSql(int tableSize, int valueSize) {
Random random = new Random(System.currentTimeMillis());
StringBuilder builder = new StringBuilder("insert into ");
for (int i = 0; i < tableSize; i++) {
builder.append("t" + i).append(" using weather tags(").append(random.nextInt(100)).append(") values");
for (int j = 0; j < valueSize; j++) {
builder.append(" (now + ").append(i).append("s, ").append(random.nextInt(100)).append(")");
}
}
return builder.toString();
}
}
package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver;
import org.junit.Assert;
import org.junit.Test;
import java.sql.*;
import java.util.Properties;
public class CharsetTest {
private static final String host = "127.0.0.1";
@Test
public void test() throws SQLException {
// given
String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// when
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, temperature nchar(10))");
stmt.execute("insert into weather values(now, '北京')");
// then
ResultSet rs = stmt.executeQuery("select * from weather");
while (rs.next()) {
Object value = rs.getObject("temperature");
Assert.assertTrue(value instanceof String);
Assert.assertEquals("北京", value.toString());
}
}
}
}
package com.taosdata.jdbc.rs; package com.taosdata.jdbc.confprops;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
......
package com.taosdata.jdbc.confprops;
import org.junit.Assert;
import org.junit.Test;
import java.sql.*;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TaosInfoMonitorTest {
private static final String host = "127.0.0.1";
private Random random = new Random(System.currentTimeMillis());
@Test
public void testCreateTooManyConnection() throws InterruptedException {
List<Thread> threads = IntStream.range(1, 11).mapToObj(i -> new Thread(() -> {
final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata";
int connSize = random.nextInt(10);
for (int j = 0; j < connSize; j++) {
try {
Connection conn = DriverManager.getConnection(url);
TimeUnit.MILLISECONDS.sleep(random.nextInt(3000));
int stmtSize = random.nextInt(100);
for (int k = 0; k < stmtSize; k++) {
Statement stmt = conn.createStatement();
TimeUnit.MILLISECONDS.sleep(random.nextInt(3000));
ResultSet rs = stmt.executeQuery("show databases");
while (rs.next()) {
}
rs.close();
stmt.close();
}
} catch (SQLException | InterruptedException throwables) {
Assert.fail();
}
}
}, "thread-" + i)).collect(Collectors.toList());
threads.forEach(Thread::start);
for (Thread thread : threads) {
thread.join();
}
}
}
package com.taosdata.jdbc.cases; package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver; import com.taosdata.jdbc.TSDBDriver;
import org.junit.Test; import org.junit.Test;
......
package com.taosdata.jdbc.confprops;
import com.taosdata.jdbc.TSDBDriver;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.sql.*;
import java.time.Instant;
import java.util.Properties;
public class TimestampFormatTest {
private static final String host = "127.0.0.1";
private long ts = Instant.now().toEpochMilli();
@Test
public void string() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
// when
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals("STRING", actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
String value = rs.getString("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value);
}
}
}
@Test
public void stringInProperties() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
// when
String timestampFormat = "STRING";
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat);
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
String value = rs.getString("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value);
}
}
}
@Test
public void timestampInUrl() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata&timestampFormat=";
String timestampFormat = "TIMESTAMP";
// when
try (Connection conn = DriverManager.getConnection(url + timestampFormat);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Test
public void timestampInProperties() throws SQLException {
// given
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
String timestampFormat = "TIMESTAMP";
// when
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat);
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Test
public void utcInUrl() throws SQLException {
// given
String timestampFormat = "UTC";
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata&timestampFormat=" + timestampFormat;
// when & then
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
Assert.assertTrue(value instanceof Timestamp);
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Test
public void utcInProperties() throws SQLException {
// given
String timestampFormat = "UTC";
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
// when
Properties props = new Properties();
props.setProperty(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT, timestampFormat);
try (Connection conn = DriverManager.getConnection(url, props);
Statement stmt = conn.createStatement()) {
// then
String actual = conn.getClientInfo(TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT);
Assert.assertEquals(timestampFormat, actual);
ResultSet rs = stmt.executeQuery("select * from test.weather");
while (rs.next()) {
Object value = rs.getObject("ts");
Assert.assertTrue(value instanceof Timestamp);
String expect = new Timestamp(ts).toString();
Assert.assertEquals(expect, value.toString());
}
}
}
@Before
public void before() throws SQLException {
String url = "jdbc:TAOS-RS://" + host + ":6041/?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute("drop database if exists test");
stmt.execute("create database if not exists test");
stmt.execute("use test");
stmt.execute("create table weather(ts timestamp, temperature nchar(10))");
stmt.execute("insert into weather values(" + ts + ", '北京')");
}
}
}
...@@ -23,14 +23,12 @@ public class RestfulConnectionTest { ...@@ -23,14 +23,12 @@ public class RestfulConnectionTest {
} }
@Test @Test
public void createStatement() { public void createStatement() throws SQLException {
try (Statement stmt = conn.createStatement()) { try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select server_status()"); ResultSet rs = stmt.executeQuery("select server_status()");
rs.next(); rs.next();
int status = rs.getInt("server_status()"); int status = rs.getInt("server_status()");
assertEquals(1, status); assertEquals(1, status);
} catch (SQLException e) {
e.printStackTrace();
} }
} }
...@@ -359,13 +357,9 @@ public class RestfulConnectionTest { ...@@ -359,13 +357,9 @@ public class RestfulConnectionTest {
} }
@Test @Test
public void unwrap() { public void unwrap() throws SQLException {
try { RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class);
RestfulConnection restfulConnection = conn.unwrap(RestfulConnection.class); Assert.assertNotNull(restfulConnection);
Assert.assertNotNull(restfulConnection);
} catch (SQLException e) {
e.printStackTrace();
}
} }
@Test @Test
...@@ -374,32 +368,22 @@ public class RestfulConnectionTest { ...@@ -374,32 +368,22 @@ public class RestfulConnectionTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { Properties properties = new Properties();
Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/log?user=root&password=taosdata", properties);
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); // create test database for test cases
conn = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/log?user=root&password=taosdata", properties); try (Statement stmt = conn.createStatement()) {
// create test database for test cases stmt.execute("create database if not exists test");
try (Statement stmt = conn.createStatement()) {
stmt.execute("create database if not exists test");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} }
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (conn != null)
if (conn != null) conn.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -1085,30 +1085,26 @@ public class RestfulDatabaseMetaDataTest { ...@@ -1085,30 +1085,26 @@ public class RestfulDatabaseMetaDataTest {
} }
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() throws SQLException {
try { Properties properties = new Properties();
Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
Properties properties = new Properties(); properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); connection = DriverManager.getConnection(url, properties);
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); Statement stmt = connection.createStatement();
connection = DriverManager.getConnection(url, properties); stmt.execute("drop database if exists log");
metaData = connection.getMetaData().unwrap(RestfulDatabaseMetaData.class); stmt.execute("create database if not exists log precision 'us'");
} catch (ClassNotFoundException e) { stmt.execute("use log");
e.printStackTrace(); stmt.execute("create table `dn` (ts TIMESTAMP,cpu_taosd FLOAT,cpu_system FLOAT,cpu_cores INT,mem_taosd FLOAT,mem_system FLOAT,mem_total INT,disk_used FLOAT,disk_total INT,band_speed FLOAT,io_read FLOAT,io_write FLOAT,req_http INT,req_select INT,req_insert INT) TAGS (dnodeid INT,fqdn BINARY(128))");
} catch (SQLException e) { stmt.execute("insert into dn1 using dn tags(1,'a') (ts) values(now)");
e.printStackTrace();
} metaData = connection.getMetaData().unwrap(RestfulDatabaseMetaData.class);
} }
@AfterClass @AfterClass
public static void afterClass() { public static void afterClass() throws SQLException {
try { if (connection != null)
if (connection != null) connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
\ No newline at end of file
...@@ -14,7 +14,7 @@ public class RestfulJDBCTest { ...@@ -14,7 +14,7 @@ public class RestfulJDBCTest {
private Connection connection; private Connection connection;
@Test @Test
public void testCase001() { public void testCase001() throws SQLException {
// given // given
String sql = "drop database if exists restful_test"; String sql = "drop database if exists restful_test";
// when // when
...@@ -38,7 +38,7 @@ public class RestfulJDBCTest { ...@@ -38,7 +38,7 @@ public class RestfulJDBCTest {
} }
@Test @Test
public void testCase002() { public void testCase002() throws SQLException {
// given // given
String sql = "create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"; String sql = "create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)";
// when // when
...@@ -48,7 +48,7 @@ public class RestfulJDBCTest { ...@@ -48,7 +48,7 @@ public class RestfulJDBCTest {
} }
@Test @Test
public void testCase004() { public void testCase004() throws SQLException {
for (int i = 1; i <= 100; i++) { for (int i = 1; i <= 100; i++) {
// given // given
String sql = "create table t" + i + " using weather tags('beijing', '" + i + "')"; String sql = "create table t" + i + " using weather tags('beijing', '" + i + "')";
...@@ -60,7 +60,7 @@ public class RestfulJDBCTest { ...@@ -60,7 +60,7 @@ public class RestfulJDBCTest {
} }
@Test @Test
public void testCase005() { public void testCase005() throws SQLException {
int rows = 0; int rows = 0;
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
for (int j = 1; j <= 100; j++) { for (int j = 1; j <= 100; j++) {
...@@ -99,7 +99,7 @@ public class RestfulJDBCTest { ...@@ -99,7 +99,7 @@ public class RestfulJDBCTest {
} }
@Test @Test
public void testCase007() { public void testCase007() throws SQLException {
// given // given
String sql = "drop database restful_test"; String sql = "drop database restful_test";
...@@ -110,51 +110,34 @@ public class RestfulJDBCTest { ...@@ -110,51 +110,34 @@ public class RestfulJDBCTest {
Assert.assertFalse(execute); Assert.assertFalse(execute);
} }
private int executeUpdate(Connection connection, String sql) { private int executeUpdate(Connection connection, String sql) throws SQLException {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
return stmt.executeUpdate(sql); return stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} }
return 0;
} }
private boolean execute(Connection connection, String sql) { private boolean execute(Connection connection, String sql) throws SQLException {
try (Statement stmt = connection.createStatement()) { try (Statement stmt = connection.createStatement()) {
return stmt.execute(sql); return stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} }
return false;
} }
private ResultSet executeQuery(Connection connection, String sql) { private ResultSet executeQuery(Connection connection, String sql) throws SQLException {
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
return statement.executeQuery(sql); return statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
} }
return null;
} }
@Before @Before
public void before() { public void before() throws SQLException {
try { connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata&httpKeepAlive=false");
connection = DriverManager.getConnection("jdbc:TAOS-RS://" + host + ":6041/restful_test?user=root&password=taosdata");
} catch (SQLException e) {
e.printStackTrace();
}
} }
@After @After
public void after() { public void after() throws SQLException {
try { if (connection != null)
if (connection != null) connection.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
...@@ -543,15 +543,6 @@ public class SQLTest { ...@@ -543,15 +543,6 @@ public class SQLTest {
Assert.assertNotNull(rs); Assert.assertNotNull(rs);
} }
@Test
public void testCase053() {
String sql = "select avg(cpu_taosd), avg(cpu_system), max(cpu_cores), avg(mem_taosd), avg(mem_system), max(mem_total), avg(disk_used), max(disk_total), avg(band_speed), avg(io_read), avg(io_write), sum(req_http), sum(req_select), sum(req_insert) from log.dn1 where ts> now - 60m and ts<= now interval(1m) fill(value, 0)";
// when
ResultSet rs = executeQuery(connection, sql);
// then
Assert.assertNotNull(rs);
}
private boolean execute(Connection connection, String sql) { private boolean execute(Connection connection, String sql) {
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
return statement.execute(sql); return statement.execute(sql);
......
...@@ -17,7 +17,6 @@ public class HttpClientPoolUtilTest { ...@@ -17,7 +17,6 @@ public class HttpClientPoolUtilTest {
String user = "root"; String user = "root";
String password = "taosdata"; String password = "taosdata";
String host = "127.0.0.1"; String host = "127.0.0.1";
// String host = "master";
@Test @Test
public void useLog() { public void useLog() {
......
...@@ -485,8 +485,8 @@ typedef struct { ...@@ -485,8 +485,8 @@ typedef struct {
int16_t numOfCols; // the number of columns will be load from vnode int16_t numOfCols; // the number of columns will be load from vnode
SInterval interval; SInterval interval;
SSessionWindow sw; // session window SSessionWindow sw; // session window
uint16_t tagCondLen; // tag length in current query uint32_t tagCondLen; // tag length in current query
uint16_t colCondLen; // column length in current query int32_t colCondLen; // column length in current query
int16_t numOfGroupCols; // num of group by columns int16_t numOfGroupCols; // num of group by columns
int16_t orderByIdx; int16_t orderByIdx;
int16_t orderType; // used in group by xx order by xxx int16_t orderType; // used in group by xx order by xxx
......
...@@ -2,12 +2,13 @@ CMAKE_MINIMUM_REQUIRED(VERSION 3.0...3.20) ...@@ -2,12 +2,13 @@ CMAKE_MINIMUM_REQUIRED(VERSION 3.0...3.20)
PROJECT(TDengine) PROJECT(TDengine)
INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/client/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/client/inc)
INCLUDE_DIRECTORIES(inc)
FIND_PACKAGE(Git) FIND_PACKAGE(Git)
IF (GIT_FOUND) IF (GIT_FOUND)
MESSAGE("Git found") MESSAGE("Git found")
EXECUTE_PROCESS( EXECUTE_PROCESS(
COMMAND ${GIT_EXECUTABLE} log --pretty=oneline -n 1 ${CMAKE_CURRENT_LIST_DIR}/taosdemo.c COMMAND ${GIT_EXECUTABLE} log --pretty=oneline -n 1 ${CMAKE_CURRENT_LIST_DIR}
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
RESULT_VARIABLE RESULT RESULT_VARIABLE RESULT
OUTPUT_VARIABLE TAOSDEMO_COMMIT_SHA1) OUTPUT_VARIABLE TAOSDEMO_COMMIT_SHA1)
...@@ -18,7 +19,7 @@ IF (GIT_FOUND) ...@@ -18,7 +19,7 @@ IF (GIT_FOUND)
STRING(STRIP "${TAOSDEMO_COMMIT_SHA1}" TAOSDEMO_COMMIT_SHA1) STRING(STRIP "${TAOSDEMO_COMMIT_SHA1}" TAOSDEMO_COMMIT_SHA1)
ENDIF () ENDIF ()
EXECUTE_PROCESS( EXECUTE_PROCESS(
COMMAND ${GIT_EXECUTABLE} status -z -s ${CMAKE_CURRENT_LIST_DIR}/taosdemo.c COMMAND ${GIT_EXECUTABLE} status -z -s ${CMAKE_CURRENT_LIST_DIR}
RESULT_VARIABLE RESULT RESULT_VARIABLE RESULT
OUTPUT_VARIABLE TAOSDEMO_STATUS) OUTPUT_VARIABLE TAOSDEMO_STATUS)
IF (TD_LINUX) IF (TD_LINUX)
...@@ -64,7 +65,7 @@ ELSE () ...@@ -64,7 +65,7 @@ ELSE ()
ENDIF () ENDIF ()
IF (TD_LINUX) IF (TD_LINUX)
AUX_SOURCE_DIRECTORY(. SRC) AUX_SOURCE_DIRECTORY(./src SRC)
ADD_EXECUTABLE(taosdemo ${SRC}) ADD_EXECUTABLE(taosdemo ${SRC})
IF (TD_SOMODE_STATIC) IF (TD_SOMODE_STATIC)
...@@ -73,9 +74,9 @@ IF (TD_LINUX) ...@@ -73,9 +74,9 @@ IF (TD_LINUX)
TARGET_LINK_LIBRARIES(taosdemo taos cJson ${LINK_JEMALLOC}) TARGET_LINK_LIBRARIES(taosdemo taos cJson ${LINK_JEMALLOC})
ENDIF () ENDIF ()
ELSEIF (TD_WINDOWS) ELSEIF (TD_WINDOWS)
AUX_SOURCE_DIRECTORY(. SRC) AUX_SOURCE_DIRECTORY(./src SRC)
ADD_EXECUTABLE(taosdemo ${SRC}) ADD_EXECUTABLE(taosdemo ${SRC})
SET_SOURCE_FILES_PROPERTIES(./taosdemo.c PROPERTIES COMPILE_FLAGS -w) SET_SOURCE_FILES_PROPERTIES(./src/demoUtil.c PROPERTIES COMPILE_FLAGS -w)
IF (TD_SOMODE_STATIC) IF (TD_SOMODE_STATIC)
TARGET_LINK_LIBRARIES(taosdemo taos_static cJson lua) TARGET_LINK_LIBRARIES(taosdemo taos_static cJson lua)
ELSE () ELSE ()
...@@ -83,7 +84,7 @@ ELSEIF (TD_WINDOWS) ...@@ -83,7 +84,7 @@ ELSEIF (TD_WINDOWS)
ENDIF () ENDIF ()
ELSEIF (TD_DARWIN) ELSEIF (TD_DARWIN)
# missing a few dependencies, such as <argp.h> # missing a few dependencies, such as <argp.h>
AUX_SOURCE_DIRECTORY(. SRC) AUX_SOURCE_DIRECTORY(./src SRC)
ADD_EXECUTABLE(taosdemo ${SRC}) ADD_EXECUTABLE(taosdemo ${SRC})
IF (TD_SOMODE_STATIC) IF (TD_SOMODE_STATIC)
......
此差异已折叠。
/*
* Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
*
* This program is free software: you can use, redistribute, and/or modify
* it under the terms of the GNU Affero General Public License, version 3
* or later ("AGPL"), as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __DEMODATA__
#define __DEMODATA__
#include "cJSON.h"
#include "demo.h"
/***** Global variables ******/
extern char * g_sampleDataBuf;
extern char * g_sampleBindBatchArray;
extern int32_t * g_randint;
extern uint32_t *g_randuint;
extern int64_t * g_randbigint;
extern uint64_t *g_randubigint;
extern float * g_randfloat;
extern double * g_randdouble;
extern char * g_randbool_buff;
extern char * g_randint_buff;
extern char * g_randuint_buff;
extern char * g_rand_voltage_buff;
extern char * g_randbigint_buff;
extern char * g_randubigint_buff;
extern char * g_randsmallint_buff;
extern char * g_randusmallint_buff;
extern char * g_randtinyint_buff;
extern char * g_randutinyint_buff;
extern char * g_randfloat_buff;
extern char * g_rand_current_buff;
extern char * g_rand_phase_buff;
extern char * g_randdouble_buff;
/***** Declare functions *****/
int init_rand_data();
char * rand_bool_str();
int32_t rand_bool();
char * rand_tinyint_str();
int32_t rand_tinyint();
char * rand_utinyint_str();
int32_t rand_utinyint();
char * rand_smallint_str();
int32_t rand_smallint();
char * rand_usmallint_str();
int32_t rand_usmallint();
char * rand_int_str();
int32_t rand_int();
char * rand_uint_str();
int32_t rand_uint();
char * rand_bigint_str();
int64_t rand_bigint();
char * rand_ubigint_str();
int64_t rand_ubigint();
char * rand_float_str();
float rand_float();
char * demo_current_float_str();
float UNUSED_FUNC demo_current_float();
char * demo_voltage_int_str();
int32_t UNUSED_FUNC demo_voltage_int();
char * demo_phase_float_str();
float UNUSED_FUNC demo_phase_float();
void rand_string(char *str, int size);
char * rand_double_str();
double rand_double();
int generateTagValuesForStb(SSuperTable *stbInfo, int64_t tableSeq,
char *tagsValBuf);
int64_t getTSRandTail(int64_t timeStampStep, int32_t seq, int disorderRatio,
int disorderRange);
int32_t prepareStbStmtBindTag(char *bindArray, SSuperTable *stbInfo,
char *tagsVal, int32_t timePrec);
int32_t prepareStmtWithoutStb(threadInfo *pThreadInfo, char *tableName,
uint32_t batch, int64_t insertRows,
int64_t recordFrom, int64_t startTime);
int32_t generateStbInterlaceData(threadInfo *pThreadInfo, char *tableName,
uint32_t batchPerTbl, uint64_t i,
uint32_t batchPerTblTimes, uint64_t tableSeq,
char *buffer, int64_t insertRows,
int64_t startTime, uint64_t *pRemainderBufLen);
int64_t generateInterlaceDataWithoutStb(char *tableName, uint32_t batch,
uint64_t tableSeq, char *dbName,
char *buffer, int64_t insertRows,
int64_t startTime,
uint64_t *pRemainderBufLen);
int32_t generateStbProgressiveData(SSuperTable *stbInfo, char *tableName,
int64_t tableSeq, char *dbName, char *buffer,
int64_t insertRows, uint64_t recordFrom,
int64_t startTime, int64_t *pSamplePos,
int64_t *pRemainderBufLen);
int32_t generateProgressiveDataWithoutStb(
char *tableName, threadInfo *pThreadInfo, char *buffer, int64_t insertRows,
uint64_t recordFrom, int64_t startTime, int64_t *pRemainderBufLen);
int64_t generateStbRowData(SSuperTable *stbInfo, char *recBuf,
int64_t remainderBufLen, int64_t timestamp);
int prepareSampleForStb(SSuperTable *stbInfo);
int prepareSampleForNtb();
int parseSamplefileToStmtBatch(SSuperTable *stbInfo);
int parseStbSampleToStmtBatchForThread(threadInfo * pThreadInfo,
SSuperTable *stbInfo, uint32_t timePrec,
uint32_t batch);
int parseNtbSampleToStmtBatchForThread(threadInfo *pThreadInfo,
uint32_t timePrec, uint32_t batch);
int prepareSampleData();
int32_t generateSmlConstPart(char *sml, SSuperTable *stbInfo,
threadInfo *pThreadInfo, int tbSeq);
int32_t generateSmlMutablePart(char *line, char *sml, SSuperTable *stbInfo,
threadInfo *pThreadInfo, int64_t timestamp);
int32_t generateSmlJsonTags(cJSON *tagsList, SSuperTable *stbInfo,
threadInfo *pThreadInfo, int tbSeq);
int32_t generateSmlJsonCols(cJSON *array, cJSON *tag, SSuperTable *stbInfo,
threadInfo *pThreadInfo, int64_t timestamp);
#endif
\ No newline at end of file
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
"cache": 16, "cache": 16,
"blocks": 8, "blocks": 8,
"precision": "ms", "precision": "ms",
"keep": 365, "keep": 36500,
"minRows": 100, "minRows": 100,
"maxRows": 4096, "maxRows": 4096,
"comp":2, "comp":2,
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
/*
* Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
*
* This program is free software: you can use, redistribute, and/or modify
* it under the terms of the GNU Affero General Public License, version 3
* or later ("AGPL"), as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "demo.h"
int64_t g_totalChildTables = DEFAULT_CHILDTABLES;
int64_t g_actualChildTables = 0;
FILE * g_fpOfInsertResult = NULL;
char * g_dupstr = NULL;
SDbs g_Dbs;
SQueryMetaInfo g_queryInfo;
SArguments g_args = {
DEFAULT_METAFILE, // metaFile
DEFAULT_TEST_MODE, // test_mode
DEFAULT_HOST, // host
DEFAULT_PORT, // port
DEFAULT_IFACE, // iface
TSDB_DEFAULT_USER, // user
TSDB_DEFAULT_PASS, // password
DEFAULT_DATABASE, // database
DEFAULT_REPLICA, // replica
DEFAULT_TB_PREFIX, // tb_prefix
DEFAULT_ESCAPE_CHAR, // escapeChar
DEFAULT_SQLFILE, // sqlFile
DEFAULT_USE_METRIC, // use_metric
DEFAULT_DROP_DB, // drop_database
DEFAULT_AGGR_FUNC, // aggr_func
DEFAULT_DEBUG, // debug_print
DEFAULT_VERBOSE, // verbose_print
DEFAULT_PERF_STAT, // performance statistic print
DEFAULT_ANS_YES, // answer_yes;
DEFAULT_OUTPUT, // output_file
DEFAULT_SYNC_MODE, // mode : sync or async
DEFAULT_DATA_TYPE, // data_type
DEFAULT_DATATYPE, // dataType
DEFAULT_BINWIDTH, // binwidth
DEFAULT_COL_COUNT, // columnCount, timestamp + float + int + float
DEFAULT_LEN_ONE_ROW, // lenOfOneRow
DEFAULT_NTHREADS, // nthreads
DEFAULT_INSERT_INTERVAL, // insert_interval
DEFAULT_TIMESTAMP_STEP, // timestamp_step
DEFAULT_QUERY_TIME, // query_times
DEFAULT_PREPARED_RAND, // prepared_rand
DEFAULT_INTERLACE_ROWS, // interlaceRows;
DEFAULT_REQ_PER_REQ, // reqPerReq
TSDB_MAX_ALLOWED_SQL_LEN, // max_sql_len
DEFAULT_CHILDTABLES, // ntables
DEFAULT_INSERT_ROWS, // insertRows
DEFAULT_ABORT, // abort
DEFAULT_RATIO, // disorderRatio
DEFAULT_DISORDER_RANGE, // disorderRange
DEFAULT_METHOD_DEL, // method_of_delete
DEFAULT_TOTAL_INSERT, // totalInsertRows;
DEFAULT_TOTAL_AFFECT, // totalAffectedRows;
DEFAULT_DEMO_MODE, // demo_mode;
};
int main(int argc, char *argv[]) {
if (parse_args(argc, argv)) {
exit(EXIT_FAILURE);
}
debugPrint("meta file: %s\n", g_args.metaFile);
if (g_args.metaFile) {
g_totalChildTables = 0;
if (getInfoFromJsonFile(g_args.metaFile)) {
exit(EXIT_FAILURE);
}
if (testMetaFile()) {
exit(EXIT_FAILURE);
}
} else {
memset(&g_Dbs, 0, sizeof(SDbs));
g_Dbs.db = calloc(1, sizeof(SDataBase));
if (NULL == g_Dbs.db) {
errorPrint("%s", "failed to allocate memory\n");
}
g_Dbs.db[0].superTbls = calloc(1, sizeof(SSuperTable));
if (NULL == g_Dbs.db[0].superTbls) {
errorPrint("%s", "failed to allocate memory\n");
}
setParaFromArg();
if (NULL != g_args.sqlFile) {
TAOS *qtaos = taos_connect(g_Dbs.host, g_Dbs.user, g_Dbs.password,
g_Dbs.db[0].dbName, g_Dbs.port);
querySqlFile(qtaos, g_args.sqlFile);
taos_close(qtaos);
} else {
testCmdLine();
}
}
postFreeResource();
return 0;
}
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
...@@ -1139,7 +1139,7 @@ static int32_t mnodeAlterDbFp(SMnodeMsg *pMsg) { ...@@ -1139,7 +1139,7 @@ static int32_t mnodeAlterDbFp(SMnodeMsg *pMsg) {
return sdbUpdateRow(&row); return sdbUpdateRow(&row);
} }
//bnNotify(); bnNotify();
return TSDB_CODE_MND_ACTION_IN_PROGRESS; return TSDB_CODE_MND_ACTION_IN_PROGRESS;
} }
......
...@@ -121,7 +121,7 @@ static int32_t mnodeProcessShowMsg(SMnodeMsg *pMsg) { ...@@ -121,7 +121,7 @@ static int32_t mnodeProcessShowMsg(SMnodeMsg *pMsg) {
} }
if (!tsMnodeShowMetaFp[pShowMsg->type] || !tsMnodeShowRetrieveFp[pShowMsg->type]) { if (!tsMnodeShowMetaFp[pShowMsg->type] || !tsMnodeShowRetrieveFp[pShowMsg->type]) {
mError("show type:%s is not support", mnodeGetShowType(pShowMsg->type)); mWarn("show type:%s is not support", mnodeGetShowType(pShowMsg->type));
return TSDB_CODE_COM_OPS_NOT_SUPPORT; return TSDB_CODE_COM_OPS_NOT_SUPPORT;
} }
......
...@@ -276,10 +276,10 @@ int32_t mnodeCreateUser(SAcctObj *pAcct, char *name, char *pass, void *pMsg) { ...@@ -276,10 +276,10 @@ int32_t mnodeCreateUser(SAcctObj *pAcct, char *name, char *pass, void *pMsg) {
code = sdbInsertRow(&row); code = sdbInsertRow(&row);
if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_MND_ACTION_IN_PROGRESS) { if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_MND_ACTION_IN_PROGRESS) {
mError("user:%s, failed to create by %s, reason:%s", pUser->user, mnodeGetUserFromMsg(pMsg), tstrerror(code)); mError("user:%s, failed to create, reason:%s", pUser->user, tstrerror(code));
tfree(pUser); tfree(pUser);
} else { } else {
mLInfo("user:%s, is created by %s", pUser->user, mnodeGetUserFromMsg(pMsg)); mLInfo("user:%s, is created successfully", pUser->user);
} }
return code; return code;
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册