diff --git a/Jenkinsfile b/Jenkinsfile index 15640f81393f5544cf16d75fa72da062dbbda8b0..0f0a09f2be366eab9488e281f7d65ce9d7592e24 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -116,7 +116,7 @@ def pre_test(){ make > /dev/null make install > /dev/null cd ${WKC}/tests - pip3 install ${WKC}/src/connector/python/ + pip3 install taospy ''' return 1 } diff --git a/Jenkinsfile2 b/Jenkinsfile2 index d93ed9df5b70ce791c444005316bc279ef82666f..4acb3a78b3ca8e96fec4f4e6ccdccecb2f31da04 100644 --- a/Jenkinsfile2 +++ b/Jenkinsfile2 @@ -21,21 +21,25 @@ def sync_source() { if (env.CHANGE_TARGET == 'master') { sh ''' cd ${WKC} + git clean -fxd git checkout master ''' } else if (env.CHANGE_TARGET == '2.0') { sh ''' cd ${WKC} + git clean -fxd git checkout 2.0 ''' } else if (env.CHANGE_TARGET == '2.4') { sh ''' cd ${WKC} + git clean -fxd git checkout 2.4 ''' } else { sh ''' cd ${WKC} + git clean -fxd git checkout develop ''' } @@ -83,6 +87,16 @@ def sync_source() { cd ${WKC} git fetch origin +refs/pull/${CHANGE_ID}/merge git checkout -qf FETCH_HEAD + + if [ ! -d src/connector/python/.github ]; then + rm -rf src/connector/python/* || : + rm -rf src/connector/python/.* || : + git clone --depth 1 https://github.com/taosdata/taos-connector-python src/connector/python || echo "failed to clone python connector" + else + cd src/connector/python || echo "src/connector/python not exist" + git pull || : + cd ${WKC} + fi ''' } else if (env.CHANGE_URL =~ /\/TDinternal\//) { sh ''' @@ -90,6 +104,16 @@ def sync_source() { cd ${WK} git fetch origin +refs/pull/${CHANGE_ID}/merge git checkout -qf FETCH_HEAD + + if [ ! -d community/src/connector/python/.github ]; then + rm -rf community/src/connector/python/* || : + rm -rf community/src/connector/python/.* || : + git clone --depth 1 https://github.com/taosdata/taos-connector-python community/src/connector/python || echo "failed to clone python connector" + else + cd community/src/connector/python || echo "community/src/connector/python not exist" + git pull || : + cd ${WK} + fi ''' } else { sh ''' diff --git a/README-CN.md b/README-CN.md index 4a023cb4a11cd7fdf00bfdec1b382edc907e14fe..4ace609b38022432643719d0a2f9ca8155646bb5 100644 --- a/README-CN.md +++ b/README-CN.md @@ -23,13 +23,13 @@ TDengine 是一款高性能、分布式、支持 SQL 的时序数据库。而且 - **零管理**:安装、集群几秒搞定,无任何依赖,不用分库分表,系统运行状态监测能与 Grafana 或其他运维工具无缝集成。 -- **零学习成本**:采用 SQL 查询语言,支持 Python, Java, C/C++, Go, Rust, Node.js 等多种编程语言,与 MySQL 相似,零学习成本。 +- **零学习成本**:采用 SQL 查询语言,支持 Python、Java、C/C++、Go、Rust、Node.js 等多种编程语言,与 MySQL 相似,零学习成本。 -- **无缝集成**:不用一行代码,即可与 Telegraf, Grafana, EMQ X, Prometheus, StatsD, collectd, Matlab, R 等第三方工具无缝集成。 +- **无缝集成**:不用一行代码,即可与 Telegraf、Grafana、EMQX、Prometheus、StatsD、collectd、Matlab、R 等第三方工具无缝集成。 - **互动 Console**: 通过命令行 console,不用编程,执行 SQL 语句就能做即席查询、各种数据库的操作、管理以及集群的维护. -TDengine 可以广泛应用于物联网、工业互联网、车联网、IT 运维、能源、金融等领域, 让大量设备、数据采集器每天产生的高达 TB 甚至 PB 级的数据能得到高效实时的处理,对业务的运行状态进行实时的监测、预警,从大数据中挖掘出商业价值。 +TDengine 可以广泛应用于物联网、工业互联网、车联网、IT 运维、能源、金融等领域,让大量设备、数据采集器每天产生的高达 TB 甚至 PB 级的数据能得到高效实时的处理,对业务的运行状态进行实时的监测、预警,从大数据中挖掘出商业价值。 # 文档 @@ -272,12 +272,12 @@ taos 在 TDengine 终端中,用户可以通过 SQL 命令来创建/删除数据库、表等,并进行插入查询操作。 ```bash -create database demo; -use demo; -create table t (ts timestamp, speed int); -insert into t values ('2019-07-15 00:00:00', 10); -insert into t values ('2019-07-15 01:00:00', 20); -select * from t; +CREATE DATABASE demo; +USE demo; +CREATE TABLE t (ts TIMESTAMP, speed INT); +INSERT INTO t VALUES('2019-07-15 00:00:00', 10); +INSERT INTO t VALUES('2019-07-15 01:00:00', 20); +SELECT * FROM t; ts | speed | =================================== 19-07-15 00:00:00.000| 10| diff --git a/README.md b/README.md index 06491a8c77602583723d3bed1b2857285d600304..82702ae91f1637c9721f8b47cdc6f67d44a8dda3 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ TDengine is a high-performance, scalable time-series database with SQL support. - **All in One**: TDengine has built-in caching, stream processing and data subscription functions, it is no longer necessary to integrate Kafka/Redis/HBase/Spark or other software in some scenarios. It makes the system architecture much simpler and easy to maintain. -- **Seamless Integration**: Without a single line of code, TDengine provide seamless integration with third-party tools such as Telegraf, Grafana, EMQ X, Prometheus, StatsD, collectd, etc. More will be integrated. +- **Seamless Integration**: Without a single line of code, TDengine provide seamless integration with third-party tools such as Telegraf, Grafana, EMQX, Prometheus, StatsD, collectd, etc. More will be integrated. - **Zero Management**: Installation and cluster setup can be done in seconds. Data partitioning and sharding are executed automatically. TDengine’s running status can be monitored via Grafana or other DevOps tools. diff --git a/alert/app/rule.go b/alert/app/rule.go index e318edab2ac830b13b496930e8339031eccccc69..1233aeb52627fd92ecabf4f25b854e2e803c3ac8 100644 --- a/alert/app/rule.go +++ b/alert/app/rule.go @@ -96,6 +96,7 @@ func (alert *Alert) doRefresh(firing bool, rule *Rule) bool { case (!firing) && (alert.State == AlertStateFiring): alert.State = AlertStateWaiting alert.EndsAt = time.Now() + return false case firing && (alert.State == AlertStateWaiting): alert.StartsAt = time.Now() diff --git a/cmake/define.inc b/cmake/define.inc index a15a0725ebcc04683cee3559e69cf667a060fc7d..9e3d4a0dfa05d1bdbc783da68d470c3a57f57d7b 100755 --- a/cmake/define.inc +++ b/cmake/define.inc @@ -287,9 +287,17 @@ IF (TD_LINUX) SET(COMMON_FLAGS "${COMMON_FLAGS} -pipe -Wshadow") ENDIF () +MESSAGE(STATUS "CMAKE_CXX_COMPILER_ID: " ${CMAKE_CXX_COMPILER_ID}) +IF ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + EXECUTE_PROCESS( COMMAND ${CMAKE_CXX_COMPILER} --version OUTPUT_VARIABLE clang_full_version_string ) + string (REGEX REPLACE ".*clang version ([0-9]+\\.[0-9]+).*" "\\1" CLANG_VERSION_STRING ${clang_full_version_string}) + IF (CLANG_VERSION_STRING GREATER_EQUAL 13.0) + SET(COMMON_FLAGS "${COMMON_FLAGS} -Wno-unused-but-set-variable") + ENDIF () +ENDIF () + INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/os/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/util/inc) INCLUDE_DIRECTORIES(${TD_COMMUNITY_DIR}/src/common/inc) -MESSAGE(STATUS "CMAKE_CXX_COMPILER_ID: " ${CMAKE_CXX_COMPILER_ID}) diff --git a/docs-cn/01-intro/01-intro.md b/docs-cn/01-intro/01-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..d6b0968e47dd71bdfa648072b198641d74caa8b3 --- /dev/null +++ b/docs-cn/01-intro/01-intro.md @@ -0,0 +1,87 @@ +--- +sidebar_label: 产品简介 +toc_max_heading_level: 2 +--- + +# 产品简介 + +## TDengine 简介 + +TDengine 是一款高性能、分布式、支持 SQL 的时序数据库。而且除时序数据库功能外,它还提供缓存、数据订阅、流式计算等功能,最大程度减少研发和运维的复杂度,且核心代码,包括集群功能全部开源(开源协议,AGPL v3.0)。与其他时序数据数据库相比,TDengine 有以下特点: + +- **高性能**:通过创新的存储引擎设计,无论是数据写入还是查询,TDengine 的性能比通用数据库快 10 倍以上,也远超其他时序数据库,而且存储空间也大为节省。 + +- **分布式**:通过原生分布式的设计,TDengine 提供了水平扩展的能力,只需要增加节点就能获得更强的数据处理能力,同时通过多副本机制保证了系统的高可用。 + +- **支持 SQL**:TDengine 采用 SQL 作为数据查询语言,减少学习和迁移成本,同时提供 SQL 扩展来处理时序数据特有的分析,而且支持方便灵活的 schemaless 数据写入。 + +- **All in One**:将数据库、消息队列、缓存、流式计算等功能融合一起,应用无需再集成 Kafka/Redis/HBase/Spark 等软件,大幅降低应用开发和维护成本。 + +- **零管理**:安装、集群几秒搞定,无任何依赖,不用分库分表,系统运行状态监测能与 Grafana 或其他运维工具无缝集成。 + +- **零学习成本**:采用 SQL 查询语言,支持 Python, Java, C/C++, Go, Rust, Node.js 等多种编程语言,与 MySQL 相似,零学习成本。 + +- **无缝集成**:不用一行代码,即可与 Telegraf, Grafana, EMQX, Prometheus, StatsD, collectd, Matlab, R 等第三方工具无缝集成。 + +- **互动 Console**: 通过命令行 console,不用编程,执行 SQL 语句就能做即席查询、各种数据库的操作、管理以及集群的维护. + +采用 TDengine,可将典型的物联网、车联网、工业互联网大数据平台的总拥有成本大幅降低。但需要指出的是,因充分利用了物联网时序数据的特点,它无法用来处理网络爬虫、微博、微信、电商、ERP、CRM 等通用型数据。 + +![TDengine技术生态图](eco_system.png) + +
图 1. TDengine技术生态图
+ +## TDengine 总体适用场景 + +作为一个 IoT 大数据平台,TDengine 的典型适用场景是在 IoT 范畴,而且用户有一定的数据量。本文后续的介绍主要针对这个范畴里面的系统。范畴之外的系统,比如 CRM,ERP 等,不在本文讨论范围内。 + +### 数据源特点和需求 + +从数据源角度,设计人员可以从下面几个角度分析 TDengine 在目标应用系统里面的适用性。 + +| 数据源特点和需求 | 不适用 | 可能适用 | 非常适用 | 简单说明 | +| ---------------------------- | ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | +| 总体数据量巨大 | | | √ | TDengine 在容量方面提供出色的水平扩展功能,并且具备匹配高压缩的存储结构,达到业界最优的存储效率。 | +| 数据输入速度偶尔或者持续巨大 | | | √ | TDengine 的性能大大超过同类产品,可以在同样的硬件环境下持续处理大量的输入数据,并且提供很容易在用户环境里面运行的性能评估工具。 | +| 数据源数目巨大 | | | √ | TDengine 设计中包含专门针对大量数据源的优化,包括数据的写入和查询,尤其适合高效处理海量(千万或者更多量级)的数据源。 | + +### 系统架构要求 + +| 系统架构要求 | 不适用 | 可能适用 | 非常适用 | 简单说明 | +| ---------------------- | ------ | -------- | -------- | ----------------------------------------------------------------------------------------------------- | +| 要求简单可靠的系统架构 | | | √ | TDengine 的系统架构非常简单可靠,自带消息队列,缓存,流式计算,监控等功能,无需集成额外的第三方产品。 | +| 要求容错和高可靠 | | | √ | TDengine 的集群功能,自动提供容错灾备等高可靠功能。 | +| 标准化规范 | | | √ | TDengine 使用标准的 SQL 语言提供主要功能,遵守标准化规范。 | + +### 系统功能需求 + +| 系统功能需求 | 不适用 | 可能适用 | 非常适用 | 简单说明 | +| -------------------------- | ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------- | +| 要求完整的内置数据处理算法 | | √ | | TDengine 的实现了通用的数据处理算法,但是还没有做到妥善处理各行各业的所有要求,因此特殊类型的处理还需要应用层面处理。 | +| 需要大量的交叉查询处理 | | √ | | 这种类型的处理更多应该用关系型数据系统处理,或者应该考虑 TDengine 和关系型数据系统配合实现系统功能。 | + +### 系统性能需求 + +| 系统性能需求 | 不适用 | 可能适用 | 非常适用 | 简单说明 | +| ---------------------- | ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------ | +| 要求较大的总体处理能力 | | | √ | TDengine 的集群功能可以轻松地让多服务器配合达成处理能力的提升。 | +| 要求高速处理数据 | | | √ | TDengine 的专门为 IoT 优化的存储和数据处理的设计,一般可以让系统得到超出同类产品多倍数的处理速度提升。 | +| 要求快速处理小粒度数据 | | | √ | 这方面 TDengine 性能可以完全对标关系型和 NoSQL 型数据处理系统。 | + +### 系统维护需求 + +| 系统维护需求 | 不适用 | 可能适用 | 非常适用 | 简单说明 | +| ---------------------- | ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------- | +| 要求系统可靠运行 | | | √ | TDengine 的系统架构非常稳定可靠,日常维护也简单便捷,对维护人员的要求简洁明了,最大程度上杜绝人为错误和事故。 | +| 要求运维学习成本可控 | | | √ | 同上。 | +| 要求市场有大量人才储备 | √ | | | TDengine 作为新一代产品,目前人才市场里面有经验的人员还有限。但是学习成本低,我们作为厂家也提供运维的培训和辅助服务。 | + +## TDengine 与其他数据库的对比测试 + +- [用 InfluxDB 开源的性能测试工具对比 InfluxDB 和 TDengine](https://www.taosdata.com/blog/2020/01/13/1105.html) +- [TDengine 与 OpenTSDB 对比测试](https://www.taosdata.com/blog/2019/08/21/621.html) +- [TDengine 与 Cassandra 对比测试](https://www.taosdata.com/blog/2019/08/14/573.html) +- [TDengine 与 InfluxDB 对比测试](https://www.taosdata.com/blog/2019/07/19/419.html) +- [TDengine VS InfluxDB ,写入性能大 PK !](https://www.taosdata.com/2021/11/05/3248.html) +- [TDengine 和 InfluxDB 查询性能对比测试报告](https://www.taosdata.com/2022/02/22/5969.html) +- [TDengine 与 InfluxDB、OpenTSDB、Cassandra、MySQL、ClickHouse 等数据库的对比测试报告](https://www.taosdata.com/downloads/TDengine_Testing_Report_cn.pdf) diff --git a/docs-cn/01-intro/_category_.yml b/docs-cn/01-intro/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..1fdaed6b943d4a0877325bf00005307fb2f19880 --- /dev/null +++ b/docs-cn/01-intro/_category_.yml @@ -0,0 +1 @@ +label: TDengine 介绍 diff --git a/docs-cn/01-intro/eco_system.png b/docs-cn/01-intro/eco_system.png new file mode 100644 index 0000000000000000000000000000000000000000..bf8bf8f1e0a2311fc12202d712a8a2f9b8ce419b Binary files /dev/null and b/docs-cn/01-intro/eco_system.png differ diff --git a/docs-cn/02-concept/02-concept.md b/docs-cn/02-concept/02-concept.md new file mode 100644 index 0000000000000000000000000000000000000000..ccaa1b51e0410c2a2e02513f5ce6e4a2c6e00325 --- /dev/null +++ b/docs-cn/02-concept/02-concept.md @@ -0,0 +1,68 @@ +# 基本概念 + +## 物联网典型场景 + +在典型的物联网、车联网、运维监测场景中,往往有多种不同类型的数据采集设备,采集一个到多个不同的物理量。而同一种采集设备类型,往往又有多个具体的采集设备分布在不同的地点。大数据处理系统就是要将各种采集的数据汇总,然后进行计算和分析。对于同一类设备,其采集的数据类似如下的表格: + +| Device ID | Time Stamp | Value 1 | Value 2 | Value 3 | Tag 1 | Tag 2 | +| :-------: | :-----------: | :-----: | :-----: | :-----: | :---: | :---: | +| D1001 | 1538548685000 | 10.3 | 219 | 0.31 | Red | Tesla | +| D1002 | 1538548684000 | 10.2 | 220 | 0.23 | Blue | BMW | +| D1003 | 1538548686500 | 11.5 | 221 | 0.35 | Black | Honda | +| D1004 | 1538548685500 | 13.4 | 223 | 0.29 | Red | Volvo | +| D1001 | 1538548695000 | 12.6 | 218 | 0.33 | Red | Tesla | +| D1004 | 1538548696600 | 11.8 | 221 | 0.28 | Black | Honda | + + +每一条记录都有设备 ID,时间戳,采集的物理量,还有与每个设备相关的静态标签。每个设备是受外界的触发,或按照设定的周期采集数据。采集的数据点是时序的,是一个数据流。 + +**数据特征** + +除时序特征外,仔细研究发现,物联网、车联网、运维监测类数据还具有很多其他明显的特征。 + +1. 数据是结构化的; +2. 数据极少有更新或删除操作; +3. 无需传统数据库的事务处理; +4. 相对互联网应用,写多读少; +5. 流量平稳,根据设备数量和采集频次,可以预测出来; +6. 用户关注的是一段时间的趋势,而不是某一特点时间点的值; +7. 数据是有保留期限的; +8. 数据的查询分析一定是基于时间段和地理区域的; +9. 除存储查询外,还往往需要各种统计和实时计算操作; +10. 数据量巨大,一天采集的数据就可以超过 100 亿条。 + +充分利用上述特征,TDengine 采取了一特殊的优化的存储和计算设计来处理时序数据,能将系统处理能力显著提高。 + +## 数据采集点 + +持续按照预设频率生成数据的软件或硬件设备称为数据采集点。TDengine中推荐一个数据采集点生成的数据存储在对应的一个或若干个表中。采集点产生的数据通常是包括时间戳、测量值、标签等必要信息构成的元组。 + +## 采集量 + +数据采集点生成的具有时间、测量值、标签的元组信息。除了时间戳、标签信息以外的测量值称为采集量。 + +## 标签 + +表的结构化描述信息,以一维数组形式存在。标签模式需要在创建超级表的时候指定,后续可动态调整。只有基于超级表创建的子表才具有标签。标签信息的内容首次创建子表的时候指定,并可按需调整。可以看到,TDengine中标签信息是表级别,而不是记录级别。 + +## 数据库 + + TDengine中数据库与普通数据库管理系统中的数据库语义和行为相同,但是结合应用需求增加了若干配置参数用以控制其行为。 + +## 超级表 + +超级表(Super Table, STable)是TDengine中一个重要的概念。超级表是面向相同数据模式的数据表,提供(数据+标签)模式管理和查询处理的逻辑抽象。通常将基于超级表创建的表称为该超级表的子表,并在系统内部建立逻辑关联。超级表与(基于其创建的)子表的关系体现在以下几个方面: + +超级表的子表共享其数据模式和标签模式。因此,不能通过子表调整数据或标签的模式。对于超级表的数据模式修改立即对所有的子表生效。 + +超级表自身不能存储任何数据或标签信息。因此,不能向一个超级表写入数据,只能将数据写入子表中。 + +针对超级表的查询,将所有子表中的数据视为一个整体数据集进行处理。但是可以直接发起针对某个或若干个子表的查询,此时查询请求将该子表视为一个普通的表进行处理。 + +## 表 + +一系列二维数组的集合,用来代表和储存数据对象之间的关系,由纵向的列和横向的行组成。TDengine中的表与普通数据库中的表没有差别。 + +但是,对于通过超级表创建的子表,还具有额外的标签数据信息。不能针对某个子表调整数据模式。每个子表具有与其关联的标签数据,并可按需调整内容。但是模式调整必须要通过超级表模式调整来完成。 + +使用TDengine存储和管理物联网数据的时候,推荐使用一个子表存储一个数据采集点生成的数据,而使用超级表用来代表一组相同类型的数据采集点的集合。 diff --git a/docs-cn/02-concept/_category_.yml b/docs-cn/02-concept/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..aad75dce21f63a6510bc0b8da4c93952767adfdf --- /dev/null +++ b/docs-cn/02-concept/_category_.yml @@ -0,0 +1 @@ +label: 基本概念 \ No newline at end of file diff --git a/docs-cn/03-get-started/03-get-started.md b/docs-cn/03-get-started/03-get-started.md new file mode 100644 index 0000000000000000000000000000000000000000..90a86b44e6ceb4bc6cfe3c6851e189d169b6ccdb --- /dev/null +++ b/docs-cn/03-get-started/03-get-started.md @@ -0,0 +1,211 @@ +# 立即开始 + +## 从 Docker 快速开始 + +如果已经安装了 docker, 只需执行下面的命令。 + +```shell +docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp tdengine/tdengine +``` + +确定该容器已经启动并且在正常运行 + +```shell +docker ps +``` + +进入该容器并执行 bash + +```shell +docker exec -it bash +``` + +然后就可以执行相关的 Linux 命令操作和访问 TDengine + +详细操作方法请参照 [通过 Docker 快速体验 TDengine](/train-fqa/docker)。 + +:::info +从 2.4.0.10 开始,除 taosd 以外,Docker 镜像还包含:taos、taosAdapter、taosdump、taosBenchmark、TDinsight 安装脚本和示例代码。启动 Docker 容器时,将同时启动 taosAdapter 和 taosd,实现对 RESTful 的支持。 + +::: + +:::note +暂时不建议生产环境采用 Docker 来部署 TDengine 的客户端或服务端,但在开发环境下或初次尝试时,使用 Docker 方式部署是十分方便的。特别是,利用 Docker,可以方便地在 macOS 和 Windows 环境下尝试 TDengine。 + +::: + +## 安装 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import PkgInstall from "./\_pkg_install.mdx"; +import AptGetInstall from "./\_apt_get_install.mdx"; +import SrcInstall from "./\_src_install.mdx"; + +TDengine 包括服务端、客户端和周边生态工具软件,目前 2.0 版服务端仅在 Linux 系统上安装和运行,后续将支持 Windows、macOS 等系统。客户端可以在 Windows 或 Linux 上安装和运行。在任何操作系统上的应用都可以使用 RESTful 接口连接服务端程序 taosd,其中 2.4 之后版本默认使用单独运行的独立组件 taosAdapter 提供 http 服务和更多数据写入方式。taosAdapter 需要手动启动。 +之前版本 TDengine 服务端,以及所有服务端 lite 版,均使用内置 http 服务。 + +TDengine 支持 X64/ARM64/MIPS64/Alpha64 硬件平台,后续将支持 ARM32、RISC-V 等 CPU 架构。 + + + + + + + + + + + + + +## 启动 + +使用 `systemctl` 命令来启动 TDengine 的服务进程。 + +```bash +systemctl start taosd +``` + +检查服务是否正常工作: + +```bash +systemctl status taosd +``` + +如果 TDengine 服务正常工作,那么您可以通过 TDengine 的命令行程序 `taos` 来访问并体验 TDengine。 + +:::info + +- systemctl 命令需要 _root_ 权限来运行,如果您非 _root_ 用户,请在命令前添加 sudo 。 +- 为更好的获得产品反馈,改善产品,TDengine 会采集基本的使用信息,但您可以修改系统配置文件 taos.cfg 里的配置参数 telemetryReporting,将其设为 0,就可将其关闭。 +- TDengine 采用 FQDN(一般就是 hostname)作为节点的 ID,为保证正常运行,需要给运行 taosd 的服务器配置好 hostname,在客户端应用运行的机器配置好 DNS 服务或 hosts 文件,保证 FQDN 能够解析。 +- `systemctl stop taosd` 指令在执行后并不会马上停止 TDengine 服务,而是会等待系统中必要的落盘工作正常完成。在数据量很大的情况下,这可能会消耗较长时间。 + +TDengine 支持在使用 [`systemd`](https://en.wikipedia.org/wiki/Systemd) 做进程服务管理的 Linux 系统上安装,用 `which systemctl` 命令来检测系统中是否存在 `systemd` 包: + +```bash +which systemctl +``` + +如果系统中不支持 `systemd`,也可以用手动运行 `/usr/local/taos/bin/taosd` 方式启动 TDengine 服务。 + +:::note + +## 进入命令行 + +执行 TDengine 客户端程序,您只要在 Linux 终端执行 `taos` 即可。 + +```bash +taos +``` + +如果连接服务成功,将会打印出欢迎消息和版本信息。如果失败,则会打印错误消息出来(请参考 [FAQ](/train-fqa/faq) 来解决终端连接服务端失败的问题)。客户端的提示符号如下: + +```cmd +taos> +``` + +在 TDengine 客户端中,用户可以通过 SQL 命令来创建/删除数据库、表等,并进行插入查询操作。在终端中运行的 SQL 语句需要以分号结束来运行。示例: + +```sql +create database demo; +use demo; +create table t (ts timestamp, speed int); +insert into t values ('2019-07-15 00:00:00', 10); +insert into t values ('2019-07-15 01:00:00', 20); +select * from t; + ts | speed | +======================================== + 2019-07-15 00:00:00.000 | 10 | + 2019-07-15 01:00:00.000 | 20 | +Query OK, 2 row(s) in set (0.003128s) +``` + +除执行 SQL 语句外,系统管理员还可以从 TDengine 客户端进行检查系统运行状态、添加删除用户账号等操作。 + +## 命令行参数 + +您可通过配置命令行参数来改变 TDengine 客户端的行为。以下为常用的几个命令行参数: + +- -c, --config-dir: 指定配置文件目录,默认为 `/etc/taos` +- -h, --host: 指定服务的 FQDN 地址或 IP 地址,默认为连接本地服务 +- -s, --commands: 在不进入终端的情况下运行 TDengine 命令 +- -u, --user: 连接 TDengine 服务端的用户名,缺省为 root +- -p, --password: 连接 TDengine 服务端的密码,缺省为 taosdata +- -?, --help: 打印出所有命令行参数 + +示例: + +```bash +taos -h h1.taos.com -s "use db; show tables;" +``` + +## 运行 SQL 命令脚本 + +TDengine 终端可以通过 `source` 命令来运行 SQL 命令脚本。 + +```sql +taos> source ; +``` + +## taos shell 小技巧 + +- 可以使用上下光标键查看历史输入的指令 +- 修改用户密码:在 shell 中使用 `alter user` 命令,缺省密码为 taosdata +- ctrl+c 中止正在进行中的查询 +- 执行 `RESET QUERY CACHE` 可清除本地缓存的表 schema +- 批量执行 SQL 语句。可以将一系列的 shell 命令(以英文 ; 结尾,每个 SQL 语句为一行)按行存放在文件里,在 shell 里执行命令 `source ` 自动执行该文件里所有的 SQL 语句 +- 输入 q 回车,退出 taos shell + +## 使用 taosBenchmark 体验写入速度 + +启动 TDengine 的服务,在 Linux 终端执行 `taosBenchmark` (曾命名为 taosdemo): + +```bash +taosBenchmark +``` + +该命令将在数据库 test 下面自动创建一张超级表 meters,该超级表下有 1 万张表,表名为 "d0" 到 "d9999",每张表有 1 万条记录,每条记录有 (ts, current, voltage, phase) 四个字段,时间戳从 "2017-07-14 10:40:00 000" 到 "2017-07-14 10:40:09 999",每张表带有标签 location 和 groupId,groupId 被设置为 1 到 10, location 被设置为 "beijing" 或者 "shanghai"。 + +这条命令很快完成 1 亿条记录的插入。具体时间取决于硬件性能,即使在一台普通的 PC 服务器往往也仅需十几秒。 + +## taosBenchmark 详细功能列表 + +taosBenchmark 命令本身带有很多选项,配置表的数目、记录条数等等,请执行 `taosBenchmark --help` 详细列出。您可以设置不同参数进行体验。 + +taosBenchmark 详细使用方法请参照 [如何使用 taosBenchmark 对 TDengine 进行性能测试](https://www.taosdata.com/2021/10/09/3111.html)。 + +## 使用 taos shell 体验查询速度 + +在 TDengine 客户端输入查询命令,体验查询速度。 + +查询超级表下记录总条数: + +```sql +taos> select count(*) from test.meters; +``` + +查询 1 亿条记录的平均值、最大值、最小值等: + +```sql +taos> select avg(current), max(voltage), min(phase) from test.meters; +``` + +查询 location="beijing" 的记录总条数: + +```sql +taos> select count(*) from test.meters where location="beijing"; +``` + +查询 groupId=10 的所有记录的平均值、最大值、最小值等: + +```sql +taos> select avg(current), max(voltage), min(phase) from test.meters where groupId=10; +``` + +对表 d10 按 10s 进行平均值、最大值和最小值聚合统计: + +```sql +taos> select avg(current), max(voltage), min(phase) from test.d10 interval(10s); +``` diff --git a/docs-cn/03-get-started/_apt_get_install.mdx b/docs-cn/03-get-started/_apt_get_install.mdx new file mode 100644 index 0000000000000000000000000000000000000000..8161d8e805c94e4fdc60a63f7cefc452eb833f5a --- /dev/null +++ b/docs-cn/03-get-started/_apt_get_install.mdx @@ -0,0 +1,26 @@ +如果,可以使用 apt-get 工具从官方仓库安装。 + +**安装包仓库** + +``` +wget -qO - http://repos.taosdata.com/tdengine.key | sudo apt-key add - +echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-stable stable main" | sudo tee /etc/apt/sources.list.d/tdengine-stable.list +``` + +如果安装 Beta 版需要安装包仓库 + +``` +echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list +``` + +**使用 apt-get 命令安装** + +``` +sudo apt-get update +apt-cache policy tdengine +sudo apt-get install tdengine +``` + +:::tip +apt-get 方式只适用于 Debian 或 Ubuntu 系统 +:::: diff --git a/docs-cn/03-get-started/_category_.yml b/docs-cn/03-get-started/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..b2348fade63c7bb717eac3e6e6b8dfda3c73b17a --- /dev/null +++ b/docs-cn/03-get-started/_category_.yml @@ -0,0 +1 @@ +label: 立即开始 diff --git a/docs-cn/03-get-started/_pkg_install.mdx b/docs-cn/03-get-started/_pkg_install.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c3d1d97fe318422207f8aadbe60f3ec27dae6e08 --- /dev/null +++ b/docs-cn/03-get-started/_pkg_install.mdx @@ -0,0 +1,13 @@ +import PkgList from "./_pkg_list.mdx"; + +TDengine 的安装非常简单,从下载到安装成功仅仅只要几秒钟。 + +为方便使用,从 2.4.0.10 开始,标准的服务端安装包包含了 taos、taosd、taosAdapter、taosdump、taosBenchmark、TDinsight 安装脚本和示例代码;如果您只需要用到服务端程序和客户端连接的 C/C++ 语言支持,也可以仅下载 lite 版本的安装包。 + +在安装包格式上,我们提供 tar.gz, rpm 和 deb 格式,为企业客户提供 tar.gz 格式安装包,以方便在特定操作系统上使用。需要注意的是,rpm 和 deb 包不含 taosdump、taosBenchmark 和 TDinsight 安装脚本,这些工具需要通过安装 taosTool 包获得。 + +发布版本包括稳定版和 Beta 版,Beta 版含有更多新功能。正式上线或测试建议安装稳定版。您可以根据需要选择下载: + + + +具体的安装方法,请参见 [安装包的安装和卸载](/operation/pkg-install) 以及 [视频教程](https://www.taosdata.com/blog/2020/11/11/1941.html)。 diff --git a/docs-cn/03-get-started/_pkg_list.mdx b/docs-cn/03-get-started/_pkg_list.mdx new file mode 100644 index 0000000000000000000000000000000000000000..1ed8a107170302c37ac66d2e0087cb14122cf5cb --- /dev/null +++ b/docs-cn/03-get-started/_pkg_list.mdx @@ -0,0 +1,48 @@ +**最新安装包** + + + +**所有下载** + +https://www.taosdata.com/all-downloads diff --git a/docs-cn/03-get-started/_src_install.mdx b/docs-cn/03-get-started/_src_install.mdx new file mode 100644 index 0000000000000000000000000000000000000000..2004d73fe0d7a4c4aaf50fa42e996841c8c08275 --- /dev/null +++ b/docs-cn/03-get-started/_src_install.mdx @@ -0,0 +1,3 @@ +如果您希望对 TDengine 贡献代码或对内部实现感兴趣,请参考我们的 [TDengine GitHub 主页](https://github.com/taosdata/TDengine) 下载源码构建和安装. + +下载其他组件、最新 Beta 版及之前版本的安装包,请点击[这里](https://www.taosdata.com/cn/all-downloads/)。 diff --git a/docs-cn/04-connect/_category_.yml b/docs-cn/04-connect/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..f75d563ac9e061f8b8d66392031413f4051e351e --- /dev/null +++ b/docs-cn/04-connect/_category_.yml @@ -0,0 +1 @@ +label: 建立连接 diff --git a/docs-cn/04-connect/_connect_c.mdx b/docs-cn/04-connect/_connect_c.mdx new file mode 100644 index 0000000000000000000000000000000000000000..4d6f1cfe1b06ef9baeb7da2bb2559880ada99fbf --- /dev/null +++ b/docs-cn/04-connect/_connect_c.mdx @@ -0,0 +1,3 @@ +```c +{{#include docs-examples/c/connect_example.c}} +``` diff --git a/docs-cn/04-connect/_connect_cs_native.mdx b/docs-cn/04-connect/_connect_cs_native.mdx new file mode 100644 index 0000000000000000000000000000000000000000..19dc4bb52b8d033d49882d9be6e7a9c76e8fe61f --- /dev/null +++ b/docs-cn/04-connect/_connect_cs_native.mdx @@ -0,0 +1,9 @@ +首先添加 [TDengine.Connector](https://www.nuget.org/packages/TDengine.Connector/) 的引用: + +```bash +dotnet add package TDengine.Connector +``` + +```csharp +{{#include docs-examples/csharp/ConnectExample.cs}} +``` diff --git a/docs-cn/04-connect/_connect_go.mdx b/docs-cn/04-connect/_connect_go.mdx new file mode 100644 index 0000000000000000000000000000000000000000..17d7eb98ba3fa7483edd54978771e03cc051ff53 --- /dev/null +++ b/docs-cn/04-connect/_connect_go.mdx @@ -0,0 +1,11 @@ +```go-mod title=go.mod +module goexample + +go 1.17 + +require github.com/taosdata/driver-go/v2 develop +``` + +```go +{{#include docs-examples/go/connect/restexample/main.go}} +``` diff --git a/docs-cn/04-connect/_connect_go_native.mdx b/docs-cn/04-connect/_connect_go_native.mdx new file mode 100644 index 0000000000000000000000000000000000000000..22e155f6a00fbd3db646e04c2b9f11337432cd26 --- /dev/null +++ b/docs-cn/04-connect/_connect_go_native.mdx @@ -0,0 +1,22 @@ +:::note +driver-go 使用 cgo 封装了 taosc 的 API。cgo 需要使用 gcc 编译 C 的源码。因此需要确保你的系统上有 gcc。 + +::: + +```go-mod title=go.mod +module goexample + +go 1.17 + +require github.com/taosdata/driver-go/v2 develop +``` + +```go title="使用 database/sql 包建立连接" +{{#include docs-examples/go/connect/cgoexample/main.go}} +``` + +也可以使用 driver-go 的 af 包建立连接。这个模块封装了 TDengine 的高级功能, 如:动态绑定、订阅等。 + +```go title="使用 af 包建立连接" +{{#include docs-examples/go/connect/afconn/main.go}} +``` diff --git a/docs-cn/04-connect/_connect_java.mdx b/docs-cn/04-connect/_connect_java.mdx new file mode 100644 index 0000000000000000000000000000000000000000..4282e57215a896656c5ca2a51df45f3bef1cdd5a --- /dev/null +++ b/docs-cn/04-connect/_connect_java.mdx @@ -0,0 +1,11 @@ +```xml title=pom.xml + + com.taosdata.jdbc + taos-jdbcdriver + 2.0.37 + +``` + +```java +{{#include docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java}} +``` diff --git a/docs-cn/04-connect/_connect_java_native.mdx b/docs-cn/04-connect/_connect_java_native.mdx new file mode 100644 index 0000000000000000000000000000000000000000..9d75df6684ace21d1e7c5995d07d578b8d3803d2 --- /dev/null +++ b/docs-cn/04-connect/_connect_java_native.mdx @@ -0,0 +1,11 @@ +```xml title=pom.xml + + com.taosdata.jdbc + taos-jdbcdriver + 2.0.37 + +``` + +```java +{{#include docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java}} +``` diff --git a/docs-cn/04-connect/_connect_node.mdx b/docs-cn/04-connect/_connect_node.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/04-connect/_connect_node_native.mdx b/docs-cn/04-connect/_connect_node_native.mdx new file mode 100644 index 0000000000000000000000000000000000000000..7168d9268a10f23c66dcc7a85cc54b162ff5f80f --- /dev/null +++ b/docs-cn/04-connect/_connect_node_native.mdx @@ -0,0 +1,14 @@ +首先需要安装 node.js 的连接器 `td2.0-connector`: + +```bash +npm install td2.0-connector +``` + +:::note +推荐使用 `node-v12.8.0` 或 `node-v12.20.0` + +::: + +```js +{{#include docs-examples/node/nativeexample/connect.js}} +``` diff --git a/docs-cn/04-connect/_connect_python_native.mdx b/docs-cn/04-connect/_connect_python_native.mdx new file mode 100644 index 0000000000000000000000000000000000000000..1a258988835c383285f16ff9eb0b64518941f7b0 --- /dev/null +++ b/docs-cn/04-connect/_connect_python_native.mdx @@ -0,0 +1,9 @@ +推荐使用 `python >= 3.4`。首先需要安装 python 连接器 `taospy`。执行以下命令即可: + +``` +pip3 install taospy +``` + +```python +{{#include docs-examples/python/connect_exmaple.py}} +``` diff --git a/docs-cn/04-connect/_connect_restful.mdx b/docs-cn/04-connect/_connect_restful.mdx new file mode 100644 index 0000000000000000000000000000000000000000..d68903aa3979f5098e83a029bae42d5f8363fa93 --- /dev/null +++ b/docs-cn/04-connect/_connect_restful.mdx @@ -0,0 +1,22 @@ +下面用 curl 工具来演示访问 RESTful 接口。在命令行执行下面的命令: + +```bash +curl http://localhost:6041/rest/sql -u root:taosdata -d "select server_version()" +``` + +- `-u` 用于指定访问数据库的用户名和密码。 +- `-d` 用于指定发送要执行的 SQL 语句。它会被放入 POST 请求的 Body 中。 + +如果正常,会返回一个 JSON 字符串,里面包含了服务端的版本。例如: + +```json +{ + "status": "succ", + "head": ["server_version()"], + "column_meta": [["server_version()", 8, 7]], + "data": [["2.4.0.0"]], + "rows": 1 +} +``` + +了解更多:[RESTful API](/reference/restful-api)。 diff --git a/docs-cn/04-connect/_connect_rust.mdx b/docs-cn/04-connect/_connect_rust.mdx new file mode 100644 index 0000000000000000000000000000000000000000..b167278a55f9b3dca97367e0b391fef28a00d6ec --- /dev/null +++ b/docs-cn/04-connect/_connect_rust.mdx @@ -0,0 +1,8 @@ +```toml title=Cargo.toml +[dependencies] +libtaos = { version = "*", features = ["rest"] } +``` + +```rust +{{#include docs-examples/rust/restexample/examples/connect.rs}} +``` diff --git a/docs-cn/04-connect/_connect_rust_native.mdx b/docs-cn/04-connect/_connect_rust_native.mdx new file mode 100644 index 0000000000000000000000000000000000000000..0ee07c295eb457322d32caaa4cb027593ac5966d --- /dev/null +++ b/docs-cn/04-connect/_connect_rust_native.mdx @@ -0,0 +1,8 @@ +```toml title=Cargo.toml +[dependencies] +libtaos = { version = "0.4.2"} +``` + +```rust +{{#include docs-examples/rust/nativeexample/examples/connect.rs}} +``` diff --git a/docs-cn/04-connect/index.mdx b/docs-cn/04-connect/index.mdx new file mode 100644 index 0000000000000000000000000000000000000000..4594f5b907c6b49e65668f6205d909c9d417f0db --- /dev/null +++ b/docs-cn/04-connect/index.mdx @@ -0,0 +1,86 @@ +# 建立连接 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import ConnRest from "./_connect_restful.mdx"; +import ConnJava from "./_connect_java.mdx"; +import ConnGo from "./_connect_go.mdx"; +import ConnRust from "./_connect_rust.mdx"; +import ConnNode from "./_connect_node.mdx"; +import ConnJavaNative from "./_connect_java_native.mdx"; +import ConnPythonNative from "./_connect_python_native.mdx"; +import ConnGoNative from "./_connect_go_native.mdx"; +import ConnRustNative from "./_connect_rust_native.mdx"; +import ConnNodeNative from "./_connect_node_native.mdx"; +import ConnCSNative from "./_connect_cs_native.mdx"; +import ConnC from "./_connect_c.mdx"; + +## 连接器介绍 + +TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java、Python、Go、Node.js、C# 、RESTful 等,便于用户快速开发应用。 + +![image-connecotr](/img/connector.png) + +
(图:连接器工作原理)
+ +TDengine 提供了 RESTful 接口,应用程序无需安装任何依赖,只需发送 HTTP 请求就可以连接到 TDengine。同时也提供了各语言的连接器,使用驱动程序 (taosc) 连接 TDengine。通过驱动程序可以使用 TDengine 更丰富的功能。 + +## 前提条件 + +在执行这一步之前,请确保有一个正在运行的,且可以访问到的 TDengine。以下所有示例代码,都假设 TDengine 安装在本机,且 fqdn(默认 localhost) 和 serverPort(默认 6030) 都使用默认配置。 + +## 建立连接 + +### RESTful + +如果你安装的是 TDengine 2.4 之后的版本,使用 RESTful 方式连接时还需启动 taosAdaper。 + + + + + + + + + + + + + + + + + + + +### 本地驱动 + +在没有安装 TDengine 服务端软件的系统上使用本地驱动连接 TDengine, 需要提前[安装客户端驱动程序](/reference/connector/#安装客户端驱动)。 +:::note +需要单独安装客户端时,为避免客户端驱动和服务端不兼容,请尽量使用一致的版本。 + +::: + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs-cn/05-model/_category_.yml b/docs-cn/05-model/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5dae7c27cf17ff737aa8301bc79aad468c28791 --- /dev/null +++ b/docs-cn/05-model/_category_.yml @@ -0,0 +1,2 @@ +label: 数据建模 + diff --git a/docs-cn/05-model/index.mdx b/docs-cn/05-model/index.mdx new file mode 100644 index 0000000000000000000000000000000000000000..7b1ae38439a5644340d9600eb2332546b335bc14 --- /dev/null +++ b/docs-cn/05-model/index.mdx @@ -0,0 +1,88 @@ +--- +slug: /model +--- + +# TDengine 数据建模 + +TDengine 采用关系型数据模型,需要建库、建表。因此对于一个具体的应用场景,需要考虑库、超级表和普通表的设计。本节不讨论细致的语法规则,只介绍概念。 + +关于数据建模请参考[视频教程](https://www.taosdata.com/blog/2020/11/11/1945.html)。 + +## 创建库 + +不同类型的数据采集点往往具有不同的数据特征,包括数据采集频率的高低,数据保留时间的长短,副本的数目,数据块的大小,是否允许更新数据等等。为了在各种场景下 TDengine 都能最大效率的工作,TDengine 建议将不同数据特征的表创建在不同的库里,因为每个库可以配置不同的存储策略。创建一个库时,除 SQL 标准的选项外,应用还可以指定保留时长、副本数、内存块个数、时间精度、文件块里最大最小记录条数、是否压缩、一个数据文件覆盖的天数等多种参数。比如: + +```sql +CREATE DATABASE power KEEP 365 DAYS 10 BLOCKS 6 UPDATE 1; +``` + +上述语句将创建一个名为 power 的库,这个库的数据将保留 365 天(超过 365 天将被自动删除),每 10 天一个数据文件,内存块数为 6,允许更新数据。详细的语法及参数请见 [数据库管理](/reference/taos-sql/database) 章节。 + +创建库之后,需要使用 SQL 命令 `USE` 将当前库切换过来,例如: + +```sql +USE power; +``` + +将当前连接里操作的库换为 power,否则对具体表操作前,需要使用“库名.表名”来指定库的名字。 + +:::note + +- 任何一张表或超级表是属于一个库的,在创建表之前,必须先创建库。 +- 处于两个不同库的表是不能进行 JOIN 操作的。 +- 创建并插入记录、查询历史记录的时候,均需要指定时间戳。 + +::: + +## 创建超级表 + +一个物联网系统,往往存在多种类型的设备,比如对于电网,存在智能电表、变压器、母线、开关等等。为便于多表之间的聚合,使用 TDengine, 需要对每个类型的数据采集点创建一个超级表。以[表 1](/tdinternal/arch#model_table1) 中的智能电表为例,可以使用如下的 SQL 命令创建超级表: + +```sql +CREATE STABLE meters (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int); +``` + +:::note +这一指令中的 STABLE 关键字,在 2.0.15 之前的版本中需写作 TABLE 。 +::: + +与创建普通表一样,创建表时,需要提供表名(示例中为 meters),表结构 Schema,即数据列的定义。第一列必须为时间戳(示例中为 ts),其他列为采集的物理量(示例中为 current, voltage, phase),数据类型可以为整型、浮点型、字符串等。除此之外,还需要提供标签的 schema (示例中为 location, groupId),标签的数据类型可以为整型、浮点型、字符串等。采集点的静态属性往往可以作为标签,比如采集点的地理位置、设备型号、设备组 ID、管理员 ID 等等。标签的 schema 可以事后增加、删除、修改。具体定义以及细节请见 [TAOS SQL 的超级表管理](/reference/taos-sql/stable) 章节。 + +每一种类型的数据采集点需要建立一个超级表,因此一个物联网系统,往往会有多个超级表。对于电网,我们就需要对智能电表、变压器、母线、开关等都建立一个超级表。在物联网中,一个设备就可能有多个数据采集点(比如一台风力发电的风机,有的采集点采集电流、电压等电参数,有的采集点采集温度、湿度、风向等环境参数),这个时候,对这一类型的设备,需要建立多张超级表。一张超级表里包含的采集物理量必须是同时采集的(时间戳是一致的)。 + +一张超级表最多容许 1024 列,如果一个采集点采集的物理量个数超过 1024,需要建多张超级表来处理。一个系统可以有多个 DB,一个 DB 里可以有一到多个超级表。(从 2.1.7.0 版本开始,列数限制由 1024 列放宽到了 4096 列。) + +## 创建表 + +TDengine 对每个数据采集点需要独立建表。与标准的关系型数据库一样,一张表有表名,Schema,但除此之外,还可以带有一到多个标签。创建时,需要使用超级表做模板,同时指定标签的具体值。以[表 1](/tdinternal/arch#model_table1)中的智能电表为例,可以使用如下的 SQL 命令建表: + +```sql +CREATE TABLE d1001 USING meters TAGS ("Beijing.Chaoyang", 2); +``` + +其中 d1001 是表名,meters 是超级表的表名,后面紧跟标签 Location 的具体标签值 ”Beijing.Chaoyang",标签 groupId 的具体标签值 2。虽然在创建表时,需要指定标签值,但可以事后修改。详细细则请见 [TAOS SQL 的表管理](/reference/taos-sql/table) 章节。 + +:::warning +目前 TDengine 没有从技术层面限制使用一个 database (dbA)的超级表作为模板建立另一个 database (dbB)的子表,后续会禁止这种用法,不建议使用这种方法建表。 + +::: + +TDengine 建议将数据采集点的全局唯一 ID 作为表名(比如设备序列号)。但对于有的场景,并没有唯一的 ID,可以将多个 ID 组合成一个唯一的 ID。不建议将具有唯一性的 ID 作为标签值。 + +### 自动建表 + +在某些特殊场景中,用户在写数据时并不确定某个数据采集点的表是否存在,此时可在写入数据时使用自动建表语法来创建不存在的表,若该表已存在则不会建立新表。比如: + +```sql +INSERT INTO d1001 USING meters TAGS ("Beijng.Chaoyang", 2) VALUES (now, 10.2, 219, 0.32); +``` + +上述 SQL 语句将记录`(now, 10.2, 219, 0.32)`插入表 d1001。如果表 d1001 还未创建,则使用超级表 meters 做模板自动创建,同时打上标签值 `"Beijing.Chaoyang", 2`。 + +关于自动建表的详细语法请参见 [插入记录时自动建表](reference/taos-sql/insert#插入记录时自动建表) 章节。 + +## 多列模型 vs 单列模型 + +TDengine 支持多列模型,只要物理量是一个数据采集点同时采集的(时间戳一致),这些量就可以作为不同列放在一张超级表里。但还有一种极限的设计,单列模型,每个采集的物理量都单独建表,因此每种类型的物理量都单独建立一超级表。比如电流、电压、相位,就建三张超级表。 + +TDengine 建议尽可能采用多列模型,因为插入效率以及存储效率更高。但对于有些场景,一个采集点的采集量的种类经常变化,这个时候,如果采用多列模型,就需要频繁修改超级表的结构定义,让应用变的复杂,这个时候,采用单列模型会显得更简单。 diff --git a/docs-cn/06-insert-data/01-sql-writing.mdx b/docs-cn/06-insert-data/01-sql-writing.mdx new file mode 100644 index 0000000000000000000000000000000000000000..bd41f2f4552759cdde9a34207bee50feeda197c1 --- /dev/null +++ b/docs-cn/06-insert-data/01-sql-writing.mdx @@ -0,0 +1,123 @@ +# SQL 写入 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import JavaSQL from "./_java_sql.mdx"; +import JavaStmt from "./_java_stmt.mdx"; +import PySQL from "./_py_sql.mdx"; +import PyStmt from "./_py_stmt.mdx"; +import GoSQL from "./_go_sql.mdx"; +import GoStmt from "./_go_stmt.mdx"; +import RustSQL from "./_rust_sql.mdx"; +import RustStmt from "./_rust_stmt.mdx"; +import NodeSQL from "./_js_sql.mdx"; +import NodeStmt from "./_js_stmt.mdx"; +import CsSQL from "./_cs_sql.mdx"; +import CsStmt from "./_cs_stmt.mdx"; +import CSQL from "./_c_sql.mdx"; +import CStmt from "./_c_stmt.mdx"; + +## SQL 写入 + +应用通过连接器执行 insert 语句来插入数据,用户还可以通过 TAOS Shell,手动输入 insert 语句插入数据。比如下面这条 insert 就将一条记录写入到表 d1001 中: + +```sql +INSERT INTO d1001 VALUES (1538548685000, 10.3, 219, 0.31); +``` + +TDengine 支持一次写入多条记录,比如下面这条命令就将两条记录写入到表 d1001 中: + +```sql +INSERT INTO d1001 VALUES (1538548684000, 10.2, 220, 0.23) (1538548696650, 10.3, 218, 0.25); +``` + +TDengine 也支持一次向多个表写入数据,比如下面这条命令就向 d1001 写入两条记录,向 d1002 写入一条记录: + +```sql +INSERT INTO d1001 VALUES (1538548685000, 10.3, 219, 0.31) (1538548695000, 12.6, 218, 0.33) d1002 VALUES (1538548696800, 12.3, 221, 0.31); +``` + +详细的 SQL INSERT 语法规则请见 [TAOS SQL 的数据写入](/reference/taos-sql/insert) 章节。 + +:::info + +- 要提高写入效率,需要批量写入。一批写入的记录条数越多,插入效率就越高。但一条记录不能超过 16K,一条 SQL 语句总长度不能超过 1M 。 +- TDengine 支持多线程同时写入,要进一步提高写入速度,一个客户端需要打开 20 个以上的线程同时写。但线程数达到一定数量后,无法再提高,甚至还会下降,因为线程频繁切换,带来额外开销。 + +::: + +:::warning + +- 对同一张表,如果新插入记录的时间戳已经存在,默认情形下(UPDATE=0)新记录将被直接抛弃,也就是说,在一张表里,时间戳必须是唯一的。如果应用自动生成记录,很有可能生成的时间戳是一样的,这样,成功插入的记录条数会小于应用插入的记录条数。如果在创建数据库时使用了 UPDATE 1 选项,插入相同时间戳的新记录将覆盖原有记录。 +- 写入的数据的时间戳必须大于当前时间减去配置参数 keep 的时间。如果 keep 配置为 3650 天,那么无法写入比 3650 天还早的数据。写入数据的时间戳也不能大于当前时间加配置参数 days。如果 days 为 2,那么无法写入比当前时间还晚 2 天的数据。 + +::: + +## 示例程序 + +### 普通 SQL 写入 + + + + + + + + + + + + + + + + + + + + + + + + + +:::note + +1. 无论 RESTFful 方式建立连接还是本地驱动方式建立连接,以上示例代码都能正常工作。 +2. 唯一需要注意的是:由于 RESTful 接口无状态, 不能使用 `use db` 语句来切换数据库, 所以在上面示例中使用了`dbName.tbName`指定表名。 + +::: + +### 动态绑定写入 + +TDengine 也提供了支持参数绑定的 Prepare API,与 MySQL 一样,这些 API 目前也仅支持用问号 `?` 来代表待绑定的参数。文档中有时也会把此功能称为“原生接口写入”。从 2.1.1.0 和 2.1.2.0 版本开始,TDengine 大幅改进了参数绑定接口对数据写入(INSERT)场景的支持。这样在通过参数绑定接口写入数据时,就避免了 SQL 语法解析的资源消耗,从而在绝大多数情况下显著提升写入性能。 + + + + + + + + + + + + + + + + + + + + + + + + + +:::note + +只有使用本地驱动方式建立连接,才能使用动态绑定功能。 + +::: diff --git a/docs-cn/06-insert-data/02-influxdb-line.mdx b/docs-cn/06-insert-data/02-influxdb-line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..af7136cde408ef3bf11e5e9f2a85acfeea7256ae --- /dev/null +++ b/docs-cn/06-insert-data/02-influxdb-line.mdx @@ -0,0 +1,41 @@ +--- +sidebar_label: InfluxDB Line 协议 +--- + +# InfluxDB Line 协议 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import JavaLine from "./_java_line.mdx"; +import PyLine from "./_py_line.mdx"; +import GoLine from "./_go_line.mdx"; +import RustLine from "./_rust_line.mdx"; +import NodeLine from "./_js_line.mdx"; +import CsLine from "./_cs_line.mdx"; +import CLine from "./_c_line.mdx"; + +## 示例代码 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs-cn/06-insert-data/03-opentsdb-telnet.mdx b/docs-cn/06-insert-data/03-opentsdb-telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..85ef3762738a84453de5934baf381183b9766a89 --- /dev/null +++ b/docs-cn/06-insert-data/03-opentsdb-telnet.mdx @@ -0,0 +1,64 @@ +--- +sidebar_label: OpentsDB Telnet 协议 +--- + +# OpentsDB Telnet 协议 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import JavaTelnet from "./_java_opts_telnet.mdx"; +import PyTelnet from "./_py_opts_telnet.mdx"; +import GoTelnet from "./_go_opts_telnet.mdx"; +import RustTelnet from "./_rust_opts_telnet.mdx"; +import NodeTelnet from "./_js_opts_telnet.mdx"; +import CsTelnet from "./_cs_opts_telnet.mdx"; +import CTelnet from "./_c_opts_telnet.mdx"; + +## 示例代码 + + + + + + + + + + + + + + + + + + + + + + + + + +以上示例代码会自动创建 2 个超级表, 每个超级表有 4 条数据。 + +```cmd +taos> use test; +Database changed. + +taos> show stables; + name | created_time | columns | tags | tables | +============================================================================================ + meters.current | 2022-03-30 17:04:10.877 | 2 | 2 | 2 | + meters.voltage | 2022-03-30 17:04:10.882 | 2 | 2 | 2 | +Query OK, 2 row(s) in set (0.002544s) + +taos> select tbname, * from `meters.current`; + tbname | ts | value | groupid | location | +================================================================================================================================== + t_0e7bcfa21a02331c06764f275... | 2022-03-28 09:56:51.249 | 10.800000000 | 3 | Beijing.Haidian | + t_0e7bcfa21a02331c06764f275... | 2022-03-28 09:56:51.250 | 11.300000000 | 3 | Beijing.Haidian | + t_7e7b26dd860280242c6492a16... | 2022-03-28 09:56:51.249 | 10.300000000 | 2 | Beijing.Chaoyang | + t_7e7b26dd860280242c6492a16... | 2022-03-28 09:56:51.250 | 12.600000000 | 2 | Beijing.Chaoyang | +Query OK, 4 row(s) in set (0.005399s) +``` diff --git a/docs-cn/06-insert-data/04-opentsdb-json.mdx b/docs-cn/06-insert-data/04-opentsdb-json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..469ba89e016e7358924ceb26b428cc0362e761f3 --- /dev/null +++ b/docs-cn/06-insert-data/04-opentsdb-json.mdx @@ -0,0 +1,62 @@ +--- +sidebar_label: OpentsDB JSON 格式协议 +--- + +# OpentsDB JSON 格式协议 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import JavaJson from "./_java_opts_json.mdx"; +import PyJson from "./_py_opts_json.mdx"; +import GoJson from "./_go_opts_json.mdx"; +import RustJson from "./_rust_opts_json.mdx"; +import NodeJson from "./_js_opts_json.mdx"; +import CsJson from "./_cs_opts_json.mdx"; +import CJson from "./_c_opts_json.mdx"; + +## 示例代码 + + + + + + + + + + + + + + + + + + + + + + + + + +以上示例代码会自动创建 2 个超级表, 每个超级表有 2 条数据。 + +```cmd +taos> use test; +Database changed. + +taos> show stables; + name | created_time | columns | tags | tables | +============================================================================================ + meters.current | 2022-03-29 16:05:25.193 | 2 | 2 | 1 | + meters.voltage | 2022-03-29 16:05:25.200 | 2 | 2 | 1 | +Query OK, 2 row(s) in set (0.001954s) + +taos> select * from `meters.current`; + ts | value | groupid | location | +=================================================================================================================== + 2022-03-28 09:56:51.249 | 10.300000000 | 2.000000000 | Beijing.Chaoyang | + 2022-03-28 09:56:51.250 | 12.600000000 | 2.000000000 | Beijing.Chaoyang | +Query OK, 2 row(s) in set (0.004076s) +``` diff --git a/docs-cn/06-insert-data/_c_line.mdx b/docs-cn/06-insert-data/_c_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/06-insert-data/_c_opts_json.mdx b/docs-cn/06-insert-data/_c_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/06-insert-data/_c_opts_telnet.mdx b/docs-cn/06-insert-data/_c_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/06-insert-data/_c_sql.mdx b/docs-cn/06-insert-data/_c_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/06-insert-data/_c_stmt.mdx b/docs-cn/06-insert-data/_c_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/06-insert-data/_category_.yml b/docs-cn/06-insert-data/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0d91789ea15e8cb40769d53be35bc94598858ae --- /dev/null +++ b/docs-cn/06-insert-data/_category_.yml @@ -0,0 +1,5 @@ +label: 写入数据 +link: + type: generated-index + slug: /insert-data/ + description: "TDengine 支持多种接口写入协议,包括 SQL,InfluxDB Line 协议, OpentsDB Telnet 协议, OpentsDB JSON 格式协议。数据可以单条插入,也可以批量插入,可以插入一个数据采集点的数据,也可以同时插入多个数据采集点的数据。支持多线程插入,支持时间乱序数据插入,也支持历史数据插入。" diff --git a/docs-cn/06-insert-data/_cs_line.mdx b/docs-cn/06-insert-data/_cs_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..9c275ee3d7c7a1e52fbb34dbae922004543ee3ce --- /dev/null +++ b/docs-cn/06-insert-data/_cs_line.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/InfluxDBLineExample.cs}} +``` diff --git a/docs-cn/06-insert-data/_cs_opts_json.mdx b/docs-cn/06-insert-data/_cs_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..3d538b8506b298241faecd8098f89571359135c9 --- /dev/null +++ b/docs-cn/06-insert-data/_cs_opts_json.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/OptsJsonExample.cs}} +``` diff --git a/docs-cn/06-insert-data/_cs_opts_telnet.mdx b/docs-cn/06-insert-data/_cs_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c53bf3d7233115351e5af03b7d9e6318aa4a0da6 --- /dev/null +++ b/docs-cn/06-insert-data/_cs_opts_telnet.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/OptsTelnetExample.cs}} +``` diff --git a/docs-cn/06-insert-data/_cs_sql.mdx b/docs-cn/06-insert-data/_cs_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c7688bfbe77a1135424d829fe9b29fbb1bc93ae2 --- /dev/null +++ b/docs-cn/06-insert-data/_cs_sql.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/SQLInsertExample.cs}} +``` diff --git a/docs-cn/06-insert-data/_cs_stmt.mdx b/docs-cn/06-insert-data/_cs_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..97c3b910ffeb9e0c88fc143a02014115e819c147 --- /dev/null +++ b/docs-cn/06-insert-data/_cs_stmt.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/StmtInsertExample.cs}} +``` diff --git a/docs-cn/06-insert-data/_go_line.mdx b/docs-cn/06-insert-data/_go_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..cd225945b70e28bef2ca7fdaf0d9be0ad7ffc18c --- /dev/null +++ b/docs-cn/06-insert-data/_go_line.mdx @@ -0,0 +1,3 @@ +```go +{{#include docs-examples/go/insert/line/main.go}} +``` diff --git a/docs-cn/06-insert-data/_go_opts_json.mdx b/docs-cn/06-insert-data/_go_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..0c0d3e5b6330e046988cdd02234285ec67e92f01 --- /dev/null +++ b/docs-cn/06-insert-data/_go_opts_json.mdx @@ -0,0 +1,3 @@ +```go +{{#include docs-examples/go/insert/json/main.go}} +``` diff --git a/docs-cn/06-insert-data/_go_opts_telnet.mdx b/docs-cn/06-insert-data/_go_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..d5ca40cc146e62412476289853e8e2739e0e9e4b --- /dev/null +++ b/docs-cn/06-insert-data/_go_opts_telnet.mdx @@ -0,0 +1,3 @@ +```go +{{#include docs-examples/go/insert/telnet/main.go}} +``` diff --git a/docs-cn/06-insert-data/_go_sql.mdx b/docs-cn/06-insert-data/_go_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..613a65add1741eb763a4b24e65d180d05f7d670f --- /dev/null +++ b/docs-cn/06-insert-data/_go_sql.mdx @@ -0,0 +1,3 @@ +```go +{{#include docs-examples/go/insert/sql/main.go}} +``` diff --git a/docs-cn/06-insert-data/_go_stmt.mdx b/docs-cn/06-insert-data/_go_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c49b4c2e12dcd41ea9543f69f4485668e371e5f8 --- /dev/null +++ b/docs-cn/06-insert-data/_go_stmt.mdx @@ -0,0 +1,8 @@ +```go +{{#include docs-examples/go/insert/stmt/main.go}} +``` + +:::tip +driver-go 的模块 `github.com/taosdata/driver-go/v2/wrapper` 是 C 接口的底层封装。使用这个模块也可以实现动态绑定写入。 + +::: diff --git a/docs-cn/06-insert-data/_java_line.mdx b/docs-cn/06-insert-data/_java_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..2e59a5d4701b2a2ab04ec5711845dc5c80067a1e --- /dev/null +++ b/docs-cn/06-insert-data/_java_line.mdx @@ -0,0 +1,3 @@ +```java +{{#include docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java}} +``` diff --git a/docs-cn/06-insert-data/_java_opts_json.mdx b/docs-cn/06-insert-data/_java_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..826a1a07d9405cb193849f9d21e5444f68517914 --- /dev/null +++ b/docs-cn/06-insert-data/_java_opts_json.mdx @@ -0,0 +1,3 @@ +```java +{{#include docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java}} +``` diff --git a/docs-cn/06-insert-data/_java_opts_telnet.mdx b/docs-cn/06-insert-data/_java_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..954dcc1a482a150dea0b190e1e0593adbfbde796 --- /dev/null +++ b/docs-cn/06-insert-data/_java_opts_telnet.mdx @@ -0,0 +1,3 @@ +```java +{{#include docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java}} +``` diff --git a/docs-cn/06-insert-data/_java_sql.mdx b/docs-cn/06-insert-data/_java_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..a863378defe43b1f22c1f98087a34f053a7d6619 --- /dev/null +++ b/docs-cn/06-insert-data/_java_sql.mdx @@ -0,0 +1,3 @@ +```java +{{#include docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java:insert}} +``` \ No newline at end of file diff --git a/docs-cn/06-insert-data/_java_stmt.mdx b/docs-cn/06-insert-data/_java_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..54443e535fa84bdf8dc9161ed4ad00f50b26266c --- /dev/null +++ b/docs-cn/06-insert-data/_java_stmt.mdx @@ -0,0 +1,3 @@ +```java +{{#include docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java}} +``` diff --git a/docs-cn/06-insert-data/_js_line.mdx b/docs-cn/06-insert-data/_js_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..172c9bc17b8cff8b2620720b235a9c8e69bd4197 --- /dev/null +++ b/docs-cn/06-insert-data/_js_line.mdx @@ -0,0 +1,3 @@ +```js +{{#include docs-examples/node/nativeexample/influxdb_line_example.js}} +``` diff --git a/docs-cn/06-insert-data/_js_opts_json.mdx b/docs-cn/06-insert-data/_js_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..20ac9ec91e8dc6675828b16d7da0acb09afd3b5f --- /dev/null +++ b/docs-cn/06-insert-data/_js_opts_json.mdx @@ -0,0 +1,3 @@ +```js +{{#include docs-examples/node/nativeexample/opentsdb_json_example.js}} +``` diff --git a/docs-cn/06-insert-data/_js_opts_telnet.mdx b/docs-cn/06-insert-data/_js_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c3c8c40bd642f4f443de88e3db006ad50724d514 --- /dev/null +++ b/docs-cn/06-insert-data/_js_opts_telnet.mdx @@ -0,0 +1,3 @@ +```js +{{#include docs-examples/node/nativeexample/opentsdb_telnet_example.js}} +``` diff --git a/docs-cn/06-insert-data/_js_sql.mdx b/docs-cn/06-insert-data/_js_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..f5e17c76892a57a94192a95451b508b1c176c984 --- /dev/null +++ b/docs-cn/06-insert-data/_js_sql.mdx @@ -0,0 +1,3 @@ +```js +{{#include docs-examples/node/nativeexample/insert_example.js}} +``` diff --git a/docs-cn/06-insert-data/_js_stmt.mdx b/docs-cn/06-insert-data/_js_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..17a6c9785c7dc1e3c3fa6a59982913f1f139f9c2 --- /dev/null +++ b/docs-cn/06-insert-data/_js_stmt.mdx @@ -0,0 +1,12 @@ +```js title=一次绑定一行 +{{#include docs-examples/node/nativeexample/param_bind_example.js}} +``` + +```js title=一次绑定多行 +{{#include docs-examples/node/nativeexample/multi_bind_example.js:insertData}} +``` + +:::info +一次绑定一行效率不如一次绑定多行,但支持非 INSERT 语句。一次绑定多行效率更高,但仅支持 INSERT 语句。 + +::: diff --git a/docs-cn/06-insert-data/_py_line.mdx b/docs-cn/06-insert-data/_py_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..d3bb1ebb3403b53fa43bfc9d5d1a0de9764d7583 --- /dev/null +++ b/docs-cn/06-insert-data/_py_line.mdx @@ -0,0 +1,3 @@ +```py +{{#include docs-examples/python/line_protocol_example.py}} +``` diff --git a/docs-cn/06-insert-data/_py_opts_json.mdx b/docs-cn/06-insert-data/_py_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..cfbfe13ccfdb4f3f34b77300812863fdf70d0f59 --- /dev/null +++ b/docs-cn/06-insert-data/_py_opts_json.mdx @@ -0,0 +1,3 @@ +```py +{{#include docs-examples/python/json_protocol_example.py}} +``` diff --git a/docs-cn/06-insert-data/_py_opts_telnet.mdx b/docs-cn/06-insert-data/_py_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..14bc65a7a3da815abadf7f25c8deffeac666c8d7 --- /dev/null +++ b/docs-cn/06-insert-data/_py_opts_telnet.mdx @@ -0,0 +1,3 @@ +```py +{{#include docs-examples/python/telnet_line_protocol_example.py}} +``` diff --git a/docs-cn/06-insert-data/_py_sql.mdx b/docs-cn/06-insert-data/_py_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c0e15b8ec115b9244d50a47c9eafec04bcfdd70c --- /dev/null +++ b/docs-cn/06-insert-data/_py_sql.mdx @@ -0,0 +1,3 @@ +```py +{{#include docs-examples/python/native_insert_example.py}} +``` diff --git a/docs-cn/06-insert-data/_py_stmt.mdx b/docs-cn/06-insert-data/_py_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..8241ea86bc64ac64d842dc0a6cddc0eae0399503 --- /dev/null +++ b/docs-cn/06-insert-data/_py_stmt.mdx @@ -0,0 +1,12 @@ +```py title=一次绑定一行 +{{#include docs-examples/python/bind_param_example.py}} +``` + +```py title=一次绑定多行 +{{#include docs-examples/python/multi_bind_example.py:bind_batch}} +``` + +:::info +一次绑定一行效率不如一次绑定多行,但支持非 INSERT 语句。一次绑定多行效率更高,但仅支持 INSERT 语句。 + +::: \ No newline at end of file diff --git a/docs-cn/06-insert-data/_rust_line.mdx b/docs-cn/06-insert-data/_rust_line.mdx new file mode 100644 index 0000000000000000000000000000000000000000..696ddb7b854751b8dee01047066f97f74212933f --- /dev/null +++ b/docs-cn/06-insert-data/_rust_line.mdx @@ -0,0 +1,3 @@ +```rust +{{#include docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs}} +``` diff --git a/docs-cn/06-insert-data/_rust_opts_json.mdx b/docs-cn/06-insert-data/_rust_opts_json.mdx new file mode 100644 index 0000000000000000000000000000000000000000..97d9052dacd1894cc7548a59951ecfaad9caee87 --- /dev/null +++ b/docs-cn/06-insert-data/_rust_opts_json.mdx @@ -0,0 +1,3 @@ +```rust +{{#include docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs}} +``` diff --git a/docs-cn/06-insert-data/_rust_opts_telnet.mdx b/docs-cn/06-insert-data/_rust_opts_telnet.mdx new file mode 100644 index 0000000000000000000000000000000000000000..14021f43d8aff30c35dc30c5d278d4e51f375024 --- /dev/null +++ b/docs-cn/06-insert-data/_rust_opts_telnet.mdx @@ -0,0 +1,3 @@ +```rust +{{#include docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs}} +``` diff --git a/docs-cn/06-insert-data/_rust_sql.mdx b/docs-cn/06-insert-data/_rust_sql.mdx new file mode 100644 index 0000000000000000000000000000000000000000..8e8013e4ad734efcc262ea2f750b82210a538e49 --- /dev/null +++ b/docs-cn/06-insert-data/_rust_sql.mdx @@ -0,0 +1,3 @@ +```rust +{{#include docs-examples/rust/restexample/examples/insert_example.rs}} +``` diff --git a/docs-cn/06-insert-data/_rust_stmt.mdx b/docs-cn/06-insert-data/_rust_stmt.mdx new file mode 100644 index 0000000000000000000000000000000000000000..590a7a0e717426ed0235331c49dfc578bc55b2f7 --- /dev/null +++ b/docs-cn/06-insert-data/_rust_stmt.mdx @@ -0,0 +1,3 @@ +```rust +{{#include docs-examples/rust/nativeexample/examples/stmt_example.rs}} +``` diff --git a/docs-cn/07-query-data/_c.mdx b/docs-cn/07-query-data/_c.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/07-query-data/_c_async.mdx b/docs-cn/07-query-data/_c_async.mdx new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs-cn/07-query-data/_category_.yml b/docs-cn/07-query-data/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..69273cb31cc54fd438bf82b408e529f8d3d9ccb4 --- /dev/null +++ b/docs-cn/07-query-data/_category_.yml @@ -0,0 +1 @@ +label: 查询数据 diff --git a/docs-cn/07-query-data/_cs.mdx b/docs-cn/07-query-data/_cs.mdx new file mode 100644 index 0000000000000000000000000000000000000000..2ab52feb564eff0fe251bc9900ea2539171e5dba --- /dev/null +++ b/docs-cn/07-query-data/_cs.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/QueryExample.cs}} +``` diff --git a/docs-cn/07-query-data/_cs_async.mdx b/docs-cn/07-query-data/_cs_async.mdx new file mode 100644 index 0000000000000000000000000000000000000000..f868994b303e62016b5e2f9304275135855c6ae5 --- /dev/null +++ b/docs-cn/07-query-data/_cs_async.mdx @@ -0,0 +1,3 @@ +```csharp +{{#include docs-examples/csharp/AsyncQueryExample.cs}} +``` diff --git a/docs-cn/07-query-data/_go.mdx b/docs-cn/07-query-data/_go.mdx new file mode 100644 index 0000000000000000000000000000000000000000..417c12315c06517e2f3de850ac9a379b7714b519 --- /dev/null +++ b/docs-cn/07-query-data/_go.mdx @@ -0,0 +1,3 @@ +```go +{{#include docs-examples/go/query/sync/main.go}} +``` diff --git a/docs-cn/07-query-data/_go_async.mdx b/docs-cn/07-query-data/_go_async.mdx new file mode 100644 index 0000000000000000000000000000000000000000..72fff411b980a0dcbdcaf4274722c63e0351db6f --- /dev/null +++ b/docs-cn/07-query-data/_go_async.mdx @@ -0,0 +1,3 @@ +```go +{{#include docs-examples/go/query/async/main.go}} +``` diff --git a/docs-cn/07-query-data/_java.mdx b/docs-cn/07-query-data/_java.mdx new file mode 100644 index 0000000000000000000000000000000000000000..519b9266144486231caf3ee593e973d438941ee4 --- /dev/null +++ b/docs-cn/07-query-data/_java.mdx @@ -0,0 +1,3 @@ +```java +{{#include docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java}} +``` diff --git a/docs-cn/07-query-data/_js.mdx b/docs-cn/07-query-data/_js.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c5e4c4f3fc20d3940a2bc6e13e6a5dea8a15ff13 --- /dev/null +++ b/docs-cn/07-query-data/_js.mdx @@ -0,0 +1,3 @@ +```js +{{#include docs-examples/node/nativeexample/query_example.js}} +``` diff --git a/docs-cn/07-query-data/_js_async.mdx b/docs-cn/07-query-data/_js_async.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c65d54ed12f6c4bbeb333e0de0ba9ca4638bff84 --- /dev/null +++ b/docs-cn/07-query-data/_js_async.mdx @@ -0,0 +1,3 @@ +```js +{{#include docs-examples/node/nativeexample/async_query_example.js}} +``` diff --git a/docs-cn/07-query-data/_py.mdx b/docs-cn/07-query-data/_py.mdx new file mode 100644 index 0000000000000000000000000000000000000000..6a1bacdd3ef91e9484c1d87d6a22de8b128e2144 --- /dev/null +++ b/docs-cn/07-query-data/_py.mdx @@ -0,0 +1,11 @@ +通过迭代逐行获取查询结果。 + +```py +{{#include docs-examples/python/query_example.py:iter}} +``` + +一次获取所有查询结果,并把每一行转化为一个字典返回。 + +```py +{{#include docs-examples/python/query_example.py:fetch_all}} +``` diff --git a/docs-cn/07-query-data/_py_async.mdx b/docs-cn/07-query-data/_py_async.mdx new file mode 100644 index 0000000000000000000000000000000000000000..2399a50df645804788036e17bf223c53482d4eaf --- /dev/null +++ b/docs-cn/07-query-data/_py_async.mdx @@ -0,0 +1,8 @@ +```py +{{#include docs-examples/python/async_query_example.py}} +``` + +:::note +这个示例程序,目前在 Windows 系统上还无法运行 + +::: diff --git a/docs-cn/07-query-data/_rust.mdx b/docs-cn/07-query-data/_rust.mdx new file mode 100644 index 0000000000000000000000000000000000000000..742d70fd025ff44b573eedf78441c9d73defad45 --- /dev/null +++ b/docs-cn/07-query-data/_rust.mdx @@ -0,0 +1,3 @@ +```rust +{{#include docs-examples/rust/restexample/examples/query_example.rs}} +``` diff --git a/docs-cn/07-query-data/index.mdx b/docs-cn/07-query-data/index.mdx new file mode 100644 index 0000000000000000000000000000000000000000..ae03007eb61e8ab64fb783f8c5c06fbcf6f47ce6 --- /dev/null +++ b/docs-cn/07-query-data/index.mdx @@ -0,0 +1,179 @@ +--- +slug: /query-data +--- + +# 查询数据 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import JavaQuery from "./_java.mdx"; +import PyQuery from "./_py.mdx"; +import GoQuery from "./_go.mdx"; +import RustQuery from "./_rust.mdx"; +import NodeQuery from "./_js.mdx"; +import CsQuery from "./_cs.mdx"; +import CQuery from "./_c.mdx"; +import PyAsync from "./_py_async.mdx"; +import NodeAsync from "./_js_async.mdx"; +import CsAsync from "./_cs_async.mdx"; +import CAsync from "./_c_async.mdx"; + +## 主要查询功能 + +TDengine 采用 SQL 作为查询语言。应用程序可以通过 C/C++, Java, Go, C#, Python, Node.js 连接器发送 SQL 语句,用户可以通过 TDengine 提供的命令行(Command Line Interface, CLI)工具 TAOS Shell 手动执行 SQL 即席查询(Ad-Hoc Query)。TDengine 支持如下查询功能: + +- 单列、多列数据查询 +- 标签和数值的多种过滤条件:>, <, =, <\>, like 等 +- 聚合结果的分组(Group by)、排序(Order by)、约束输出(Limit/Offset) +- 数值列及聚合结果的四则运算 +- 时间戳对齐的连接查询(Join Query: 隐式连接)操作 +- 多种聚合/计算函数: count, max, min, avg, sum, twa, stddev, leastsquares, top, bottom, first, last, percentile, apercentile, last_row, spread, diff 等 + +例如:在 TAOS Shell 中,从表 d1001 中查询出 voltage > 215 的记录,按时间降序排列,仅仅输出 2 条。 + +```sql +taos> select * from d1001 where voltage > 215 order by ts desc limit 2; + ts | current | voltage | phase | +====================================================================================== + 2018-10-03 14:38:16.800 | 12.30000 | 221 | 0.31000 | + 2018-10-03 14:38:15.000 | 12.60000 | 218 | 0.33000 | +Query OK, 2 row(s) in set (0.001100s) +``` + +为满足物联网场景的需求,TDengine 支持几个特殊的函数,比如 twa(时间加权平均),spread (最大值与最小值的差),last_row(最后一条记录)等,更多与物联网场景相关的函数将添加进来。TDengine 还支持连续查询。 + +具体的查询语法请看 [TAOS SQL 的数据查询](https://www.taosdata.com/cn/documentation/taos-sql#select) 章节。 + +## 多表聚合查询 + +物联网场景中,往往同一个类型的数据采集点有多个。TDengine 采用超级表(STable)的概念来描述某一个类型的数据采集点,一张普通的表来描述一个具体的数据采集点。同时 TDengine 使用标签来描述数据采集点的静态属性,一个具体的数据采集点有具体的标签值。通过指定标签的过滤条件,TDengine 提供了一高效的方法将超级表(某一类型的数据采集点)所属的子表进行聚合查询。对普通表的聚合函数以及绝大部分操作都适用于超级表,语法完全一样。 + +**示例 1**:在 TAOS Shell,查找北京所有智能电表采集的电压平均值,并按照 location 分组 + +``` +taos> SELECT AVG(voltage) FROM meters GROUP BY location; + avg(voltage) | location | +============================================================= + 222.000000000 | Beijing.Haidian | + 219.200000000 | Beijing.Chaoyang | +Query OK, 2 row(s) in set (0.002136s) +``` + +**示例 2**:在 TAOS shell, 查找 groupId 为 2 的所有智能电表过去 24 小时的记录条数,电流的最大值 + +``` +taos> SELECT count(*), max(current) FROM meters where groupId = 2 and ts > now - 24h; + cunt(*) | max(current) | +================================== + 5 | 13.4 | +Query OK, 1 row(s) in set (0.002136s) +``` + +TDengine 仅容许对属于同一个超级表的表之间进行聚合查询,不同超级表之间的聚合查询不支持。在 [TAOS SQL 的数据查询](https://www.taosdata.com/cn/documentation/taos-sql#select) 一章,查询类操作都会注明是否支持超级表。 + +## 降采样查询、插值 + +物联网场景里,经常需要通过降采样(down sampling)将采集的数据按时间段进行聚合。TDengine 提供了一个简便的关键词 interval 让按照时间窗口的查询操作变得极为简单。比如,将智能电表 d1001 采集的电流值每 10 秒钟求和 + +``` +taos> SELECT sum(current) FROM d1001 INTERVAL(10s); + ts | sum(current) | +====================================================== + 2018-10-03 14:38:00.000 | 10.300000191 | + 2018-10-03 14:38:10.000 | 24.900000572 | +Query OK, 2 row(s) in set (0.000883s) +``` + +降采样操作也适用于超级表,比如:将北京所有智能电表采集的电流值每秒钟求和 + +``` +taos> SELECT SUM(current) FROM meters where location like "Beijing%" INTERVAL(1s); + ts | sum(current) | +====================================================== + 2018-10-03 14:38:04.000 | 10.199999809 | + 2018-10-03 14:38:05.000 | 32.900000572 | + 2018-10-03 14:38:06.000 | 11.500000000 | + 2018-10-03 14:38:15.000 | 12.600000381 | + 2018-10-03 14:38:16.000 | 36.000000000 | +Query OK, 5 row(s) in set (0.001538s) +``` + +降采样操作也支持时间偏移,比如:将所有智能电表采集的电流值每秒钟求和,但要求每个时间窗口从 500 毫秒开始 + +``` +taos> SELECT SUM(current) FROM meters INTERVAL(1s, 500a); + ts | sum(current) | +====================================================== + 2018-10-03 14:38:04.500 | 11.189999809 | + 2018-10-03 14:38:05.500 | 31.900000572 | + 2018-10-03 14:38:06.500 | 11.600000000 | + 2018-10-03 14:38:15.500 | 12.300000381 | + 2018-10-03 14:38:16.500 | 35.000000000 | +Query OK, 5 row(s) in set (0.001521s) +``` + +物联网场景里,每个数据采集点采集数据的时间是难同步的,但很多分析算法(比如 FFT)需要把采集的数据严格按照时间等间隔的对齐,在很多系统里,需要应用自己写程序来处理,但使用 TDengine 的降采样操作就轻松解决。如果一个时间间隔里,没有采集的数据,TDengine 还提供插值计算的功能。 + +语法规则细节请见 [TAOS SQL 的时间维度聚合](https://www.taosdata.com/cn/documentation/taos-sql#aggregation) 章节。 + +## 示例代码 + +### 查询数据 + +在 [SQL 写入](/insert-data/sql-writing) 一章,我们创建了 power 数据库,并向 meters 表写入了一些数据,以下示例代码展示如何查询这个表的数据。 + + + + + + + + + + + + + + + + + + + + + + + + + +:::note + +1. 无论 RESTFful 方式建立连接还是本地驱动方式建立连接,以上示例代码都能正常工作。 +2. 唯一需要注意的是:由于 RESTful 接口无状态, 不能使用 `use db` 语句来切换数据库。 + +::: + +### 异步查询 + +除同步查询 API 之外,TDengine 还提供性能更高的异步调用 API 处理数据插入、查询操作。在软硬件环境相同的情况下,异步 API 处理数据插入的速度比同步 API 快 2-4 倍。异步 API 采用非阻塞式的调用方式,在系统真正完成某个具体数据库操作前,立即返回。调用的线程可以去处理其他工作,从而可以提升整个应用的性能。异步 API 在网络延迟严重的情况下,优点尤为突出。 + + + + + + + + + + + + + + + + +:::note + +只有使用本地驱动方式连接连接,才能使用异步查询功能。 + +::: diff --git a/docs-cn/08-advance-feature/01-continuous-query.mdx b/docs-cn/08-advance-feature/01-continuous-query.mdx new file mode 100644 index 0000000000000000000000000000000000000000..5b9f595601824eb1625a9e0b0ee4f4cbb268b2e0 --- /dev/null +++ b/docs-cn/08-advance-feature/01-continuous-query.mdx @@ -0,0 +1,70 @@ +--- +sidebar_label: 连续查询 +--- + +# 连续查询(Continuous Query) + +连续查询是 TDengine 定期自动执行的查询,采用滑动窗口的方式进行计算,是一种简化的时间驱动的流式计算。针对库中的表或超级表,TDengine 可提供定期自动执行的连续查询,用户可让 TDengine 推送查询的结果,也可以将结果再写回到 TDengine 中。每次执行的查询是一个时间窗口,时间窗口随着时间流动向前滑动。在定义连续查询的时候需要指定时间窗口(time window, 参数 interval)大小和每次前向增量时间(forward sliding times, 参数 sliding)。 + +TDengine 的连续查询采用时间驱动模式,可以直接使用 TAOS SQL 进行定义,不需要额外的操作。使用连续查询,可以方便快捷地按照时间窗口生成结果,从而对原始采集数据进行降采样(down sampling)。用户通过 TAOS SQL 定义连续查询以后,TDengine 自动在最后的一个完整的时间周期末端拉起查询,并将计算获得的结果推送给用户或者写回 TDengine。 + +TDengine 提供的连续查询与普通流计算中的时间窗口计算具有以下区别: + +- 不同于流计算的实时反馈计算结果,连续查询只在时间窗口关闭以后才开始计算。例如时间周期是 1 天,那么当天的结果只会在 23:59:59 以后才会生成。 +- 如果有历史记录写入到已经计算完成的时间区间,连续查询并不会重新进行计算,也不会重新将结果推送给用户。对于写回 TDengine 的模式,也不会更新已经存在的计算结果。 +- 使用连续查询推送结果的模式,服务端并不缓存客户端计算状态,也不提供 Exactly-Once 的语意保证。如果用户的应用端崩溃,再次拉起的连续查询将只会从再次拉起的时间开始重新计算最近的一个完整的时间窗口。如果使用写回模式,TDengine 可确保数据写回的有效性和连续性。 + +## 使用连续查询 + +下面以智能电表场景为例介绍连续查询的具体使用方法。假设我们通过下列 SQL 语句创建了超级表和子表: + +```sql +create table meters (ts timestamp, current float, voltage int, phase float) tags (location binary(64), groupId int); +create table D1001 using meters tags ("Beijing.Chaoyang", 2); +create table D1002 using meters tags ("Beijing.Haidian", 2); +... +``` + +我们已经知道,可以通过下面这条 SQL 语句以一分钟为时间窗口、30 秒为前向增量统计这些电表的平均电压。 + +```sql +select avg(voltage) from meters interval(1m) sliding(30s); +``` + +每次执行这条语句,都会重新计算所有数据。 如果需要每隔 30 秒执行一次来增量计算最近一分钟的数据,可以把上面的语句改进成下面的样子,每次使用不同的 `startTime` 并定期执行: + +```sql +select avg(voltage) from meters where ts > {startTime} interval(1m) sliding(30s); +``` + +这样做没有问题,但 TDengine 提供了更简单的方法,只要在最初的查询语句前面加上 `create table {tableName} as` 就可以了,例如: + +```sql +create table avg_vol as select avg(voltage) from meters interval(1m) sliding(30s); +``` + +会自动创建一个名为 `avg_vol` 的新表,然后每隔 30 秒,TDengine 会增量执行 `as` 后面的 SQL 语句,并将查询结果写入这个表中,用户程序后续只要从 `avg_vol` 中查询数据即可。例如: + +```sql +taos> select * from avg_vol; + ts | avg_voltage_ | +=================================================== + 2020-07-29 13:37:30.000 | 222.0000000 | + 2020-07-29 13:38:00.000 | 221.3500000 | + 2020-07-29 13:38:30.000 | 220.1700000 | + 2020-07-29 13:39:00.000 | 223.0800000 | +``` + +需要注意,查询时间窗口的最小值是 10 毫秒,没有时间窗口范围的上限。 + +此外,TDengine 还支持用户指定连续查询的起止时间。如果不输入开始时间,连续查询将从第一条原始数据所在的时间窗口开始;如果没有输入结束时间,连续查询将永久运行;如果用户指定了结束时间,连续查询在系统时间达到指定的时间以后停止运行。比如使用下面的 SQL 创建的连续查询将运行一小时,之后会自动停止。 + +```sql +create table avg_vol as select avg(voltage) from meters where ts > now and ts <= now + 1h interval(1m) sliding(30s); +``` + +需要说明的是,上面例子中的 `now` 是指创建连续查询的时间,而不是查询执行的时间,否则,查询就无法自动停止了。另外,为了尽量避免原始数据延迟写入导致的问题,TDengine 中连续查询的计算有一定的延迟。也就是说,一个时间窗口过去后,TDengine 并不会立即计算这个窗口的数据,所以要稍等一会(一般不会超过 1 分钟)才能查到计算结果。 + +## 管理连续查询 + +用户可在控制台中通过 `show streams` 命令来查看系统中全部运行的连续查询,并可以通过 `kill stream` 命令杀掉对应的连续查询。后续版本会提供更细粒度和便捷的连续查询管理命令。 diff --git a/docs-cn/08-advance-feature/02-subscribe.mdx b/docs-cn/08-advance-feature/02-subscribe.mdx new file mode 100644 index 0000000000000000000000000000000000000000..a7c8dcf0213b2e78bda26fecaedd9179f99878f0 --- /dev/null +++ b/docs-cn/08-advance-feature/02-subscribe.mdx @@ -0,0 +1,288 @@ +--- +sidebar_position: 2 +sidebar_label: 数据订阅 +--- + +# 数据订阅 + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +基于数据天然的时间序列特性,TDengine 的数据写入(insert)与消息系统的数据发布(pub)逻辑上一致,均可视为系统中插入一条带时间戳的新记录。同时,TDengine 在内部严格按照数据时间序列单调递增的方式保存数据。本质上来说,TDengine 中里每一张表均可视为一个标准的消息队列。 + +TDengine 内嵌支持轻量级的消息订阅与推送服务。使用系统提供的 API,用户可使用普通查询语句订阅数据库中的一张或多张表。订阅的逻辑和操作状态的维护均是由客户端完成,客户端定时轮询服务器是否有新的记录到达,有新的记录到达就会将结果反馈到客户。 + +TDengine 的订阅与推送服务的状态是客户端维持,TDengine 服务器并不维持。因此如果应用重启,从哪个时间点开始获取最新数据,由应用决定。 + +TDengine 的 API 中,与订阅相关的主要有以下三个: + +```c +taos_subscribe +taos_consume +taos_unsubscribe +``` + +这些 API 的文档请见 [C/C++ Connector](https://www.taosdata.com/cn/documentation/connector#c-cpp),下面仍以智能电表场景为例介绍一下它们的具体用法(超级表和子表结构请参考上一节“连续查询”),完整的示例代码可以在 [这里](https://github.com/taosdata/TDengine/blob/master/examples/c/subscribe.c) 找到。 + +如果我们希望当某个电表的电流超过一定限制(比如 10A)后能得到通知并进行一些处理, 有两种方法:一是分别对每张子表进行查询,每次查询后记录最后一条数据的时间戳,后续只查询这个时间戳之后的数据: + +```sql +select * from D1001 where ts > {last_timestamp1} and current > 10; +select * from D1002 where ts > {last_timestamp2} and current > 10; +... +``` + +这确实可行,但随着电表数量的增加,查询数量也会增加,客户端和服务端的性能都会受到影响,当电表数增长到一定的程度,系统就无法承受了。 + +另一种方法是对超级表进行查询。这样,无论有多少电表,都只需一次查询: + +```sql +select * from meters where ts > {last_timestamp} and current > 10; +``` + +但是,如何选择 `last_timestamp` 就成了一个新的问题。因为,一方面数据的产生时间(也就是数据时间戳)和数据入库的时间一般并不相同,有时偏差还很大;另一方面,不同电表的数据到达 TDengine 的时间也会有差异。所以,如果我们在查询中使用最慢的那台电表的数据的时间戳作为 `last_timestamp`,就可能重复读入其它电表的数据;如果使用最快的电表的时间戳,其它电表的数据就可能被漏掉。 + +TDengine 的订阅功能为上面这个问题提供了一个彻底的解决方案。 + +首先是使用 `taos_subscribe` 创建订阅: + +```c +TAOS_SUB* tsub = NULL; +if (async) { +  // create an asynchronized subscription, the callback function will be called every 1s +  tsub = taos_subscribe(taos, restart, topic, sql, subscribe_callback, &blockFetch, 1000); +} else { +  // create an synchronized subscription, need to call 'taos_consume' manually +  tsub = taos_subscribe(taos, restart, topic, sql, NULL, NULL, 0); +} +``` + +TDengine 中的订阅既可以是同步的,也可以是异步的,上面的代码会根据从命令行获取的参数 `async` 的值来决定使用哪种方式。这里,同步的意思是用户程序要直接调用 `taos_consume` 来拉取数据,而异步则由 API 在内部的另一个线程中调用 `taos_consume`,然后把拉取到的数据交给回调函数 `subscribe_callback`去处理。(注意,`subscribe_callback` 中不宜做较为耗时的操作,否则有可能导致客户端阻塞等不可控的问题。) + +参数 `taos` 是一个已经建立好的数据库连接,在同步模式下无特殊要求。但在异步模式下,需要注意它不会被其它线程使用,否则可能导致不可预计的错误,因为回调函数在 API 的内部线程中被调用,而 TDengine 的部分 API 不是线程安全的。 + +参数 `sql` 是查询语句,可以在其中使用 where 子句指定过滤条件。在我们的例子中,如果只想订阅电流超过 10A 时的数据,可以这样写: + +```sql +select * from meters where current > 10; +``` + +注意,这里没有指定起始时间,所以会读到所有时间的数据。如果只想从一天前的数据开始订阅,而不需要更早的历史数据,可以再加上一个时间条件: + +```sql +select * from meters where ts > now - 1d and current > 10; +``` + +订阅的 `topic` 实际上是它的名字,因为订阅功能是在客户端 API 中实现的,所以没必要保证它全局唯一,但需要它在一台客户端机器上唯一。 + +如果名为 `topic` 的订阅不存在,参数 `restart` 没有意义;但如果用户程序创建这个订阅后退出,当它再次启动并重新使用这个 `topic` 时,`restart` 就会被用于决定是从头开始读取数据,还是接续上次的位置进行读取。本例中,如果 `restart` 是 **true**(非零值),用户程序肯定会读到所有数据。但如果这个订阅之前就存在了,并且已经读取了一部分数据,且 `restart` 是 **false**(**0**),用户程序就不会读到之前已经读取的数据了。 + +`taos_subscribe`的最后一个参数是以毫秒为单位的轮询周期。在同步模式下,如果前后两次调用 `taos_consume` 的时间间隔小于此时间,`taos_consume` 会阻塞,直到间隔超过此时间。异步模式下,这个时间是两次调用回调函数的最小时间间隔。 + +`taos_subscribe` 的倒数第二个参数用于用户程序向回调函数传递附加参数,订阅 API 不对其做任何处理,只原样传递给回调函数。此参数在同步模式下无意义。 + +订阅创建以后,就可以消费其数据了,同步模式下,示例代码是下面的 else 部分: + +```c +if (async) { +  getchar(); +} else while(1) { +  TAOS_RES* res = taos_consume(tsub); +  if (res == NULL) { +    printf("failed to consume data."); +    break; +  } else { +    print_result(res, blockFetch); +    getchar(); +  } +} +``` + +这里是一个 **while** 循环,用户每按一次回车键就调用一次 `taos_consume`,而 `taos_consume` 的返回值是查询到的结果集,与 `taos_use_result` 完全相同,例子中使用这个结果集的代码是函数 `print_result`: + +```c +void print_result(TAOS_RES* res, int blockFetch) { +  TAOS_ROW row = NULL; +  int num_fields = taos_num_fields(res); +  TAOS_FIELD* fields = taos_fetch_fields(res); +  int nRows = 0; +  if (blockFetch) { +    nRows = taos_fetch_block(res, &row); +    for (int i = 0; i < nRows; i++) { +      char temp[256]; +      taos_print_row(temp, row + i, fields, num_fields); +      puts(temp); +    } +  } else { +    while ((row = taos_fetch_row(res))) { +      char temp[256]; +      taos_print_row(temp, row, fields, num_fields); +      puts(temp); +      nRows++; +    } +  } +  printf("%d rows consumed.\n", nRows); +} +``` + +其中的 `taos_print_row` 用于处理订阅到数据,在我们的例子中,它会打印出所有符合条件的记录。而异步模式下,消费订阅到的数据则显得更为简单: + +```c +void subscribe_callback(TAOS_SUB* tsub, TAOS_RES *res, void* param, int code) { +  print_result(res, *(int*)param); +} +``` + +当要结束一次数据订阅时,需要调用 `taos_unsubscribe`: + +```c +taos_unsubscribe(tsub, keep); +``` + +其第二个参数,用于决定是否在客户端保留订阅的进度信息。如果这个参数是**false**(**0**),那无论下次调用 `taos_subscribe` 时的 `restart` 参数是什么,订阅都只能重新开始。另外,进度信息的保存位置是 _{DataDir}/subscribe/_ 这个目录下,每个订阅有一个与其 `topic` 同名的文件,删掉某个文件,同样会导致下次创建其对应的订阅时只能重新开始。 + +代码介绍完毕,我们来看一下实际的运行效果。假设: + +- 示例代码已经下载到本地 +- TDengine 也已经在同一台机器上安装好 +- 示例所需的数据库、超级表、子表已经全部创建好 + +则可以在示例代码所在目录执行以下命令来编译并启动示例程序: + +```bash +make +./subscribe -sql='select * from meters where current > 10;' +``` + +示例程序启动后,打开另一个终端窗口,启动 TDengine 的 shell 向 **D1001** 插入一条电流为 12A 的数据: + +```sql +$ taos +> use test; +> insert into D1001 values(now, 12, 220, 1); +``` + +这时,因为电流超过了 10A,您应该可以看到示例程序将它输出到了屏幕上。您可以继续插入一些数据观察示例程序的输出。 + +## 示例代码 + + + + + + + + + + + +## Java 使用数据订阅功能 + +订阅功能也提供了 Java 开发接口,相关说明请见 [Java Connector](https://www.taosdata.com/cn/documentation/connector/java#subscribe)。需要注意的是,目前 Java 接口没有提供异步订阅模式,但用户程序可以通过创建 `TimerTask` 等方式达到同样的效果。 + +下面以一个示例程序介绍其具体使用方法。它所完成的功能与前面介绍的 C 语言示例基本相同,也是订阅数据库中所有电流超过 10A 的记录。 + +### 准备数据 + +```sql +# 创建 power 库 +taos> create database power; +# 切换库 +taos> use power; +# 创建超级表 +taos> create table meters(ts timestamp, current float, voltage int, phase int) tags(location binary(64), groupId int); +# 创建表 +taos> create table d1001 using meters tags ("Beijing.Chaoyang", 2); +taos> create table d1002 using meters tags ("Beijing.Haidian", 2); +# 插入测试数据 +taos> insert into d1001 values("2020-08-15 12:00:00.000", 12, 220, 1),("2020-08-15 12:10:00.000", 12.3, 220, 2),("2020-08-15 12:20:00.000", 12.2, 220, 1); +taos> insert into d1002 values("2020-08-15 12:00:00.000", 9.9, 220, 1),("2020-08-15 12:10:00.000", 10.3, 220, 1),("2020-08-15 12:20:00.000", 11.2, 220, 1); +# 从超级表 meters 查询电流大于 10A 的记录 +taos> select * from meters where current > 10; + ts | current | voltage | phase | location | groupid | +=========================================================================================================== + 2020-08-15 12:10:00.000 | 10.30000 | 220 | 1 | Beijing.Haidian | 2 | + 2020-08-15 12:20:00.000 | 11.20000 | 220 | 1 | Beijing.Haidian | 2 | + 2020-08-15 12:00:00.000 | 12.00000 | 220 | 1 | Beijing.Chaoyang | 2 | + 2020-08-15 12:10:00.000 | 12.30000 | 220 | 2 | Beijing.Chaoyang | 2 | + 2020-08-15 12:20:00.000 | 12.20000 | 220 | 1 | Beijing.Chaoyang | 2 | +Query OK, 5 row(s) in set (0.004896s) +``` + +### 示例程序 + +```java +public class SubscribeDemo { + private static final String topic = "topic-meter-current-bg-10"; + private static final String sql = "select * from meters where current > 10"; + + public static void main(String[] args) { + Connection connection = null; + TSDBSubscribe subscribe = null; + + try { + Class.forName("com.taosdata.jdbc.TSDBDriver"); + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + String jdbcUrl = "jdbc:TAOS://127.0.0.1:6030/power?user=root&password=taosdata"; + connection = DriverManager.getConnection(jdbcUrl, properties); + subscribe = ((TSDBConnection) connection).subscribe(topic, sql, true); // 创建订阅 + int count = 0; + while (count < 10) { + TimeUnit.SECONDS.sleep(1); // 等待1秒,避免频繁调用 consume,给服务端造成压力 + TSDBResultSet resultSet = subscribe.consume(); // 消费数据 + if (resultSet == null) { + continue; + } + ResultSetMetaData metaData = resultSet.getMetaData(); + while (resultSet.next()) { + int columnCount = metaData.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + System.out.print(metaData.getColumnLabel(i) + ": " + resultSet.getString(i) + "\t"); + } + System.out.println(); + count++; + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (null != subscribe) + subscribe.close(true); // 关闭订阅 + if (connection != null) + connection.close(); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + } + } +} +``` + +运行示例程序,首先,它会消费符合查询条件的所有历史数据: + +```bash +# java -jar subscribe.jar + +ts: 1597464000000 current: 12.0 voltage: 220 phase: 1 location: Beijing.Chaoyang groupid : 2 +ts: 1597464600000 current: 12.3 voltage: 220 phase: 2 location: Beijing.Chaoyang groupid : 2 +ts: 1597465200000 current: 12.2 voltage: 220 phase: 1 location: Beijing.Chaoyang groupid : 2 +ts: 1597464600000 current: 10.3 voltage: 220 phase: 1 location: Beijing.Haidian groupid : 2 +ts: 1597465200000 current: 11.2 voltage: 220 phase: 1 location: Beijing.Haidian groupid : 2 +``` + +接着,使用 taos 客户端向表中新增一条数据: + +```sql +# taos +taos> use power; +taos> insert into d1001 values("2020-08-15 12:40:00.000", 12.4, 220, 1); +``` + +因为这条数据的电流大于 10A,示例程序会将其消费: + +``` +ts: 1597466400000 current: 12.4 voltage: 220 phase: 1 location: Beijing.Chaoyang groupid: 2 +``` diff --git a/docs-cn/08-advance-feature/03-cache.md b/docs-cn/08-advance-feature/03-cache.md new file mode 100644 index 0000000000000000000000000000000000000000..909404085ad9ba05517a6201495bbcfc1ab6ce9e --- /dev/null +++ b/docs-cn/08-advance-feature/03-cache.md @@ -0,0 +1,21 @@ +--- +sidebar_label: 缓存 +--- + +# 缓存(Cache) + +TDengine 采用时间驱动缓存管理策略(First-In-First-Out,FIFO),又称为写驱动的缓存管理机制。这种策略有别于读驱动的数据缓存模式(Least-Recent-Used,LRU),直接将最近写入的数据保存在系统的缓存中。当缓存达到临界值的时候,将最早的数据批量写入磁盘。一般意义上来说,对于物联网数据的使用,用户最为关心最近产生的数据,即当前状态。TDengine 充分利用了这一特性,将最近到达的(当前状态)数据保存在缓存中。 + +TDengine 通过查询函数向用户提供毫秒级的数据获取能力。直接将最近到达的数据保存在缓存中,可以更加快速地响应用户针对最近一条或一批数据的查询分析,整体上提供更快的数据库查询响应能力。从这个意义上来说,可通过设置合适的配置参数将 TDengine 作为数据缓存来使用,而不需要再部署额外的缓存系统,可有效地简化系统架构,降低运维的成本。需要注意的是,TDengine 重启以后系统的缓存将被清空,之前缓存的数据均会被批量写入磁盘,缓存的数据将不会像专门的 key-value 缓存系统再将之前缓存的数据重新加载到缓存中。 + +TDengine 分配固定大小的内存空间作为缓存空间,缓存空间可根据应用的需求和硬件资源配置。通过适当的设置缓存空间,TDengine 可以提供极高性能的写入和查询的支持。TDengine 中每个虚拟节点(virtual node)创建时分配独立的缓存池。每个虚拟节点管理自己的缓存池,不同虚拟节点间不共享缓存池。每个虚拟节点内部所属的全部表共享该虚拟节点的缓存池。 + +TDengine 将内存池按块划分进行管理,数据在内存块里是以行(row)的形式存储。一个 vnode 的内存池是在 vnode 创建时按块分配好,而且每个内存块按照先进先出的原则进行管理。在创建内存池时,块的大小由系统配置参数 cache 决定;每个 vnode 中内存块的数目则由配置参数 blocks 决定。因此对于一个 vnode,总的内存大小为:`cache * blocks`。一个 cache block 需要保证每张表能存储至少几十条以上记录,才会有效率。 + +你可以通过函数 last_row() 快速获取一张表或一张超级表的最后一条记录,这样很便于在大屏显示各设备的实时状态或采集值。例如: + +```sql +select last_row(voltage) from meters where location='Beijing.Chaoyang'; +``` + +该 SQL 语句将获取所有位于北京朝阳区的电表最后记录的电压值。 diff --git a/docs-cn/08-advance-feature/04-udf.md b/docs-cn/08-advance-feature/04-udf.md new file mode 100644 index 0000000000000000000000000000000000000000..2cc88d8963e9eb57e908ed3f062fe287301b1d30 --- /dev/null +++ b/docs-cn/08-advance-feature/04-udf.md @@ -0,0 +1,412 @@ +--- +sidebar_label: UDF +--- + +# UDF(用户定义函数) + +在有些应用场景中,应用逻辑需要的查询无法直接使用系统内置的函数来表示。利用 UDF 功能,TDengine 可以插入用户编写的处理代码并在查询中使用它们,就能够很方便地解决特殊应用场景中的使用需求。 UDF 通常以数据表中的一列数据做为输入,同时支持以嵌套子查询的结果作为输入。 + +从 2.2.0.0 版本开始,TDengine 支持通过 C/C++ 语言进行 UDF 定义。接下来结合示例讲解 UDF 的使用方法。 + +## 用 C/C++ 语言来定义 UDF + +TDengine 提供 3 个 UDF 的源代码示例,分别为: + +- [add_one.c](#add_one.c) +- [abs_max.c](#abs_max.c) +- [demo.c](#demo.c) + +### 标量函数 + +[add_one.c](https://github.com/taosdata/TDengine/blob/develop/tests/script/sh/add_one.c) 是结构最简单的 UDF 实现。其功能为:对传入的一个数据列(可能因 WHERE 子句进行了筛选)中的每一项,都输出 +1 之后的值,并且要求输入的列数据类型为 INT。 + +这一具体的处理逻辑在函数 `void add_one(char* data, short itype, short ibytes, int numOfRows, long long* ts, char* dataOutput, char* interBuf, char* tsOutput, int* numOfOutput, short otype, short obytes, SUdfInit* buf)` 中定义。这类用于实现 UDF 的基础计算逻辑的函数,我们称为 udfNormalFunc,也就是对行数据块的标量计算函数。需要注意的是,udfNormalFunc 的参数项是固定的,用于按照约束完成与引擎之间的数据交换。 + +- udfNormalFunc 中各参数的具体含义是: + - data:输入数据。 + - itype:输入数据的类型。这里采用的是短整型表示法,与各种数据类型对应的值可以参见 [column_meta 中的列类型说明](https://www.taosdata.com/cn/documentation/connector#column_meta)。例如 4 用于表示 INT 型。 + - iBytes:输入数据中每个值会占用的字节数。 + - numOfRows:输入数据的总行数。 + - ts:主键时间戳在输入中的列数据(只读)。 + - dataOutput:输出数据的缓冲区,缓冲区大小为用户指定的输出类型大小 \* numOfRows。 + - interBuf:中间计算结果的缓冲区,大小为用户在创建 UDF 时指定的 BUFSIZE 大小。通常用于计算中间结果与最终结果不一致时使用,由引擎负责分配与释放。 + - tsOutput:主键时间戳在输出时的列数据,如果非空可用于输出结果对应的时间戳。 + - numOfOutput:输出结果的个数(行数)。 + - oType:输出数据的类型。取值含义与 itype 参数一致。 + - oBytes:输出数据中每个值占用的字节数。 + - buf:用于在 UDF 与引擎间的状态控制信息传递块。 + +### 聚合函数 + +[abs_max.c](https://github.com/taosdata/TDengine/blob/develop/tests/script/sh/abs_max.c) 实现的是一个聚合函数,功能是对一组数据按绝对值取最大值。 + +其计算过程为:与所在查询语句相关的数据会被分为多个行数据块,对每个行数据块调用 udfNormalFunc(在本例的实现代码中,实际函数名是 `abs_max`)来生成每个子表的中间结果,再将子表的中间结果调用 udfMergeFunc(本例中,其实际的函数名是 `abs_max_merge`)进行聚合,生成超级表的最终聚合结果或中间结果。聚合查询最后还会通过 udfFinalizeFunc(本例中,其实际的函数名是 `abs_max_finalize`)再把超级表的中间结果处理为最终结果,最终结果只能含 0 或 1 条结果数据。 + +值得注意的是,udfNormalFunc、udfMergeFunc、udfFinalizeFunc 之间,函数名约定使用相同的前缀,此前缀即 udfNormalFunc 的实际函数名。udfMergeFunc 的函数名后缀 `_merge`、udfFinalizeFunc 的函数名后缀 `_finalize`,是 UDF 实现规则的一部分,系统会按照这些函数名后缀来调用相应功能。 + +- udfMergeFunc 用于对计算中间结果进行聚合,只有针对超级表的聚合查询才需要调用该函数。本例中 udfMergeFunc 对应的实现函数为 `void abs_max_merge(char* data, int32_t numOfRows, char* dataOutput, int32_t* numOfOutput, SUdfInit* buf)`,其中各参数的具体含义是: + + - data:udfNormalFunc 的输出数据数组,如果使用了 interBuf 那么 data 就是 interBuf 的数组。 + - numOfRows:data 中数据的行数。 + - dataOutput:输出数据的缓冲区,大小等于一条最终结果的大小。如果此时输出还不是最终结果,可以选择输出到 interBuf 中即 data 中。 + - numOfOutput:输出结果的个数(行数)。 + - buf:用于在 UDF 与引擎间的状态控制信息传递块。 + +- udfFinalizeFunc 用于对计算结果进行最终计算,通常用于有 interBuf 使用的场景。本例中 udfFinalizeFunc 对应的实现函数为 `void abs_max_finalize(char* dataOutput, char* interBuf, int* numOfOutput, SUdfInit* buf)`,其中各参数的具体含义是: + - dataOutput:输出数据的缓冲区。 + - interBuf:中间结算结果缓冲区,可作为输入。 + - numOfOutput:输出数据的个数,对聚合函数来说只能是 0 或者 1。 + - buf:用于在 UDF 与引擎间的状态控制信息传递块。 + +其他典型场景,如协方差的计算,即可通过定义聚合 UDF 的方式实现。 + +### 其他 UDF 函数 + +用户 UDF 程序除了需要实现上面几个函数外,还有两个用于初始化和释放 UDF 与引擎间的状态控制信息传递块的函数。具体来说,也即对应 udfInitFunc 和 udfDestroyFunc。其函数名命名规则同样是采取以 udfNormalFunc 的实际函数名为前缀,以 `_init` 和 `_destroy` 为后缀。系统会在初始化和资源释放时调用对应名称的函数。 + +- udfInitFunc 用于初始化状态控制信息传递块。上例中 udfInitFunc 对应的实现函数为 `int abs_max_init(SUdfInit* buf)`,其中各参数的具体含义是: + + - buf:用于在 UDF 与引擎间的状态控制信息传递块。 + +- udfDestroyFunc 用于释放状态控制信息传递块。上例中 udfDestroyFunc 对应的实现函数为 `void abs_max_destroy(SUdfInit* buf)`,其中各参数的具体含义是: + - buf:用于在 UDF 与引擎间的状态控制信息传递块。 + +目前该功能暂时没有实际意义,待后续扩展使用。 + +### UDF 实现方式的规则总结 + +根据 UDF 函数类型的不同,用户所要实现的功能函数也不同: + +- 标量函数:UDF 中需实现 udfNormalFunc。 +- 聚合函数:UDF 中需实现 udfNormalFunc、udfMergeFunc(对超级表查询)、udfFinalizeFunc。 + +需要注意的是,如果对应的函数不需要具体的功能,也需要实现一个空函数。 + +## 编译 UDF + +用户定义函数的 C 语言源代码无法直接被 TDengine 系统使用,而是需要先编译为 .so 链接库,之后才能载入 TDengine 系统。 + +例如,按照上一章节描述的规则准备好了用户定义函数的源代码 add_one.c,那么可以执行如下指令编译得到动态链接库文件: + +```bash +gcc -g -O0 -fPIC -shared add_one.c -o add_one.so +``` + +这样就准备好了动态链接库 add_one.so 文件,可以供后文创建 UDF 时使用了。为了保证可靠的系统运行,编译器 GCC 推荐使用 7.5 及以上版本。 + +## 在系统中管理和使用 UDF + +### 创建 UDF + +用户可以通过 SQL 指令在系统中加载客户端所在主机上的 UDF 函数库(不能通过 RESTful 接口或 HTTP 管理界面来进行这一过程)。一旦创建成功,则当前 TDengine 集群的所有用户都可以在 SQL 指令中使用这些函数。UDF 存储在系统的 MNode 节点上,因此即使重启 TDengine 系统,已经创建的 UDF 也仍然可用。 + +在创建 UDF 时,需要区分标量函数和聚合函数。如果创建时声明了错误的函数类别,则可能导致通过 SQL 指令调用函数时出错。此外, UDF 支持输入与输出类型不一致,用户需要保证输入数据类型与 UDF 程序匹配,UDF 输出数据类型与 OUTPUTTYPE 匹配。 + +- 创建标量函数:`CREATE FUNCTION ids(X) AS ids(Y) OUTPUTTYPE typename(Z) [ BUFSIZE B ];` + + - ids(X):标量函数未来在 SQL 指令中被调用时的函数名,必须与函数实现中 udfNormalFunc 的实际名称一致; + - ids(Y):包含 UDF 函数实现的动态链接库的库文件绝对路径(指的是库文件在当前客户端所在主机上的保存路径,通常是指向一个 .so 文件),这个路径需要用英文单引号或英文双引号括起来; + - typename(Z):此函数计算结果的数据类型,与上文中 udfNormalFunc 的 itype 参数不同,这里不是使用数字表示法,而是直接写类型名称即可; + - B:中间计算结果的缓冲区大小,单位是字节,最小 0,最大 512,如果不使用可以不设置。 + + 例如,如下语句可以把 add_one.so 创建为系统中可用的 UDF: + + ```sql + CREATE FUNCTION add_one AS "/home/taos/udf_example/add_one.so" OUTPUTTYPE INT; + ``` + +- 创建聚合函数:`CREATE AGGREGATE FUNCTION ids(X) AS ids(Y) OUTPUTTYPE typename(Z) [ BUFSIZE B ];` + + - ids(X):聚合函数未来在 SQL 指令中被调用时的函数名,必须与函数实现中 udfNormalFunc 的实际名称一致; + - ids(Y):包含 UDF 函数实现的动态链接库的库文件绝对路径(指的是库文件在当前客户端所在主机上的保存路径,通常是指向一个 .so 文件),这个路径需要用英文单引号或英文双引号括起来; + - typename(Z):此函数计算结果的数据类型,与上文中 udfNormalFunc 的 itype 参数不同,这里不是使用数字表示法,而是直接写类型名称即可; + - B:中间计算结果的缓冲区大小,单位是字节,最小 0,最大 512,如果不使用可以不设置。 + + 关于中间计算结果的使用,可以参考示例程序[demo.c](https://github.com/taosdata/TDengine/blob/develop/tests/script/sh/demo.c) + + 例如,如下语句可以把 demo.so 创建为系统中可用的 UDF: + + ```sql + CREATE AGGREGATE FUNCTION demo AS "/home/taos/udf_example/demo.so" OUTPUTTYPE DOUBLE bufsize 14; + ``` + +### 管理 UDF + +- 删除指定名称的用户定义函数:`DROP FUNCTION ids(X);` + - ids(X):此参数的含义与 CREATE 指令中的 ids(X) 参数一致,也即要删除的函数的名字,例如 `DROP FUNCTION add_one;`。 +- 显示系统中当前可用的所有 UDF:`SHOW FUNCTIONS;` + +### 调用 UDF + +在 SQL 指令中,可以直接以在系统中创建 UDF 时赋予的函数名来调用用户定义函数。例如: + +```sql +SELECT X(c) FROM table/stable; +``` + +表示对名为 c 的数据列调用名为 X 的用户定义函数。SQL 指令中用户定义函数可以配合 WHERE 等查询特性来使用。 + +## UDF 的一些使用限制 + +在当前版本下,使用 UDF 存在如下这些限制: + +1. 在创建和调用 UDF 时,服务端和客户端都只支持 Linux 操作系统; +2. UDF 不能与系统内建的 SQL 函数混合使用,暂不支持在一条 SQL 语句中使用多个不同名的 UDF ; +3. UDF 只支持以单个数据列作为输入; +4. UDF 只要创建成功,就会被持久化存储到 MNode 节点中; +5. 无法通过 RESTful 接口来创建 UDF; +6. UDF 在 SQL 中定义的函数名,必须与 .so 库文件实现中的接口函数名前缀保持一致,也即必须是 udfNormalFunc 的名称,而且不可与 TDengine 中已有的内建 SQL 函数重名。 + +## 代码附件 + +### [add_one.c](https://github.com/taosdata/TDengine/blob/develop/tests/script/sh/add_one.c) + +```c +#include +#include +#include + +typedef struct SUdfInit{ + int maybe_null; /* 1 if function can return NULL */ + int decimals; /* for real functions */ + long long length; /* For string functions */ + char *ptr; /* free pointer for function data */ + int const_item; /* 0 if result is independent of arguments */ +} SUdfInit; + +void add_one(char* data, short itype, short ibytes, int numOfRows, long long* ts, char* dataOutput, char* interBUf, char* tsOutput, + int* numOfOutput, short otype, short obytes, SUdfInit* buf) { + int i; + int r = 0; + // printf("add_one input data:%p, type:%d, rows:%d, ts:%p,%lld, dataoutput:%p, tsOutput:%p, numOfOutput:%p, buf:%p\n", data, itype, numOfRows, ts, *ts, dataOutput, tsOutput, numOfOutput, buf); + if (itype == 4) { + for(i=0;i +#include +#include +#include + +typedef struct SUdfInit{ + int maybe_null; /* 1 if function can return NULL */ + int decimals; /* for real functions */ + int64_t length; /* For string functions */ + char *ptr; /* free pointer for function data */ + int const_item; /* 0 if result is independent of arguments */ +} SUdfInit; + + +#define TSDB_DATA_INT_NULL 0x80000000L +#define TSDB_DATA_BIGINT_NULL 0x8000000000000000L + +void abs_max(char* data, short itype, short ibytes, int numOfRows, int64_t* ts, char* dataOutput, char* interBuf, char* tsOutput, + int* numOfOutput, short otype, short obytes, SUdfInit* buf) { + int i; + int64_t r = 0; + // printf("abs_max input data:%p, type:%d, rows:%d, ts:%p, %" PRId64 ", dataoutput:%p, tsOutput:%p, numOfOutput:%p, buf:%p\n", data, itype, numOfRows, ts, *ts, dataOutput, tsOutput, numOfOutput, buf); + if (itype == 5) { + r=*(int64_t *)dataOutput; + *numOfOutput=0; + + for(i=0;i r) { + r = v; + } + } + + *(int64_t *)dataOutput=r; + + // printf("abs_max out, dataoutput:%" PRId64", numOfOutput:%d\n", *(int64_t *)dataOutput, *numOfOutput); + }else { + *numOfOutput=0; + } +} + + + +void abs_max_finalize(char* dataOutput, char* interBuf, int* numOfOutput, SUdfInit* buf) { + int i; + //int64_t r = 0; + // printf("abs_max_finalize dataoutput:%p:%d, numOfOutput:%d, buf:%p\n", dataOutput, *dataOutput, *numOfOutput, buf); + // *numOfOutput=1; + // printf("abs_max finalize, dataoutput:%" PRId64", numOfOutput:%d\n", *(int64_t *)dataOutput, *numOfOutput); +} + +void abs_max_merge(char* data, int32_t numOfRows, char* dataOutput, int32_t* numOfOutput, SUdfInit* buf) { + int64_t r = 0; + + if (numOfRows > 0) { + r = *((int64_t *)data); + } + // printf("abs_max_merge numOfRows:%d, dataoutput:%p, buf:%p\n", numOfRows, dataOutput, buf); + for (int i = 1; i < numOfRows; ++i) { + // printf("abs_max_merge %d - %" PRId64"\n", i, *((int64_t *)data + i)); + if (*((int64_t*)data + i) > r) { + r= *((int64_t*)data + i); + } + } + + *(int64_t*)dataOutput=r; + if (numOfRows > 0) { + *numOfOutput=1; + } else { + *numOfOutput=0; + } + + // printf("abs_max_merge, dataoutput:%" PRId64", numOfOutput:%d\n", *(int64_t *)dataOutput, *numOfOutput); +} + + +int abs_max_init(SUdfInit* buf) { + // printf("abs_max init\n"); + return 0; +} + + +void abs_max_destroy(SUdfInit* buf) { + // printf("abs_max destroy\n"); +} +``` + +### [demo.c](https://github.com/taosdata/TDengine/blob/develop/tests/script/sh/demo.c) + +```c +#include +#include +#include + +typedef struct SUdfInit{ + int maybe_null; /* 1 if function can return NULL */ + int decimals; /* for real functions */ + long long length; /* For string functions */ + char *ptr; /* free pointer for function data */ + int const_item; /* 0 if result is independent of arguments */ +} SUdfInit; + +typedef struct SDemo{ + double sum; + int num; + short otype; +}SDemo; + +#define FLOAT_NULL 0x7FF00000 // it is an NAN +#define DOUBLE_NULL 0x7FFFFF0000000000L // it is an NAN + + +void demo(char* data, short itype, short ibytes, int numOfRows, long long* ts, char* dataOutput, char* interBuf, char* tsOutput, + int* numOfOutput, short otype, short obytes, SUdfInit* buf) { + int i; + double r = 0; + SDemo *p = (SDemo *)interBuf; + SDemo *q = (SDemo *)dataOutput; + printf("demo input data:%p, type:%d, rows:%d, ts:%p,%lld, dataoutput:%p, interBUf:%p, tsOutput:%p, numOfOutput:%p, buf:%p\n", data, itype, numOfRows, ts, *ts, dataOutput, interBuf, tsOutput, numOfOutput, buf); + + for(i=0;isum += r*r; + } + + p->otype = otype; + p->num += numOfRows; + + q->sum = p->sum; + q->num = p->num; + q->otype = p->otype; + + *numOfOutput=1; + + printf("demo out, sum:%f, num:%d, numOfOutput:%d\n", p->sum, p->num, *numOfOutput); +} + + +void demo_merge(char* data, int32_t numOfRows, char* dataOutput, int32_t* numOfOutput, SUdfInit* buf) { + int i; + SDemo *p = (SDemo *)data; + SDemo res = {0}; + printf("demo_merge input data:%p, rows:%d, dataoutput:%p, numOfOutput:%p, buf:%p\n", data, numOfRows, dataOutput, numOfOutput, buf); + + for(i=0;isum * p->sum; + res.num += p->num; + p++; + } + + p->sum = res.sum; + p->num = res.num; + + *numOfOutput=1; + + printf("demo out, sum:%f, num:%d, numOfOutput:%d\n", p->sum, p->num, *numOfOutput); +} + + + +void demo_finalize(char* dataOutput, char* interBuf, int* numOfOutput, SUdfInit* buf) { + SDemo *p = (SDemo *)interBuf; + printf("demo_finalize interbuf:%p, numOfOutput:%p, buf:%p, sum:%f, num:%d\n", interBuf, numOfOutput, buf, p->sum, p->num); + if (p->otype == 6) { + if (p->num != 30000) { + *(unsigned int *)dataOutput = FLOAT_NULL; + } else { + *(float *)dataOutput = (float)(p->sum / p->num); + } + printf("finalize values:%f\n", *(float *)dataOutput); + } else if (p->otype == 7) { + if (p->num != 30000) { + *(unsigned long long *)dataOutput = DOUBLE_NULL; + } else { + *(double *)dataOutput = (double)(p->sum / p->num); + } + printf("finalize values:%f\n", *(double *)dataOutput); + } + + *numOfOutput=1; + + printf("demo finalize, numOfOutput:%d\n", *numOfOutput); +} + + +int demo_init(SUdfInit* buf) { + printf("demo init\n"); + return 0; +} + + +void demo_destroy(SUdfInit* buf) { + printf("demo destroy\n"); +} +``` diff --git a/docs-cn/08-advance-feature/08-advance-feature.md b/docs-cn/08-advance-feature/08-advance-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..4de393203389c0df473d471c3d934aa640d06b49 --- /dev/null +++ b/docs-cn/08-advance-feature/08-advance-feature.md @@ -0,0 +1,19 @@ +# 高级功能 + +本章介绍以下TDengine中的高级功能。 + +## 连续查询 + +连续查询是一个按照预设频率自动执行的查询功能,提供按照时间窗口的聚合查询能力,是一种简化的时间驱动流式计算。 + +## 订阅 + +轻量级的数据订阅与推送服务。连续写入到TDengine中时序数据均能够推动到订阅客户端。 + +## 缓存 + +提供写驱动的缓存管理机制,将每个表最近的一条写入记录数据持续保存在缓存中,可以提供给高性能的最近状态查询。 + +## 用户定义函数 + +支持用户编码的聚合函数和标量函数,在查询中嵌入并使用用户定义函数,拓展查询的能力和功能。 diff --git a/docs-cn/08-advance-feature/_05-stream.md b/docs-cn/08-advance-feature/_05-stream.md new file mode 100644 index 0000000000000000000000000000000000000000..30a9dbdf6888c2981e076c950350bfe1c6769f15 --- /dev/null +++ b/docs-cn/08-advance-feature/_05-stream.md @@ -0,0 +1,5 @@ +--- +sidebar_label: 流计算 +--- + +# 流计算 diff --git a/docs-cn/08-advance-feature/_category_.yml b/docs-cn/08-advance-feature/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..29235a943efebff0bd732fad8654f138c2b24bc9 --- /dev/null +++ b/docs-cn/08-advance-feature/_category_.yml @@ -0,0 +1 @@ +label: 高级功能 \ No newline at end of file diff --git a/docs-cn/09-third-party/01-grafana.mdx b/docs-cn/09-third-party/01-grafana.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c34c617010daf92225f5e086355ec5d822c39d51 --- /dev/null +++ b/docs-cn/09-third-party/01-grafana.mdx @@ -0,0 +1,96 @@ +--- +sidebar_label: Grafana +--- + +# Grafana + +TDengine 能够与开源数据可视化系统 [Grafana](https://www.grafana.com/) 快速集成搭建数据监测报警系统,整个过程无需任何代码开发,TDengine 中数据表中内容可以在仪表盘(DashBoard)上进行可视化展现。关于 TDengine 插件的使用您可以在[GitHub](https://github.com/taosdata/grafanaplugin/blob/master/README.md)中了解更多。 + +## 安装 Grafana + +目前 TDengine 支持 Grafana 7.0 以上的版本。用户可以根据当前的操作系统,到 Grafana 官网下载安装包,并执行安装。下载地址如下:。 + +## 配置 Grafana + +TDengine 的 Grafana 插件托管在 GitHub,可从 下载,当前最新版本为 3.1.3。 + +推荐使用 [`grafana-cli` 命令行工具](https://grafana.com/docs/grafana/latest/administration/cli/) 进行插件安装。 + +```bash +sudo -u grafana grafana-cli \ + --pluginUrl https://github.com/taosdata/grafanaplugin/releases/download/v3.1.3/tdengine-datasource-3.1.3.zip \ + plugins install tdengine-datasource +``` + +或者下载到本地并解压到 Grafana 插件目录。 + +```bash +GF_VERSION=3.1.3 +wget https://github.com/taosdata/grafanaplugin/releases/download/v$GF_VERSION/tdengine-datasource-$GF_VERSION.zip +``` + +以 CentOS 7.2 操作系统为例,将插件包解压到 /var/lib/grafana/plugins 目录下,重新启动 grafana 即可。 + +```bash +sudo unzip tdengine-datasource-$GF_VERSION.zip -d /var/lib/grafana/plugins/ +``` + +Grafana 7.3+ / 8.x 版本会对插件进行签名检查,因此还需要在 grafana.ini 文件中增加如下行,才能正确使用插件: + +```ini +[plugins] +allow_loading_unsigned_plugins = tdengine-datasource +``` + +在 Docker 环境下,可以使用如下的环境变量设置自动安装并设置 TDengine 插件: + +```bash +GF_INSTALL_PLUGINS=https://github.com/taosdata/grafanaplugin/releases/download/v3.1.3/tdengine-datasource-3.1.3.zip;tdengine-datasource +GF_PLUGINS_ALLOW_LOADING_UNSIGNED_PLUGINS=tdengine-datasource +``` + +## 使用 Grafana + +### 配置数据源 + +用户可以直接通过 http://localhost:3000 的网址,登录 Grafana 服务器(用户名/密码:admin/admin),通过左侧 `Configuration -> Data Sources` 可以添加数据源,如下图所示: + +![img](/img/connections/add_datasource1.jpg) + +点击 `Add data source` 可进入新增数据源页面,在查询框中输入 TDengine 可选择添加,如下图所示: + +![img](/img/connections/add_datasource2.jpg) + +进入数据源配置页面,按照默认提示修改相应配置即可: + +![img](/img/connections/add_datasource3.jpg) + +- Host: TDengine 集群的中任意一台服务器的 IP 地址与 TDengine RESTful 接口的端口号(6041),默认 http://localhost:6041。注意:从 2.4 版本开始 RESTful 服务默认使用独立组件 taosAdapter 提供,请参考相关文档配置部署。 +- User:TDengine 用户名。 +- Password:TDengine 用户密码。 + +点击 `Save & Test` 进行测试,成功会有如下提示: + +![img](/img/connections/add_datasource4.jpg) + +### 创建 Dashboard + +回到主界面创建 Dashboard,点击 Add Query 进入面板查询页面: + +![img](/img/connections/create_dashboard1.jpg) + +如上图所示,在 Query 中选中 `TDengine` 数据源,在下方查询框可输入相应 sql 进行查询,具体说明如下: + +- INPUT SQL:输入要查询的语句(该 SQL 语句的结果集应为两列多行),例如:`select avg(mem_system) from log.dn where ts >= $from and ts < $to interval($interval)` ,其中,from、to 和 interval 为 TDengine 插件的内置变量,表示从 Grafana 插件面板获取的查询范围和时间间隔。除了内置变量外,`也支持可以使用自定义模板变量`。 +- ALIAS BY:可设置当前查询别名。 +- GENERATE SQL: 点击该按钮会自动替换相应变量,并生成最终执行的语句。 + +按照默认提示查询当前 TDengine 部署所在服务器指定间隔系统内存平均使用量如下: + +![img](/img/connections/create_dashboard2.jpg) + +> 关于如何使用 Grafana 创建相应的监测界面以及更多有关使用 Grafana 的信息,请参考 Grafana 官方的[文档](https://grafana.com/docs/)。 + +### 导入 Dashboard + +在 2.3.3.0 及以上版本,您可以导入 TDinsight Dashboard (Grafana Dashboard ID: [15167](https://grafana.com/grafana/dashboards/15167)) 作为 TDengine 集群的监控可视化工具。安装和使用说明请见 [TDinsight 用户手册](https://www.taosdata.com/cn/documentation/tools/insight)。 diff --git a/docs-cn/09-third-party/02-prometheus.md b/docs-cn/09-third-party/02-prometheus.md new file mode 100644 index 0000000000000000000000000000000000000000..605fe817fe2dde219dea2448f8c8e45fa8a50183 --- /dev/null +++ b/docs-cn/09-third-party/02-prometheus.md @@ -0,0 +1,34 @@ +--- +sidebar_label: Prometheus +--- + +# Prometheus 写入 + +remote_read 和 remote_write 是 Prometheus 数据读写分离的集群方案。 +只需要将 remote_read 和 remote_write url 指向 taosAdapter 对应的 url 同时设置 Basic 验证即可使用。 + +- remote_read url : `http://host_to_taosAdapter:port(default 6041)/prometheus/v1/remote_read/:db` +- remote_write url : `http://host_to_taosAdapter:port(default 6041)/prometheus/v1/remote_write/:db` + +Basic 验证: + +- username: TDengine 连接用户名 +- password: TDengine 连接密码 + +示例 prometheus.yml 如下: + +```yaml +remote_write: + - url: "http://localhost:6041/prometheus/v1/remote_write/prometheus_data" + basic_auth: + username: root + password: taosdata + +remote_read: + - url: "http://localhost:6041/prometheus/v1/remote_read/prometheus_data" + basic_auth: + username: root + password: taosdata + remote_timeout: 10s + read_recent: true +``` diff --git a/docs-cn/09-third-party/03-telegraf.md b/docs-cn/09-third-party/03-telegraf.md new file mode 100644 index 0000000000000000000000000000000000000000..191193b426995fb7e3036605f52ddef963da0d55 --- /dev/null +++ b/docs-cn/09-third-party/03-telegraf.md @@ -0,0 +1,32 @@ +--- +sidebar_label: Telegraf +--- + +# Telegraf 写入 + +安装 Telegraf 请参考[官方文档](https://portal.influxdata.com/downloads/)。 + +TDengine 新版本(2.3.0.0+)包含一个 taosAdapter 独立程序,负责接收包括 Telegraf 的多种应用的数据写入。 + +配置方法,在 /etc/telegraf/telegraf.conf 增加如下文字,其中 database name 请填写希望在 TDengine 保存 Telegraf 数据的数据库名,TDengine server/cluster host、username 和 password 填写 TDengine 实际值: + +``` +[[outputs.http]] + url = "http://:6041/influxdb/v1/write?db=" + method = "POST" + timeout = "5s" + username = "" + password = "" + data_format = "influx" + influx_max_line_bytes = 250 +``` + +然后重启 telegraf: + +``` +sudo systemctl start telegraf +``` + +即可在 TDengine 中查询 metrics 数据库中 Telegraf 写入的数据。 + +taosAdapter 相关配置参数请参考 taosadapter --help 命令输出以及相关文档。 diff --git a/docs-cn/09-third-party/05-collectd.md b/docs-cn/09-third-party/05-collectd.md new file mode 100644 index 0000000000000000000000000000000000000000..c94dd8cb977c0a01d67839467b04e414e33eaf3d --- /dev/null +++ b/docs-cn/09-third-party/05-collectd.md @@ -0,0 +1,26 @@ +--- +sidebar_label: collectd +--- + +# collectd 写入 + +安装 collectd,请参考[官方文档](https://collectd.org/download.shtml)。 + +TDengine 新版本(2.3.0.0+)包含一个 taosAdapter 独立程序,负责接收包括 collectd 的多种应用的数据写入。 + +在 /etc/collectd/collectd.conf 文件中增加如下内容,其中 host 和 port 请填写 TDengine 和 taosAdapter 配置的实际值: + +``` +LoadPlugin network + + Server "" "" + +``` + +重启 collectd + +``` +sudo systemctl start collectd +``` + +taosAdapter 相关配置参数请参考 taosadapter --help 命令输出以及相关文档。 diff --git a/docs-cn/09-third-party/06-statsd.md b/docs-cn/09-third-party/06-statsd.md new file mode 100644 index 0000000000000000000000000000000000000000..b1bf4b06e4a52258df0a2aa3ed5a0a4c7872abb5 --- /dev/null +++ b/docs-cn/09-third-party/06-statsd.md @@ -0,0 +1,31 @@ +--- +sidebar_label: StatsD +--- + +# StatsD 直接写入 + +安装 StatsD +请参考[官方文档](https://github.com/statsd/statsd)。 + +TDengine 新版本(2.3.0.0+)包含一个 taosAdapter 独立程序,负责接收包括 StatsD 的多种应用的数据写入。 + +在 config.js 文件中增加如下内容后启动 StatsD,其中 host 和 port 请填写 TDengine 和 taosAdapter 配置的实际值: + +``` +backends 部分添加 "./backends/repeater" +repeater 部分添加 { host:'', port: } +``` + +示例配置文件: + +``` +{ +port: 8125 +, backends: ["./backends/repeater"] +, repeater: [{ host: '127.0.0.1', port: 6044}] +} +``` + +taosAdapter 相关配置参数请参考 taosadapter --help 命令输出以及相关文档。 + +icinga2 可以收集监控和性能数据并写入 OpenTSDB,taosAdapter 可以支持接收 icinga2 的数据并写入到 TDengine 中。 diff --git a/docs-cn/09-third-party/07-icinga2.md b/docs-cn/09-third-party/07-icinga2.md new file mode 100644 index 0000000000000000000000000000000000000000..d83e4fcd309ba2ce54bb0a8a8754bdd2ca19968d --- /dev/null +++ b/docs-cn/09-third-party/07-icinga2.md @@ -0,0 +1,18 @@ +--- +sidebar_label: icinga2 +--- + +# icinga2 写入 + +- 参考链接 `https://icinga.com/docs/icinga-2/latest/doc/14-features/#opentsdb-writer` 使能 opentsdb-writer +- 使能 taosAdapter 配置项 opentsdb_telnet.enable +- 修改配置文件 /etc/icinga2/features-enabled/opentsdb.conf + +``` +object OpenTsdbWriter "opentsdb" { + host = "host to taosAdapter" + port = 6048 +} +``` + +taosAdapter 相关配置参数请参考 taosadapter --help 命令输出以及相关文档。 \ No newline at end of file diff --git a/docs-cn/09-third-party/08-tcollector.md b/docs-cn/09-third-party/08-tcollector.md new file mode 100644 index 0000000000000000000000000000000000000000..70ae0762ee3e1d39876569d4169b26afe1038a34 --- /dev/null +++ b/docs-cn/09-third-party/08-tcollector.md @@ -0,0 +1,12 @@ +--- +sidebar_label: TCollector +--- + +# TCollector 写入 + +TCollector 是一个在客户侧收集本地收集器并发送数据到 OpenTSDB 的进程,taosAdaapter 可以支持接收 TCollector 的数据并写入到 TDengine 中。 + +使能 taosAdapter 配置项 opentsdb_telnet.enable +修改 TCollector 配置文件,修改 OpenTSDB 宿主机地址为 taosAdapter 被部署的地址,并修改端口号为 taosAdapter 使用的端口(默认 6049)。 + +taosAdapter 相关配置参数请参考 taosadapter --help 命令输出以及相关文档。 diff --git a/docs-cn/09-third-party/09-emq-broder.md b/docs-cn/09-third-party/09-emq-broder.md new file mode 100644 index 0000000000000000000000000000000000000000..0d2bd4d2f996247119bca736d295b7faf5d55e23 --- /dev/null +++ b/docs-cn/09-third-party/09-emq-broder.md @@ -0,0 +1,7 @@ +--- +sidebar_label: EMQ Broker +--- + +# EMQ Broker 写入 + +MQTT 是流行的物联网数据传输协议,[EMQ](https://github.com/emqx/emqx)是一开源的 MQTT Broker 软件,无需任何代码,只需要在 EMQ Dashboard 里使用“规则”做简单配置,即可将 MQTT 的数据直接写入 TDengine。EMQ X 支持通过 发送到 Web 服务的方式保存数据到 TDEngine,也在企业版上提供原生的 TDEngine 驱动实现直接保存。详细使用方法请参考 [EMQ 官方文档](https://docs.emqx.io/broker/latest/cn/rule/rule-example.html#%E4%BF%9D%E5%AD%98%E6%95%B0%E6%8D%AE%E5%88%B0-tdengine)。 diff --git a/docs-cn/09-third-party/10-hive-mq-broker.md b/docs-cn/09-third-party/10-hive-mq-broker.md new file mode 100644 index 0000000000000000000000000000000000000000..81657da1009c286ece906116abf33428868c1971 --- /dev/null +++ b/docs-cn/09-third-party/10-hive-mq-broker.md @@ -0,0 +1,7 @@ +--- +sidebar_label: HiveMQ Broker +--- + +# HiveMQ Broker 写入 + +[HiveMQ](https://www.hivemq.com/) 是一个提供免费个人版和企业版的 MQTT 代理,主要用于企业和新兴的机器到机器 M2M 通讯和内部传输,满足可伸缩性、易管理和安全特性。HiveMQ 提供了开源的插件开发包。可以通过 HiveMQ extension - TDengine 保存数据到 TDengine。详细使用方法请参考 [HiveMQ extension - TDengine 说明文档](https://github.com/huskar-t/hivemq-tdengine-extension/blob/b62a26ecc164a310104df57691691b237e091c89/README.md)。 diff --git a/docs-cn/09-third-party/_category_.yml b/docs-cn/09-third-party/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..cf9d95e5f9e0941f64159ffa17619839fdafbf05 --- /dev/null +++ b/docs-cn/09-third-party/_category_.yml @@ -0,0 +1,6 @@ +label: 第三方工具 +link: + type: generated-index + slug: /third-party/ + description: TDengine 通过对标准 SQL 命令、常用数据库连接器标准(例如 JDBC)、ORM 以及其他流行时序数据库写入协议(例如 InfluxDB Line Protocol、OpenTSDB JSON、OpenTSDB Telnet 等)的支持可以使 TDengine 非常容易和第三方工具共同使用。 + diff --git a/docs-cn/10-cluster/01-deploy.md b/docs-cn/10-cluster/01-deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..338d672d50504d3bf36825f9130ed1a7bfcf2041 --- /dev/null +++ b/docs-cn/10-cluster/01-deploy.md @@ -0,0 +1,136 @@ +# 集群部署 + +## 准备工作 + +### 第零步 + +规划集群所有物理节点的 FQDN,将规划好的 FQDN 分别添加到每个物理节点的/etc/hostname;修改每个物理节点的/etc/hosts,将所有集群物理节点的 IP 与 FQDN 的对应添加好。【如部署了 DNS,请联系网络管理员在 DNS 上做好相关配置】 + +### 第一步 + +如果搭建集群的物理节点中,存有之前的测试数据、装过 1.X 的版本,或者装过其他版本的 TDengine,请先将其删除,并清空所有数据(如果需要保留原有数据,请联系涛思交付团队进行旧版本升级、数据迁移),具体步骤请参考博客《TDengine 多种安装包的安装和卸载》。 + +:::note +因为 FQDN 的信息会写进文件,如果之前没有配置或者更改 FQDN,且启动了 TDengine。请一定在确保数据无用或者备份的前提下,清理一下之前的数据(rm -rf /var/lib/taos/\*); +::: + +:::note +客户端也需要配置,确保它可以正确解析每个节点的 FQDN 配置,不管是通过 DNS 服务,还是修改 hosts 文件。 +::: + +### 第二步 + +建议关闭所有物理节点的防火墙,至少保证端口:6030 - 6042 的 TCP 和 UDP 端口都是开放的。强烈建议先关闭防火墙,集群搭建完毕之后,再来配置端口; + +### 第三步 + +在所有物理节点安装 TDengine,且版本必须是一致的,但不要启动 taosd。安装时,提示输入是否要加入一个已经存在的 TDengine 集群时,第一个物理节点直接回车创建新集群,后续物理节点则输入该集群任何一个在线的物理节点的 FQDN:端口号(默认 6030); + +### 第四步 + +检查所有数据节点,以及应用程序所在物理节点的网络设置: + +每个物理节点上执行命令 `hostname -f`,查看和确认所有节点的 hostname 是不相同的(应用驱动所在节点无需做此项检查); + +每个物理节点上执行 ping host,其中 host 是其他物理节点的 hostname,看能否 ping 通其它物理节点;如果不能 ping 通,需要检查网络设置,或/etc/hosts 文件(Windows 系统默认路径为 C:\Windows\system32\drivers\etc\hosts),或 DNS 的配置。如果无法 ping 通,是无法组成集群的; + +从应用运行的物理节点,ping taosd 运行的数据节点,如果无法 ping 通,应用是无法连接 taosd 的,请检查应用所在物理节点的 DNS 设置或 hosts 文件; + +每个数据节点的 End Point 就是输出的 hostname 外加端口号,比如 h1.taosdata.com:6030。 + +### 第五步 + +修改 TDengine 的配置文件(所有节点的文件/etc/taos/taos.cfg 都需要修改)。假设准备启动的第一个数据节点 End Point 为 h1.taosdata.com:6030,其与集群配置相关参数如下: + +```c +// firstEp 是每个数据节点首次启动后连接的第一个数据节点 +firstEp h1.taosdata.com:6030 + +// 必须配置为本数据节点的FQDN,如果本机只有一个hostname, 可注释掉本项 +fqdn h1.taosdata.com + +// 配置本数据节点的端口号,缺省是6030 +serverPort 6030 + +// 副本数为偶数的时候,需要配置,请参考《Arbitrator的使用》的部分 +arbitrator ha.taosdata.com:6042 +``` + +一定要修改的参数是 firstEp 和 fqdn。在每个数据节点,firstEp 需全部配置成一样,但 fqdn 一定要配置成其所在数据节点的值。其他参数可不做任何修改,除非你很清楚为什么要修改。 + +加入到集群中的数据节点 dnode,涉及集群相关的下表 9 项参数必须完全相同,否则不能成功加入到集群中。 + +| **#** | **配置参数名称** | **含义** | +| ----- | ------------------ | ------------------------------------------- | +| 1 | numOfMnodes | 系统中管理节点个数 | +| 2 | mnodeEqualVnodeNum | 一个 mnode 等同于 vnode 消耗的个数 | +| 3 | offlineThreshold | dnode 离线阈值,超过该时间将导致 Dnode 离线 | +| 4 | statusInterval | dnode 向 mnode 报告状态时长 | +| 5 | arbitrator | 系统中裁决器的 End Point | +| 6 | timezone | 时区 | +| 7 | balance | 是否启动负载均衡 | +| 8 | maxTablesPerVnode | 每个 vnode 中能够创建的最大表个数 | +| 9 | maxVgroupsPerDb | 每个 DB 中能够使用的最大 vgroup 个数 | + +:::note +在 2.0.19.0 及更早的版本中,除以上 9 项参数外,dnode 加入集群时,还会要求 locale 和 charset 参数的取值也一致。 + +::: + +## 启动集群 + +### 启动第一个数据节点 + +按照《立即开始》里的步骤,启动第一个数据节点,例如 h1.taosdata.com,然后执行 taos, 启动 taos shell,从 shell 里执行命令"SHOW dnodes;",如下所示: + +``` +Welcome to the TDengine shell from Linux, Client Version:2.0.0.0 + + +Copyright (c) 2017 by TAOS Data, Inc. All rights reserved. + +taos> show dnodes; + id | end_point | vnodes | cores | status | role | create_time | +===================================================================================== + 1 | h1.taos.com:6030 | 0 | 2 | ready | any | 2020-07-31 03:49:29.202 | +Query OK, 1 row(s) in set (0.006385s) + +taos> +``` + +上述命令里,可以看到这个刚启动的这个数据节点的 End Point 是:h1.taos.com:6030,就是这个新集群的 firstEp。 + +### 启动后续数据节点 + +将后续的数据节点添加到现有集群,具体有以下几步: + +按照《立即开始》一章的方法在每个物理节点启动 taosd;(注意:每个物理节点都需要在 taos.cfg 文件中将 firstEp 参数配置为新集群首个节点的 End Point——在本例中是 h1.taos.com:6030) + +在第一个数据节点,使用 CLI 程序 taos,登录进 TDengine 系统,执行命令: + +```sql +CREATE DNODE "h2.taos.com:6030"; +``` + +将新数据节点的 End Point (准备工作中第四步获知的) 添加进集群的 EP 列表。"fqdn:port"需要用双引号引起来,否则出错。请注意将示例的“h2.taos.com:6030" 替换为这个新数据节点的 End Point。 + +然后执行命令 + +```sql +SHOW DNODES; +``` + +查看新节点是否被成功加入。如果该被加入的数据节点处于离线状态,请做两个检查: + +查看该数据节点的 taosd 是否正常工作,如果没有正常运行,需要先检查为什么 +查看该数据节点 taosd 日志文件 taosdlog.0 里前面几行日志(一般在/var/log/taos 目录),看日志里输出的该数据节点 fqdn 以及端口号是否为刚添加的 End Point。如果不一致,需要将正确的 End Point 添加进去。 +按照上述步骤可以源源不断的将新的数据节点加入到集群。 + +:::tip + +任何已经加入集群在线的数据节点,都可以作为后续待加入节点的 firstEp。 +firstEp 这个参数仅仅在该数据节点首次加入集群时有作用,加入集群后,该数据节点会保存最新的 mnode 的 End Point 列表,不再依赖这个参数。 +接下来,配置文件中的 firstEp 参数就主要在客户端连接的时候使用了,例如 taos shell 如果不加参数,会默认连接由 firstEp 指定的节点。 +两个没有配置 firstEp 参数的数据节点 dnode 启动后,会独立运行起来。这个时候,无法将其中一个数据节点加入到另外一个数据节点,形成集群。无法将两个独立的集群合并成为新的集群。 + +::: diff --git a/docs-cn/10-cluster/02-cluster-mgmt.md b/docs-cn/10-cluster/02-cluster-mgmt.md new file mode 100644 index 0000000000000000000000000000000000000000..625dd4a7744fbf380b139c2c3e36ff553fd044cf --- /dev/null +++ b/docs-cn/10-cluster/02-cluster-mgmt.md @@ -0,0 +1,77 @@ +# 集群管理 + +## 数据节点管理 + +上面已经介绍如何从零开始搭建集群。集群组建完后,还可以随时添加新的数据节点进行扩容,或删除数据节点,并检查集群当前状态。 + +提示: + +以下所有执行命令的操作需要先登陆进 TDengine 系统,必要时请使用 root 权限。 +添加数据节点 +执行 CLI 程序 taos,执行: + +```sql +CREATE DNODE "fqdn:port"; +``` + +将新数据节点的 End Point 添加进集群的 EP 列表。"fqdn:port"需要用双引号引起来,否则出错。一个数据节点对外服务的 fqdn 和 port 可以通过配置文件 taos.cfg 进行配置,缺省是自动获取。【强烈不建议用自动获取方式来配置 FQDN,可能导致生成的数据节点的 End Point 不是所期望的】 + +## 删除数据节点 + +执行 CLI 程序 taos,执行: + +```sql +DROP DNODE "fqdn:port | dnodeID"; +``` + +通过"fqdn:port"或"dnodeID"来指定一个具体的节点都是可以的。其中 fqdn 是被删除的节点的 FQDN,port 是其对外服务器的端口号;dnodeID 可以通过 SHOW DNODES 获得。 + +:::warning + +一个数据节点一旦被 drop 之后,不能重新加入集群。需要将此节点重新部署(清空数据文件夹)。集群在完成 drop dnode 操作之前,会将该 dnode 的数据迁移走。 +请注意 drop dnode 和 停止 taosd 进程是两个不同的概念,不要混淆:因为删除 dnode 之前要执行迁移数据的操作,因此被删除的 dnode 必须保持在线状态。待删除操作结束之后,才能停止 taosd 进程。 +一个数据节点被 drop 之后,其他节点都会感知到这个 dnodeID 的删除操作,任何集群中的节点都不会再接收此 dnodeID 的请求。 +dnodeID 是集群自动分配的,不得人工指定。它在生成时是递增的,不会重复。 + +::: + +## 手动迁移数据节点 + +手动将某个 vnode 迁移到指定的 dnode。 + +执行 CLI 程序 taos,执行: + +```sql +ALTER DNODE BALANCE "VNODE:-DNODE:"; +``` + +其中:source-dnodeId 是源 dnodeId,也就是待迁移的 vnode 所在的 dnodeID;vgId 可以通过 SHOW VGROUPS 获得,列表的第一列;dest-dnodeId 是目标 dnodeId。 + +:::warning + +只有在集群的自动负载均衡选项关闭时(balance 设置为 0),才允许手动迁移。 +只有处于正常工作状态的 vnode 才能被迁移:master/slave,当处于 offline/unsynced/syncing 状态时,是不能迁移的。 +迁移前,务必核实目标 dnode 的资源足够:CPU、内存、硬盘。 + +::: + +## 查看数据节点 + +执行 CLI 程序 taos,执行: + +```sql +SHOW DNODES; +``` + +它将列出集群中所有的 dnode,每个 dnode 的 ID,end_point(fqdn:port),状态(ready, offline 等),vnode 数目,还未使用的 vnode 数目等信息。在添加或删除一个数据节点后,可以使用该命令查看。 + +## 查看虚拟节点组 + +为充分利用多核技术,并提供 scalability,数据需要分片处理。因此 TDengine 会将一个 DB 的数据切分成多份,存放在多个 vnode 里。这些 vnode 可能分布在多个数据节点 dnode 里,这样就实现了水平扩展。一个 vnode 仅仅属于一个 DB,但一个 DB 可以有多个 vnode。vnode 的是 mnode 根据当前系统资源的情况,自动进行分配的,无需任何人工干预。 + +执行 CLI 程序 taos,执行: + +```sql +USE SOME_DATABASE; +SHOW VGROUPS; +``` diff --git a/docs-cn/10-cluster/03-ha-and-lb.md b/docs-cn/10-cluster/03-ha-and-lb.md new file mode 100644 index 0000000000000000000000000000000000000000..0ac526a8754902e077dd91d7da6ce84f952a0860 --- /dev/null +++ b/docs-cn/10-cluster/03-ha-and-lb.md @@ -0,0 +1,85 @@ +# 高可用与负载均衡 + +## vnode 的高可用性 + +TDengine 通过多副本的机制来提供系统的高可用性,包括 vnode 和 mnode 的高可用性。 + +vnode 的副本数是与 DB 关联的,一个集群里可以有多个 DB,根据运营的需求,每个 DB 可以配置不同的副本数。创建数据库时,通过参数 replica 指定副本数(缺省为 1)。如果副本数为 1,系统的可靠性无法保证,只要数据所在的节点宕机,就将无法提供服务。集群的节点数必须大于等于副本数,否则创建表时将返回错误"more dnodes are needed"。比如下面的命令将创建副本数为 3 的数据库 demo: + +```sql +CREATE DATABASE demo replica 3; +``` + +一个 DB 里的数据会被切片分到多个 vnode group,vnode group 里的 vnode 数目就是 DB 的副本数,同一个 vnode group 里各 vnode 的数据是完全一致的。为保证高可用性,vnode group 里的 vnode 一定要分布在不同的数据节点 dnode 里(实际部署时,需要在不同的物理机上),只要一个 vgroup 里超过半数的 vnode 处于工作状态,这个 vgroup 就能正常的对外服务。 + +一个数据节点 dnode 里可能有多个 DB 的数据,因此一个 dnode 离线时,可能会影响到多个 DB。如果一个 vnode group 里的一半或一半以上的 vnode 不工作,那么该 vnode group 就无法对外服务,无法插入或读取数据,这样会影响到它所属的 DB 的一部分表的读写操作。 + +因为 vnode 的引入,无法简单地给出结论:“集群中过半数据节点 dnode 工作,集群就应该工作”。但是对于简单的情形,很好下结论。比如副本数为 3,只有三个 dnode,那如果仅有一个节点不工作,整个集群还是可以正常工作的,但如果有两个数据节点不工作,那整个集群就无法正常工作了。 + +## Mnode 的高可用性 + +TDengine 集群是由 mnode (taosd 的一个模块,管理节点) 负责管理的,为保证 mnode 的高可用,可以配置多个 mnode 副本,副本数由系统配置参数 numOfMnodes 决定,有效范围为 1-3。为保证元数据的强一致性,mnode 副本之间是通过同步的方式进行数据复制的。 + +一个集群有多个数据节点 dnode,但一个 dnode 至多运行一个 mnode 实例。多个 dnode 情况下,哪个 dnode 可以作为 mnode 呢?这是完全由系统根据整个系统资源情况,自动指定的。用户可通过 CLI 程序 taos,在 TDengine 的 console 里,执行如下命令: + +```sql +SHOW MNODES; +``` + +来查看 mnode 列表,该列表将列出 mnode 所处的 dnode 的 End Point 和角色(master, slave, unsynced 或 offline)。当集群中第一个数据节点启动时,该数据节点一定会运行一个 mnode 实例,否则该数据节点 dnode 无法正常工作,因为一个系统是必须有至少一个 mnode 的。如果 numOfMnodes 配置为 2,启动第二个 dnode 时,该 dnode 也将运行一个 mnode 实例。 + +为保证 mnode 服务的高可用性,numOfMnodes 必须设置为 2 或更大。因为 mnode 保存的元数据必须是强一致的,如果 numOfMnodes 大于 2,复制参数 quorum 自动设为 2,也就是说,至少要保证有两个副本写入数据成功,才通知客户端应用写入成功。 + +:::note +一个 TDengine 高可用系统,无论是 vnode 还是 mnode, 都必须配置多个副本。 + +::: + +## 负载均衡 + +有三种情况,将触发负载均衡,而且都无需人工干预。 + +当一个新数据节点添加进集群时,系统将自动触发负载均衡,一些节点上的数据将被自动转移到新数据节点上,无需任何人工干预。 +当一个数据节点从集群中移除时,系统将自动把该数据节点上的数据转移到其他数据节点,无需任何人工干预。 +如果一个数据节点过热(数据量过大),系统将自动进行负载均衡,将该数据节点的一些 vnode 自动挪到其他节点。 +当上述三种情况发生时,系统将启动各个数据节点的负载计算,从而决定如何挪动。 + +:::tip +负载均衡由参数 balance 控制,它决定是否启动自动负载均衡, 0 表示禁用, 1 表示启用自动负载均衡。\*\* + +::: + +## 数据节点离线处理 + +如果一个数据节点离线,TDengine 集群将自动检测到。有如下两种情况: + +该数据节点离线超过一定时间(taos.cfg 里配置参数 offlineThreshold 控制时长),系统将自动把该数据节点删除,产生系统报警信息,触发负载均衡流程。如果该被删除的数据节点重新上线时,它将无法加入集群,需要系统管理员重新将其添加进集群才会开始工作。 + +离线后,在 offlineThreshold 的时长内重新上线,系统将自动启动数据恢复流程,等数据完全恢复后,该节点将开始正常工作。 + +:::note +如果一个虚拟节点组(包括 mnode 组)里所归属的每个数据节点都处于离线或 unsynced 状态,必须等该虚拟节点组里的所有数据节点都上线、都能交换状态信息后,才能选出 Master,该虚拟节点组才能对外提供服务。比如整个集群有 3 个数据节点,副本数为 3,如果 3 个数据节点都宕机,然后 2 个数据节点重启,是无法工作的,只有等 3 个数据节点都重启成功,才能对外服务。 + +::: + +## Arbitrator 的使用 + +如果副本数为偶数,当一个 vnode group 里一半或超过一半的 vnode 不工作时,是无法从中选出 master 的。同理,一半或超过一半的 mnode 不工作时,是无法选出 mnode 的 master 的,因为存在“split brain”问题。 + +为解决这个问题,TDengine 引入了 Arbitrator 的概念。Arbitrator 模拟一个 vnode 或 mnode 在工作,但只简单的负责网络连接,不处理任何数据插入或访问。只要包含 Arbitrator 在内,超过半数的 vnode 或 mnode 工作,那么该 vnode group 或 mnode 组就可以正常的提供数据插入或查询服务。比如对于副本数为 2 的情形,如果一个节点 A 离线,但另外一个节点 B 正常,而且能连接到 Arbitrator,那么节点 B 就能正常工作。 + +总之,在目前版本下,TDengine 建议在双副本环境要配置 Arbitrator,以提升系统的可用性。 + +Arbitrator 的执行程序名为 tarbitrator。该程序对系统资源几乎没有要求,只需要保证有网络连接,找任何一台 Linux 服务器运行它即可。以下简要描述安装配置的步骤: + +请点击 安装包下载,在 TDengine Arbitrator Linux 一节中,选择合适的版本下载并安装。 +该应用的命令行参数 -p 可以指定其对外服务的端口号,缺省是 6042。 + +修改每个 taosd 实例的配置文件,在 taos.cfg 里将参数 arbitrator 设置为 tarbitrator 程序所对应的 End Point。(如果该参数配置了,当副本数为偶数时,系统将自动连接配置的 Arbitrator。如果副本数为奇数,即使配置了 Arbitrator,系统也不会去建立连接。) + +在配置文件中配置了的 Arbitrator,会出现在 SHOW DNODES; 指令的返回结果中,对应的 role 列的值会是“arb”。 +查看集群 Arbitrator 的状态【2.0.14.0 以后支持】 + +```sql +SHOW DNODES; +``` diff --git a/docs-cn/10-cluster/_category_.yml b/docs-cn/10-cluster/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..df953cb6dd297c91f1e6d1e2d30690afab293982 --- /dev/null +++ b/docs-cn/10-cluster/_category_.yml @@ -0,0 +1,12 @@ +label: 集群管理 +link: + type: generated-index + slug: /cluster/ + description: "TDengine支持以集群方式部署,以提升系统的处理能力和高可用性。TDengine集群支持任意数据的多副本从而提升高可用性,并自动实现负载均衡。同时TDengine集群具有很好的横向扩展能力以处理更多的数据采集点和更大的数据量。" + keywords: + [ + 集群, + 高可用, + 负载均衡, + 横向扩展 + ] diff --git a/docs-cn/11-operation/01-pkg-install.md b/docs-cn/11-operation/01-pkg-install.md new file mode 100644 index 0000000000000000000000000000000000000000..257e9bb351bd18071dad7a7f149937c74e45c0ed --- /dev/null +++ b/docs-cn/11-operation/01-pkg-install.md @@ -0,0 +1,245 @@ +# 安装、卸载、启动和停止 + +TDengine 开源版本提供 deb 和 rpm 格式安装包,用户可以根据自己的运行环境选择合适的安装包。其中 deb 支持 Debian/Ubuntu 等系统,rpm 支持 CentOS/RHEL/SUSE 等系统。同时我们也为企业用户提供 tar.gz 格式安装包。 + +## deb 包的安装和卸载 + +### 安装 deb + +1、从官网下载获得 deb 安装包,比如 TDengine-server-2.0.0.0-Linux-x64.deb; +2、进入到 TDengine-server-2.0.0.0-Linux-x64.deb 安装包所在目录,执行如下的安装命令: + +``` +$ sudo dpkg -i TDengine-server-2.4.0.7-Linux-x64.deb +(Reading database ... 137504 files and directories currently installed.) +Preparing to unpack TDengine-server-2.4.0.7-Linux-x64.deb ... +TDengine is removed successfully! +Unpacking tdengine (2.4.0.7) over (2.4.0.7) ... +Setting up tdengine (2.4.0.7) ... +Start to install TDengine... + +System hostname is: shuduo-1804 + +Enter FQDN:port (like h1.taosdata.com:6030) of an existing TDengine cluster node to join +OR leave it blank to build one: + +Enter your email address for priority support or enter empty to skip: +Created symlink /etc/systemd/system/multi-user.target.wants/taosd.service → /etc/systemd/system/taosd.service. + +To configure TDengine : edit /etc/taos/taos.cfg +To start TDengine : sudo systemctl start taosd +To access TDengine : taos -h shuduo-1804 to login into TDengine server + + +TDengine is installed successfully! +``` + +注:当安装第一个节点时,出现 Enter FQDN:提示的时候,不需要输入任何内容。只有当安装第二个或以后更多的节点时,才需要输入已有集群中任何一个可用节点的 FQDN,支持该新节点加入集群。当然也可以不输入,而是在新节点启动前,配置到新节点的配置文件中。 + +后续两种安装包也是同样的操作。 + +### 卸载 deb + +卸载命令如下: + +``` +$ sudo dpkg -r tdengine +(Reading database ... 137504 files and directories currently installed.) +Removing tdengine (2.4.0.7) ... +TDengine is removed successfully! +``` + +## rpm 包的安装和卸载 + +### 安装 rpm + +1、从官网下载获得 rpm 安装包,比如 TDengine-server-2.0.0.0-Linux-x64.rpm; +2、进入到 TDengine-server-2.0.0.0-Linux-x64.rpm 安装包所在目录,执行如下的安装命令: + +``` +$ sudo rpm -ivh TDengine-server-2.4.0.7-Linux-x64.rpm +Preparing... ################################# [100%] +Updating / installing... + 1:tdengine-2.4.0.7-3 ################################# [100%] +Start to install TDengine... + +System hostname is: centos7 + +Enter FQDN:port (like h1.taosdata.com:6030) of an existing TDengine cluster node to join +OR leave it blank to build one: + +Enter your email address for priority support or enter empty to skip: + +Created symlink from /etc/systemd/system/multi-user.target.wants/taosd.service to /etc/systemd/system/taosd.service. + +To configure TDengine : edit /etc/taos/taos.cfg +To start TDengine : sudo systemctl start taosd +To access TDengine : taos -h centos7 to login into TDengine server + + +TDengine is installed successfully! +``` + +### 卸载 rpm + +卸载命令如下: + +``` +$ sudo rpm -e tdengine +TDengine is removed successfully! +``` + +## tar.gz 格式安装包的安装和卸载 + +### 安装 tar.gz 安装包 + +1、从官网下载获得 tar.gz 安装包,比如 TDengine-server-2.4.0.7-Linux-x64.tar.gz; +2、进入到 TDengine-server-2.4.0.7-Linux-x64.tar.gz 安装包所在目录,先解压文件后,进入子目录,执行其中的 install.sh 安装脚本: + +``` +$ tar xvzf TDengine-enterprise-server-2.4.0.7-Linux-x64.tar.gz +TDengine-enterprise-server-2.4.0.7/ +TDengine-enterprise-server-2.4.0.7/driver/ +TDengine-enterprise-server-2.4.0.7/driver/vercomp.txt +TDengine-enterprise-server-2.4.0.7/driver/libtaos.so.2.4.0.7 +TDengine-enterprise-server-2.4.0.7/install.sh +TDengine-enterprise-server-2.4.0.7/examples/ +... + +$ ll +total 43816 +drwxrwxr-x 3 ubuntu ubuntu 4096 Feb 22 09:31 ./ +drwxr-xr-x 20 ubuntu ubuntu 4096 Feb 22 09:30 ../ +drwxrwxr-x 4 ubuntu ubuntu 4096 Feb 22 09:30 TDengine-enterprise-server-2.4.0.7/ +-rw-rw-r-- 1 ubuntu ubuntu 44852544 Feb 22 09:31 TDengine-enterprise-server-2.4.0.7-Linux-x64.tar.gz + +$ cd TDengine-enterprise-server-2.4.0.7/ + + $ ll +total 40784 +drwxrwxr-x 4 ubuntu ubuntu 4096 Feb 22 09:30 ./ +drwxrwxr-x 3 ubuntu ubuntu 4096 Feb 22 09:31 ../ +drwxrwxr-x 2 ubuntu ubuntu 4096 Feb 22 09:30 driver/ +drwxrwxr-x 10 ubuntu ubuntu 4096 Feb 22 09:30 examples/ +-rwxrwxr-x 1 ubuntu ubuntu 33294 Feb 22 09:30 install.sh* +-rw-rw-r-- 1 ubuntu ubuntu 41704288 Feb 22 09:30 taos.tar.gz + +$ sudo ./install.sh + +Start to update TDengine... +Created symlink /etc/systemd/system/multi-user.target.wants/taosd.service → /etc/systemd/system/taosd.service. +Nginx for TDengine is updated successfully! + +To configure TDengine : edit /etc/taos/taos.cfg +To configure Taos Adapter (if has) : edit /etc/taos/taosadapter.toml +To start TDengine : sudo systemctl start taosd +To access TDengine : use taos -h shuduo-1804 in shell OR from http://127.0.0.1:6060 + +TDengine is updated successfully! +Install taoskeeper as a standalone service +taoskeeper is installed, enable it by `systemctl enable taoskeeper` +``` + +说明:install.sh 安装脚本在执行过程中,会通过命令行交互界面询问一些配置信息。如果希望采取无交互安装方式,那么可以用 -e no 参数来执行 install.sh 脚本。运行 `./install.sh -h` 指令可以查看所有参数的详细说明信息。 + +### tar.gz 安装后的卸载 + +卸载命令如下: + +``` +$ rmtaos +Nginx for TDengine is running, stopping it... +TDengine is removed successfully! + +taosKeeper is removed successfully! +``` + +## 安装目录说明 + +TDengine 成功安装后,主安装目录是 /usr/local/taos,目录内容如下: + +``` +$ cd /usr/local/taos +$ ll +$ ll +total 28 +drwxr-xr-x 7 root root 4096 Feb 22 09:34 ./ +drwxr-xr-x 12 root root 4096 Feb 22 09:34 ../ +drwxr-xr-x 2 root root 4096 Feb 22 09:34 bin/ +drwxr-xr-x 2 root root 4096 Feb 22 09:34 cfg/ +lrwxrwxrwx 1 root root 13 Feb 22 09:34 data -> /var/lib/taos/ +drwxr-xr-x 2 root root 4096 Feb 22 09:34 driver/ +drwxr-xr-x 10 root root 4096 Feb 22 09:34 examples/ +drwxr-xr-x 2 root root 4096 Feb 22 09:34 include/ +lrwxrwxrwx 1 root root 13 Feb 22 09:34 log -> /var/log/taos/ +``` + +- 自动生成配置文件目录、数据库目录、日志目录。 +- 配置文件缺省目录:/etc/taos/taos.cfg, 软链接到 /usr/local/taos/cfg/taos.cfg; +- 数据库缺省目录:/var/lib/taos, 软链接到 /usr/local/taos/data; +- 日志缺省目录:/var/log/taos, 软链接到 /usr/local/taos/log; +- /usr/local/taos/bin 目录下的可执行文件,会软链接到 /usr/bin 目录下; +- /usr/local/taos/driver 目录下的动态库文件,会软链接到 /usr/lib 目录下; +- /usr/local/taos/include 目录下的头文件,会软链接到到 /usr/include 目录下; + +## 卸载和更新文件说明 + +卸载安装包的时候,将保留配置文件、数据库文件和日志文件,即 /etc/taos/taos.cfg 、 /var/lib/taos 、 /var/log/taos 。如果用户确认后不需保留,可以手工删除,但一定要慎重,因为删除后,数据将永久丢失,不可以恢复! + +如果是更新安装,当缺省配置文件( /etc/taos/taos.cfg )存在时,仍然使用已有的配置文件,安装包中携带的配置文件修改为 taos.cfg.orig 保存在 /usr/local/taos/cfg/ 目录,可以作为设置配置参数的参考样例;如果不存在配置文件,就使用安装包中自带的配置文件。 + +## TDengine 的启动、停止、卸载 + +TDengine 使用 Linux 系统的 systemd/systemctl/service 来管理系统的启动和、停止、重启操作。TDengine 的服务进程是 taosd,默认情况下 TDengine 在系统启动后将自动启动。DBA 可以通过 systemd/systemctl/service 手动操作停止、启动、重新启动服务。 + +以 systemctl 为例,命令如下: + +- 启动服务进程:`systemctl start taosd` + +- 停止服务进程:`systemctl stop taosd` + +- 重启服务进程:`systemctl restart taosd` + +- 查看服务状态:`systemctl status taosd` + +注意:TDengine 在 2.4 版本之后包含一个独立组件 taosAdapter 需要使用 systemctl 命令管理 taosAdapter 服务的启动和停止。 + +如果服务进程处于活动状态,则 status 指令会显示如下的相关信息: + +``` +...... + +Active: active (running) + +...... +``` + +如果后台服务进程处于停止状态,则 status 指令会显示如下的相关信息: + +``` +...... + +Active: inactive (dead) + +...... +``` + +## 注意事项 + +- TDengine 提供了多种安装包,但最好不要在一个系统上同时使用 tar.gz 安装包和 deb 或 rpm 安装包。否则会相互影响,导致在使用时出现问题。 + +- 对于 deb 包安装后,如果安装目录被手工误删了部分,出现卸载、或重新安装不能成功。此时,需要清除 TDengine 包的安装信息,执行如下命令: + +``` +$ sudo rm -f /var/lib/dpkg/info/tdengine* +``` + +然后再重新进行安装就可以了。 + +- 对于 rpm 包安装后,如果安装目录被手工误删了部分,出现卸载、或重新安装不能成功。此时,需要清除 TDengine 包的安装信息,执行如下命令: + +``` +$ sudo rpm -e --noscripts tdengine +``` + +然后再重新进行安装就可以了。 diff --git a/docs-cn/11-operation/02-planning.mdx b/docs-cn/11-operation/02-planning.mdx new file mode 100644 index 0000000000000000000000000000000000000000..1e62c54ff04f4204be996cf2c92b51f6fdf59d91 --- /dev/null +++ b/docs-cn/11-operation/02-planning.mdx @@ -0,0 +1,82 @@ +--- +sidebar_label: 容量规划 +--- + +# 容量规划 + +使用 TDengine 来搭建一个物联网大数据平台,计算资源、存储资源需要根据业务场景进行规划。下面分别讨论系统运行所需要的内存、CPU 以及硬盘空间。 + +## 内存需求 + +每个 Database 可以创建固定数目的 vgroup,默认与 CPU 核数相同,可通过 maxVgroupsPerDb 配置;vgroup 中的每个副本会是一个 vnode;每个 vnode 会占用固定大小的内存(大小与数据库的配置参数 blocks 和 cache 有关);每个 Table 会占用与标签总长度有关的内存;此外,系统会有一些固定的内存开销。因此,每个 DB 需要的系统内存可通过如下公式计算: + +``` +Database Memory Size = maxVgroupsPerDb * (blocks * cache + 10MB) + numOfTables * (tagSizePerTable + 0.5KB) +``` + +示例:假设是 4 核机器,cache 是缺省大小 16M, blocks 是缺省值 6,并且一个 DB 中有 10 万张表,标签总长度是 256 字节,则这个 DB 总的内存需求为:4 \* (16 \* 6 + 10) + 100000 \* (0.25 + 0.5) / 1000 = 499M。 + +在实际的系统运维中,我们通常会更关心 TDengine 服务进程(taosd)会占用的内存量。 + +``` +taosd 内存总量 = vnode 内存 + mnode 内存 + 查询内存 +``` + +其中: + +1. “vnode 内存”指的是集群中所有的 Database 存储分摊到当前 taosd 节点上所占用的内存资源。可以按上文“Database Memory Size”计算公式估算每个 DB 的内存占用量进行加总,再按集群中总共的 TDengine 节点数做平均(如果设置为多副本,则还需要乘以对应的副本倍数)。 +2. “mnode 内存”指的是集群中管理节点所占用的资源。如果一个 taosd 节点上分布有 mnode 管理节点,则内存消耗还需要增加“0.2KB \* 集群中数据表总数”。 +3. “查询内存”指的是服务端处理查询请求时所需要占用的内存。单条查询语句至少会占用“0.2KB \* 查询涉及的数据表总数”的内存量。 + +注意:以上内存估算方法,主要讲解了系统的“必须内存需求”,而不是“内存总数上限”。在实际运行的生产环境中,由于操作系统缓存、资源管理调度等方面的原因,内存规划应当在估算结果的基础上保留一定冗余,以维持系统状态和系统性能的稳定性。并且,生产环境通常会配置系统资源的监控工具,以便及时发现硬件资源的紧缺情况。 + +最后,如果内存充裕,可以考虑加大 Blocks 的配置,这样更多数据将保存在内存里,提高查询速度。 + +### 客户端内存需求 + +客户端应用采用 taosc 客户端驱动连接服务端,会有内存需求的开销。 + +客户端的内存开销主要由写入过程中的 SQL 语句、表的元数据信息缓存、以及结构性开销构成。系统最大容纳的表数量为 N(每个通过超级表创建的表的 meta data 开销约 256 字节),最大并行写入线程数量 T,最大 SQL 语句长度 S(通常是 1 Mbytes)。由此可以进行客户端内存开销的估算(单位 MBytes): + +``` +M = (T * S * 3 + (N / 4096) + 100) +``` + +举例如下:用户最大并发写入线程数 100,子表数总数 10,000,000,那么客户端的内存最低要求是: + +``` +100 * 3 + (10000000 / 4096) + 100 = 2741 (MBytes) +``` + +即配置 3 GBytes 内存是最低要求。 + +## CPU 需求 + +CPU 的需求取决于如下两方面: + +- **数据插入** TDengine 单核每秒能至少处理一万个插入请求。每个插入请求可以带多条记录,一次插入一条记录与插入 10 条记录,消耗的计算资源差别很小。因此每次插入,条数越大,插入效率越高。如果一个插入请求带 200 条以上记录,单核就能达到每秒插入 100 万条记录的速度。但对前端数据采集的要求越高,因为需要缓存记录,然后一批插入。 +- **查询需求** TDengine 提供高效的查询,但是每个场景的查询差异很大,查询频次变化也很大,难以给出客观数字。需要用户针对自己的场景,写一些查询语句,才能确定。 + +因此仅对数据插入而言,CPU 是可以估算出来的,但查询所耗的计算资源无法估算。在实际运营过程中,不建议 CPU 使用率超过 50%,超过后,需要增加新的节点,以获得更多计算资源。 + +## 存储需求 + +TDengine 相对于通用数据库,有超高的压缩比,在绝大多数场景下,TDengine 的压缩比不会低于 5 倍,有的场合,压缩比可达到 10 倍以上,取决于实际场景的数据特征。压缩前的原始数据大小可通过如下方式计算: + +``` +Raw DataSize = numOfTables * rowSizePerTable * rowsPerTable +``` + +示例:1000 万台智能电表,每台电表每 15 分钟采集一次数据,每次采集的数据 128 字节,那么一年的原始数据量是:10000000 \* 128 \* 24 \* 60 / 15 \* 365 = 44.8512T。TDengine 大概需要消耗 44.851 / 5 = 8.97024T 空间。 + +用户可以通过参数 keep,设置数据在磁盘中的最大保存时长。为进一步减少存储成本,TDengine 还提供多级存储,最冷的数据可以存放在最廉价的存储介质上,应用的访问不用做任何调整,只是读取速度降低了。 + +为提高速度,可以配置多块硬盘,这样可以并发写入或读取数据。需要提醒的是,TDengine 采取多副本的方式提供数据的高可靠,因此不再需要采用昂贵的磁盘阵列。 + +## 物理机或虚拟机台数 + +根据上面的内存、CPU、存储的预估,就可以知道整个系统需要多少核、多少内存、多少存储空间。如果数据副本数不为 1,总需求量需要再乘以副本数。 + +因为 TDengine 具有很好的水平扩展能力,根据总量,再根据单个物理机或虚拟机的资源,就可以轻松决定需要购置多少台物理机或虚拟机了。 + +**立即计算 CPU、内存、存储,请参见:[资源估算方法](https://www.taosdata.com/config/config.html)。** \ No newline at end of file diff --git a/docs-cn/11-operation/03-tolerance.md b/docs-cn/11-operation/03-tolerance.md new file mode 100644 index 0000000000000000000000000000000000000000..bd293f1609d1fd7bfd5ef22171ed13ff0e822a25 --- /dev/null +++ b/docs-cn/11-operation/03-tolerance.md @@ -0,0 +1,26 @@ +# 容错和灾备 + +## 容错 + +TDengine 支持**WAL**(Write Ahead Log)机制,实现数据的容错能力,保证数据的高可用。 + +TDengine 接收到应用的请求数据包时,先将请求的原始数据包写入数据库日志文件,等数据成功写入数据库数据文件后,再删除相应的 WAL。这样保证了 TDengine 能够在断电等因素导致的服务重启时从数据库日志文件中恢复数据,避免数据的丢失。 + +涉及的系统配置参数有两个: + +- walLevel:WAL 级别,0:不写 wal; 1:写 wal, 但不执行 fsync; 2:写 wal, 而且执行 fsync。 +- fsync:当 walLevel 设置为 2 时,执行 fsync 的周期。设置为 0,表示每次写入,立即执行 fsync。 + +如果要 100%的保证数据不丢失,需要将 walLevel 设置为 2,fsync 设置为 0。这时写入速度将会下降。但如果应用侧启动的写数据的线程数达到一定的数量(超过 50),那么写入数据的性能也会很不错,只会比 fsync 设置为 3000 毫秒下降 30%左右。 + +## 灾备 + +TDengine 的集群通过多个副本的机制,来提供系统的高可用性,实现灾备能力。 + +TDengine 集群是由 mnode 负责管理的,为保证 mnode 的高可靠,可以配置多个 mnode 副本,副本数由系统配置参数 numOfMnodes 决定,为了支持高可靠,需要设置大于 1。为保证元数据的强一致性,mnode 副本之间通过同步方式进行数据复制,保证了元数据的强一致性。 + +TDengine 集群中的时序数据的副本数是与数据库关联的,一个集群里可以有多个数据库,每个数据库可以配置不同的副本数。创建数据库时,通过参数 replica 指定副本数。为了支持高可靠,需要设置副本数大于 1。 + +TDengine 集群的节点数必须大于等于副本数,否则创建表时将报错。 + +当 TDengine 集群中的节点部署在不同的物理机上,并设置多个副本数时,就实现了系统的高可靠性,无需再使用其他软件或工具。TDengine 企业版还可以将副本部署在不同机房,从而实现异地容灾。 diff --git a/docs-cn/11-operation/06-admin.md b/docs-cn/11-operation/06-admin.md new file mode 100644 index 0000000000000000000000000000000000000000..0ecbe0ae2e3c6e5132c7ca84da182987ecce779f --- /dev/null +++ b/docs-cn/11-operation/06-admin.md @@ -0,0 +1,40 @@ +# 用户管理 + +系统管理员可以在 CLI 界面里添加、删除用户,也可以修改密码。CLI 里 SQL 语法如下: + +```sql +CREATE USER PASS <'password'>; +``` + +创建用户,并指定用户名和密码,密码需要用单引号引起来,单引号为英文半角 + +```sql +DROP USER ; +``` + +删除用户,限 root 用户使用 + +```sql +ALTER USER PASS <'password'>; +``` + +修改用户密码,为避免被转换为小写,密码需要用单引号引用,单引号为英文半角 + +```sql +ALTER USER PRIVILEGE ; +``` + +修改用户权限为:write 或 read,不需要添加单引号 + +说明:系统内共有 super/write/read 三种权限级别,但目前不允许通过 alter 指令把 super 权限赋予用户。 + +```sql +SHOW USERS; +``` + +显示所有用户 + +:::note +SQL 语法中,< >表示需要用户输入的部分,但请不要输入< >本身。 + +::: diff --git a/docs-cn/11-operation/07-import.md b/docs-cn/11-operation/07-import.md new file mode 100644 index 0000000000000000000000000000000000000000..422842aa588c5c8d0253a2a8f841dcf3dbdf1143 --- /dev/null +++ b/docs-cn/11-operation/07-import.md @@ -0,0 +1,59 @@ +# 数据导入 + +TDengine 提供多种方便的数据导入功能,一种按脚本文件导入,一种按数据文件导入,一种是 taosdump 工具导入本身导出的文件。 + +## 按脚本文件导入 + +TDengine 的 shell 支持 source filename 命令,用于批量运行文件中的 SQL 语句。用户可将建库、建表、写数据等 SQL 命令写在同一个文件中,每条命令单独一行,在 shell 中运行 source 命令,即可按顺序批量运行文件中的 SQL 语句。以‘#’开头的 SQL 语句被认为是注释,shell 将自动忽略。 + +## 按数据文件导入 + +TDengine 也支持在 shell 对已存在的表从 CSV 文件中进行数据导入。CSV 文件只属于一张表且 CSV 文件中的数据格式需与要导入表的结构相同,在导入的时候,其语法如下: + +```sql +insert into tb1 file 'path/data.csv'; +``` + +:::note +注意:如果 CSV 文件首行存在描述信息,请手动删除后再导入。如某列为空,填 NULL,无引号。\*\* + +::: + +例如,现在存在一个子表 d1001, 其表结构如下: + +```sql +taos> DESCRIBE d1001 + Field | Type | Length | Note | +================================================================================= + ts | TIMESTAMP | 8 | | + current | FLOAT | 4 | | + voltage | INT | 4 | | + phase | FLOAT | 4 | | + location | BINARY | 64 | TAG | + groupid | INT | 4 | TAG | +``` + +要导入的 data.csv 的格式如下: + +```csv +'2018-10-04 06:38:05.000',10.30000,219,0.31000 +'2018-10-05 06:38:15.000',12.60000,218,0.33000 +'2018-10-06 06:38:16.800',13.30000,221,0.32000 +'2018-10-07 06:38:05.000',13.30000,219,0.33000 +'2018-10-08 06:38:05.000',14.30000,219,0.34000 +'2018-10-09 06:38:05.000',15.30000,219,0.35000 +'2018-10-10 06:38:05.000',16.30000,219,0.31000 +'2018-10-11 06:38:05.000',17.30000,219,0.32000 +'2018-10-12 06:38:05.000',18.30000,219,0.31000 +``` + +那么可以用如下命令导入数据: + +```sql +taos> insert into d1001 file '~/data.csv'; +Query OK, 9 row(s) affected (0.004763s) +``` + +## taosdump 工具导入 + +TDengine 提供了方便的数据库导入导出工具 taosdump。用户可以将 taosdump 从一个系统导出的数据,导入到其他系统中。具体使用方法,请参见:[TDengine 数据备份工具: taosdump](https://www.taosdata.com/docs/cn/v2.0/tools/taosdump)。 diff --git a/docs-cn/11-operation/08-export.md b/docs-cn/11-operation/08-export.md new file mode 100644 index 0000000000000000000000000000000000000000..fc5be04d5975bd035eed994a9b3a18dff0eacc50 --- /dev/null +++ b/docs-cn/11-operation/08-export.md @@ -0,0 +1,19 @@ +# 数据导出 + +为方便数据导出,TDengine 提供了两种导出方式,分别是按表导出和用 taosdump 导出。 + +## 按表导出 CSV 文件 + +如果用户需要导出一个表或一个 STable 中的数据,可在 taos shell 中运行: + +```sql +select * from >> data.csv; +``` + +这样,表 tb_name 中的数据就会按照 CSV 格式导出到文件 data.csv 中。 + +## 用 taosdump 导出数据 + +利用 taosdump,用户可以根据需要选择导出所有数据库、一个数据库或者数据库中的一张表,所有数据或一时间段的数据,甚至仅仅表的定义。 + +具体使用方法,请参见博客:[TDengine DUMP 工具使用指南](https://github.com/taosdata/taos-tools/blob/develop/taosdump-user-manual-CN.md)。 diff --git a/docs-cn/11-operation/09-status.md b/docs-cn/11-operation/09-status.md new file mode 100644 index 0000000000000000000000000000000000000000..fec725292bf56b924d5ca6f824b7e1628b22670c --- /dev/null +++ b/docs-cn/11-operation/09-status.md @@ -0,0 +1,39 @@ +# 系统连接、任务查询管理 + +系统管理员可以从 CLI 查询系统的连接、正在进行的查询、流式计算,并且可以关闭连接、停止正在进行的查询和流式计算。CLI 里 SQL 语法如下: + +```sql +SHOW CONNECTIONS; +``` + +显示数据库的连接,其中一列显示 ip:port, 为连接的 IP 地址和端口号。 + +```sql +KILL CONNECTION ; +``` + +强制关闭数据库连接,其中的 connection-id 是 SHOW CONNECTIONS 中显示的第一列的数字。 + +```sql +SHOW QUERIES; +``` + +显示数据查询,其中第一列显示的以冒号隔开的两个数字为 query-id,为发起该 query 应用连接的 connection-id 和查询次数。 + +```sql +KILL QUERY ; +``` + +强制关闭数据查询,其中 query-id 是 SHOW QUERIES 中显示的 connection-id:query-no 字串,如“105:2”,拷贝粘贴即可。 + +```sql +SHOW STREAMS; +``` + +显示流式计算,其中第一列显示的以冒号隔开的两个数字为 stream-id, 为启动该 stream 应用连接的 connection-id 和发起 stream 的次数。 + +```sql +KILL STREAM ; +``` + +强制关闭流式计算,其中的中 stream-id 是 SHOW STREAMS 中显示的 connection-id:stream-no 字串,如 103:2,拷贝粘贴即可。 diff --git a/docs-cn/11-operation/10-monitor.md b/docs-cn/11-operation/10-monitor.md new file mode 100644 index 0000000000000000000000000000000000000000..367d1dd54ef5d53b43542600c55b8337e721c013 --- /dev/null +++ b/docs-cn/11-operation/10-monitor.md @@ -0,0 +1,52 @@ +# 系统监控 + +TDengine 启动后,会自动创建一个监测数据库 log,并自动将服务器的 CPU、内存、硬盘空间、带宽、请求数、磁盘读写速度、慢查询等信息定时写入该数据库。TDengine 还将重要的系统操作(比如登录、创建、删除数据库等)日志以及各种错误报警信息记录下来存放在 log 库里。系统管理员可以从 CLI 直接查看这个数据库,也可以在 WEB 通过图形化界面查看这些监测信息。 + +这些监测信息的采集缺省是打开的,但可以修改配置文件里的选项 monitor 将其关闭或打开。 + +## TDinsight - 使用监控数据库 + Grafana 对 TDengine 进行监控的解决方案 + +从 2.3.3.0 开始,监控数据库将提供更多的监控项,您可以从 [TDinsight Grafana Dashboard](https://grafana.com/grafana/dashboards/15167) 了解如何使用 TDinsight 方案对 TDengine 进行监控。 + +我们提供了一个自动化脚本 `TDinsight.sh` 对 TDinsight 进行部署。 + +下载 `TDinsight.sh`: + +```bash +wget https://github.com/taosdata/grafanaplugin/raw/master/dashboards/TDinsight.sh +chmod +x TDinsight.sh +``` + +准备: + +1. TDengine Server 信息: + + - TDengine RESTful 服务:对本地而言,可以是 `http://localhost:6041`,使用参数 `-a`。 + - TDengine 用户名和密码,使用 `-u` `-p` 参数设置。 + +2. Grafana 告警通知 + + - 使用已经存在的 Grafana Notification Channel `uid`,参数 `-E`。该参数可以使用 `curl -u admin:admin localhost:3000/api/alert-notifications |jq` 来获取。 + + ```bash + sudo ./TDinsight.sh -a http://localhost:6041 -u root -p taosdata -E + ``` + + - 使用 TDengine 数据源插件内置的阿里云短信告警通知,使用 `-s` 启用之,并设置如下参数: + + 1. 阿里云短信服务 Key ID,参数 `-I` + 2. 阿里云短信服务 Key Secret,参数 `K` + 3. 阿里云短信服务签名,参数 `-S` + 4. 短信通知模板号,参数 `-C` + 5. 短信通知模板输入参数,JSON 格式,参数 `-T`,如 `{"alarm_level":"%s","time":"%s","name":"%s","content":"%s"}` + 6. 逗号分隔的通知手机列表,参数 `-B` + + ```bash + sudo ./TDinsight.sh -a http://localhost:6041 -u root -p taosdata -s \ + -I XXXXXXX -K XXXXXXXX -S taosdata -C SMS_1111111 -B 18900000000 \ + -T '{"alarm_level":"%s","time":"%s","name":"%s","content":"%s"}' + ``` + +运行程序并重启 Grafana 服务,打开面板:`http://localhost:3000/d/tdinsight`。 + +更多使用场景和限制请参考[TDinsight](https://github.com/taosdata/grafanaplugin/blob/master/dashboards/TDinsight.md) 文档。 diff --git a/docs-cn/11-operation/11-optimize.md b/docs-cn/11-operation/11-optimize.md new file mode 100644 index 0000000000000000000000000000000000000000..ea82246770349113d08d2ac05b0ee321b696fbf4 --- /dev/null +++ b/docs-cn/11-operation/11-optimize.md @@ -0,0 +1,98 @@ +# 性能优化 + +因数据行 [update](https://www.taosdata.com/cn/documentation/faq#update)、表删除、数据过期等原因,TDengine 的磁盘存储文件有可能出现数据碎片,影响查询操作的性能表现。从 2.1.3.0 版本开始,新增 SQL 指令 COMPACT 来启动碎片重整过程: + +```sql +COMPACT VNODES IN (vg_id1, vg_id2, ...) +``` + +COMPACT 命令对指定的一个或多个 VGroup 启动碎片重整,系统会通过任务队列尽快安排重整操作的具体执行。COMPACT 指令所需的 VGroup id,可以通过 `SHOW VGROUPS;` 指令的输出结果获取;而且在 `SHOW VGROUPS;` 中会有一个 compacting 列,值为 2 时表示对应的 VGroup 处于排队等待进行重整的状态,值为 1 时表示正在进行碎片重整,为 0 时则表示并没有处于重整状态(未要求进行重整或已经完成重整)。 + +需要注意的是,碎片重整操作会大幅消耗磁盘 I/O。因此在重整进行期间,有可能会影响节点的写入和查询性能,甚至在极端情况下导致短时间的阻写。 + +## 存储参数优化 + +不同应用场景的数据往往具有不同的数据特征,比如保留天数、副本数、采集频次、记录大小、采集点的数量、压缩等都可完全不同。为获得在存储上的最高效率,TDengine 提供如下存储相关的系统配置参数(既可以作为 create database 指令的参数,也可以写在 taos.cfg 配置文件中用来设定创建新数据库时所采用的默认值): + +| # | 配置参数名称 | 单位 | 含义 | **取值范围** | **缺省值** | +| --- | ------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------- | +| 1 | days | 天 | 一个数据文件存储数据的时间跨度 | | 10 | +| 2 | keep | 天 | (可通过 alter database 修改)数据库中数据保留的天数。 | 3650 | +| 3 | cache | MB | 内存块的大小 | | 16 | +| 4 | blocks | | (可通过 alter database 修改)每个 VNODE(TSDB)中有多少个 cache 大小的内存块。因此一个 VNODE 使用的内存大小粗略为(cache \* blocks)。 | | 6 | +| 5 | quorum | | (可通过 alter database 修改)多副本环境下指令执行的确认数要求 | 1-2 | 1 | +| 6 | minRows | | 文件块中记录的最小条数 | | 100 | +| 7 | maxRows | | 文件块中记录的最大条数 | | 4096 | +| 8 | comp | | (可通过 alter database 修改)文件压缩标志位 | 0:关闭,1:一阶段压缩,2:两阶段压缩 | 2 | +| 9 | walLevel | | (作为 database 的参数时名为 wal;在 taos.cfg 中作为参数时需要写作 walLevel)WAL 级别 | 1:写 wal,但不执行 fsync;2:写 wal, 而且执行 fsync | 1 | +| 10 | fsync | 毫秒 | 当 wal 设置为 2 时,执行 fsync 的周期。设置为 0,表示每次写入,立即执行 fsync。 | | 3000 | +| 11 | replica | | (可通过 alter database 修改)副本个数 | 1-3 | 1 | +| 12 | precision | | 时间戳精度标识(2.1.2.0 版本之前、2.0.20.7 版本之前在 taos.cfg 文件中不支持此参数。)(从 2.1.5.0 版本开始,新增对纳秒时间精度的支持) | ms 表示毫秒,us 表示微秒,ns 表示纳秒 | ms | +| 13 | update | | 是否允许数据更新(从 2.1.7.0 版本开始此参数支持 0 ~ 2 的取值范围,在此之前取值只能是 [0, 1];而 2.0.8.0 之前的版本在 SQL 指令中不支持此参数。) | 0:不允许;1:允许更新整行;2:允许部分列更新。 | 0 | +| 14 | cacheLast | | (可通过 alter database 修改)是否在内存中缓存子表的最近数据(从 2.1.2.0 版本开始此参数支持 0 ~ 3 的取值范围,在此之前取值只能是 [0, 1];而 2.0.11.0 之前的版本在 SQL 指令中不支持此参数。)(2.1.2.0 版本之前、2.0.20.7 版本之前在 taos.cfg 文件中不支持此参数。) | 0:关闭;1:缓存子表最近一行数据;2:缓存子表每一列的最近的非 NULL 值;3:同时打开缓存最近行和列功能 | 0 | + +对于一个应用场景,可能有多种数据特征的数据并存,最佳的设计是将具有相同数据特征的表放在一个库里,这样一个应用有多个库,而每个库可以配置不同的存储参数,从而保证系统有最优的性能。TDengine 允许应用在创建库时指定上述存储参数,如果指定,该参数就将覆盖对应的系统配置参数。举例,有下述 SQL: + +```sql + CREATE DATABASE demo DAYS 10 CACHE 32 BLOCKS 8 REPLICA 3 UPDATE 1; +``` + +该 SQL 创建了一个库 demo, 每个数据文件存储 10 天数据,内存块为 32 兆字节,每个 VNODE 占用 8 个内存块,副本数为 3,允许更新,而其他参数与系统配置完全一致。 + +一个数据库创建成功后,仅部分参数可以修改并实时生效,其余参数不能修改: + +| **参数名** | **能否修改** | **范围** | **修改语法示例** | +| ----------- | ------------ | ---------------------------------------------------------- | -------------------------------------- | +| name | | | | +| create time | | | | +| ntables | | | | +| vgroups | | | | +| replica | **YES** | 在线 dnode 数目为:
1:1-1;
2:1-2;
\>=3:1-3 | ALTER DATABASE REPLICA _n_ | +| quorum | **YES** | 1-2 | ALTER DATABASE QUORUM _n_ | +| days | | | | +| keep | **YES** | days-365000 | ALTER DATABASE KEEP _n_ | +| cache | | | | +| blocks | **YES** | 3-1000 | ALTER DATABASE BLOCKS _n_ | +| minrows | | | | +| maxrows | | | | +| wal | | | | +| fsync | | | | +| comp | **YES** | 0-2 | ALTER DATABASE COMP _n_ | +| precision | | | | +| status | | | | +| update | | | | +| cachelast | **YES** | 0 \| 1 \| 2 \| 3 | ALTER DATABASE CACHELAST _n_ | + +**说明:**在 2.1.3.0 版本之前,通过 ALTER DATABASE 语句修改这些参数后,需要重启服务器才能生效。 + +TDengine 集群中加入一个新的 dnode 时,涉及集群相关的一些参数必须与已有集群的配置相同,否则不能成功加入到集群中。会进行校验的参数如下: + +- numOfMnodes:系统中管理节点个数。默认值:3。(2.0 版本从 2.0.20.11 开始、2.1 及以上版本从 2.1.6.0 开始,numOfMnodes 默认值改为 1。) +- mnodeEqualVnodeNum: 一个 mnode 等同于 vnode 消耗的个数。默认值:4。 +- offlineThreshold: dnode 离线阈值,超过该时间将导致该 dnode 从集群中删除。单位为秒,默认值:86400\*10(即 10 天)。 +- statusInterval: dnode 向 mnode 报告状态时长。单位为秒,默认值:1。 +- maxTablesPerVnode: 每个 vnode 中能够创建的最大表个数。默认值:1000000。 +- maxVgroupsPerDb: 每个数据库中能够使用的最大 vgroup 个数。 +- arbitrator: 系统中裁决器的 end point,缺省为空。 +- timezone、locale、charset 的配置见客户端配置。(2.0.20.0 及以上的版本里,集群中加入新节点已不要求 locale 和 charset 参数取值一致) +- balance:是否启用负载均衡。0:否,1:是。默认值:1。 +- flowctrl:是否启用非阻塞流控。0:否,1:是。默认值:1。 +- slaveQuery:是否启用 slave vnode 参与查询。0:否,1:是。默认值:1。 +- adjustMaster:是否启用 vnode master 负载均衡。0:否,1:是。默认值:1。 + +为方便调试,可通过 SQL 语句临时调整每个 dnode 的日志配置,系统重启后会失效: + +```sql +ALTER DNODE +``` + +- dnode_id: 可以通过 SQL 语句"SHOW DNODES"命令获取 +- config: 要调整的日志参数,在如下列表中取值 + > resetlog 截断旧日志文件,创建一个新日志文件 + > debugFlag < 131 | 135 | 143 > 设置 debugFlag 为 131、135 或者 143 + +例如: + +``` +alter dnode 1 debugFlag 135; +``` diff --git a/docs-cn/11-operation/17-diagnose.md b/docs-cn/11-operation/17-diagnose.md new file mode 100644 index 0000000000000000000000000000000000000000..666fe6e655cab27962d156d97bf14086feaa32b5 --- /dev/null +++ b/docs-cn/11-operation/17-diagnose.md @@ -0,0 +1,126 @@ +# 诊断及其他 + +## 网络连接诊断 + +当出现客户端应用无法访问服务端时,需要确认客户端与服务端之间网络的各端口连通情况,以便有针对性地排除故障。 + +目前网络连接诊断支持在:Linux 与 Linux,Linux 与 Windows 之间进行诊断测试。 + +诊断步骤: + +1. 如拟诊断的端口范围与服务器 taosd 实例的端口范围相同,须先停掉 taosd 实例 +2. 服务端命令行输入:`taos -n server -P ` 以服务端身份启动对端口 port 为基准端口的监听 +3. 客户端命令行输入:`taos -n client -h -P ` 以客户端身份启动对指定的服务器、指定的端口发送测试包 + +服务端运行正常的话会输出以下信息: + +```bash +# taos -n server -P 6000 +12/21 14:50:13.522509 0x7f536f455200 UTL work as server, host:172.27.0.7 startPort:6000 endPort:6011 pkgLen:1000 + +12/21 14:50:13.522659 0x7f5352242700 UTL TCP server at port:6000 is listening +12/21 14:50:13.522727 0x7f5351240700 UTL TCP server at port:6001 is listening +... +... +... +12/21 14:50:13.523954 0x7f5342fed700 UTL TCP server at port:6011 is listening +12/21 14:50:13.523989 0x7f53437ee700 UTL UDP server at port:6010 is listening +12/21 14:50:13.524019 0x7f53427ec700 UTL UDP server at port:6011 is listening +12/21 14:50:22.192849 0x7f5352242700 UTL TCP: read:1000 bytes from 172.27.0.8 at 6000 +12/21 14:50:22.192993 0x7f5352242700 UTL TCP: write:1000 bytes to 172.27.0.8 at 6000 +12/21 14:50:22.237082 0x7f5351a41700 UTL UDP: recv:1000 bytes from 172.27.0.8 at 6000 +12/21 14:50:22.237203 0x7f5351a41700 UTL UDP: send:1000 bytes to 172.27.0.8 at 6000 +12/21 14:50:22.237450 0x7f5351240700 UTL TCP: read:1000 bytes from 172.27.0.8 at 6001 +12/21 14:50:22.237576 0x7f5351240700 UTL TCP: write:1000 bytes to 172.27.0.8 at 6001 +12/21 14:50:22.281038 0x7f5350a3f700 UTL UDP: recv:1000 bytes from 172.27.0.8 at 6001 +12/21 14:50:22.281141 0x7f5350a3f700 UTL UDP: send:1000 bytes to 172.27.0.8 at 6001 +... +... +... +12/21 14:50:22.677443 0x7f5342fed700 UTL TCP: read:1000 bytes from 172.27.0.8 at 6011 +12/21 14:50:22.677576 0x7f5342fed700 UTL TCP: write:1000 bytes to 172.27.0.8 at 6011 +12/21 14:50:22.721144 0x7f53427ec700 UTL UDP: recv:1000 bytes from 172.27.0.8 at 6011 +12/21 14:50:22.721261 0x7f53427ec700 UTL UDP: send:1000 bytes to 172.27.0.8 at 6011 +``` + +客户端运行正常会输出以下信息: + +```bash +# taos -n client -h 172.27.0.7 -P 6000 +12/21 14:50:22.192434 0x7fc95d859200 UTL work as client, host:172.27.0.7 startPort:6000 endPort:6011 pkgLen:1000 + +12/21 14:50:22.192472 0x7fc95d859200 UTL server ip:172.27.0.7 is resolved from host:172.27.0.7 +12/21 14:50:22.236869 0x7fc95d859200 UTL successed to test TCP port:6000 +12/21 14:50:22.237215 0x7fc95d859200 UTL successed to test UDP port:6000 +... +... +... +12/21 14:50:22.676891 0x7fc95d859200 UTL successed to test TCP port:6010 +12/21 14:50:22.677240 0x7fc95d859200 UTL successed to test UDP port:6010 +12/21 14:50:22.720893 0x7fc95d859200 UTL successed to test TCP port:6011 +12/21 14:50:22.721274 0x7fc95d859200 UTL successed to test UDP port:6011 +``` + +仔细阅读打印出来的错误信息,可以帮助管理员找到原因,以解决问题。 + +## 启动状态及 RPC 诊断 + +`taos -n startup -h ` + +判断 taosd 服务端是否成功启动,是数据库管理员经常遇到的一种情形。特别当若干台服务器组成集群时,判断每个服务端实例是否成功启动就会是一个重要问题。除检索 taosd 服务端日志文件进行问题定位、分析外,还可以通过 `taos -n startup -h ` 来诊断一个 taosd 进程的启动状态。 + +针对多台服务器组成的集群,当服务启动过程耗时较长时,可通过该命令行来诊断每台服务器的 taosd 实例的启动状态,以准确定位问题。 + +`taos -n rpc -h ` + +该命令用来诊断已经启动的 taosd 实例的端口是否可正常访问。如果 taosd 程序异常或者失去响应,可以通过 `taos -n rpc -h ` 来发起一个与指定 fqdn 的 rpc 通信,看看 taosd 是否能收到,以此来判定是网络问题还是 taosd 程序异常问题。 + +## sync 及 arbitrator 诊断 + +``` +taos -n sync -P 6040 -h +taos -n sync -P 6042 -h +``` + +用来诊断 sync 端口是否工作正常,判断服务端 sync 模块是否成功工作。另外,-P 6042 用来诊断 arbitrator 是否配置正常,判断指定服务器的 arbitrator 是否能正常工作。 + +## 网络速度诊断 + +`taos -n speed -h -P 6030 -N 10 -l 10000000 -S TCP` + +从 2.2.0.0 版本开始,taos 工具新提供了一个网络速度诊断的模式,可以对一个正在运行中的 taosd 实例或者 `taos -n server` 方式模拟的一个服务端实例,以非压缩传输的方式进行网络测速。这个模式下可供调整的参数如下: + +-n:设为“speed”时,表示对网络速度进行诊断。 +-h:所要连接的服务端的 FQDN 或 ip 地址。如果不设置这一项,会使用本机 taos.cfg 文件中 FQDN 参数的设置作为默认值。 +-P:所连接服务端的网络端口。默认值为 6030。 +-N:诊断过程中使用的网络包总数。最小值是 1、最大值是 10000,默认值为 100。 +-l:单个网络包的大小(单位:字节)。最小值是 1024、最大值是 1024 _ 1024 _ 1024,默认值为 1000。 +-S:网络封包的类型。可以是 TCP 或 UDP,默认值为 TCP。 + +## FQDN 解析速度诊断 + +`taos -n fqdn -h ` + +从 2.2.0.0 版本开始,taos 工具新提供了一个 FQDN 解析速度的诊断模式,可以对一个目标 FQDN 地址尝试解析,并记录解析过程中所消耗的时间。这个模式下可供调整的参数如下: + +-n:设为“fqdn”时,表示对 FQDN 解析进行诊断。 +-h:所要解析的目标 FQDN 地址。如果不设置这一项,会使用本机 taos.cfg 文件中 FQDN 参数的设置作为默认值。 + +## 服务端日志 + +taosd 服务端日志文件标志位 debugflag 默认为 131,在 debug 时往往需要将其提升到 135 或 143 。 + +一旦设定为 135 或 143,日志文件增长很快,特别是写入、查询请求量较大时,增长速度惊人。如合并保存日志,很容易把日志内的关键信息(如配置信息、错误信息等)冲掉。为此,服务端将重要信息日志与其他日志分开存放: + +- taosinfo 存放重要信息日志, 包括:INFO/ERROR/WARNING 级别的日志信息。不记录 DEBUG、TRACE 级别的日志。 +- taosdlog 服务器端生成的日志,记录 taosinfo 中全部信息外,还根据设置的日志输出级别,记录 DEBUG(日志级别 135)、TRACE(日志级别是 143)。 + +## 客户端日志 + +每个独立运行的客户端(一个进程)生成一个独立的客户端日志,其命名方式采用 taoslog+<序号> 的方式命名。文件标志位 debugflag 默认为 131,在 debug 时往往需要将其提升到 135 或 143 。 + +- taoslog 客户端(driver)生成的日志,默认记录客户端 INFO/ERROR/WARNING 级别日志,还根据设置的日志输出级别,记录 DEBUG(日志级别 135)、TRACE(日志级别是 143)。 + +其中,日志文件最大长度由 numOfLogLines 来进行配置,一个 taosd 实例最多保留两个文件。 + +taosd 服务端日志采用异步落盘写入机制,优点是可以避免硬盘写入压力太大,对性能造成很大影响。缺点是,在极端情况下,存在少量日志行数丢失的可能。 diff --git a/docs-cn/11-operation/_category_.yml b/docs-cn/11-operation/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..930e441defdc80215ce5d90375a9cbd2d4bad947 --- /dev/null +++ b/docs-cn/11-operation/_category_.yml @@ -0,0 +1,4 @@ +label: 运维指南 +link: + slug: /operation/ + type: generated-index diff --git a/docs-cn/13-tdinternal/01-arch.md b/docs-cn/13-tdinternal/01-arch.md new file mode 100644 index 0000000000000000000000000000000000000000..f276a8e86ba52aa63a49b0c8f3022a3acb7f39ba --- /dev/null +++ b/docs-cn/13-tdinternal/01-arch.md @@ -0,0 +1,447 @@ +--- +sidebar_label: 数据模型和整体架构 +--- + +# 数据模型和整体架构 + +## 数据模型 + +### 物联网典型场景 + +在典型的物联网、车联网、运维监测场景中,往往有多种不同类型的数据采集设备,采集一个到多个不同的物理量。而同一种采集设备类型,往往又有多个具体的采集设备分布在不同的地点。大数据处理系统就是要将各种采集的数据汇总,然后进行计算和分析。对于同一类设备,其采集的数据都是很规则的。以智能电表为例,假设每个智能电表采集电流、电压、相位三个量,其采集的数据类似如下的表格: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
设备ID时间戳采集量标签
Device IDTime StampcurrentvoltagephaselocationgroupId
d1001153854868500010.32190.31Beijing.Chaoyang2
d1002153854868400010.22200.23Beijing.Chaoyang3
d1003153854868650011.52210.35Beijing.Haidian3
d1004153854868550013.42230.29Beijing.Haidian2
d1001153854869500012.62180.33Beijing.Chaoyang2
d1004153854869660011.82210.28Beijing.Haidian2
d1002153854869665010.32180.25Beijing.Chaoyang3
d1001153854869680012.32210.31Beijing.Chaoyang2
+ +
表 1:智能电表数据示例
+ +每一条记录都有设备 ID,时间戳,采集的物理量(如上图中的电流、电压、相位),还有与每个设备相关的静态标签(如上述表 1 中的位置 Location 和分组 groupId)。每个设备是受外界的触发,或按照设定的周期采集数据。采集的数据点是时序的,是一个数据流。 + +### 数据特征 + +除时序特征外,仔细研究发现,物联网、车联网、运维监测类数据还具有很多其他明显的特征: + +1. 数据高度结构化; +2. 数据极少有更新或删除操作; +3. 无需传统数据库的事务处理; +4. 相对互联网应用,写多读少; +5. 流量平稳,根据设备数量和采集频次,可以预测出来; +6. 用户关注的是一段时间的趋势,而不是某一特定时间点的值; +7. 数据有保留期限; +8. 数据的查询分析一定是基于时间段和空间区域; +9. 除存储、查询操作外,还需要各种统计和实时计算操作; +10. 数据量巨大,一天可能采集的数据就可以超过 100 亿条。 + +充分利用上述特征,TDengine 采取了经特殊优化的存储和计算设计来处理时序数据,它将系统处理能力显著提高,同时大幅降低了系统运维的复杂度。 + +### 关系型数据库模型 + +因为采集的数据一般是结构化数据,同时为降低学习门槛,TDengine 采用传统的关系型数据库模型管理数据。因此用户需要先创建库,然后创建表,之后才能插入或查询数据。TDengine 采用的是结构化存储,而不是 NoSQL 的 key-value 存储。 + +### 一个数据采集点一张表 + +为充分利用其数据的时序性和其他数据特点,TDengine 要求**对每个数据采集点单独建表**(比如有一千万个智能电表,就需创建一千万张表,上述表格中的 d1001, d1002, d1003, d1004 都需单独建表),用来存储这个采集点所采集的时序数据。这种设计有几大优点: + +1. 能保证一个采集点的数据在存储介质上是以块为单位连续存储的。如果读取一个时间段的数据,它能大幅减少随机读取操作,成数量级的提升读取和查询速度。 +2. 由于不同采集设备产生数据的过程完全独立,每个设备的数据源是唯一的,一张表也就只有一个写入者,这样就可采用无锁方式来写,写入速度就能大幅提升。 +3. 对于一个数据采集点而言,其产生的数据是时序的,因此写的操作可用追加的方式实现,进一步大幅提高数据写入速度。 + +如果采用传统的方式,将多个设备的数据写入一张表,由于网络延时不可控,不同设备的数据到达服务器的时序是无法保证的,写入操作是要有锁保护的,而且一个设备的数据是难以保证连续存储在一起的。**采用一个数据采集点一张表的方式,能最大程度的保证单个数据采集点的插入和查询的性能是最优的。** + +TDengine 建议用数据采集点的名字(如上表中的 D1001)来做表名。每个数据采集点可能同时采集多个物理量(如上表中的 curent, voltage, phase),每个物理量对应一张表中的一列,数据类型可以是整型、浮点型、字符串等。除此之外,表的第一列必须是时间戳,即数据类型为 timestamp。对采集的数据,TDengine 将自动按照时间戳建立索引,但对采集的物理量不建任何索引。数据用列式存储方式保存。 + +### 超级表:同一类型数据采集点的集合 + +由于一个数据采集点一张表,导致表的数量巨增,难以管理,而且应用经常需要做采集点之间的聚合操作,聚合的操作也变得复杂起来。为解决这个问题,TDengine 引入超级表(Super Table,简称为 STable)的概念。 + +超级表是指某一特定类型的数据采集点的集合。同一类型的数据采集点,其表的结构是完全一样的,但每个表(数据采集点)的静态属性(标签)是不一样的。描述一个超级表(某一特定类型的数据采集点的集合),除需要定义采集量的表结构之外,还需要定义其标签的 schema,标签的数据类型可以是整数、浮点数、字符串,标签可以有多个,可以事后增加、删除或修改。如果整个系统有 N 个不同类型的数据采集点,就需要建立 N 个超级表。 + +在 TDengine 的设计里,**表用来代表一个具体的数据采集点,超级表用来代表一组相同类型的数据采集点集合**。当为某个具体数据采集点创建表时,用户使用超级表的定义做模板,同时指定该具体采集点(表)的标签值。与传统的关系型数据库相比,表(一个数据采集点)是带有静态标签的,而且这些标签可以事后增加、删除、修改。**一张超级表包含有多张表,这些表具有相同的时序数据 schema,但带有不同的标签值**。 + +当对多个具有相同数据类型的数据采集点进行聚合操作时,TDengine 会先把满足标签过滤条件的表从超级表中找出来,然后再扫描这些表的时序数据,进行聚合操作,这样需要扫描的数据集会大幅减少,从而显著提高聚合计算的性能。 + +## 集群与基本逻辑单元 + +TDengine 的设计是基于单个硬件、软件系统不可靠,基于任何单台计算机都无法提供足够计算能力和存储能力处理海量数据的假设进行设计的。因此 TDengine 从研发的第一天起,就按照分布式高可靠架构进行设计,是支持水平扩展的,这样任何单台或多台服务器发生硬件故障或软件错误都不影响系统的可用性和可靠性。同时,通过节点虚拟化并辅以自动化负载均衡技术,TDengine 能最高效率地利用异构集群中的计算和存储资源降低硬件投资。 + +### 主要逻辑单元 + +TDengine 分布式架构的逻辑结构图如下: + +![TDengine架构示意图](/img/architecture/structure.png) + +
图 1 TDengine架构示意图
+ +一个完整的 TDengine 系统是运行在一到多个物理节点上的,逻辑上,它包含数据节点(dnode)、TDengine 应用驱动(taosc)以及应用(app)。系统中存在一到多个数据节点,这些数据节点组成一个集群(cluster)。应用通过 taosc 的 API 与 TDengine 集群进行互动。下面对每个逻辑单元进行简要介绍。 + +**物理节点(pnode):** pnode 是一独立运行、拥有自己的计算、存储和网络能力的计算机,可以是安装有 OS 的物理机、虚拟机或 Docker 容器。物理节点由其配置的 FQDN (Fully Qualified Domain Name)来标识。TDengine 完全依赖 FQDN 来进行网络通讯,如果不了解 FQDN,请看博文[《一篇文章说清楚 TDengine 的 FQDN》](https://www.taosdata.com/blog/2020/09/11/1824.html)。 + +**数据节点(dnode):** dnode 是 TDengine 服务器侧执行代码 taosd 在物理节点上的一个运行实例,一个工作的系统必须有至少一个数据节点。dnode 包含零到多个逻辑的虚拟节点(vnode),零或者至多一个逻辑的管理节点(mnode)。dnode 在系统中的唯一标识由实例的 End Point (EP)决定。EP 是 dnode 所在物理节点的 FQDN (Fully Qualified Domain Name)和系统所配置的网络端口号(Port)的组合。通过配置不同的端口,一个物理节点(一台物理机、虚拟机或容器)可以运行多个实例,或有多个数据节点。 + +**虚拟节点(vnode):** 为更好的支持数据分片、负载均衡,防止数据过热或倾斜,数据节点被虚拟化成多个虚拟节点(vnode,图中 V2, V3, V4 等)。每个 vnode 都是一个相对独立的工作单元,是时序数据存储的基本单元,具有独立的运行线程、内存空间与持久化存储的路径。一个 vnode 包含一定数量的表(数据采集点)。当创建一张新表时,系统会检查是否需要创建新的 vnode。一个数据节点上能创建的 vnode 的数量取决于该数据节点所在物理节点的硬件资源。一个 vnode 只属于一个 DB,但一个 DB 可以有多个 vnode。一个 vnode 除存储的时序数据外,也保存有所包含的表的 schema、标签值等。一个虚拟节点由所属的数据节点的 EP,以及所属的 VGroup ID 在系统内唯一标识,由管理节点创建并管理。 + +**管理节点(mnode):** 一个虚拟的逻辑单元,负责所有数据节点运行状态的监控和维护,以及节点之间的负载均衡(图中 M)。同时,管理节点也负责元数据(包括用户、数据库、表、静态标签等)的存储和管理,因此也称为 Meta Node。TDengine 集群中可配置多个(开源版最多不超过 3 个) mnode,它们自动构建成为一个虚拟管理节点组(图中 M0, M1, M2)。mnode 间采用 master/slave 的机制进行管理,而且采取强一致方式进行数据同步, 任何数据更新操作只能在 Master 上进行。mnode 集群的创建由系统自动完成,无需人工干预。每个 dnode 上至多有一个 mnode,由所属的数据节点的 EP 来唯一标识。每个 dnode 通过内部消息交互自动获取整个集群中所有 mnode 所在的 dnode 的 EP。 + +**虚拟节点组(VGroup):** 不同数据节点上的 vnode 可以组成一个虚拟节点组(vnode group)来保证系统的高可靠。虚拟节点组内采取 master/slave 的方式进行管理。写操作只能在 master vnode 上进行,系统采用异步复制的方式将数据同步到 slave vnode,这样确保了一份数据在多个物理节点上有拷贝。一个 vgroup 里虚拟节点个数就是数据的副本数。如果一个 DB 的副本数为 N,系统必须有至少 N 数据节点。副本数在创建 DB 时通过参数 replica 可以指定,缺省为 1。使用 TDengine 的多副本特性,可以不再需要昂贵的磁盘阵列等存储设备,就可以获得同样的数据高可靠性。虚拟节点组由管理节点创建、管理,并且由管理节点分配一个系统唯一的 ID,VGroup ID。如果两个虚拟节点的 vnode group ID 相同,说明他们属于同一个组,数据互为备份。虚拟节点组里虚拟节点的个数是可以动态改变的,容许只有一个,也就是没有数据复制。VGroup ID 是永远不变的,即使一个虚拟节点组被删除,它的 ID 也不会被收回重复利用。 + +**TAOSC:** taosc 是 TDengine 给应用提供的驱动程序(driver),负责处理应用与集群的接口交互,提供 C/C++ 语言原生接口,内嵌于 JDBC、C#、Python、Go、Node.js 语言连接库里。应用都是通过 taosc 而不是直接连接集群中的数据节点与整个集群进行交互的。这个模块负责获取并缓存元数据;将插入、查询等请求转发到正确的数据节点;在把结果返回给应用时,还需要负责最后一级的聚合、排序、过滤等操作。对于 JDBC、C/C++、C#、Python、Go、Node.js 接口而言,这个模块是在应用所处的物理节点上运行。同时,为支持全分布式的 RESTful 接口,taosc 在 TDengine 集群的每个 dnode 上都有一运行实例。 + +### 节点之间的通讯 + +**通讯方式:**TDengine 系统的各个数据节点之间,以及应用驱动与各数据节点之间的通讯是通过 TCP/UDP 进行的。因为考虑到物联网场景,数据写入的包一般不大,因此 TDengine 除采用 TCP 做传输之外,还采用 UDP 方式,因为 UDP 更加高效,而且不受连接数的限制。TDengine 实现了自己的超时、重传、确认等机制,以确保 UDP 的可靠传输。对于数据量不到 15K 的数据包,采取 UDP 的方式进行传输,超过 15K 的,或者是查询类的操作,自动采取 TCP 的方式进行传输。同时,TDengine 根据配置和数据包,会自动对数据进行压缩/解压缩,数字签名/认证等处理。对于数据节点之间的数据复制,只采用 TCP 方式进行数据传输。 + +**FQDN 配置:**一个数据节点有一个或多个 FQDN,可以在系统配置文件 taos.cfg 通过参数"fqdn"进行指定,如果没有指定,系统将自动获取计算机的 hostname 作为其 FQDN。如果节点没有配置 FQDN,可以直接将该节点的配置参数 fqdn 设置为它的 IP 地址。但不建议使用 IP,因为 IP 地址可变,一旦变化,将让集群无法正常工作。一个数据节点的 EP(End Point) 由 FQDN + Port 组成。采用 FQDN,需要保证 DNS 服务正常工作,或者在节点以及应用所在的节点配置好 hosts 文件。另外,这个参数值的长度需要控制在 96 个字符以内。 + +**端口配置:**一个数据节点对外的端口由 TDengine 的系统配置参数 serverPort 决定,对集群内部通讯的端口是 serverPort+5。为支持多线程高效的处理 UDP 数据,每个对内和对外的 UDP 连接,都需要占用 5 个连续的端口。 + +- 集群内数据节点之间的数据复制操作占用一个 TCP 端口,是 serverPort+10。 +- 集群数据节点对外提供 RESTful 服务占用一个 TCP 端口,是 serverPort+11。 +- 集群内数据节点与 Arbitrator 节点之间通讯占用一个 TCP 端口,是 serverPort+12。 + +因此一个数据节点总的端口范围为 serverPort 到 serverPort+12,总共 13 个 TCP/UDP 端口。使用时,需要确保防火墙将这些端口打开。每个数据节点可以配置不同的 serverPort。(详细的端口情况请参见 [TDengine 2.0 端口说明](https://www.taosdata.com/cn/documentation/faq#port)) + +**集群对外连接:**TDengine 集群可以容纳单个、多个甚至几千个数据节点。应用只需要向集群中任何一个数据节点发起连接即可,连接需要提供的网络参数是一数据节点的 End Point(FQDN 加配置的端口号)。通过命令行 CLI 启动应用 taos 时,可以通过选项-h 来指定数据节点的 FQDN, -P 来指定其配置的端口号,如果端口不配置,将采用 TDengine 的系统配置参数 serverPort。 + +**集群内部通讯:**各个数据节点之间通过 TCP/UDP 进行连接。一个数据节点启动时,将获取 mnode 所在的 dnode 的 EP 信息,然后与系统中的 mnode 建立起连接,交换信息。获取 mnode 的 EP 信息有三步: + +1. 检查 mnodeEpSet.json 文件是否存在,如果不存在或不能正常打开获得 mnode EP 信息,进入第二步; +2. 检查系统配置文件 taos.cfg,获取节点配置参数 firstEp、secondEp(这两个参数指定的节点可以是不带 mnode 的普通节点,这样的话,节点被连接时会尝试重定向到 mnode 节点),如果不存在或者 taos.cfg 里没有这两个配置参数,或无效,进入第三步; +3. 将自己的 EP 设为 mnode EP,并独立运行起来。 + +获取 mnode EP 列表后,数据节点发起连接,如果连接成功,则成功加入进工作的集群,如果不成功,则尝试 mnode EP 列表中的下一个。如果都尝试了,但连接都仍然失败,则休眠几秒后,再进行尝试。 + +**MNODE 的选择:**TDengine 逻辑上有管理节点,但没有单独的执行代码,服务器侧只有一套执行代码 taosd。那么哪个数据节点会是管理节点呢?这是系统自动决定的,无需任何人工干预。原则如下:一个数据节点启动时,会检查自己的 End Point, 并与获取的 mnode EP List 进行比对,如果在其中,该数据节点认为自己应该启动 mnode 模块,成为 mnode。如果自己的 EP 不在 mnode EP List 里,则不启动 mnode 模块。在系统的运行过程中,由于负载均衡、宕机等原因,mnode 有可能迁移至新的 dnode,但一切都是透明的,无需人工干预,配置参数的修改,是 mnode 自己根据资源做出的决定。 + +**新数据节点的加入:**系统有了一个数据节点后,就已经成为一个工作的系统。添加新的节点进集群时,有两个步骤,第一步:使用 TDengine CLI 连接到现有工作的数据节点,然后用命令"create dnode"将新的数据节点的 End Point 添加进去; 第二步:在新的数据节点的系统配置参数文件 taos.cfg 里,将 firstEp, secondEp 参数设置为现有集群中任意两个数据节点的 EP 即可。具体添加的详细步骤请见详细的用户手册。这样就把集群一步一步的建立起来。 + +**重定向:**无论是 dnode 还是 taosc,最先都是要发起与 mnode 的连接,但 mnode 是系统自动创建并维护的,因此对于用户来说,并不知道哪个 dnode 在运行 mnode。TDengine 只要求向系统中任何一个工作的 dnode 发起连接即可。因为任何一个正在运行的 dnode,都维护有目前运行的 mnode EP List。当收到一个来自新启动的 dnode 或 taosc 的连接请求,如果自己不是 mnode,则将 mnode EP List 回复给对方,taosc 或新启动的 dnode 收到这个 list, 就重新尝试建立连接。当 mnode EP List 发生改变,通过节点之间的消息交互,各个数据节点就很快获取最新列表,并通知 taosc。 + +### 一个典型的消息流程 + +为解释 vnode、mnode、taosc 和应用之间的关系以及各自扮演的角色,下面对写入数据这个典型操作的流程进行剖析。 + +![TDengine典型的操作流程](/img/architecture/message.png) + +
图 2 TDengine 典型的操作流程
+ +1. 应用通过 JDBC 或其他 API 接口发起插入数据的请求。 +2. taosc 会检查缓存,看是否保存有该表的 meta data。如果有,直接到第 4 步。如果没有,taosc 将向 mnode 发出 get meta-data 请求。 +3. mnode 将该表的 meta-data 返回给 taosc。Meta-data 包含有该表的 schema, 而且还有该表所属的 vgroup 信息(vnode ID 以及所在的 dnode 的 End Point,如果副本数为 N,就有 N 组 End Point)。如果 taosc 迟迟得不到 mnode 回应,而且存在多个 mnode, taosc 将向下一个 mnode 发出请求。 +4. taosc 向 master vnode 发起插入请求。 +5. vnode 插入数据后,给 taosc 一个应答,表示插入成功。如果 taosc 迟迟得不到 vnode 的回应,taosc 会认为该节点已经离线。这种情况下,如果被插入的数据库有多个副本,taosc 将向 vgroup 里下一个 vnode 发出插入请求。 +6. taosc 通知 APP,写入成功。 + +对于第二和第三步,taosc 启动时,并不知道 mnode 的 End Point,因此会直接向配置的集群对外服务的 End Point 发起请求。如果接收到该请求的 dnode 并没有配置 mnode,该 dnode 会在回复的消息中告知 mnode EP 列表,这样 taosc 会重新向新的 mnode 的 EP 发出获取 meta-data 的请求。 + +对于第四和第五步,没有缓存的情况下,taosc 无法知道虚拟节点组里谁是 master,就假设第一个 vnodeID 就是 master,向它发出请求。如果接收到请求的 vnode 并不是 master,它会在回复中告知谁是 master,这样 taosc 就向建议的 master vnode 发出请求。一旦得到插入成功的回复,taosc 会缓存 master 节点的信息。 + +上述是插入数据的流程,查询、计算的流程也完全一致。taosc 把这些复杂的流程全部封装屏蔽了,对于应用来说无感知也无需任何特别处理。 + +通过 taosc 缓存机制,只有在第一次对一张表操作时,才需要访问 mnode,因此 mnode 不会成为系统瓶颈。但因为 schema 有可能变化,而且 vgroup 有可能发生改变(比如负载均衡发生),因此 taosc 会定时和 mnode 交互,自动更新缓存。 + +## 存储模型与数据分区、分片 + +### 存储模型 + +TDengine 存储的数据包括采集的时序数据以及库、表相关的元数据、标签数据等,这些数据具体分为三部分: + +- 时序数据:存放于 vnode 里,由 data、head 和 last 三个文件组成,数据量大,查询量取决于应用场景。容许乱序写入,但暂时不支持删除操作,并且仅在 update 参数设置为 1 时允许更新操作。通过采用一个采集点一张表的模型,一个时间段的数据是连续存储,对单张表的写入是简单的追加操作,一次读,可以读到多条记录,这样保证对单个采集点的插入和查询操作,性能达到最优。 +- 标签数据:存放于 vnode 里的 meta 文件,支持增删改查四个标准操作。数据量不大,有 N 张表,就有 N 条记录,因此可以全内存存储。如果标签过滤操作很多,查询将十分频繁,因此 TDengine 支持多核多线程并发查询。只要计算资源足够,即使有数千万张表,过滤结果能毫秒级返回。 +- 元数据:存放于 mnode 里,包含系统节点、用户、DB、Table Schema 等信息,支持增删改查四个标准操作。这部分数据的量不大,可以全内存保存,而且由于客户端有缓存,查询量也不大。因此目前的设计虽是集中式存储管理,但不会构成性能瓶颈。 + +与典型的 NoSQL 存储模型相比,TDengine 将标签数据与时序数据完全分离存储,它具有两大优势: + +- 能够极大地降低标签数据存储的冗余度:一般的 NoSQL 数据库或时序数据库,采用的 K-V 存储,其中的 Key 包含时间戳、设备 ID、各种标签。每条记录都带有这些重复的内容,浪费存储空间。而且如果应用要在历史数据上增加、修改或删除标签,需要遍历数据,重写一遍,操作成本极其昂贵。 +- 能够实现极为高效的多表之间的聚合查询:做多表之间聚合查询时,先把符合标签过滤条件的表查找出来,然后再查找这些表相应的数据块,这样大幅减少要扫描的数据集,从而大幅提高查询效率。而且标签数据采用全内存的结构进行管理和维护,千万级别规模的标签数据查询可以在毫秒级别返回。 + +### 数据分片 + +对于海量的数据管理,为实现水平扩展,一般都需要采取分片(Sharding)分区(Partitioning)策略。TDengine 是通过 vnode 来实现数据分片的,通过一个时间段一个数据文件来实现时序数据分区的。 + +vnode(虚拟数据节点)负责为采集的时序数据提供写入、查询和计算功能。为便于负载均衡、数据恢复、支持异构环境,TDengine 将一个数据节点根据其计算和存储资源切分为多个 vnode。这些 vnode 的管理是 TDengine 自动完成的,对应用完全透明。 + +对于单独一个数据采集点,无论其数据量多大,一个 vnode(或 vnode group, 如果副本数大于 1)有足够的计算资源和存储资源来处理(如果每秒生成一条 16 字节的记录,一年产生的原始数据不到 0.5G),因此 TDengine 将一张表(一个数据采集点)的所有数据都存放在一个 vnode 里,而不会让同一个采集点的数据分布到两个或多个 dnode 上。而且一个 vnode 可存储多个数据采集点(表)的数据,一个 vnode 可容纳的表的数目的上限为一百万。设计上,一个 vnode 里所有的表都属于同一个 DB。一个数据节点上,除非特殊配置,一个 DB 拥有的 vnode 数目不会超过系统核的数目。 + +创建 DB 时,系统并不会马上分配资源。但当创建一张表时,系统将看是否有已经分配的 vnode, 且该 vnode 是否有空余的表空间,如果有,立即在该有空位的 vnode 创建表。如果没有,系统将从集群中,根据当前的负载情况,在一个 dnode 上创建一新的 vnode, 然后创建表。如果 DB 有多个副本,系统不是只创建一个 vnode,而是一个 vgroup (虚拟数据节点组)。系统对 vnode 的数目没有任何限制,仅仅受限于物理节点本身的计算和存储资源。 + +每张表的 meta data(包含 schema, 标签等)也存放于 vnode 里,而不是集中存放于 mnode,实际上这是对 Meta 数据的分片,这样便于高效并行的进行标签过滤操作。 + +### 数据分区 + +TDengine 除 vnode 分片之外,还对时序数据按照时间段进行分区。每个数据文件只包含一个时间段的时序数据,时间段的长度由 DB 的配置参数 days 决定。这种按时间段分区的方法还便于高效实现数据的保留策略,只要数据文件超过规定的天数(系统配置参数 keep),将被自动删除。而且不同的时间段可以存放于不同的路径和存储介质,以便于大数据的冷热管理,实现多级存储。 + +总的来说,**TDengine 是通过 vnode 以及时间两个维度,对大数据进行切分**,便于并行高效的管理,实现水平扩展。 + +### 负载均衡 + +每个 dnode 都定时向 mnode(虚拟管理节点)报告其状态(包括硬盘空间、内存大小、CPU、网络、虚拟节点个数等),因此 mnode 了解整个集群的状态。基于整体状态,当 mnode 发现某个 dnode 负载过重,它会将 dnode 上的一个或多个 vnode 挪到其他 dnode。在挪动过程中,对外服务继续进行,数据插入、查询和计算操作都不受影响。 + +如果 mnode 一段时间没有收到 dnode 的状态报告,mnode 会认为这个 dnode 已经离线。如果离线时间超过一定时长(时长由配置参数 offlineThreshold 决定),该 dnode 将被 mnode 强制剔除出集群。该 dnode 上的 vnodes 如果副本数大于 1,系统将自动在其他 dnode 上创建新的副本,以保证数据的副本数。如果该 dnode 上还有 mnode, 而且 mnode 的副本数大于 1,系统也将自动在其他 dnode 上创建新的 mnode, 以保证 mnode 的副本数。 + +当新的数据节点被添加进集群,因为新的计算和存储被添加进来,系统也将自动启动负载均衡流程。 + +负载均衡过程无需任何人工干预,应用也无需重启,将自动连接新的节点,完全透明。 + +**提示:负载均衡由参数 balance 控制,决定开启/关闭自动负载均衡。** + +## 数据写入与复制流程 + +如果一个数据库有 N 个副本,那一个虚拟节点组就有 N 个虚拟节点,但是只有一个是 master,其他都是 slave。当应用将新的记录写入系统时,只有 master vnode 能接受写的请求。如果 slave vnode 收到写的请求,系统将通知 taosc 需要重新定向。 + +### Master Vnode 写入流程 + +Master Vnode 遵循下面的写入流程: + +![TDengine Master写入流程](/img/architecture/write_master.png) + +
图 3 TDengine Master 写入流程
+ +1. master vnode 收到应用的数据插入请求,验证 OK,进入下一步; +2. 如果系统配置参数 walLevel 大于 0,vnode 将把该请求的原始数据包写入数据库日志文件 WAL。如果 walLevel 设置为 2,而且 fsync 设置为 0,TDengine 还将 WAL 数据立即落盘,以保证即使宕机,也能从数据库日志文件中恢复数据,避免数据的丢失; +3. 如果有多个副本,vnode 将把数据包转发给同一虚拟节点组内的 slave vnodes, 该转发包带有数据的版本号(version); +4. 写入内存,并将记录加入到 skip list; +5. master vnode 返回确认信息给应用,表示写入成功。 +6. 如果第 2、3、4 步中任何一步失败,将直接返回错误给应用。 + +### Slave Vnode 写入流程 + +对于 slave vnode,写入流程是: + +![TDengine Slave 写入流程](/img/architecture/write_slave.png) + +
图 4 TDengine Slave 写入流程
+ +1. slave vnode 收到 Master vnode 转发了的数据插入请求。检查 last version 是否与 master 一致,如果一致,进入下一步。如果不一致,需要进入同步状态。 +2. 如果系统配置参数 walLevel 大于 0,vnode 将把该请求的原始数据包写入数据库日志文件 WAL。如果 walLevel 设置为 2,而且 fsync 设置为 0,TDengine 还将 WAL 数据立即落盘,以保证即使宕机,也能从数据库日志文件中恢复数据,避免数据的丢失。 +3. 写入内存,更新内存中的 skip list。 + +与 master vnode 相比,slave vnode 不存在转发环节,也不存在回复确认环节,少了两步。但写内存与 WAL 是完全一样的。 + +### 主从选择 + +Vnode 会保持一个数据版本号(version),对内存数据进行持久化存储时,对该版本号也进行持久化存储。每个数据更新操作,无论是采集的时序数据还是元数据,这个版本号将增加 1。 + +一个 vnode 启动时,角色(master、slave) 是不定的,数据是处于未同步状态,它需要与虚拟节点组内其他节点建立 TCP 连接,并互相交换 status,其中包括 version 和自己的角色。通过 status 的交换,系统进入选主流程,规则如下: + +1. 如果只有一个副本,该副本永远就是 master +2. 所有副本都在线时,版本最高的被选为 master +3. 在线的虚拟节点数过半,而且有虚拟节点是 slave 的话,该虚拟节点自动成为 master +4. 对于 2 和 3,如果多个虚拟节点满足成为 master 的要求,那么虚拟节点组的节点列表里,最前面的选为 master + +更多的关于数据复制的流程,请见[TDengine 2.0 数据复制模块设计](https://www.taosdata.com/cn/documentation/architecture/replica/)。 + +### 同步复制 + +对于数据一致性要求更高的场景,异步数据复制无法满足要求,因为有极小的概率丢失数据,因此 TDengine 提供同步复制的机制供用户选择。在创建数据库时,除指定副本数 replica 之外,用户还需要指定新的参数 quorum。如果 quorum 大于 1,它表示每次 master 转发给副本时,需要等待 quorum-1 个回复确认,才能通知应用,数据在 slave 已经写入成功。如果在一定的时间内,得不到 quorum-1 个回复确认,master vnode 将返回错误给应用。 + +采用同步复制,系统的性能会有所下降,而且 latency 会增加。因为元数据要强一致,mnode 之间的数据同步缺省就是采用的同步复制。 + +## 缓存与持久化 + +### 缓存 + +TDengine 采用时间驱动缓存管理策略(First-In-First-Out,FIFO),又称为写驱动的缓存管理机制。这种策略有别于读驱动的数据缓存模式(Least-Recent-Used,LRU),直接将最近写入的数据保存在系统的缓存中。当缓存达到临界值的时候,将最早的数据批量写入磁盘。一般意义上来说,对于物联网数据的使用,用户最为关心的是刚产生的数据,即当前状态。TDengine 充分利用这一特性,将最近到达的(当前状态)数据保存在缓存中。 + +TDengine 通过查询函数向用户提供毫秒级的数据获取能力。直接将最近到达的数据保存在缓存中,可以更加快速地响应用户针对最近一条或一批数据的查询分析,整体上提供更快的数据库查询响应能力。从这个意义上来说,**可通过设置合适的配置参数将 TDengine 作为数据缓存来使用,而不需要再部署 Redis 或其他额外的缓存系统**,可有效地简化系统架构,降低运维的成本。需要注意的是,TDengine 重启以后系统的缓存将被清空,之前缓存的数据均会被批量写入磁盘,缓存的数据将不会像专门的 key-value 缓存系统再将之前缓存的数据重新加载到缓存中。 + +每个 vnode 有自己独立的内存,而且由多个固定大小的内存块组成,不同 vnode 之间完全隔离。数据写入时,类似于日志的写法,数据被顺序追加写入内存,但每个 vnode 维护有自己的 skip list,便于迅速查找。当三分之一以上的内存块写满时,启动落盘操作,而且后续写的操作在新的内存块进行。这样,一个 vnode 里有三分之一内存块是保留有最近的数据的,以达到缓存、快速查找的目的。一个 vnode 的内存块的个数由配置参数 blocks 决定,内存块的大小由配置参数 cache 决定。 + +### 持久化存储 + +TDengine 采用数据驱动的方式让缓存中的数据写入硬盘进行持久化存储。当 vnode 中缓存的数据达到一定规模时,为了不阻塞后续数据的写入,TDengine 也会拉起落盘线程将缓存的数据写入持久化存储。TDengine 在数据落盘时会打开新的数据库日志文件,在落盘成功后则会删除老的数据库日志文件,避免日志文件无限制地增长。 + +为充分利用时序数据特点,TDengine 将一个 vnode 保存在持久化存储的数据切分成多个文件,每个文件只保存固定天数的数据,这个天数由系统配置参数 days 决定。切分成多个文件后,给定查询的起止日期,无需任何索引,就可以立即定位需要打开哪些数据文件,大大加快读取速度。 + +对于采集的数据,一般有保留时长,这个时长由系统配置参数 keep 决定。超过这个设置天数的数据文件,将被系统自动删除,释放存储空间。 + +给定 days 与 keep 两个参数,一个典型工作状态的 vnode 中总的数据文件数为:`向上取整(keep/days)+1`个。总的数据文件个数不宜过大,也不宜过小。10 到 100 以内合适。基于这个原则,可以设置合理的 days。目前的版本,参数 keep 可以修改,但对于参数 days,一旦设置后,不可修改。 + +在每个数据文件里,一张表的数据是一块一块存储的。一张表可以有一到多个数据文件块。在一个文件块里,数据是列式存储的,占用的是一片连续的存储空间,这样大大提高读取速度。文件块的大小由系统参数 maxRows (每块最大记录条数)决定,缺省值为 4096。这个值不宜过大,也不宜过小。过大,定位具体时间段的数据的搜索时间会变长,影响读取速度;过小,数据块的索引太大,压缩效率偏低,也影响读取速度。 + +每个数据文件(.data 结尾)都有一个对应的索引文件(.head 结尾),该索引文件对每张表都有一数据块的摘要信息,记录了每个数据块在数据文件中的偏移量,数据的起止时间等信息,以帮助系统迅速定位需要查找的数据。每个数据文件还有一对应的 last 文件(.last 结尾),该文件是为防止落盘时数据块碎片化而设计的。如果一张表落盘的记录条数没有达到系统配置参数 minRows(每块最小记录条数),将被先存储到 last 文件,等下次落盘时,新落盘的记录将与 last 文件的记录进行合并,再写入数据文件。 + +数据写入磁盘时,根据系统配置参数 comp 决定是否压缩数据。TDengine 提供了三种压缩选项:无压缩、一阶段压缩和两阶段压缩,分别对应 comp 值为 0、1 和 2 的情况。一阶段压缩根据数据的类型进行了相应的压缩,压缩算法包括 delta-delta 编码、simple 8B 方法、zig-zag 编码、LZ4 等算法。二阶段压缩在一阶段压缩的基础上又用通用压缩算法进行了压缩,压缩率更高。 + +### 多级存储 + +说明:多级存储功能仅企业版支持,从 2.0.16.0 版本开始提供。 + +在默认配置下,TDengine 会将所有数据保存在 /var/lib/taos 目录下,而且每个 vnode 的数据文件保存在该目录下的不同目录。为扩大存储空间,尽量减少文件读取的瓶颈,提高数据吞吐率 TDengine 可通过配置系统参数 dataDir 让多个挂载的硬盘被系统同时使用。 + +除此之外,TDengine 也提供了数据分级存储的功能,将不同时间段的数据存储在挂载的不同介质上的目录里,从而实现不同“热度”的数据存储在不同的存储介质上,充分利用存储,节约成本。比如,最新采集的数据需要经常访问,对硬盘的读取性能要求高,那么用户可以配置将这些数据存储在 SSD 盘上。超过一定期限的数据,查询需求量没有那么高,那么可以存储在相对便宜的 HDD 盘上。 + +多级存储支持 3 级,每级最多可配置 16 个挂载点。 + +TDengine 多级存储配置方式如下(在配置文件/etc/taos/taos.cfg 中): + +``` +dataDir [path] +``` + +- path: 挂载点的文件夹路径 +- level: 介质存储等级,取值为 0,1,2。 + 0 级存储最新的数据,1 级存储次新的数据,2 级存储最老的数据,省略默认为 0。 + 各级存储之间的数据流向:0 级存储 -> 1 级存储 -> 2 级存储。 + 同一存储等级可挂载多个硬盘,同一存储等级上的数据文件分布在该存储等级的所有硬盘上。 + 需要说明的是,数据在不同级别的存储介质上的移动,是由系统自动完成的,用户无需干预。 +- primary: 是否为主挂载点,0(否)或 1(是),省略默认为 1。 + +在配置中,只允许一个主挂载点的存在(level=0, primary=1),例如采用如下的配置方式: + +``` +dataDir /mnt/data1 0 1 +dataDir /mnt/data2 0 0 +dataDir /mnt/data3 1 0 +dataDir /mnt/data4 1 0 +dataDir /mnt/data5 2 0 +dataDir /mnt/data6 2 0 +``` + +注意: + +1. 多级存储不允许跨级配置,合法的配置方案有:仅 0 级,仅 0 级+ 1 级,以及 0 级+ 1 级+ 2 级。而不允许只配置 level=0 和 level=2,而不配置 level=1。 +2. 禁止手动移除使用中的挂载盘,挂载盘目前不支持非本地的网络盘。 +3. 多级存储目前不支持删除已经挂载的硬盘的功能。 + +## 数据查询 + +TDengine 提供了多种多样针对表和超级表的查询处理功能,除了常规的聚合查询之外,还提供针对时序数据的窗口查询、统计聚合等功能。TDengine 的查询处理需要客户端、vnode、mnode 节点协同完成。 + +### 单表查询 + +SQL 语句的解析和校验工作在客户端完成。解析 SQL 语句并生成抽象语法树(Abstract Syntax Tree, AST),然后对其进行校验和检查。以及向管理节点(mnode)请求查询中指定表的元数据信息(table metadata)。 + +根据元数据信息中的 End Point 信息,将查询请求序列化后发送到该表所在的数据节点(dnode)。dnode 接收到查询请求后,识别出该查询请求指向的虚拟节点(vnode),将消息转发到 vnode 的查询执行队列。vnode 的查询执行线程建立基础的查询执行环境,并立即返回该查询请求,同时开始执行该查询。 + +客户端在获取查询结果的时候,dnode 的查询执行队列中的工作线程会等待 vnode 执行线程执行完成,才能将查询结果返回到请求的客户端。 + +### 按时间轴聚合、降采样、插值 + +时序数据有别于普通数据的显著特征是每条记录均具有时间戳,因此针对具有时间戳的数据在时间轴上进行聚合是不同于普通数据库的重要功能。从这点上来看,与流计算引擎的窗口查询有相似的地方。 + +在 TDengine 中引入关键词 interval 来进行时间轴上固定长度时间窗口的切分,并按照时间窗口对数据进行聚合,对窗口范围内的数据按需进行聚合。例如: + +```sql +SELECT COUNT(*) FROM d1001 INTERVAL(1h); +``` + +针对 d1001 设备采集的数据,按照 1 小时的时间窗口返回每小时存储的记录数量。 + +在需要连续获得查询结果的应用场景下,如果给定的时间区间存在数据缺失,会导致该区间数据结果也丢失。TDengine 提供策略针对时间轴聚合计算的结果进行插值,通过使用关键词 fill 就能够对时间轴聚合结果进行插值。例如: + +```sql +SELECT COUNT(*) FROM d1001 WHERE ts >= '2017-7-14 00:00:00' AND ts < '2017-7-14 23:59:59' INTERVAL(1h) FILL(PREV); +``` + +针对 d1001 设备采集数据统计每小时记录数,如果某一个小时不存在数据,则返回之前一个小时的统计数据。TDengine 提供前向插值(prev)、线性插值(linear)、NULL 值填充(NULL)、特定值填充(value)。 + +### 多表聚合查询 + +TDengine 对每个数据采集点单独建表,但在实际应用中经常需要对不同的采集点数据进行聚合。为高效的进行聚合操作,TDengine 引入超级表(STable)的概念。超级表用来代表一特定类型的数据采集点,它是包含多张表的表集合,集合里每张表的模式(schema)完全一致,但每张表都带有自己的静态标签,标签可以有多个,可以随时增加、删除和修改。应用可通过指定标签的过滤条件,对一个 STable 下的全部或部分表进行聚合或统计操作,这样大大简化应用的开发。其具体流程如下图所示: + +![多表聚合查询原理图](/img/architecture/multi_tables.png) + +
图 5 多表聚合查询原理图
+ +1. 应用将一个查询条件发往系统; +2. taosc 将超级表的名字发往 meta node(管理节点); +3. 管理节点将超级表所拥有的 vnode 列表发回 taosc; +4. taosc 将计算的请求连同标签过滤条件发往这些 vnode 对应的多个数据节点; +5. 每个 vnode 先在内存里查找出自己节点里符合标签过滤条件的表的集合,然后扫描存储的时序数据,完成相应的聚合计算,将结果返回给 taosc; +6. taosc 将多个数据节点返回的结果做最后的聚合,将其返回给应用。 + +由于 TDengine 在 vnode 内将标签数据与时序数据分离存储,通过在内存里过滤标签数据,先找到需要参与聚合操作的表的集合,将需要扫描的数据集大幅减少,大幅提升聚合计算速度。同时,由于数据分布在多个 vnode/dnode,聚合计算操作在多个 vnode 里并发进行,又进一步提升了聚合的速度。 对普通表的聚合函数以及绝大部分操作都适用于超级表,语法完全一样,细节请看 TAOS SQL。 + +### 预计算 + +为有效提升查询处理的性能,针对物联网数据的不可更改的特点,在数据块头部记录该数据块中存储数据的统计信息:包括最大值、最小值、和。我们称之为预计算单元。如果查询处理涉及整个数据块的全部数据,直接使用预计算结果,完全不需要读取数据块的内容。由于预计算数据量远小于磁盘上存储的数据块数据的大小,对于磁盘 I/O 为瓶颈的查询处理,使用预计算结果可以极大地减小读取 I/O 压力,加速查询处理的流程。预计算机制与 Postgre SQL 的索引 BRIN(block range index)有异曲同工之妙。 diff --git a/docs-cn/13-tdinternal/02-replica.md b/docs-cn/13-tdinternal/02-replica.md new file mode 100644 index 0000000000000000000000000000000000000000..037ce0682ade1677da00287dd5f30696c3eaf17b --- /dev/null +++ b/docs-cn/13-tdinternal/02-replica.md @@ -0,0 +1,257 @@ +--- +sidebar_label: 数据复制模块设计 +--- + +# 数据复制模块设计 + +## 数据复制概述 + +数据复制(Replication)是指同一份数据在多个物理地点保存。它的目的是防止数据丢失,提高系统的高可用性(High Availability),而且通过应用访问多个副本,提升数据查询性能。 + +在高可靠的大数据系统里,数据复制是必不可少的一大功能。数据复制又分为实时复制与非实时复制。实时复制是指任何数据的更新(包括数据的增加、删除、修改)操作,会被实时的复制到所有副本,这样任何一台机器宕机或网络出现故障,整个系统还能提供最新的数据,保证系统的正常工作。而非实时复制,是指传统的数据备份操作,按照固定的时间周期,将一份数据全量或增量复制到其他地方。如果主节点宕机,副本是很大可能没有最新数据,因此在有些场景是无法满足要求的。 + +TDengine面向的是物联网场景,需要支持数据的实时复制,来最大程度保证系统的可靠性。实时复制有两种方式,一种是异步复制,一种是同步复制。异步复制(Asynchronous Replication)是指数据由Master转发给Slave后,Master并不需要等待Slave回复确认,这种方式效率高,但有极小的概率会丢失数据。同步复制是指Master将数据转发给Slave后,需要等待Slave的回复确认,才会通知应用写入成功,这种方式效率偏低,但能保证数据绝不丢失。 + +数据复制是与数据存储(写入、读取)密切相关的,但两者又是相对独立,可以完全脱耦的。在TDengine系统中,有两种不同类型的数据,一种是时序数据,由TSDB模块负责;一种是元数据(Meta Data), 由MNODE负责。这两种性质不同的数据都需要同步功能。数据复制模块通过不同的实例启动配置参数,为这两种类型数据都提供同步功能。 + +在阅读本文之前,请先阅读《[TDengine 2.0 整体架构](https://www.taosdata.com/cn/documentation/architecture/)》,了解TDengine的集群设计和基本概念 + +特别注明:本文中提到数据更新操作包括数据的增加、删除与修改。 + +## 基本概念和定义 + +TDengine里存在vnode, mnode, vnode用来存储时序数据,mnode用来存储元数据。但从同步数据复制的模块来看,两者没有本质的区别,因此本文里的虚拟节点不仅包括vnode, 也包括mnode, vgroup也指mnode group, 除非特别注明。 + +**版本(version)**: + +一个虚拟节点组里多个虚拟节点互为备份,来保证数据的有效与可靠,是依靠虚拟节点组的数据版本号来维持的。TDengine2.0设计里,对于版本的定义如下:客户端发起增加、删除、修改的流程,无论是一条记录还是多条,只要是在一个请求里,这个数据更新请求被TDengine的一个虚拟节点收到后,经过合法性检查后,可以被写入系统时,就会被分配一个版本号。这个版本号在一个虚拟节点里从1开始,是单调连续递增的。无论这条记录是采集的时序数据还是meta data, 一样处理。当Master转发一个写入请求到slave时,必须带上版本号。一个虚拟节点将一数据更新请求写入WAL时,需要带上版本号。 + +不同虚拟节点组的数据版本号是完全独立的,互不相干的。版本号本质上是数据更新记录的transaction ID,但用来标识数据集的版本。 + +**角色(role):** + +一个虚拟节点可以是master, slave, unsynced或offline状态。 + +- master: 具有最新的数据,容许客户端往里写入数据,一个虚拟节点组,至多一个master. +- slave:与master是同步的,但不容许客户端往里写入数据,根据配置,可以容许客户端对其进行查询。 +- unsynced: 节点处于非同步状态,比如虚拟节点刚启动、或与其他虚拟节点的连接出现故障等。处于该状态时,该虚拟节点既不能提供写入,也不能提供查询服务。 +- offline: 由于宕机或网络原因,无法访问到某虚拟节点时,其他虚拟节点将该虚拟节点标为离线。但请注意,该虚拟节点本身的状态可能是unsynced或其他,但不会是离线。 + +**Quorum:** + +指数据写入成功所需要的确认数。对于异步复制,quorum设为1,具有master角色的虚拟节点自己确认即可。对于同步复制,需要至少大于等于2。原则上,Quorum >=1 并且 Quorum <= replication(副本数)。这个参数在启动一个同步模块实例时需要提供。 + +**WAL:** + +TDengine的WAL(Write Ahead Log)与cassandra的commit log, mySQL的bin log, Postgres的WAL没本质区别。没有写入数据库文件,还保存在内存的数据都会先存在WAL。当数据已经成功写入数据库数据文件,相应的WAL会被删除。但需要特别指明的是,在TDengine系统里,有几点: + +- 每个虚拟节点有自己独立的wal +- WAL里包含而且仅仅包含来自客户端的数据更新操作,每个更新操作都会被打上一个版本号 + +**复制实例:** + +复制模块只是一可执行的代码,复制实例是指正在运行的复制模块的一个实例,一个节点里,可以存在多个实例。原则上,一个节点有多少虚拟节点,就可以启动多少实例。对于副本数为1的场景,应用可以决定是否需要启动同步实例。应用启动一个同步模块的实例时,需要提供的就是虚拟节点组的配置信息,包括: + +- 虚拟节点个数,即replication number +- 各虚拟节点所在节点的信息,包括node的end point +- quorum, 需要的数据写入成功的确认数 +- 虚拟节点的初始版本号 + +## 数据复制模块的基本工作原理 + +TDengine采取的是Master-Slave模式进行同步,与流行的RAFT一致性算法比较一致。总结下来,有几点: + +1. 一个vgroup里有一到多个虚拟节点,每个虚拟节点都有自己的角色 +2. 客户端只能向角色是master的虚拟节点发起数据更新操作,因为master具有最新版本的数据,如果向非Master发起数据更新操作,会直接收到错误 +3. 客户端可以向master, 也可以向角色是Slave的虚拟节点发起查询操作,但不能对unsynced的虚拟节点发起任何操作 +4. 如果master不存在,这个vgroup是不能对外提供数据更新和查询服务的 +5. master收到客户端的数据更新操作时,会将其转发给slave节点 +6. 一个虚拟节点的版本号比master低的时候,会发起数据恢复流程,成功后,才会成为slave + +数据实时复制有三个主要流程:选主、数据转发、数据恢复。后续做详细讨论。 + +## 虚拟节点之间的网络连接 + +虚拟节点之间通过TCP进行连接,节点之间的状态交换、数据包的转发都是通过这个TCP连接(peerFd)进行。为避免竞争,两个虚拟节点之间的TCP连接,总是由IP地址(UINT32)小的节点作为TCP客户端发起。一旦TCP连接被中断,虚拟节点能通过TCP socket自动检测到,将对方标为offline。如果监测到任何错误(比如数据恢复流程),虚拟节点将主动重置该连接。 + +一旦作为客户端的节点连接不成或中断,它将周期性的每隔一秒钟去试图去连接一次。因为TCP本身有心跳机制,虚拟节点之间不再另行提供心跳。 + +如果一个unsynced节点要发起数据恢复流程,它与Master将建立起专有的TCP连接(syncFd)。数据恢复完成后,该连接会被关闭。而且为限制资源的使用,系统只容许一定数量(配置参数tsMaxSyncNum)的数据恢复的socket存在。如果超过这个数字,系统会将新的数据恢复请求延后处理。 + +任意一个节点,无论有多少虚拟节点,都会启动而且只会启动一个TCP server, 来接受来自其他虚拟节点的上述两类TCP的连接请求。当TCP socket建立起来,客户端侧发送的消息体里会带有vgId(全局唯一的vgroup ID), TCP 服务器侧会检查该vgId是否已经在该节点启动运行。如果已经启动运行,就接受其请求。如果不存在,就直接将连接请求关闭。在TDengine代码里,mnode group的vgId设置为1。 + +## 选主流程 + +当同一组的两个虚拟节点之间(vnode A, vnode B)建立连接后,他们互换status消息。status消息里包含本地存储的同一虚拟节点组内所有虚拟节点的role和version。 + +如果一个虚拟节点(vnode A)检测到与同一虚拟节点组内另外一虚拟节点(vnode B)的连接中断,vnode A将立即把vnode B的role设置为offline。无论是接收到另外一虚拟节点发来的status消息,还是检测与另外一虚拟节点的连接中断,该虚拟节点都将进入状态处理流程。状态处理流程的规则如下: + +1. 如果检测到在线的节点数没有超过一半,则将自己的状态设置为unsynced. +2. 如果在线的虚拟节点数超过一半,会检查master节点是否存在,如果存在,则会决定是否将自己状态改为slave或启动数据恢复流程。 +3. 如果master不存在,则会检查自己保存的各虚拟节点的状态信息与从另一节点接收到的是否一致,如果一致,说明节点组里状态已经稳定一致,则会触发选举流程。如果不一致,说明状态还没趋于一致,即使master不存在,也不进行选主。由于要求状态信息一致才进行选举,每个虚拟节点根据同样的信息,会选出同一个虚拟节点做master,无需投票表决。 +4. 自己的状态是根据规则自己决定并修改的,并不需要其他节点同意,包括成为master。一个节点无权修改其他节点的状态。 +5. 如果一个虚拟节点检测到自己或其他虚拟节点的role发生改变,该节点会广播它自己保存的各个虚拟节点的状态信息(role和version)。 + +具体的流程图如下: + +![replica-master.png](/img/architecture/replica-master.png) + +选择Master的具体规则如下: + +1. 如果只有一个副本,该副本永远就是master +2. 所有副本都在线时,版本最高的被选为master +3. 在线的虚拟节点数过半,而且有虚拟节点是slave的话,该虚拟节点自动成为master +4. 对于2和3,如果多个虚拟节点满足成为master的要求,那么虚拟节点组的节点列表里,最前面的选为master + +按照上面的规则,如果所有虚拟节点都是unsynced(比如全部重启),只有所有虚拟节点上线,才能选出master,该虚拟节点组才能开始对外提供服务。当一个虚拟节点的role发生改变时,sync模块回通过回调函数notifyRole通知应用。 + +## 数据转发流程 + +如果vnode A是master, vnode B是slave, vnode A能接受客户端的写请求,而vnode B不能。当vnode A收到写的请求后,遵循下面的流程: + +![replica-forward.png](/img/architecture/replica-forward.png) + +1. 应用对写请求做基本的合法性检查,通过,则给该请求包打上一个版本号(version, 单调递增) +2. 应用将打上版本号的写请求封装一个WAL Head, 写入WAL(Write Ahead Log) +3. 应用调用API syncForwardToPeer,如果vnode B是slave状态,sync模块将包含WAL Head的数据包通过Forward消息发送给vnode B,否则就不转发。 +4. vnode B收到Forward消息后,调用回调函数writeToCache, 交给应用处理 +5. vnode B应用在写入成功后,都需要调用syncConfirmForward通知sync模块已经写入成功。 +6. 如果quorum大于1,vnode B需要等待应用的回复确认,收到确认后,vnode B发送Forward Response消息给node A。 +7. 如果quorum大于1,vnode A需要等待vnode B或其他副本对Forward消息的确认。 +8. 如果quorum大于1,vnode A收到quorum-1条确认消息后,调用回调函数confirmForward,通知应用写入成功。 +9. 如果quorum为1,上述6,7,8步不会发生。 +10. 如果要等待slave的确认,master会启动2秒的定时器(可配置),如果超时,则认为失败。 + +对于回复确认,sync模块提供的是异步回调函数,因此APP在调用syncForwardToPeer之后,无需等待,可以处理下一个操作。在Master与Slave的TCP连接管道里,可能有多个Forward消息,这些消息是严格按照应用提供的顺序排好的。对于Forward Response也是一样,TCP管道里存在多个,但都是排序好的。这个顺序,SYNC模块并没有做特别的事情,是由APP单线程顺序写来保证的(TDengine里每个vnode的写数据,都是单线程)。 + +## 数据恢复流程 + +如果一虚拟节点(vnode B) 处于unsynced状态,master存在(vnode A),而且其版本号比master的低,它将立即启动数据恢复流程。在理解恢复流程时,需要澄清几个关于文件的概念和处理规则。 + +1. 每个文件(无论是archived data的file还是wal)都有一个index, 这需要应用来维护(vnode里,该index就是fileId*3 + 0/1/2, 对应data, head与last三个文件)。如果index为0,表示系统里最老的数据文件。对于mode里的文件,数量是固定的,对应于acct, user, db, table等文件。 +2. 任何一个数据文件(file)有名字、大小,还有一个magic number。只有文件名、大小与magic number一致时,两个文件才判断是一样的,无需同步。Magic number可以是checksum, 也可以是简单的文件大小。怎么计算magic,换句话说,如何检测数据文件是否有效,完全由应用决定。 +3. 文件名的处理有点复杂,因为每台服务器的路径可能不一致。比如node A的TDengine的数据文件存放在 /etc/taos目录下,而node B的数据存放在 /home/jhtao目录下。因此同步模块需要应用在启动一个同步实例时提供一个path,这样两台服务器的绝对路径可以不一样,但仍然可以做对比,做同步。 +4. 当sync模块调用回调函数getFileInfo获得数据文件信息时,有如下的规则 + * index 为0,表示获取最老的文件,同时修改index返回给sync模块。如果index不为0,表示获取指定位置的文件。 + * 如果name为空,表示sync想获取位于index位置的文件信息,包括magic, size。Master节点会这么调用 + * 如果name不为空,表示sync想获取指定文件名和index的信息,slave节点会这么调用 + * 如果某个index的文件不存在,magic返回0,表示文件已经是最后一个。因此整个系统里,文件的index必须是连续的一段整数。 +5. 当sync模块调用回调函数getWalInfo获得wal信息时,有如下规则 + * index为0,表示获得最老的WAL文件, 返回时,index更新为具体的数字 + * 如果返回0,表示这是最新的一个WAL文件,如果返回值是1,表示后面还有更新的WAL文件 + * 返回的文件名为空,那表示没有WAL文件 +6. 无论是getFileInfo, 还是getWalInfo, 只要获取出错(不是文件不存在),返回-1即可,系统会报错,停止同步 + +整个数据恢复流程分为两大步骤,第一步,先恢复archived data(file), 然后恢复wal。具体流程如下: + +![replica-restore.png](/img/architecture/replica-restore.png) + +1. 通过已经建立的TCP连接,发送sync req给master节点 +2. master收到sync req后,以client的身份,向vnode B主动建立一新的专用于同步的TCP连接(syncFd) +3. 新的TCP连接建立成功后,master将开始retrieve流程,对应的,vnode B将同步启动restore流程 +4. Retrieve/Restore流程里,先处理所有archived data (vnode里的data, head, last文件),后处理WAL data。 +5. 对于archived data,master将通过回调函数getFileInfo获取数据文件的基本信息,包括文件名、magic以及文件大小。 +6. master 将获得的文件名、magic以及文件大小发给vnode B +7. vnode B将回调函数getFile获得magic和文件大小,如果两者一致,就认为无需同步,如果两者不一致 ,就认为需要同步。vnode B将结果通过消息FileAck发回master +8. 如果文件需要同步,master就调用sendfile把整个文件发往vnode B +9. 如果文件不需要同步,master(vnode A)就重复5,6,7,8,直到所有文件被处理完 + +对于WAL同步,流程如下: + +1. master节点调用回调函数getWalInfo,获取WAL的文件名。 +2. 如果getWalInfo返回值大于0,表示该文件还不是最后一个WAL,因此master调用sendfile一下把该文件发送给vnode B +3. 如果getWalInfo返回时为0,表示该文件是最后一个WAL,因为文件可能还处于写的状态中,sync模块要根据WAL Head的定义逐条读出记录,然后发往vnode B。 +4. vnode A读取TCP连接传来的数据,按照WAL Head,逐条读取,如果版本号比现有的大,调用回调函数writeToCache,交给应用处理。如果小,直接扔掉。 +5. 上述流程循环,直到所有WAL文件都被处理完。处理完后,master就会将新来的数据包通过Forward消息转发给slave。 + +从同步文件启动起,sync模块会通过inotify监控所有处理过的file以及wal。一旦发现被处理过的文件有更新变化,同步流程将中止,会重新启动。因为有可能落盘操作正在进行(比如历史数据导入,内存数据落盘),把已经处理过的文件进行了修改,需要重新同步才行。 + +对于最后一个WAL (LastWal)的处理逻辑有点复杂,因为这个文件往往是打开写的状态,有很多场景需要考虑,比如: + +- LastWal文件size在增长,需要重新读; +- LastWal文件虽然已经打开写,但内容为空; +- LastWal文件已经被关闭,应用生成了新的Last WAL文件; +- LastWal文件没有被关闭,但数据落盘的原因,没有读到完整的一条记录; +- LastWal文件没有被关闭,但数据落盘的原因,还有部分记录暂时读取不到; + +sync模块通过inotify监控LastWal文件的更新和关闭操作。而且在确认已经尽可能读完LastWal的数据后,会将对方同步状态设置为SYNC_CACHE。该状态下,master节点会将新的记录转发给vnode B,而此时vnode B并没有完成同步,需要把这些转发包先存在recv buffer里,等WAL处理完后,vnode A再把recv buffer里的数据包通过回调writeToCache交给应用处理。 + +等vnode B把这些buffered forwards处理完,同步流程才算结束,vnode B正式变为slave。 + +## Master分布均匀性问题 + +因为Master负责写、转发,消耗的资源会更多,因此Master在整个集群里分布均匀比较理想。 + +但在TDengine的设计里,如果多个虚拟节点都符合master条件,TDengine选在列表中最前面的做Master, 这样是否导致在集群里,Master数量的分布不均匀问题呢?这取决于应用的设计。 + +给一个具体例子,系统里仅仅有三个节点,IP地址分别为IP1, IP2, IP3. 在各个节点上,TDengine创建了多个虚拟节点组,每个虚拟节点组都有三个副本。如果三个副本的顺序在所有虚拟节点组里都是IP1, IP2, IP3, 那毫无疑问,master将集中在IP1这个节点,这是我们不想看到的。 + +但是,如果在创建虚拟节点组时,增加随机性,这个问题就不存在了。比如在vgroup 1, 顺序是IP1, IP2, IP3, 在vgroup 2里,顺序是IP2, IP3, IP1, 在vgroup 3里,顺序是IP3, IP1, IP2。最后master的分布会是均匀的。 + +因此在创建一个虚拟节点组时,应用需要保证节点的顺序是round robin或完全随机。 + +## 少数虚拟节点写入成功的问题 + +在某种情况下,写入成功的确认数大于0,但小于配置的Quorum, 虽然有虚拟节点数据更新成功,master仍然会认为数据更新失败,并通知客户端写入失败。 + +这个时候,系统存在数据不一致的问题,因为有的虚拟节点已经写入成功,而有的写入失败。一个处理方式是,Master重置(reset)与其他虚拟节点的连接,该虚拟节点组将自动进入选举流程。按照规则,已经成功写入数据的虚拟节点将成为新的master,组内的其他虚拟节点将从master那里恢复数据。 + +因为写入失败,客户端会重新写入数据。但对于TDengine而言,是OK的。因为时序数据都是有时间戳的,时间戳相同的数据更新操作,第一次会执行,但第二次会自动扔掉。对于Meta Data(增加、删除库、表等等)的操作,也是OK的。一张表、库已经被创建或删除,再创建或删除,不会被执行的。 + +在TDengine的设计里,虚拟节点与虚拟节点之间,是一个TCP连接,是一个pipeline,数据块一个接一个按顺序在这个pipeline里等待处理。一旦某个数据块的处理失败,这个连接会被重置,后续的数据块的处理都会失败。因此不会存在Pipeline里一个数据块更新失败,但下一个数据块成功的可能。 + +## Split Brain的问题 + +选举流程中,有个强制要求,那就是一定有超过半数的虚拟节点在线。但是如果replication正好是偶数,这个时候,完全可能存在splt brain问题。 + +为解决这个问题,TDengine提供Arbitrator的解决方法。Arbitrator是一个节点,它的任务就是接受任何虚拟节点的连接请求,并保持它。 + +在启动复制模块实例时,在配置参数中,应用可以提供Arbitrator的IP地址。如果是奇数个副本,复制模块不会与这个arbitrator去建立连接,但如果是偶数个副本,就会主动去建立连接。 + +Arbitrator的程序tarbitrator.c在复制模块的同一目录, 编译整个系统时,会在bin目录生成。命令行参数“-?”查看可以配置的参数,比如绑定的IP地址,监听的端口号。 + +## 与RAFT相比的异同 + +数据一致性协议流行的有两种,Paxos与Raft. 本设计的实现与Raft有很多类同之处,下面做一些比较 + +相同之处: + +- 三大流程一致:Raft里有Leader election, replication, safety,完全对应TDengine的选举、数据转发、数据恢复三个流程。 +- 节点状态定义一致:Raft里每个节点有Leader, Follower, Candidate三个状态,TDengine里是Master, Slave, Unsynced, Offline。多了一个offlince, 但本质上是一样的,因为offline是外界看一个节点的状态,但该节点本身是处于master, slave 或unsynced的。 +- 数据转发流程完全一样,Master(leader)需要等待回复确认。 +- 数据恢复流程几乎一样,Raft没有涉及历史数据同步问题,只考虑了WAL数据同步。 + +不同之处: + +- 选举流程不一样:Raft里任何一个节点是candidate时,主动向其他节点发出vote request,如果超过半数回答Yes,这个candidate就成为Leader,开始一个新的term。而TDengine的实现里,节点上线、离线或角色改变都会触发状态消息在节点组内传播,等节点组里状态稳定一致之后才触发选举流程,因为状态稳定一致,基于同样的状态信息,每个节点做出的决定会是一致的,一旦某个节点符合成为master的条件,无需其他节点认可,它会自动将自己设为master。TDengine里,任何一个节点检测到其他节点或自己的角色发生改变,就会向节点组内其他节点进行广播。Raft里不存在这样的机制,因此需要投票来解决。 +- 对WAL的一条记录,Raft用term + index来做唯一标识。但TDengine只用version(类似index),在TDengine实现里,仅仅用version是完全可行的, 因为TDengine的选举机制,没有term的概念。 + +如果整个虚拟节点组全部宕机,重启,但不是所有虚拟节点都上线,这个时候TDengine是不会选出master的,因为未上线的节点有可能有最高version的数据。而RAFT协议,只要超过半数上线,就会选出Leader。 + +## Meta Data的数据复制 + +TDengine里存在时序数据,也存在Meta Data。Meta Data对数据的可靠性要求更高,那么TDengine设计能否满足要求呢?下面做个仔细分析。 + +TDengine里Meta Data包括以下: + +- account 信息 +- 一个account下面,可以有多个user, 多个DB +- 一个DB下面有多个vgroup +- 一个DB下面有多个stable +- 一个vgroup下面有多个table +- 整个系统有多个mnode, dnode +- 一个dnode可以有多个vnode + +上述的account, user, DB, vgroup, table, stable, mnode, dnode都有自己的属性,这些属性是TDengine自己定义的,不会开放给用户进行修改。这些Meta Data的查询都比较简单,都可以采用key-value模型进行存储。这些Meta Data还具有几个特点: + +1. 上述的Meta Data之间有一定的层级关系,比如必须先创建DB,才能创建table, stable。只有先创建dnode,才可能创建vnode, 才可能创建vgroup。因此他们创建的顺序是绝对不能错的。 +2. 在客户端应用的数据更新操作得到TDengine服务器侧确认后,所执行的数据更新操作绝对不能丢失。否则会造成客户端应用与服务器的数据不一致。 +3. 上述的Meta Data是容许重复操作的。比如插入新记录后,再插入一次,删除一次后,再删除一次,更新一次后,再更新一次,不会对系统产生任何影响,不会改变系统任何状态。 + +对于特点1,本设计里,数据的写入是单线程的,按照到达的先后顺序,给每个数据更新操作打上版本号,版本号大的记录一定是晚于版本号小的写入系统,数据写入顺序是100%保证的,绝对不会让版本号大的记录先写入。复制过程中,数据块的转发也是严格按照顺序进行的,因此TDengine的数据复制设计是能保证Meta Data的创建顺序的。 + +对于特点2,只要Quorum数设置等于replica,那么一定能保证回复确认过的数据更新操作不会在服务器侧丢失。即使某节点永不起来,只要超过一半的节点还是online, 查询服务不会受到任何影响。这时,如果某个节点离线超过一定时长,系统可以自动补充新的节点,以保证在线的节点数在绝大部分时间是100%的。 + +对于特点3,完全可能发生,服务器确实持久化存储了某一数据更新操作,但客户端应用出了问题,认为操作不成功,它会重新发起操作。但对于Meta Data而言,没有关系,客户端可以再次发起同样的操作,不会有任何影响。 + +总结来看,只要quorum设置大于一,本数据复制的设计是能满足Meta Data的需求的。目前,还没有发现漏洞。 diff --git a/docs-cn/13-tdinternal/03-taosd.md b/docs-cn/13-tdinternal/03-taosd.md new file mode 100644 index 0000000000000000000000000000000000000000..874fa230290016b88fbc905233745a1052ca5a18 --- /dev/null +++ b/docs-cn/13-tdinternal/03-taosd.md @@ -0,0 +1,121 @@ +--- +sidebar_label: taosd 的设计 +--- + +# taosd的设计 + +逻辑上,TDengine系统包含dnode, taosc和App,dnode是服务器侧执行代码taosd的一个运行实例,因此taosd是TDengine的核心,本文对taosd的设计做一简单的介绍,模块内的实现细节请见其他文档。 + +## 系统模块图 + +taosd包含rpc, dnode, vnode, tsdb, query, cq, sync, wal, mnode, http, monitor等模块,具体如下图: + +![modules.png](/img/architecture/modules.png) + +taosd的启动入口是dnode模块,dnode然后启动其他模块,包括可选配置的http, monitor模块。taosc或dnode之间交互的消息都是通过rpc模块进行,dnode模块根据接收到的消息类型,将消息分发到vnode或mnode的消息队列,或由dnode模块自己消费。dnode的工作线程(worker)消费消息队列里的消息,交给mnode或vnode进行处理。下面对各个模块做简要说明。 + +## RPC模块 + +该模块负责taosd与taosc, 以及其他数据节点之间的通讯。TDengine没有采取标准的HTTP或gRPC等第三方工具,而是实现了自己的通讯模块RPC。 + +考虑到物联网场景下,数据写入的包一般不大,因此除支持TCP连接之外,RPC还支持UDP连接。当数据包小于15K时,RPC将采用UDP方式进行连接,否则将采用TCP连接。对于查询类的消息,RPC不管包的大小,总是采取TCP连接。对于UDP连接,RPC实现了自己的超时、重传、顺序检查等机制,以保证数据可靠传输。 + +RPC模块还提供数据压缩功能,如果数据包的字节数超过系统配置参数compressMsgSize, RPC在传输中将自动压缩数据,以节省带宽。 + +为保证数据的安全和数据的integrity, RPC模块采用MD5做数字签名,对数据的真实性和完整性进行认证。 + +## DNODE模块 + +该模块是整个taosd的入口,它具体负责如下任务: + +- 系统的初始化,包括 + - 从文件taos.cfg读取系统配置参数,从文件dnodeCfg.json读取数据节点的配置参数; + - 启动RPC模块,并建立起与taosc通讯的server连接,与其他数据节点通讯的server连接; + - 启动并初始化dnode的内部管理, 该模块将扫描该数据节点已有的vnode,并打开它们; + - 初始化可配置的模块,如mnode, http, monitor等。 +- 数据节点的管理,包括 + - 定时的向mnode发送status消息,报告自己的状态; + - 根据mnode的指示,创建、改变、删除vnode; + - 根据mnode的指示,修改自己的配置参数; +- 消息的分发、消费,包括 + - 为每一个vnode和mnode的创建并维护一个读队列、一个写队列; + - 将从taosc或其他数据节点来的消息,根据消息类型,将其直接分发到不同的消息队列,或由自己的管理模块直接消费; + - 维护一个读的线程池,消费读队列的消息,交给vnode或mnode处理。为支持高并发,一个读线程(Worker)可以消费多个队列的消息,一个读队列可以由多个worker消费; + - 维护一个写的线程池,消费写队列的消息,交给vnode或mnode处理。为保证写操作的序列化,一个写队列只能由一个写线程负责,但一个写线程可以负责多个写队列。 + +taosd的消息消费由dnode通过读写线程池进行控制,是系统的中枢。该模块内的结构体图如下: + +![dnode.png](/img/architecture/dnode.png) + +## VNODE模块 + +vnode是一独立的数据存储查询逻辑单元,但因为一个vnode只能容许一个DB,因此vnode内部没有account, DB, user等概念。为实现更好的模块化、封装以及未来的扩展,它有很多子模块,包括负责存储的TSDB,负责查询的Query, 负责数据复制的sync,负责数据库日志的的wal, 负责连续查询的cq(continuous query), 负责事件触发的流计算的event等模块,这些子模块只与vnode模块发生关系,与其他模块没有任何调用关系。模块图如下: + +![vnode.png](/img/architecture/vnode.png) + +vnode模块向下,与dnodeVRead,dnodeVWrite发生互动,向上,与子模块发生互动。它主要的功能有: + +- 协调各个子模块的互动。各个子模块之间都不直接调用,都需要通过vnode模块进行; +- 对于来自taosc或mnode的写操作,vnode模块将其分解为写日志(wal), 转发(sync), 本地存储(tsdb)子模块的操作; +- 对于查询操作,分发到query模块进行。 + +一个数据节点里有多个vnode, 因此vnode模块是有多个运行实例的。每个运行实例是完全独立的。 + +vnode与其子模块是通过API直接调用,而不是通过消息队列传递。而且各个子模块只与vnode模块有交互,不与dnode, rpc等模块发生任何直接关联。 + +## MNODE模块 + +mnode是整个系统的大脑,负责整个系统的资源调度,负责meta data的管理与存储。 + +一个运行的系统里,只有一个mnode,但它有多个副本(由系统配置参数numOfMnodes控制)。这些副本分布在不同的dnode里,目的是保证系统的高可靠运行。副本之间的数据复制是采用同步而非异步的方式,以确保数据的一致性,确保数据不会丢失。这些副本会自动选举一个Master,其他副本是slave。所有数据更新类的操作,都只能在master上进行,而查询类的可以在slave节点上进行。代码实现上,同步模块与vnode共享,但mnode被分配一个特殊的vgroup ID: 1,而且quorum大于1。整个集群系统是由多个dnode组成的,运行的mnode的副本数不可能超过dnode的个数,但不会超过配置的副本数。如果某个mnode副本宕机一段时间,只要超过半数的mnode副本仍在运行,运行的mnode会自动根据整个系统的资源情况,在其他dnode里再启动一个mnode, 以保证运行的副本数。 + +各个dnode通过信息交换,保存有mnode各个副本的End Point列表,并向其中的master节点定时(间隔由系统配置参数statusInterval控制)发送status消息,消息体里包含该dnode的CPU、内存、剩余存储空间、vnode个数,以及各个vnode的状态(存储空间、原始数据大小、记录条数、角色等)。这样mnode就了解整个系统的资源情况,如果用户创建新的表,就可以决定需要在哪个dnode创建;如果增加或删除dnode, 或者监测到某dnode数据过热、或离线太长,就可以决定需要挪动那些vnode,以实现负载均衡。 + +mnode里还负责account, user, DB, stable, table, vgroup, dnode的创建、删除与更新。mnode不仅把这些entity的meta data保存在内存,还做持久化存储。但为节省内存,各个表的标签值不保存在mnode(保存在vnode),而且子表不维护自己的schema, 而是与stable共享。为减小mnode的查询压力,taosc会缓存table、stable的schema。对于查询类的操作,各个slave mnode也可以提供,以减轻master压力。 + +## TSDB模块 + +TSDB模块是VNODE中的负责快速高并发地存储和读取属于该VNODE的表的元数据及采集的时序数据的引擎。除此之外,TSDB还提供了表结构的修改、表标签值的修改等功能。TSDB提供API供VNODE和Query等模块调用。TSDB中存储了两类数据,1:元数据信息;2:时序数据 + +### 元数据信息 + +TSDB中存储的元数据包含属于其所在的VNODE中表的类型,schema的定义等。对于超级表和超级表下的子表而言,又包含了tag的schema定义以及子表的tag值等。对于元数据信息而言,TSDB就相当于一个全内存的KV型数据库,属于该VNODE的表对象全部在内存中,方便快速查询表的信息。除此之外,TSDB还对其中的子表,按照tag的第一列取值做了全内存的索引,大大加快了对于标签的过滤查询。TSDB中的元数据的最新状态在落盘时,会以追加(append-only)的形式,写入到meta文件中。meta文件只进行追加操作,即便是元数据的删除,也会以一条记录的形式写入到文件末尾。TSDB也提供了对于元数据的修改操作,如表schema的修改,tag schema的修改以及tag值的修改等。 + +### 时序数据 + +每个TSDB在创建时,都会事先分配一定量的内存缓冲区,且内存缓冲区的大小可配可修改。表采集的时序数据,在写入TSDB时,首先以追加的方式写入到分配的内存缓冲区中,同时建立基于时间戳的内存索引,方便快速查询。当内存缓冲区的数据积累到一定的程度时(达到内存缓冲区总大小的1/3),则会触发落盘操作,将缓冲区中的数据持久化到硬盘文件上。时序数据在内存缓冲区中是以行(row)的形式存储的。 + +而时序数据在写入到TSDB的数据文件时,是以列(column)的形式存储的。TSDB中的数据文件包含多个数据文件组,每个数据文件组中又包含.head、.data和.last三个文件,如(v2f1801.head、v2f1801.data、v2f1801.last)数据文件组。TSDB中的数据文件组是按照时间跨度进行分片的,默认是10天一个文件组,且可通过配置文件及建库选项进行配置。分片的数据文件组又按照编号递增排列,方便快速定位某一时间段的时序数据,高效定位数据文件组。时序数据在TSDB的数据文件中是以块的形式进行列式存储的,每个块中只包含一张表的数据,且数据在一个块中是按照时间顺序递增排列的。在一个数据文件组中,.head文件负责存储数据块的索引及统计信息,如每个块的位置,压缩算法,时间戳范围等。存储在.head文件中一张表的索引信息是按照数据块中存储的数据的时间递增排列的,方便进行折半查找等工作。.head和.last文件是存储真实数据块的文件,若数据块中的数据累计到一定程度,则会写入.data文件中,否则,会写入.last文件中,等待下次落盘时合并数据写入.data文件中,从而大大减少文件中块的个数,避免数据的过度碎片化。 + +## Query模块 + +该模块负责整体系统的查询处理。客户端调用该该模块进行SQL语法解析,并将查询或写入请求发送到vnode,同时负责针对超级表的查询进行二阶段的聚合操作。在Vnode端,该模块调用TSDB模块读取系统中存储的数据进行查询处理。Query模块还定义了系统能够支持的全部查询函数,查询函数的实现机制与查询框架无耦合,可以在不修改查询流程的情况下动态增加查询函数。详细的设计请参见《TDengine 2.0查询模块设计》。 + +## SYNC模块 + +该模块实现数据的多副本复制,包括vnode与mnode的数据复制,支持异步和同步两种复制方式,以满足meta data与时序数据不同复制的需求。因为它为mnode与vnode共享,系统为mnode副本预留了一个特殊的vgroup ID:1。因此vnode group的ID是从2开始的。 + +每个vnode/mnode模块实例会有一对应的sync模块实例,他们是一一对应的。详细设计请见[TDengine 2.0 数据复制模块设计](https://www.taosdata.com/cn/documentation/architecture/replica/) + +## WAL模块 + +该模块负责将新插入的数据写入write ahead log(WAL), 为vnode, mnode共享。以保证服务器crash或其他故障,能从WAL中恢复数据。 + +每个vnode/mnode模块实例会有一对应的wal模块实例,是完全一一对应的。WAL的落盘操作由两个参数walLevel, fsync控制。看具体场景,如果要100%保证数据不会丢失,需要将walLevel配置为2,fsync设置为0,每条数据插入请求,都会实时落盘后,才会给应用确认 + +## HTTP模块 + +该模块负责处理系统对外的RESTful接口,可以通过配置,由dnode启动或停止。 + +该模块将接收到的RESTful请求,做了各种合法性检查后,将其变成标准的SQL语句,通过taosc的异步接口,将请求发往整个系统中的任一dnode。收到处理后的结果后,再翻译成HTTP协议,返回给应用。 + +如果HTTP模块启动,就意味着启动了一个taosc的实例。任一一个dnode都可以启动该模块,以实现对RESTful请求的分布式处理。 + +## Monitor模块 + +该模块负责检测一个dnode的运行状态,可以通过配置,由dnode启动或停止。原则上,每个dnode都应该启动一个monitor实例。 + +Monitor采集TDengine里的关键操作,比如创建、删除、更新账号、表、库等,而且周期性的收集CPU、内存、网络等资源的使用情况(采集周期由系统配置参数monitorInterval控制)。获得这些数据后,monitor模块将采集的数据写入系统的日志库(DB名字由系统配置参数monitorDbName控制)。 + +Monitor模块使用taosc来将采集的数据写入系统,因此每个monitor实例,都有一个taosc运行实例。 + diff --git a/docs-cn/13-tdinternal/12-tsz-compress.md b/docs-cn/13-tdinternal/12-tsz-compress.md new file mode 100644 index 0000000000000000000000000000000000000000..5072b474195fa648f5f8e29a6954e8ef6fe35e06 --- /dev/null +++ b/docs-cn/13-tdinternal/12-tsz-compress.md @@ -0,0 +1,42 @@ +# TSZ 压缩算法 + +TSZ 压缩算法是 TDengine 为浮点数据类型提供更加丰富的压缩功能,可以实现浮点数的有损至无损全状态压缩,相比原来在 TDengine 中原有压缩算法,TSZ 压缩算法压缩选项更丰富,压缩率更高,即使切到无损状态下对浮点数压缩,压缩率也会比原来的压缩算法高一倍。 + +## 适合场景 + +TSZ 压缩算法压缩率比原来的要高,但压缩时间会更长,即开启 TSZ 压缩算法写入速度会有一些下降,通常情况下会有 20% 左右的下降。影响写入速度是因为需要更多的 CPU 计算,所以从原始数据到压缩好数据的交付时间变长,导致写入速度变慢。如果您的服务器 CPU 配置很高的话,这个影响会变小甚至没有。 + +另外如果设备产生了大量的高精度浮点数,存储占用的空间非常庞大,但实际使用并不需要那么高的精度时,可以通过 TSZ 压缩的有损压缩功能,把精度压缩至指定的长度,节约存储空间。 + +总结:采集到了大量浮点数,存储时占用空间过大或出有存储空间不足,需要超高压缩率的场景。 + +## 使用步骤 + +- 检查版本支持,2.4.0.10 及之后 TDengine 的版本都支持此功能 + +- 配置选项开启功能,在 TDengine 的配置文件 taos.cfg 增加一行以下内容,打开 TSZ 功能 + +```TSZ +lossyColumns float|double +``` + +- 根据自己需要配置其它选项,如果不配置都会按默认值处理。 + +- 重启服务,配置生效。 +- 确认功能已开启,在服务启动过程中输出的信息如果有前面配置的内容,表明功能已生效: + +```TSZ Test +02/22 10:49:27.607990 00002933 UTL lossyColumns float|double +``` + +## 注意事项 + +- 确认版本是否支持 + +- 除了服务器启动时的输出的配置成功信息外,不再会有其它的信息输出是使用的哪种压缩算法,可以通过配置前后数据库文件大小来比较效果 + +- 如果浮点数类型列较少,看整体数据文件大小效果会不太明显 + +- 此压缩产生的数据文件中浮点数据部分将不能被 2.4.0.10 以下的版本解析,即不向下兼容,使用时避免更换回旧版本,以免数据不能被读取出来。 + +- 在使用过程中允许反复开启和关闭 TSZ 压缩选项的操作,前后两种压缩算法产生的数据都能正常读取。 diff --git a/docs-cn/13-tdinternal/_category_.yml b/docs-cn/13-tdinternal/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..73c78f68a520fefecc145daaa24fe7e28c7c78e2 --- /dev/null +++ b/docs-cn/13-tdinternal/_category_.yml @@ -0,0 +1,4 @@ +label: 技术内幕 +link: + slug: /tdinternal/ + type: generated-index \ No newline at end of file diff --git a/docs-cn/14-reference/01-taos-sql/01-data-type.md b/docs-cn/14-reference/01-taos-sql/01-data-type.md new file mode 100644 index 0000000000000000000000000000000000000000..107e73de5b6903d7aeaa6d6c8a68fb9f5941b7e9 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/01-data-type.md @@ -0,0 +1,52 @@ +--- +sidebar_label: 支持的数据类型 +--- + +# 支持的数据类型 + +使用 TDengine,最重要的是时间戳。创建并插入记录、查询历史记录的时候,均需要指定时间戳。时间戳有如下规则: + +- 时间格式为 `YYYY-MM-DD HH:mm:ss.MS`,默认时间分辨率为毫秒。比如:`2017-08-12 18:25:58.128` +- 内部函数 now 是客户端的当前时间 +- 插入记录时,如果时间戳为 now,插入数据时使用提交这条记录的客户端的当前时间 +- Epoch Time:时间戳也可以是一个长整数,表示从格林威治时间 1970-01-01 00:00:00.000 (UTC/GMT) 开始的毫秒数(相应地,如果所在 Database 的时间精度设置为“微秒”,则长整型格式的时间戳含义也就对应于从格林威治时间 1970-01-01 00:00:00.000 (UTC/GMT) 开始的微秒数;纳秒精度的逻辑也是类似的。) +- 时间可以加减,比如 now-2h,表明查询时刻向前推 2 个小时(最近 2 小时)。数字后面的时间单位可以是 b(纳秒)、u(微秒)、a(毫秒)、s(秒)、m(分)、h(小时)、d(天)、w(周)。 比如 `select * from t1 where ts > now-2w and ts <= now-1w`,表示查询两周前整整一周的数据。在指定降采样操作(down sampling)的时间窗口(interval)时,时间单位还可以使用 n(自然月) 和 y(自然年)。 + +TDengine 缺省的时间戳是毫秒精度,但通过在 `CREATE DATABASE` 时传递的 PRECISION 参数就可以支持微秒和纳秒。(从 2.1.5.0 版本开始支持纳秒精度) + +``` +CREATE DATABASE db_name PRECISION 'ns'; +``` + +在 TDengine 中,普通表的数据模型中可使用以下 10 种数据类型。 + +| # | **类型** | **Bytes** | **说明** | +| --- | :-------: | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | TIMESTAMP | 8 | 时间戳。缺省精度毫秒,可支持微秒和纳秒。从格林威治时间 1970-01-01 00:00:00.000 (UTC/GMT) 开始,计时不能早于该时间。(从 2.0.18.0 版本开始,已经去除了这一时间范围限制)(从 2.1.5.0 版本开始支持纳秒精度) | +| 2 | INT | 4 | 整型,范围 [-2^31+1, 2^31-1], -2^31 用作 NULL | +| 3 | BIGINT | 8 | 长整型,范围 [-2^63+1, 2^63-1], -2^63 用于 NULL | +| 4 | FLOAT | 4 | 浮点型,有效位数 6-7,范围 [-3.4E38, 3.4E38] | +| 5 | DOUBLE | 8 | 双精度浮点型,有效位数 15-16,范围 [-1.7E308, 1.7E308] | +| 6 | BINARY | 自定义 | 记录单字节字符串,建议只用于处理 ASCII 可见字符,中文等多字节字符需使用 nchar。理论上,最长可以有 16374 字节。binary 仅支持字符串输入,字符串两端需使用单引号引用。使用时须指定大小,如 binary(20) 定义了最长为 20 个单字节字符的字符串,每个字符占 1 byte 的存储空间,总共固定占用 20 bytes 的空间,此时如果用户字符串超出 20 字节将会报错。对于字符串内的单引号,可以用转义字符反斜线加单引号来表示,即 `\’`。 | +| 7 | SMALLINT | 2 | 短整型, 范围 [-32767, 32767], -32768 用于 NULL | +| 8 | TINYINT | 1 | 单字节整型,范围 [-127, 127], -128 用于 NULL | +| 9 | BOOL | 1 | 布尔型,{true, false} | +| 10 | NCHAR | 自定义 | 记录包含多字节字符在内的字符串,如中文字符。每个 nchar 字符占用 4 bytes 的存储空间。字符串两端使用单引号引用,字符串内的单引号需用转义字符 `\’`。nchar 使用时须指定字符串大小,类型为 nchar(10) 的列表示此列的字符串最多存储 10 个 nchar 字符,会固定占用 40 bytes 的空间。如果用户字符串长度超出声明长度,将会报错。 | +| 11 | JSON | | json 数据类型, 只有 tag 类型可以是 json 格式 | + + + +:::tip +TDengine 对 SQL 语句中的英文字符不区分大小写,自动转化为小写执行。因此用户大小写敏感的字符串及密码,需要使用单引号将字符串引起来。 + +::: + +:::note +虽然 Binary 类型在底层存储上支持字节型的二进制字符,但不同编程语言对二进制数据的处理方式并不保证一致,因此建议在 Binary 类型中只存储 ASCII 可见字符,而避免存储不可见字符。多字节的数据,例如中文字符,则需要使用 nchar 类型进行保存。如果强行使用 Binary 类型保存中文字符,虽然有时也能正常读写,但并不带有字符集信息,很容易出现数据乱码甚至数据损坏等情况。 + +::: + +:::note +SQL 语句中的数值类型将依据是否存在小数点,或使用科学计数法表示,来判断数值类型是否为整型或者浮点型,因此在使用时要注意相应类型越界的情况。例如,9999999999999999999 会认为超过长整型的上边界而溢出,而 9999999999999999999.0 会被认为是有效的浮点数。 + +::: diff --git a/docs-cn/14-reference/01-taos-sql/02-database.md b/docs-cn/14-reference/01-taos-sql/02-database.md new file mode 100644 index 0000000000000000000000000000000000000000..1fe934e87796313b647222a000635d113ef391bb --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/02-database.md @@ -0,0 +1,113 @@ +--- +sidebar_label: 数据库管理 +--- + +# 数据库管理 + +## 创建数据库 + +``` +CREATE DATABASE [IF NOT EXISTS] db_name [KEEP keep] [DAYS days] [UPDATE 1]; +``` + +:::info 说明 + +1. KEEP 是该数据库的数据保留多长天数,缺省是 3650 天(10 年),数据库会自动删除超过时限的数据; + +2. UPDATE 标志数据库支持更新相同时间戳数据;(从 2.1.7.0 版本开始此参数支持设为 2,表示允许部分列更新,也即更新数据行时未被设置的列会保留原值。)(从 2.0.8.0 版本开始支持此参数。注意此参数不能通过 `ALTER DATABASE` 指令进行修改。) + + 1. UPDATE 设为 0 时,表示不允许更新数据,后发送的相同时间戳的数据会被直接丢弃; + + 2. UPDATE 设为 1 时,表示更新全部列数据,即如果更新一个数据行,其中某些列没有提供取值,那么这些列会被设为 NULL; + + 3. UPDATE 设为 2 时,表示支持更新部分列数据,即如果更新一个数据行,其中某些列没有提供取值,那么这些列会保持原有数据行中的对应值; + + 4. 更多关于 UPDATE 参数的用法,请参考[FAQ](https://www.taosdata.com/cn/documentation/faq)。 + +3. 数据库名最大长度为 33; + +4. 一条 SQL 语句的最大长度为 65480 个字符; + +5. 数据库还有更多与存储相关的配置参数,请参见 [服务端配置](https://www.taosdata.com/cn/documentation/administrator#config) 章节。 + +::: + +## 显示系统当前参数 + +``` +SHOW VARIABLES; +``` + +## 使用数据库 + +``` +USE db_name; +``` + +使用/切换数据库(在 RESTful 连接方式下无效)。 + +## 删除数据库 + +``` +DROP DATABASE [IF EXISTS] db_name; +``` + +删除数据库。指定 Database 所包含的全部数据表将被删除,谨慎使用! + +## 修改数据库参数 + +``` +ALTER DATABASE db_name COMP 2; +``` + +COMP 参数是指修改数据库文件压缩标志位,缺省值为 2,取值范围为 [0, 2]。0 表示不压缩,1 表示一阶段压缩,2 表示两阶段压缩。 + +``` +ALTER DATABASE db_name REPLICA 2; +``` + +REPLICA 参数是指修改数据库副本数,取值范围 [1, 3]。在集群中使用,副本数必须小于或等于 DNODE 的数目。 + +``` +ALTER DATABASE db_name KEEP 365; +``` + +KEEP 参数是指修改数据文件保存的天数,缺省值为 3650,取值范围 [days, 365000],必须大于或等于 days 参数值。 + +``` +ALTER DATABASE db_name QUORUM 2; +``` + +QUORUM 参数是指数据写入成功所需要的确认数,取值范围 [1, 2]。对于异步复制,quorum 设为 1,具有 master 角色的虚拟节点自己确认即可。对于同步复制,quorum 设为 2。原则上,Quorum >= 1 并且 Quorum <= replica(副本数),这个参数在启动一个同步模块实例时需要提供。 + +``` +ALTER DATABASE db_name BLOCKS 100; +``` + +BLOCKS 参数是每个 VNODE (TSDB) 中有多少 cache 大小的内存块,因此一个 VNODE 的用的内存大小粗略为(cache \* blocks)。取值范围 [3, 1000]。 + +``` +ALTER DATABASE db_name CACHELAST 0; +``` + +CACHELAST 参数控制是否在内存中缓存子表的最近数据。缺省值为 0,取值范围 [0, 1, 2, 3]。其中 0 表示不缓存,1 表示缓存子表最近一行数据,2 表示缓存子表每一列的最近的非 NULL 值,3 表示同时打开缓存最近行和列功能。(从 2.0.11.0 版本开始支持参数值 [0, 1],从 2.1.2.0 版本开始支持参数值 [0, 1, 2, 3]。) +说明:缓存最近行,将显著改善 LAST_ROW 函数的性能表现;缓存每列的最近非 NULL 值,将显著改善无特殊影响(WHERE、ORDER BY、GROUP BY、INTERVAL)下的 LAST 函数的性能表现。 + +:::tip +以上所有参数修改后都可以用 show databases 来确认是否修改成功。另外,从 2.1.3.0 版本开始,修改这些参数后无需重启服务器即可生效。 +:::tip + +## 显示系统所有数据库 + +``` +SHOW DATABASES; +``` + +## 显示一个数据库的创建语句 + +``` +SHOW CREATE DATABASE db_name; +``` + +常用于数据库迁移。对一个已经存在的数据库,返回其创建语句;在另一个集群中执行该语句,就能得到一个设置完全相同的 Database。 + diff --git a/docs-cn/14-reference/01-taos-sql/03-table.md b/docs-cn/14-reference/01-taos-sql/03-table.md new file mode 100644 index 0000000000000000000000000000000000000000..81834bacd47e04249b72aa4f28d31a73b4c74e75 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/03-table.md @@ -0,0 +1,122 @@ +# 表管理 + +## 创建数据表 + +``` +CREATE TABLE [IF NOT EXISTS] tb_name (timestamp_field_name TIMESTAMP, field1_name data_type1 [, field2_name data_type2 ...]); +``` + +:::info 说明 + +1. 表的第一个字段必须是 TIMESTAMP,并且系统自动将其设为主键; +2. 表名最大长度为 192; +3. 表的每行长度不能超过 16k 个字符;(注意:每个 BINARY/NCHAR 类型的列还会额外占用 2 个字节的存储位置) +4. 子表名只能由字母、数字和下划线组成,且不能以数字开头,不区分大小写 +5. 使用数据类型 binary 或 nchar,需指定其最长的字节数,如 binary(20),表示 20 字节; +6. 为了兼容支持更多形式的表名,TDengine 引入新的转义符 "\`",可以让表名与关键词不冲突,同时不受限于上述表名称合法性约束检查。但是同样具有长度限制要求。使用转义字符以后,不再对转义字符中的内容进行大小写统一。 + 例如:\`aBc\` 和 \`abc\` 是不同的表名,但是 abc 和 aBc 是相同的表名。 + 需要注意的是转义字符中的内容必须是可打印字符。 + 上述的操作逻辑和约束要求与 MySQL 数据的操作一致。 + 从 2.3.0.0 版本开始支持这种方式。 + +::: + +### 以超级表为模板创建数据表 + +``` +CREATE TABLE [IF NOT EXISTS] tb_name USING stb_name TAGS (tag_value1, ...); +``` + +以指定的超级表为模板,指定 TAGS 的值来创建数据表。 + +### 以超级表为模板创建数据表,并指定具体的 TAGS 列 + +``` +CREATE TABLE [IF NOT EXISTS] tb_name USING stb_name (tag_name1, ...) TAGS (tag_value1, ...); +``` + +以指定的超级表为模板,指定一部分 TAGS 列的值来创建数据表(没被指定的 TAGS 列会设为空值)。 + 说明:从 2.0.17.0 版本开始支持这种方式。在之前的版本中,不允许指定 TAGS 列,而必须显式给出所有 TAGS 列的取值。 + +### 批量创建数据表 + +``` +CREATE TABLE [IF NOT EXISTS] tb_name1 USING stb_name TAGS (tag_value1, ...) [IF NOT EXISTS] tb_name2 USING stb_name TAGS (tag_value2, ...) ...; +``` + +以更快的速度批量创建大量数据表(服务器端 2.0.14 及以上版本)。 + +:::info + +1.批量建表方式要求数据表必须以超级表为模板。 2.在不超出 SQL 语句长度限制的前提下,单条语句中的建表数量建议控制在 1000 ~ 3000 之间,将会获得比较理想的建表速度。 + +::: + +## 删除数据表 + +``` +DROP TABLE [IF EXISTS] tb_name; +``` + +## 显示当前数据库下的所有数据表信息 + +``` +SHOW TABLES [LIKE tb_name_wildcar]; +``` + +显示当前数据库下的所有数据表信息。 + +## 显示一个数据表的创建语句 + +``` +SHOW CREATE TABLE tb_name; +``` + +常用于数据库迁移。对一个已经存在的数据表,返回其创建语句;在另一个集群中执行该语句,就能得到一个结构完全相同的数据表。 + +## 在线修改显示字符宽度 + +``` +SET MAX_BINARY_DISPLAY_WIDTH ; +``` + +如显示的内容后面以...结尾时,表示该内容已被截断,可通过本命令修改显示字符宽度以显示完整的内容。 + +## 获取表的结构信息 + +``` +DESCRIBE tb_name; +``` + +## 修改表定义 + +### 表增加列 + +``` +ALTER TABLE tb_name ADD COLUMN field_name data_type; +``` + +:::info + +1. 列的最大个数为 1024,最小个数为 2;(从 2.1.7.0 版本开始,改为最多允许 4096 列) +2. 列名最大长度为 64。 + +::: + +### 表删除列 + +``` +ALTER TABLE tb_name DROP COLUMN field_name; +``` + +如果表是通过超级表创建,更改表结构的操作只能对超级表进行。同时针对超级表的结构更改对所有通过该结构创建的表生效。对于不是通过超级表创建的表,可以直接修改表结构。 + +### 表修改列宽 + +``` +ALTER TABLE tb_name MODIFY COLUMN field_name data_type(length); +``` + +如果数据列的类型是可变长格式(BINARY 或 NCHAR),那么可以使用此指令修改其宽度(只能改大,不能改小)。(2.1.3.0 版本新增) + 如果表是通过超级表创建,更改表结构的操作只能对超级表进行。同时针对超级表的结构更改对所有通过该结构创建的表生效。对于不是通过超级表创建的表,可以直接修改表结构。 + diff --git a/docs-cn/14-reference/01-taos-sql/04-stable.md b/docs-cn/14-reference/01-taos-sql/04-stable.md new file mode 100644 index 0000000000000000000000000000000000000000..8ac8e669f36fc0dd7066006e5b1e4d4ca7d15cc2 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/04-stable.md @@ -0,0 +1,119 @@ +--- +sidebar_label: 超级表管理 +--- + +# 超级表 STable 管理 + +注意:在 2.0.15.0 及以后的版本中,开始支持 STABLE 保留字。也即,在本节后文的指令说明中,CREATE、DROP、ALTER 三个指令在老版本中保留字需写作 TABLE 而不是 STABLE。 + +## 创建超级表 + +``` +CREATE STABLE [IF NOT EXISTS] stb_name (timestamp_field_name TIMESTAMP, field1_name data_type1 [, field2_name data_type2 ...]) TAGS (tag1_name tag_type1, tag2_name tag_type2 [, tag3_name tag_type3]); +``` + +创建 STable,与创建表的 SQL 语法相似,但需要指定 TAGS 字段的名称和类型。 + +:::info + +1. TAGS 列的数据类型不能是 timestamp 类型;(从 2.1.3.0 版本开始,TAGS 列中支持使用 timestamp 类型,但需注意在 TAGS 中的 timestamp 列写入数据时需要提供给定值,而暂不支持四则运算,例如 `NOW + 10s` 这类表达式) +2. TAGS 列名不能与其他列名相同; +3. TAGS 列名不能为预留关键字(参见:[参数限制与保留关键字](https://www.taosdata.com/cn/documentation/administrator#keywords) 章节); +4. TAGS 最多允许 128 个,至少 1 个,总长度不超过 16 KB。 + +::: + +## 删除超级表 + +``` +DROP STABLE [IF EXISTS] stb_name; +``` + +删除 STable 会自动删除通过 STable 创建的子表。 + +## 显示当前数据库下的所有超级表信息 + +``` +SHOW STABLES [LIKE tb_name_wildcard]; +``` + +查看数据库内全部 STable,及其相关信息,包括 STable 的名称、创建时间、列数量、标签(TAG)数量、通过该 STable 建表的数量。 + +## 显示一个超级表的创建语句 + +``` +SHOW CREATE STABLE stb_name; +``` + +常用于数据库迁移。对一个已经存在的超级表,返回其创建语句;在另一个集群中执行该语句,就能得到一个结构完全相同的超级表。 + +## 获取超级表的结构信息 + +``` +DESCRIBE stb_name; +``` + +## 修改超级表普通列 + +### 超级表增加列 + +``` +ALTER STABLE stb_name ADD COLUMN field_name data_type; +``` + +### 超级表删除列 + +``` +ALTER STABLE stb_name DROP COLUMN field_name; +``` + +### 超级表修改列宽 + +``` +ALTER STABLE stb_name MODIFY COLUMN field_name data_type(length); +``` + +如果数据列的类型是可变长格式(BINARY 或 NCHAR),那么可以使用此指令修改其宽度(只能改大,不能改小)。(2.1.3.0 版本新增) + +## 修改超级表标签列 + +### 添加标签 + +``` +ALTER STABLE stb_name ADD TAG new_tag_name tag_type; +``` + +为 STable 增加一个新的标签,并指定新标签的类型。标签总数不能超过 128 个,总长度不超过 16k 个字符。 + +### 删除标签 + +``` +ALTER STABLE stb_name DROP TAG tag_name; +``` + +删除超级表的一个标签,从超级表删除某个标签后,该超级表下的所有子表也会自动删除该标签。 + +### 修改标签名 + +``` +ALTER STABLE stb_name CHANGE TAG old_tag_name new_tag_name; +``` + +修改超级表的标签名,从超级表修改某个标签名后,该超级表下的所有子表也会自动更新该标签名。 + +### 修改标签列宽度 + +``` +ALTER STABLE stb_name MODIFY TAG tag_name data_type(length); +``` + +如果标签的类型是可变长格式(BINARY 或 NCHAR),那么可以使用此指令修改其宽度(只能改大,不能改小)。(2.1.3.0 版本新增) + +### 修改子表标签值 + +``` +ALTER TABLE tb_name SET TAG tag_name=new_tag_value; +``` + +说明:除了更新标签的值的操作是针对子表进行,其他所有的标签操作(添加标签、删除标签等)均只能作用于 STable,不能对单个子表操作。对 STable 添加标签以后,依托于该 STable 建立的所有表将自动增加了一个标签,所有新增标签的默认值都是 NULL。 + diff --git a/docs-cn/14-reference/01-taos-sql/05-insert.md b/docs-cn/14-reference/01-taos-sql/05-insert.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c0c28dba3f5f64ff066f6a313e8307488c13b5 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/05-insert.md @@ -0,0 +1,150 @@ +--- +sidebar_label: 数据写入 +--- + +# 数据写入 + +## 写入语法 + +``` +INSERT INTO + tb_name + [USING stb_name [(tag1_name, ...)] TAGS (tag1_value, ...)] + [(field1_name, ...)] + VALUES (field1_value, ...) [(field1_value2, ...) ...] | FILE csv_file_path + [tb2_name + [USING stb_name [(tag1_name, ...)] TAGS (tag1_value, ...)] + [(field1_name, ...)] + VALUES (field1_value, ...) [(field1_value2, ...) ...] | FILE csv_file_path + ...]; +``` + +## 插入一条或多条记录 + +指定已经创建好的数据子表的表名,并通过 VALUES 关键字提供一行或多行数据,即可向数据库写入这些数据。例如,执行如下语句可以写入一行记录: + +``` +INSERT INTO d1001 VALUES (NOW, 10.2, 219, 0.32); +``` + +或者,可以通过如下语句写入两行记录: + +``` +INSERT INTO d1001 VALUES ('2021-07-13 14:06:32.272', 10.2, 219, 0.32) (1626164208000, 10.15, 217, 0.33); +``` + +:::note + +1. 在第二个例子中,两行记录的首列时间戳使用了不同格式的写法。其中字符串格式的时间戳写法不受所在 DATABASE 的时间精度设置影响;而长整形格式的时间戳写法会受到所在 DATABASE 的时间精度设置影响——例子中的时间戳在毫秒精度下可以写作 1626164208000,而如果是在微秒精度设置下就需要写为 1626164208000000,纳秒精度设置下需要写为 1626164208000000000。 +2. 在使用“插入多条记录”方式写入数据时,不能把第一列的时间戳取值都设为 NOW,否则会导致语句中的多条记录使用相同的时间戳,于是就可能出现相互覆盖以致这些数据行无法全部被正确保存。其原因在于,NOW 函数在执行中会被解析为所在 SQL 语句的实际执行时间,出现在同一语句中的多个 NOW 标记也就会被替换为完全相同的时间戳取值。 +3. 允许插入的最老记录的时间戳,是相对于当前服务器时间,减去配置的 keep 值(数据保留的天数);允许插入的最新记录的时间戳,是相对于当前服务器时间,加上配置的 days 值(数据文件存储数据的时间跨度,单位为天)。keep 和 days 都是可以在创建数据库时指定的,缺省值分别是 3650 天和 10 天。 + +::: + +## 插入记录,数据对应到指定的列 + +向数据子表中插入记录时,无论插入一行还是多行,都可以让数据对应到指定的列。对于 SQL 语句中没有出现的列,数据库将自动填充为 NULL。主键(时间戳)不能为 NULL。例如: + +``` +INSERT INTO d1001 (ts, current, phase) VALUES ('2021-07-13 14:06:33.196', 10.27, 0.31); +``` + +:::info +如果不指定列,也即使用全列模式——那么在 VALUES 部分提供的数据,必须为数据表的每个列都显式地提供数据。全列模式写入速度会远快于指定列,因此建议尽可能采用全列写入方式,此时空列可以填入 NULL。 + +::: + +## 向多个表插入记录 + +可以在一条语句中,分别向多个表插入一条或多条记录,并且也可以在插入过程中指定列。例如: + +``` +INSERT INTO d1001 VALUES ('2021-07-13 14:06:34.630', 10.2, 219, 0.32) ('2021-07-13 14:06:35.779', 10.15, 217, 0.33) + d1002 (ts, current, phase) VALUES ('2021-07-13 14:06:34.255', 10.27, 0.31); +``` + +## 插入记录时自动建表 + +如果用户在写数据时并不确定某个表是否存在,此时可以在写入数据时使用自动建表语法来创建不存在的表,若该表已存在则不会建立新表。自动建表时,要求必须以超级表为模板,并写明数据表的 TAGS 取值。例如: + +``` +INSERT INTO d21001 USING meters TAGS ('Beijing.Chaoyang', 2) VALUES ('2021-07-13 14:06:32.272', 10.2, 219, 0.32); +``` + +也可以在自动建表时,只是指定部分 TAGS 列的取值,未被指定的 TAGS 列将置为 NULL。例如: + +``` +INSERT INTO d21001 USING meters (groupId) TAGS (2) VALUES ('2021-07-13 14:06:33.196', 10.15, 217, 0.33); +``` + +自动建表语法也支持在一条语句中向多个表插入记录。例如: + +``` +INSERT INTO d21001 USING meters TAGS ('Beijing.Chaoyang', 2) VALUES ('2021-07-13 14:06:34.630', 10.2, 219, 0.32) ('2021-07-13 14:06:35.779', 10.15, 217, 0.33) + d21002 USING meters (groupId) TAGS (2) VALUES ('2021-07-13 14:06:34.255', 10.15, 217, 0.33) + d21003 USING meters (groupId) TAGS (2) (ts, current, phase) VALUES ('2021-07-13 14:06:34.255', 10.27, 0.31); +``` + +:::info +在 2.0.20.5 版本之前,在使用自动建表语法并指定列时,子表的列名必须紧跟在子表名称后面,而不能如例子里那样放在 TAGS 和 VALUES 之间。从 2.0.20.5 版本开始,两种写法都可以,但不能在一条 SQL 语句中混用,否则会报语法错误。 +::: + +## 插入来自文件的数据记录 + +除了使用 VALUES 关键字插入一行或多行数据外,也可以把要写入的数据放在 CSV 文件中(英文逗号分隔、英文单引号括住每个值)供 SQL 指令读取。其中 CSV 文件无需表头。例如,如果 /tmp/csvfile.csv 文件的内容为: + +``` +'2021-07-13 14:07:34.630', '10.2', '219', '0.32' +'2021-07-13 14:07:35.779', '10.15', '217', '0.33' +``` + +那么通过如下指令可以把这个文件中的数据写入子表中: + +``` +INSERT INTO d1001 FILE '/tmp/csvfile.csv'; +``` + +## 插入来自文件的数据记录,并自动建表 + +从 2.1.5.0 版本开始,支持在插入来自 CSV 文件的数据时,以超级表为模板来自动创建不存在的数据表。例如: + +``` +INSERT INTO d21001 USING meters TAGS ('Beijing.Chaoyang', 2) FILE '/tmp/csvfile.csv'; +``` + +也可以在一条语句中向多个表以自动建表的方式插入记录。例如: + +``` +INSERT INTO d21001 USING meters TAGS ('Beijing.Chaoyang', 2) FILE '/tmp/csvfile_21001.csv' + d21002 USING meters (groupId) TAGS (2) FILE '/tmp/csvfile_21002.csv'; +``` + +## 历史记录写入 + +可使用 IMPORT 或者 INSERT 命令,IMPORT 的语法,功能与 INSERT 完全一样。 + +针对 insert 类型的 SQL 语句,我们采用的流式解析策略,在发现后面的错误之前,前面正确的部分 SQL 仍会执行。下面的 SQL 中,INSERT 语句是无效的,但是 d1001 仍会被创建。 + +``` +taos> CREATE TABLE meters(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS(location BINARY(30), groupId INT); +Query OK, 0 row(s) affected (0.008245s) + +taos> SHOW STABLES; + name | created_time | columns | tags | tables | +============================================================================================ + meters | 2020-08-06 17:50:27.831 | 4 | 2 | 0 | +Query OK, 1 row(s) in set (0.001029s) + +taos> SHOW TABLES; +Query OK, 0 row(s) in set (0.000946s) + +taos> INSERT INTO d1001 USING meters TAGS('Beijing.Chaoyang', 2) VALUES('a'); + +DB error: invalid SQL: 'a' (invalid timestamp) (0.039494s) + +taos> SHOW TABLES; + table_name | created_time | columns | stable_name | +====================================================================================================== + d1001 | 2020-08-06 17:52:02.097 | 4 | meters | +Query OK, 1 row(s) in set (0.001091s) +``` diff --git a/docs-cn/14-reference/01-taos-sql/06-select.md b/docs-cn/14-reference/01-taos-sql/06-select.md new file mode 100644 index 0000000000000000000000000000000000000000..dab208f0860ab4eed435d097205e1a803350dcde --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/06-select.md @@ -0,0 +1,457 @@ +--- +sidebar_label: 数据查询 +--- + +# 数据查询 + +## 查询语法 + +``` +SELECT select_expr [, select_expr ...] + FROM {tb_name_list} + [WHERE where_condition] + [SESSION(ts_col, tol_val)] + [STATE_WINDOW(col)] + [INTERVAL(interval_val [, interval_offset]) [SLIDING sliding_val]] + [FILL(fill_mod_and_val)] + [GROUP BY col_list] + [ORDER BY col_list { DESC | ASC }] + [SLIMIT limit_val [SOFFSET offset_val]] + [LIMIT limit_val [OFFSET offset_val]] + [>> export_file]; +``` + +## 通配符 + +通配符 \* 可以用于代指全部列。对于普通表,结果中只有普通列。 + +``` +taos> SELECT * FROM d1001; + ts | current | voltage | phase | +====================================================================================== + 2018-10-03 14:38:05.000 | 10.30000 | 219 | 0.31000 | + 2018-10-03 14:38:15.000 | 12.60000 | 218 | 0.33000 | + 2018-10-03 14:38:16.800 | 12.30000 | 221 | 0.31000 | +Query OK, 3 row(s) in set (0.001165s) +``` + +在针对超级表,通配符包含 _标签列_ 。 + +``` +taos> SELECT * FROM meters; + ts | current | voltage | phase | location | groupid | +===================================================================================================================================== + 2018-10-03 14:38:05.500 | 11.80000 | 221 | 0.28000 | Beijing.Haidian | 2 | + 2018-10-03 14:38:16.600 | 13.40000 | 223 | 0.29000 | Beijing.Haidian | 2 | + 2018-10-03 14:38:05.000 | 10.80000 | 223 | 0.29000 | Beijing.Haidian | 3 | + 2018-10-03 14:38:06.500 | 11.50000 | 221 | 0.35000 | Beijing.Haidian | 3 | + 2018-10-03 14:38:04.000 | 10.20000 | 220 | 0.23000 | Beijing.Chaoyang | 3 | + 2018-10-03 14:38:16.650 | 10.30000 | 218 | 0.25000 | Beijing.Chaoyang | 3 | + 2018-10-03 14:38:05.000 | 10.30000 | 219 | 0.31000 | Beijing.Chaoyang | 2 | + 2018-10-03 14:38:15.000 | 12.60000 | 218 | 0.33000 | Beijing.Chaoyang | 2 | + 2018-10-03 14:38:16.800 | 12.30000 | 221 | 0.31000 | Beijing.Chaoyang | 2 | +Query OK, 9 row(s) in set (0.002022s) +``` + +通配符支持表名前缀,以下两个 SQL 语句均为返回全部的列: + +``` +SELECT * FROM d1001; +SELECT d1001.* FROM d1001; +``` + +在 JOIN 查询中,带前缀的\*和不带前缀\*返回的结果有差别, \*返回全部表的所有列数据(不包含标签),带前缀的通配符,则只返回该表的列数据。 + +``` +taos> SELECT * FROM d1001, d1003 WHERE d1001.ts=d1003.ts; + ts | current | voltage | phase | ts | current | voltage | phase | +================================================================================================================================== + 2018-10-03 14:38:05.000 | 10.30000| 219 | 0.31000 | 2018-10-03 14:38:05.000 | 10.80000| 223 | 0.29000 | +Query OK, 1 row(s) in set (0.017385s) +``` + +``` +taos> SELECT d1001.* FROM d1001,d1003 WHERE d1001.ts = d1003.ts; + ts | current | voltage | phase | +====================================================================================== + 2018-10-03 14:38:05.000 | 10.30000 | 219 | 0.31000 | +Query OK, 1 row(s) in set (0.020443s) +``` + +在使用 SQL 函数来进行查询的过程中,部分 SQL 函数支持通配符操作。其中的区别在于: +`count(*)`函数只返回一列。`first`、`last`、`last_row`函数则是返回全部列。 + +``` +taos> SELECT COUNT(*) FROM d1001; + count(*) | +======================== + 3 | +Query OK, 1 row(s) in set (0.001035s) +``` + +``` +taos> SELECT FIRST(*) FROM d1001; + first(ts) | first(current) | first(voltage) | first(phase) | +========================================================================================= + 2018-10-03 14:38:05.000 | 10.30000 | 219 | 0.31000 | +Query OK, 1 row(s) in set (0.000849s) +``` + +## 标签列 + +从 2.0.14 版本开始,支持在普通表的查询中指定 _标签列_,且标签列的值会与普通列的数据一起返回。 + +``` +taos> SELECT location, groupid, current FROM d1001 LIMIT 2; + location | groupid | current | +====================================================================== + Beijing.Chaoyang | 2 | 10.30000 | + Beijing.Chaoyang | 2 | 12.60000 | +Query OK, 2 row(s) in set (0.003112s) +``` + +注意:普通表的通配符 \* 中并不包含 _标签列_。 + +## 获取标签列或普通列的去重取值 + +从 2.0.15.0 版本开始,支持在超级表查询标签列时,指定 DISTINCT 关键字,这样将返回指定标签列的所有不重复取值。注意,在 2.1.6.0 版本之前,DISTINCT 只支持处理单个标签列,而从 2.1.6.0 版本开始,DISTINCT 可以对多个标签列进行处理,输出这些标签列取值不重复的组合。 + +```sql +SELECT DISTINCT tag_name [, tag_name ...] FROM stb_name; +``` + +从 2.1.7.0 版本开始,DISTINCT 也支持对数据子表或普通表进行处理,也即支持获取单个普通列的不重复取值,或多个普通列取值的不重复组合。 + +```sql +SELECT DISTINCT col_name [, col_name ...] FROM tb_name; +``` + +:::info + +1. cfg 文件中的配置参数 maxNumOfDistinctRes 将对 DISTINCT 能够输出的数据行数进行限制。其最小值是 100000,最大值是 100000000,默认值是 10000000。如果实际计算结果超出了这个限制,那么会仅输出这个数量范围内的部分。 +2. 由于浮点数天然的精度机制原因,在特定情况下,对 FLOAT 和 DOUBLE 列使用 DISTINCT 并不能保证输出值的完全唯一性。 +3. 在当前版本下,DISTINCT 不能在嵌套查询的子查询中使用,也不能与聚合函数、GROUP BY、或 JOIN 在同一条语句中混用。 + +::: + +## 结果集列名 + +`SELECT`子句中,如果不指定返回结果集合的列名,结果集列名称默认使用`SELECT`子句中的表达式名称作为列名称。此外,用户可使用`AS`来重命名返回结果集合中列的名称。例如: + +``` +taos> SELECT ts, ts AS primary_key_ts FROM d1001; + ts | primary_key_ts | +==================================================== + 2018-10-03 14:38:05.000 | 2018-10-03 14:38:05.000 | + 2018-10-03 14:38:15.000 | 2018-10-03 14:38:15.000 | + 2018-10-03 14:38:16.800 | 2018-10-03 14:38:16.800 | +Query OK, 3 row(s) in set (0.001191s) +``` + +但是针对`first(*)`、`last(*)`、`last_row(*)`不支持针对单列的重命名。 + +## 隐式结果列 + +`Select_exprs`可以是表所属列的列名,也可以是基于列的函数表达式或计算式,数量的上限 256 个。当用户使用了`interval`或`group by tags`的子句以后,在最后返回结果中会强制返回时间戳列(第一列)和 group by 子句中的标签列。后续的版本中可以支持关闭 group by 子句中隐式列的输出,列输出完全由 select 子句控制。 + +## 表(超级表)列表 + +FROM 关键字后面可以是若干个表(超级表)列表,也可以是子查询的结果。 +如果没有指定用户的当前数据库,可以在表名称之前使用数据库的名称来指定表所属的数据库。例如:`power.d1001` 方式来跨库使用表。 + +``` +SELECT * FROM power.d1001; +------------------------------ +USE power; +SELECT * FROM d1001; +``` + +## 特殊功能 + +部分特殊的查询功能可以不使用 FROM 子句执行。获取当前所在的数据库 database(): + +``` +taos> SELECT DATABASE(); + database() | +================================= + power | +Query OK, 1 row(s) in set (0.000079s) +``` + +如果登录的时候没有指定默认数据库,且没有使用`USE`命令切换数据,则返回 NULL。 + +``` +taos> SELECT DATABASE(); + database() | +================================= + NULL | +Query OK, 1 row(s) in set (0.000184s) +``` + +获取服务器和客户端版本号: + +``` +taos> SELECT CLIENT_VERSION(); + client_version() | +=================== + 2.0.0.0 | +Query OK, 1 row(s) in set (0.000070s) + +taos> SELECT SERVER_VERSION(); + server_version() | +=================== + 2.0.0.0 | +Query OK, 1 row(s) in set (0.000077s) +``` + +服务器状态检测语句。如果服务器正常,返回一个数字(例如 1)。如果服务器异常,返回 error code。该 SQL 语法能兼容连接池对于 TDengine 状态的检查及第三方工具对于数据库服务器状态的检查。并可以避免出现使用了错误的心跳检测 SQL 语句导致的连接池连接丢失的问题。 + +``` +taos> SELECT SERVER_STATUS(); + server_status() | +================== + 1 | +Query OK, 1 row(s) in set (0.000074s) + +taos> SELECT SERVER_STATUS() AS status; + status | +============== + 1 | +Query OK, 1 row(s) in set (0.000081s) +``` + +## \_block_dist 函数 + +用于获得指定的(超级)表的数据块分布信息 + +```txt title="语法" +SELECT _block_dist() FROM { tb_name | stb_name } +``` + +返回结果类型:字符串。 + +适用数据类型:不能输入任何参数。 + +嵌套子查询支持:不支持子查询或嵌套查询。 + +返回 FROM 子句中输入的表或超级表的数据块分布情况。不支持查询条件。 + +返回的结果是该表或超级表的数据块所包含的行数的数据分布直方图。 + +```txt title="返回结果" +summary: +5th=[392], 10th=[392], 20th=[392], 30th=[392], 40th=[792], 50th=[792] 60th=[792], 70th=[792], 80th=[792], 90th=[792], 95th=[792], 99th=[792] Min=[392(Rows)] Max=[800(Rows)] Avg=[666(Rows)] Stddev=[2.17] Rows=[2000], Blocks=[3], Size=[5.440(Kb)] Comp=[0.23] RowsInMem=[0] SeekHeaderTime=[1(us)] +``` + +上述信息的说明如下: + +1. 查询的(超级)表所包含的存储在文件中的数据块(data block)中所包含的数据行的数量分布直方图信息:5%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 95%, 99% 的数值; +2. 所有数据块中,包含行数最少的数据块所包含的行数量, 其中的 Min 指标 392 行。 +3. 所有数据块中,包含行数最多的数据块所包含的行数量, 其中的 Max 指标 800 行。 +4. 所有数据块行数的算数平均值 666 行(其中的 Avg 项)。 +5. 所有数据块中行数分布的均方差为 2.17 ( stddev )。 +6. 数据块包含的行的总数为 2000 行(Rows)。 +7. 数据块总数是 3 个数据块 (Blocks)。 +8. 数据块占用磁盘空间大小 5.44 Kb (size)。 +9. 压缩后的数据块的大小除以原始数据的所获得的压缩比例: 23%(Comp),及压缩后的数据规模是原始数据规模的 23%。 +10. 内存中存在的数据行数是 0,表示内存中没有数据缓存。 +11. 获取数据块信息的过程中读取头文件的时间开销 1 微秒(SeekHeaderTime)。 + +支持版本:指定计算算法的功能从 2.1.0.x 版本开始,2.1.0.0 之前的版本不支持指定使用算法的功能。 + +## TAOS SQL 中特殊关键词 + +- `TBNAME`: 在超级表查询中可视为一个特殊的标签,代表查询涉及的子表名 +- `_c0`: 表示表(超级表)的第一列 + +## 小技巧 + +获取一个超级表所有的子表名及相关的标签信息: + +``` +SELECT TBNAME, location FROM meters; +``` + +统计超级表下辖子表数量: + +``` +SELECT COUNT(TBNAME) FROM meters; +``` + +以上两个查询均只支持在 WHERE 条件子句中添加针对标签(TAGS)的过滤条件。例如: + +``` +taos> SELECT TBNAME, location FROM meters; + tbname | location | +================================================================== + d1004 | Beijing.Haidian | + d1003 | Beijing.Haidian | + d1002 | Beijing.Chaoyang | + d1001 | Beijing.Chaoyang | +Query OK, 4 row(s) in set (0.000881s) + +taos> SELECT COUNT(tbname) FROM meters WHERE groupId > 2; + count(tbname) | +======================== + 2 | +Query OK, 1 row(s) in set (0.001091s) +``` + +- 可以使用 \* 返回所有列,或指定列名。可以对数字列进行四则运算,可以给输出的列取列名。 + - 暂不支持含列名的四则运算表达式用于条件过滤算子(例如,不支持 `where a*2>6;`,但可以写 `where a>6/2;`)。 + - 暂不支持含列名的四则运算表达式作为 SQL 函数的应用对象(例如,不支持 `select min(2*a) from t;`,但可以写 `select 2*min(a) from t;`)。 +- WHERE 语句可以使用各种逻辑判断来过滤数字值,或使用通配符来过滤字符串。 +- 输出结果缺省按首列时间戳升序排序,但可以指定按降序排序( \_c0 指首列时间戳)。使用 ORDER BY 对其他字段进行排序,排序结果顺序不确定。 +- 参数 LIMIT 控制输出条数,OFFSET 指定从第几条开始输出。LIMIT/OFFSET 对结果集的执行顺序在 ORDER BY 之后。且 `LIMIT 5 OFFSET 2` 可以简写为 `LIMIT 2, 5`。 + - 在有 GROUP BY 子句的情况下,LIMIT 参数控制的是每个分组中至多允许输出的条数。 +- 参数 SLIMIT 控制由 GROUP BY 指令划分的分组中,至多允许输出几个分组的数据。且 `SLIMIT 5 SOFFSET 2` 可以简写为 `SLIMIT 2, 5`。 +- 通过 “>>” 输出结果可以导出到指定文件。 + +## 条件过滤操作 + +| **Operation** | **Note** | **Applicable Data Types** | +| ------------- | ------------------------ | ----------------------------------------- | +| > | larger than | all types except bool | +| < | smaller than | all types except bool | +| >= | larger than or equal to | all types except bool | +| <= | smaller than or equal to | all types except bool | +| = | equal to | all types | +| <\> | not equal to | all types | +| is [not] null | is null or is not null | all types | +| between and | within a certain range | all types except bool | +| in | match any value in a set | all types except first column `timestamp` | +| like | match a wildcard string | **`binary`** **`nchar`** | +| match/nmatch | filter regex | **`binary`** **`nchar`** | + +1. <\> 算子也可以写为 != ,请注意,这个算子不能用于数据表第一列的 timestamp 字段。 +2. like 算子使用通配符字符串进行匹配检查。 + - 在通配符字符串中:'%'(百分号)匹配 0 到任意个字符;'\_'(下划线)匹配单个任意 ASCII 字符。 + - 如果希望匹配字符串中原本就带有的 \_(下划线)字符,那么可以在通配符字符串中写作 `\_`,也即加一个反斜线来进行转义。(从 2.2.0.0 版本开始支持) + - 通配符字符串最长不能超过 20 字节。(从 2.1.6.1 版本开始,通配符字符串的长度放宽到了 100 字节,并可以通过 taos.cfg 中的 maxWildCardsLength 参数来配置这一长度限制。但不建议使用太长的通配符字符串,将有可能严重影响 LIKE 操作的执行性能。) +3. 同时进行多个字段的范围过滤,需要使用关键词 AND 来连接不同的查询条件,暂不支持 OR 连接的不同列之间的查询过滤条件。 + - 从 2.3.0.0 版本开始,已支持完整的同一列和/或不同列间的 AND/OR 运算。 +4. 针对单一字段的过滤,如果是时间过滤条件,则一条语句中只支持设定一个;但针对其他的(普通)列或标签列,则可以使用 `OR` 关键字进行组合条件的查询过滤。例如: `((value > 20 AND value < 30) OR (value < 12))`。 + - 从 2.3.0.0 版本开始,允许使用多个时间过滤条件,但首列时间戳的过滤运算结果只能包含一个区间。 +5. 从 2.0.17.0 版本开始,条件过滤开始支持 BETWEEN AND 语法,例如 `WHERE col2 BETWEEN 1.5 AND 3.25` 表示查询条件为“1.5 ≤ col2 ≤ 3.25”。 +6. 从 2.1.4.0 版本开始,条件过滤开始支持 IN 算子,例如 `WHERE city IN ('Beijing', 'Shanghai')`。说明:BOOL 类型写作 `{true, false}` 或 `{0, 1}` 均可,但不能写作 0、1 之外的整数;FLOAT 和 DOUBLE 类型会受到浮点数精度影响,集合内的值在精度范围内认为和数据行的值完全相等才能匹配成功;TIMESTAMP 类型支持非主键的列。 +7. 从 2.3.0.0 版本开始,条件过滤开始支持正则表达式,关键字 match/nmatch,不区分大小写。 + +## 正则表达式过滤 + +### 语法 + +```txt +WHERE (column|tbname) **match/MATCH/nmatch/NMATCH** _regex_ +``` + +### 正则表达式规范 + +确保使用的正则表达式符合 POSIX 的规范,具体规范内容可参见[Regular Expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html) + +### 使用限制 + +只能针对表名(即 tbname 筛选)、binary/nchar 类型标签值进行正则表达式过滤,不支持普通列的过滤。 + +正则匹配字符串长度不能超过 128 字节。可以通过参数 _maxRegexStringLen_ 设置和调整最大允许的正则匹配字符串,该参数是客户端配置参数,需要重启才能生效。 + +## JOIN 子句 + +从 2.2.0.0 版本开始,TDengine 对内连接(INNER JOIN)中的自然连接(Natural join)操作实现了完整的支持。也即支持“普通表与普通表之间”、“超级表与超级表之间”、“子查询与子查询之间”进行自然连接。自然连接与内连接的主要区别是,自然连接要求参与连接的字段在不同的表/超级表中必须是同名字段。也即,TDengine 在连接关系的表达中,要求必须使用同名数据列/标签列的相等关系。 + +在普通表与普通表之间的 JOIN 操作中,只能使用主键时间戳之间的相等关系。例如: + +```sql +SELECT * +FROM temp_tb_1 t1, pressure_tb_1 t2 +WHERE t1.ts = t2.ts +``` + +在超级表与超级表之间的 JOIN 操作中,除了主键时间戳一致的条件外,还要求引入能实现一一对应的标签列的相等关系。例如: + +```sql +SELECT * +FROM temp_stable t1, temp_stable t2 +WHERE t1.ts = t2.ts AND t1.deviceid = t2.deviceid AND t1.status=0; +``` + +类似地,也可以对多个子查询的查询结果进行 JOIN 操作。 + +注意,JOIN 操作存在如下限制要求: + +1. 参与一条语句中 JOIN 操作的表/超级表最多可以有 10 个。 +2. 在包含 JOIN 操作的查询语句中不支持 FILL。 +3. 暂不支持参与 JOIN 操作的表之间聚合后的四则运算。 +4. 不支持只对其中一部分表做 GROUP BY。 +5. JOIN 查询的不同表的过滤条件之间不能为 OR。 +6. JOIN 查询要求连接条件不能是普通列,只能针对标签和主时间字段列(第一列)。 + +## 嵌套查询 + +“嵌套查询”又称为“子查询”,也即在一条 SQL 语句中,“内层查询”的计算结果可以作为“外层查询”的计算对象来使用。 + +从 2.2.0.0 版本开始,TDengine 的查询引擎开始支持在 FROM 子句中使用非关联子查询(“非关联”的意思是,子查询不会用到父查询中的参数)。也即在普通 SELECT 语句的 tb_name_list 位置,用一个独立的 SELECT 语句来代替(这一 SELECT 语句被包含在英文圆括号内),于是完整的嵌套查询 SQL 语句形如: + +``` +SELECT ... FROM (SELECT ... FROM ...) ...; +``` + +:::info + +1. 目前仅支持一层嵌套,也即不能在子查询中再嵌入子查询。 +2. 内层查询的返回结果将作为“虚拟表”供外层查询使用,此虚拟表可以使用 AS 语法做重命名,以便于外层查询中方便引用。 +3. 目前不能在“连续查询”功能中使用子查询。 +4. 在内层和外层查询中,都支持普通的表间/超级表间 JOIN。内层查询的计算结果也可以再参与数据子表的 JOIN 操作。 +5. 目前内层查询、外层查询均不支持 UNION 操作。 +6. 内层查询支持的功能特性与非嵌套的查询语句能力是一致的。 + - 内层查询的 ORDER BY 子句一般没有意义,建议避免这样的写法以免无谓的资源消耗。 +7. 与非嵌套的查询语句相比,外层查询所能支持的功能特性存在如下限制: + - 计算函数部分: + _. 如果内层查询的结果数据未提供时间戳,那么计算过程依赖时间戳的函数在外层会无法正常工作。例如:TOP, BOTTOM, FIRST, LAST, DIFF。 + _. 计算过程需要两遍扫描的函数,在外层查询中无法正常工作。例如:此类函数包括:STDDEV, PERCENTILE。 + - 外层查询中不支持 IN 算子,但在内层中可以使用。 + - 外层查询不支持 GROUP BY。 + +::: + +## UNION ALL 子句 + +```txt title=语法 +SELECT ... +UNION ALL SELECT ... +[UNION ALL SELECT ...] +``` + +TDengine 支持 UNION ALL 操作符。也就是说,如果多个 SELECT 子句返回结果集的结构完全相同(列名、列类型、列数、顺序),那么可以通过 UNION ALL 把这些结果集合并到一起。目前只支持 UNION ALL 模式,也即在结果集的合并过程中是不去重的。在同一个 sql 语句中,UNION ALL 最多支持 100 个。 + +### SQL 示例 + +对于下面的例子,表 tb1 用以下语句创建: + +``` +CREATE TABLE tb1 (ts TIMESTAMP, col1 INT, col2 FLOAT, col3 BINARY(50)); +``` + +查询 tb1 刚过去的一个小时的所有记录: + +``` +SELECT * FROM tb1 WHERE ts >= NOW - 1h; +``` + +查询表 tb1 从 2018-06-01 08:00:00.000 到 2018-06-02 08:00:00.000 时间范围,并且 col3 的字符串是'nny'结尾的记录,结果按照时间戳降序: + +``` +SELECT * FROM tb1 WHERE ts > '2018-06-01 08:00:00.000' AND ts <= '2018-06-02 08:00:00.000' AND col3 LIKE '%nny' ORDER BY ts DESC; +``` + +查询 col1 与 col2 的和,并取名 complex, 时间大于 2018-06-01 08:00:00.000, col2 大于 1.2,结果输出仅仅 10 条记录,从第 5 条开始: + +``` +SELECT (col1 + col2) AS 'complex' FROM tb1 WHERE ts > '2018-06-01 08:00:00.000' AND col2 > 1.2 LIMIT 10 OFFSET 5; +``` + +查询过去 10 分钟的记录,col2 的值大于 3.14,并且将结果输出到文件 `/home/testoutpu.csv`: + +``` +SELECT COUNT(*) FROM tb1 WHERE ts >= NOW - 10m AND col2 > 3.14 >> /home/testoutpu.csv; +``` + diff --git a/docs-cn/14-reference/01-taos-sql/07-function.md b/docs-cn/14-reference/01-taos-sql/07-function.md new file mode 100644 index 0000000000000000000000000000000000000000..8b9dd773e516a68b6caed191f427319ce32bce81 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/07-function.md @@ -0,0 +1,1774 @@ +--- +sidebar_label: SQL 函数 +--- + +# SQL 函数 + +## 聚合函数 + +TDengine 支持针对数据的聚合查询。提供支持的聚合和选择函数如下: + +### COUNT + +``` +SELECT COUNT([*|field_name]) FROM tb_name [WHERE clause]; +``` + +- **功能说明**:统计表/超级表中记录行数或某列的非空值个数。 +- **返回数据类型**:长整型 INT64。 +- **应用字段**:应用全部字段。 +- **适用于**:表、超级表。 + +:::info + +- 可以使用星号(\*)来替代具体的字段,使用星号(\*)返回全部记录数量。 +- 针对同一表的(不包含 NULL 值)字段查询结果均相同。 +- 如果统计对象是具体的列,则返回该列中非 NULL 值的记录数量。 + +::: + +示例: + +``` +taos> SELECT COUNT(*), COUNT(voltage) FROM meters; + count(*) | count(voltage) | +================================================ + 9 | 9 | +Query OK, 1 row(s) in set (0.004475s) + +taos> SELECT COUNT(*), COUNT(voltage) FROM d1001; + count(*) | count(voltage) | +================================================ + 3 | 3 | +Query OK, 1 row(s) in set (0.001075s) +``` + +### AVG + +``` +SELECT AVG(field_name) FROM tb_name [WHERE clause]; +``` + +- **功能说明**:统计表/超级表中某列的平均值。 +- **返回数据类型**:双精度浮点数 Double。 +- **应用字段**:不能应用在 timestamp、binary、nchar、bool 字段。 +- **适用于**:表、超级表。 + +示例: + +``` +taos> SELECT AVG(current), AVG(voltage), AVG(phase) FROM meters; + avg(current) | avg(voltage) | avg(phase) | +==================================================================================== + 11.466666751 | 220.444444444 | 0.293333333 | +Query OK, 1 row(s) in set (0.004135s) + +taos> SELECT AVG(current), AVG(voltage), AVG(phase) FROM d1001; + avg(current) | avg(voltage) | avg(phase) | +==================================================================================== + 11.733333588 | 219.333333333 | 0.316666673 | +Query OK, 1 row(s) in set (0.000943s) +``` + +### TWA + +``` +SELECT TWA(field_name) FROM tb_name WHERE clause; +``` + +- **功能说明**:时间加权平均函数。统计表中某列在一段时间内的时间加权平均。 +- **返回数据类型**:双精度浮点数 Double。 +- **应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 +- **适用于**:表、(超级表。 + +说明:从 2.1.3.0 版本开始,TWA 函数可以在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname)。 + +### IRATE + +``` +SELECT IRATE(field_name) FROM tb_name WHERE clause; +``` + +**功能说明**:计算瞬时增长率。使用时间区间中最后两个样本数据来计算瞬时增长速率;如果这两个值呈递减关系,那么只取最后一个数用于计算,而不是使用二者差值。 + +**返回数据类型**:双精度浮点数 Double。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +适用于:**表、(超级表)**。 + +说明:(从 2.1.3.0 版本开始新增此函数)IRATE 可以在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname)。 + +### SUM + +``` +SELECT SUM(field_name) FROM tb_name [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的和。 + +**返回数据类型**:双精度浮点数 Double 和长整型 INT64。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +示例: + +``` +taos> SELECT SUM(current), SUM(voltage), SUM(phase) FROM meters; + sum(current) | sum(voltage) | sum(phase) | +================================================================================ + 103.200000763 | 1984 | 2.640000001 | +Query OK, 1 row(s) in set (0.001702s) + +taos> SELECT SUM(current), SUM(voltage), SUM(phase) FROM d1001; + sum(current) | sum(voltage) | sum(phase) | +================================================================================ + 35.200000763 | 658 | 0.950000018 | +Query OK, 1 row(s) in set (0.000980s) +``` + +### STDDEV + +``` +SELECT STDDEV(field_name) FROM tb_name [WHERE clause]; +``` + +**功能说明**:统计表中某列的均方差。 + +**返回数据类型**:双精度浮点数 Double。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表。(从 2.0.15.1 版本开始,本函数也支持**超级表**) + +示例: + +``` +taos> SELECT STDDEV(current) FROM d1001; + stddev(current) | +============================ + 1.020892909 | +Query OK, 1 row(s) in set (0.000915s) +``` + +### LEASTSQUARES + +``` +SELECT LEASTSQUARES(field_name, start_val, step_val) FROM tb_name [WHERE clause]; +``` + +- **功能说明**:统计表中某列的值是主键(时间戳)的拟合直线方程。start_val 是自变量初始值,step_val 是自变量的步长值。 +- **返回数据类型**:字符串表达式(斜率, 截距)。 +- **应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 +- **适用于**:表。 + +示例: + +``` +taos> SELECT LEASTSQUARES(current, 1, 1) FROM d1001; + leastsquares(current, 1, 1) | +===================================================== +{slop:1.000000, intercept:9.733334} | +Query OK, 1 row(s) in set (0.000921s) +``` + +### MODE + +``` +SELECT MODE(field_name) FROM tb_name [WHERE clause]; +``` + +- **功能说明**:返回出现频率最高的值,若存在多个频率相同的最高值,输出空。不能匹配标签、时间戳输出。 +- **返回数据类型**:同应用的字段。 +- **应用字段**:适合于除时间主列外的任何类型字段。 +- **说明**:由于返回数据量未知,考虑到内存因素,为了函数可以正常返回结果,建议不重复的数据量在 10 万级别,否则会报错。 +- **支持的版本**:2.6 开始的版本。 + +示例: + +``` +taos> select voltage from d002; + voltage | +======================== + 1 | + 1 | + 2 | + 19 | +Query OK, 4 row(s) in set (0.003545s) + +taos> select mode(voltage) from d002; + mode(voltage) | +======================== + 1 | +Query OK, 1 row(s) in set (0.019393s) +``` + +### HYPERLOGLOG + +``` +SELECT HYPERLOGLOG(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +- **功能说明**: + - 采用 hyperloglog 算法,返回某列的基数。该算法在数据量很大的情况下,可以明显降低内存的占用,但是求出来的基数是个估算值,标准误差(标准误差是多次实验,每次的平均数的标准差,不是与真实结果的误差)为 0.81%。 + - 在数据量较少的时候该算法不是很准确,可以使用 select count(data) from (select unique(col) as data from table) 的方法。 +- **返回结果类型**:整形。 +- **应用字段**:适合于任何类型字段。 +- **支持的版本**:2.6 开始的版本。 + +示例: + +``` +taos> select dbig from shll; + dbig | +======================== + 1 | + 1 | + 1 | + NULL | + 2 | + 19 | + NULL | + 9 | +Query OK, 8 row(s) in set (0.003755s) + +taos> select hyperloglog(dbig) from shll; + hyperloglog(dbig)| +======================== + 4 | +Query OK, 1 row(s) in set (0.008388s) +``` + +## 选择函数 + +在使用所有的选择函数的时候,可以同时指定输出 ts 列或标签列(包括 tbname),这样就可以方便地知道被选出的值是源于哪个数据行的。 + +### MIN + +``` +SELECT MIN(field_name) FROM {tb_name | stb_name} [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的值最小值。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +示例: + +``` +taos> SELECT MIN(current), MIN(voltage) FROM meters; + min(current) | min(voltage) | +====================================== + 10.20000 | 218 | +Query OK, 1 row(s) in set (0.001765s) + +taos> SELECT MIN(current), MIN(voltage) FROM d1001; + min(current) | min(voltage) | +====================================== + 10.30000 | 218 | +Query OK, 1 row(s) in set (0.000950s) +``` + +### MAX + +``` +SELECT MAX(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的值最大值。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +示例: + +``` +taos> SELECT MAX(current), MAX(voltage) FROM meters; + max(current) | max(voltage) | +====================================== + 13.40000 | 223 | +Query OK, 1 row(s) in set (0.001123s) + +taos> SELECT MAX(current), MAX(voltage) FROM d1001; + max(current) | max(voltage) | +====================================== + 12.60000 | 221 | +Query OK, 1 row(s) in set (0.000987s) +``` + +### FIRST + +``` +SELECT FIRST(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的值最先写入的非 NULL 值。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:所有字段。 + +**适用于**:表、超级表。 + +说明: + +1)如果要返回各个列的首个(时间戳最小)非 NULL 值,可以使用 FIRST(\*); + +2)如果结果集中的某列全部为 NULL 值,则该列的返回结果也是 NULL; + +3)如果结果集中所有列全部为 NULL 值,则不返回结果。 + +示例: + +``` +taos> SELECT FIRST(*) FROM meters; + first(ts) | first(current) | first(voltage) | first(phase) | +========================================================================================= +2018-10-03 14:38:04.000 | 10.20000 | 220 | 0.23000 | +Query OK, 1 row(s) in set (0.004767s) + +taos> SELECT FIRST(current) FROM d1002; + first(current) | +======================= + 10.20000 | +Query OK, 1 row(s) in set (0.001023s) +``` + +### LAST + +``` +SELECT LAST(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的值最后写入的非 NULL 值。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:所有字段。 + +**适用于**:表、超级表。 + +说明: + +1)如果要返回各个列的最后(时间戳最大)一个非 NULL 值,可以使用 LAST(\*); + +2)如果结果集中的某列全部为 NULL 值,则该列的返回结果也是 NULL;如果结果集中所有列全部为 NULL 值,则不返回结果。 + +3)在用于超级表时,时间戳完全一样且同为最大的数据行可能有多个,那么会从中随机返回一条,而并不保证多次运行所挑选的数据行必然一致。 + +示例: + +``` +taos> SELECT LAST(*) FROM meters; + last(ts) | last(current) | last(voltage) | last(phase) | +======================================================================================== +2018-10-03 14:38:16.800 | 12.30000 | 221 | 0.31000 | +Query OK, 1 row(s) in set (0.001452s) + +taos> SELECT LAST(current) FROM d1002; + last(current) | +======================= + 10.30000 | +Query OK, 1 row(s) in set (0.000843s) +``` + +### TOP + +``` +SELECT TOP(field_name, K) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**: 统计表/超级表中某列的值最大 _k_ 个非 NULL 值。如果多条数据取值一样,全部取用又会超出 k 条限制时,系统会从相同值中随机选取符合要求的数量返回。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +说明: + +1)*k*值取值范围 1≤*k*≤100; + +2)系统同时返回该记录关联的时间戳列; + +3)限制:TOP 函数不支持 FILL 子句。 + +示例: + +``` +taos> SELECT TOP(current, 3) FROM meters; + ts | top(current, 3) | +================================================= +2018-10-03 14:38:15.000 | 12.60000 | +2018-10-03 14:38:16.600 | 13.40000 | +2018-10-03 14:38:16.800 | 12.30000 | +Query OK, 3 row(s) in set (0.001548s) + +taos> SELECT TOP(current, 2) FROM d1001; + ts | top(current, 2) | +================================================= +2018-10-03 14:38:15.000 | 12.60000 | +2018-10-03 14:38:16.800 | 12.30000 | +Query OK, 2 row(s) in set (0.000810s) +``` + +### BOTTOM + +``` +SELECT BOTTOM(field_name, K) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的值最小 _k_ 个非 NULL 值。如果多条数据取值一样,全部取用又会超出 k 条限制时,系统会从相同值中随机选取符合要求的数量返回。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +说明: + +1)*k*值取值范围 1≤*k*≤100; + +2)系统同时返回该记录关联的时间戳列; + +3)限制:BOTTOM 函数不支持 FILL 子句。 + +示例: + +``` +taos> SELECT BOTTOM(voltage, 2) FROM meters; + ts | bottom(voltage, 2) | +=============================================== +2018-10-03 14:38:15.000 | 218 | +2018-10-03 14:38:16.650 | 218 | +Query OK, 2 row(s) in set (0.001332s) + +taos> SELECT BOTTOM(current, 2) FROM d1001; + ts | bottom(current, 2) | +================================================= +2018-10-03 14:38:05.000 | 10.30000 | +2018-10-03 14:38:16.800 | 12.30000 | +Query OK, 2 row(s) in set (0.000793s) +``` + +### PERCENTILE + +``` +SELECT PERCENTILE(field_name, P) FROM { tb_name } [WHERE clause]; +``` + +**功能说明**:统计表中某列的值百分比分位数。 + +**返回数据类型**: 双精度浮点数 Double。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表。 + +说明:*P*值取值范围 0≤*P*≤100,为 0 的时候等同于 MIN,为 100 的时候等同于 MAX。 + +示例: + +``` +taos> SELECT PERCENTILE(current, 20) FROM d1001; +percentile(current, 20) | +============================ + 11.100000191 | +Query OK, 1 row(s) in set (0.000787s) +``` + +### APERCENTILE + +``` +SELECT APERCENTILE(field_name, P[, algo_type]) +FROM { tb_name | stb_name } [WHERE clause] +``` + +**功能说明**:统计表/超级表中指定列的值百分比分位数,与 PERCENTILE 函数相似,但是返回近似结果。 + +**返回数据类型**: 双精度浮点数 Double。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +说明:
**P**值有效取值范围 0≤P≤100,为 0 的时候等同于 MIN,为 100 的时候等同于 MAX;
**algo_type**的有效输入:**default** 和 **t-digest**。 用于指定计算近似分位数的算法。可不提供第三个参数的输入,此时将使用 default 的算法进行计算,即 apercentile(column_name, 50, "default") 与 apercentile(column_name, 50) 等价。当使用“t-digest”参数的时候,将使用 t-digest 方式采样计算近似分位数。但该参数指定计算算法的功能从 2.2.0.x 版本开始支持,2.2.0.0 之前的版本不支持指定使用算法的功能。
+ +嵌套子查询支持:适用于内层查询和外层查询。 + +``` +taos> SELECT APERCENTILE(current, 20) FROM d1001; +apercentile(current, 20) | +============================ + 10.300000191 | +Query OK, 1 row(s) in set (0.000645s) + +taos> select apercentile (count, 80, 'default') from stb1; + apercentile (c0, 80, 'default') | +================================== + 601920857.210056424 | +Query OK, 1 row(s) in set (0.012363s) + +taos> select apercentile (count, 80, 't-digest') from stb1; + apercentile (c0, 80, 't-digest') | +=================================== + 605869120.966666579 | +Query OK, 1 row(s) in set (0.011639s) +``` + +### LAST_ROW + +``` +SELECT LAST_ROW(field_name) FROM { tb_name | stb_name }; +``` + +**功能说明**:返回表/超级表的最后一条记录。 + +**返回数据类型**:同应用的字段。 + +**应用字段**:所有字段。 + +**适用于**:表、超级表。 + +限制:LAST_ROW() 不能与 INTERVAL 一起使用。 + +说明:在用于超级表时,时间戳完全一样且同为最大的数据行可能有多个,那么会从中随机返回一条,而并不保证多次运行所挑选的数据行必然一致。
+ +{" "} + +{" "} + +
+示例: + +``` + taos> SELECT LAST_ROW(current) FROM meters; + last_row(current) | + ======================= + 12.30000 | + Query OK, 1 row(s) in set (0.001238s) + + taos> SELECT LAST_ROW(current) FROM d1002; + last_row(current) | + ======================= + 10.30000 | + Query OK, 1 row(s) in set (0.001042s) +``` + +### INTERP [2.3.1 及之后的版本] + +``` +SELECT INTERP(field_name) FROM { tb_name | stb_name } [WHERE where_condition] [ RANGE(timestamp1,timestamp2) ] [EVERY(interval)] [FILL ({ VALUE | PREV | NULL | LINEAR | NEXT})]; +``` + +**功能说明**:返回表/超级表的指定时间截面指定列的记录值(插值)。 + +**返回数据类型**:同字段类型。 + +**应用字段**:数值型字段。 + +适用于:**表、超级表、嵌套查询**。 + +说明: +1)INTERP 用于在指定时间断面获取指定列的记录值,如果该时间断面不存在符合条件的行数据,那么会根据 FILL 参数的设定进行插值。 + +2)INTERP 的输入数据为指定列的数据,可以通过条件语句(where 子句)来对原始列数据进行过滤,如果没有指定过滤条件则输入为全部数据。 + +3)INTERP 的输出时间范围根据 RANGE(timestamp1,timestamp2)字段来指定,需满足 timestamp1<=timestamp2。其中 timestamp1(必选值)为输出时间范围的起始值,即如果 timestamp1 时刻符合插值条件则 timestamp1 为输出的第一条记录,timestamp2(必选值)为输出时间范围的结束值,即输出的最后一条记录的 timestamp 不能大于 timestamp2。如果没有指定 RANGE,那么满足过滤条件的输入数据中第一条记录的 timestamp 即为 timestamp1,最后一条记录的 timestamp 即为 timestamp2,同样也满足 timestamp1 <= timestamp2。 + +4)INTERP 根据 EVERY 字段来确定输出时间范围内的结果条数,即从 timestamp1 开始每隔固定长度的时间(EVERY 值)进行插值。如果没有指定 EVERY,则默认窗口大小为无穷大,即从 timestamp1 开始只有一个窗口。 + +5)INTERP 根据 FILL 字段来决定在每个符合输出条件的时刻如何进行插值,如果没有 FILL 字段则默认不插值,即输出为原始记录值或不输出(原始记录不存在)。 + +6)INTERP 只能在一个时间序列内进行插值,因此当作用于超级表时必须跟 group by tbname 一起使用,当作用嵌套查询外层时内层子查询不能含 GROUP BY 信息。 + +7)INTERP 的插值结果不受 ORDER BY timestamp 的影响,ORDER BY timestamp 只影响输出结果的排序。 + +SQL 示例: + + 1) 单点线性插值 + +``` + taos> SELECT INTERP(*) FROM t1 RANGE('2017-7-14 18:40:00','2017-7-14 18:40:00') FILL(LINEAR); +``` + + 2) 在2017-07-14 18:00:00到2017-07-14 19:00:00间每隔5秒钟进行取值(不插值) + +``` + taos> SELECT INTERP(*) FROM t1 RANGE('2017-7-14 18:00:00','2017-7-14 19:00:00') EVERY(5s); +``` + + 3) 在2017-07-14 18:00:00到2017-07-14 19:00:00间每隔5秒钟进行线性插值 + +``` + taos> SELECT INTERP(*) FROM t1 RANGE('2017-7-14 18:00:00','2017-7-14 19:00:00') EVERY(5s) FILL(LINEAR); +``` + +4.在所有时间范围内每隔 5 秒钟进行向后插值 + +``` + taos> SELECT INTERP(*) FROM t1 EVERY(5s) FILL(NEXT); +``` + +5.根据 2017-07-14 17:00:00 到 2017-07-14 20:00:00 间的数据进行从 2017-07-14 18:00:00 到 2017-07-14 19:00:00 间每隔 5 秒钟进行线性插值 + +``` + taos> SELECT INTERP(*) FROM t1 where ts >= '2017-07-14 17:00:00' and ts <= '2017-07-14 20:00:00' RANGE('2017-7-14 18:00:00','2017-7-14 19:00:00') EVERY(5s) FILL(LINEAR); +``` + +### INTERP [2.3.1 之前的版本] + +``` +SELECT INTERP(field_name) FROM { tb_name | stb_name } WHERE ts='timestamp' [FILL ({ VALUE | PREV | NULL | LINEAR | NEXT})]; +``` + +**功能说明**:返回表/超级表的指定时间截面、指定字段的记录。 + +**返回数据类型**:同字段类型。 + +**应用字段**:数值型字段。 + +**适用于**:表、超级表。 + +说明:(从 2.0.15.0 版本开始新增此函数)
1)INTERP 必须指定时间断面,如果该时间断面不存在直接对应的数据,那么会根据 FILL 参数的设定进行插值。此外,条件语句里面可附带筛选条件,例如标签、tbname。
2)INTERP 查询要求查询的时间区间必须位于数据集合(表)的所有记录的时间范围之内。如果给定的时间戳位于时间范围之外,即使有插值指令,仍然不返回结果。
3)单个 INTERP 函数查询只能够针对一个时间点进行查询,如果需要返回等时间间隔的断面数据,可以通过 INTERP 配合 EVERY 的方式来进行查询处理(而不是使用 INTERVAL),其含义是每隔固定长度的时间进行插值。
+ 示例: + +``` + taos> SELECT INTERP(*) FROM meters WHERE ts='2017-7-14 18:40:00.004'; + interp(ts) | interp(current) | interp(voltage) | interp(phase) | + ========================================================================================== + 2017-07-14 18:40:00.004 | 9.84020 | 216 | 0.32222 | + Query OK, 1 row(s) in set (0.002652s) +``` + +如果给定的时间戳无对应的数据,在不指定插值生成策略的情况下,不会返回结果,如果指定了插值策略,会根据插值策略返回结果。 + +``` + taos> SELECT INTERP(*) FROM meters WHERE tbname IN ('d636') AND ts='2017-7-14 18:40:00.005'; + Query OK, 0 row(s) in set (0.004022s) + + taos> SELECT INTERP(*) FROM meters WHERE tbname IN ('d636') AND ts='2017-7-14 18:40:00.005' FILL(PREV); + interp(ts) | interp(current) | interp(voltage) | interp(phase) | + ========================================================================================== + 2017-07-14 18:40:00.005 | 9.88150 | 217 | 0.32500 | + Query OK, 1 row(s) in set (0.003056s) +``` + +如下所示代码表示在时间区间 `['2017-7-14 18:40:00', '2017-7-14 18:40:00.014']` 中每隔 5 毫秒 进行一次断面计算。 + +``` + taos> SELECT INTERP(current) FROM d636 WHERE ts>='2017-7-14 18:40:00' AND ts<='2017-7-14 18:40:00.014' EVERY(5a); + ts | interp(current) | + ================================================= + 2017-07-14 18:40:00.000 | 10.04179 | + 2017-07-14 18:40:00.010 | 10.16123 | + Query OK, 2 row(s) in set (0.003487s) +``` + +### TAIL + +``` +SELECT TAIL(field_name, k, offset_val) FROM {tb_name | stb_name} [WHERE clause]; +``` + +**功能说明**:返回跳过最后 offset_value 个,然后取连续 k 个记录,不忽略 NULL 值。offset_val 可以不输入。此时返回最后的 k 个记录。当有 offset_val 输入的情况下,该函数功能等效于 `order by ts desc LIMIT k OFFSET offset_val`。 + +**参数范围**:k: [1,100] offset_val: [0,100]。 + +**返回结果数据类型**:同应用的字段。 + +**应用字段**:适合于除时间主列外的任何类型字段。 + +**支持版本**:2.6 开始的版本。 + +示例: + +``` +taos> select ts,dbig from tail2; + ts | dbig | +================================================== +2021-10-15 00:31:33.000 | 1 | +2021-10-17 00:31:31.000 | NULL | +2021-12-24 00:31:34.000 | 2 | +2022-01-01 08:00:05.000 | 19 | +2022-01-01 08:00:06.000 | NULL | +2022-01-01 08:00:07.000 | 9 | +Query OK, 6 row(s) in set (0.001952s) + +taos> select tail(dbig,2,2) from tail2; +ts | tail(dbig,2,2) | +================================================== +2021-12-24 00:31:34.000 | 2 | +2022-01-01 08:00:05.000 | 19 | +Query OK, 2 row(s) in set (0.002307s) +``` + +### UNIQUE + +``` +SELECT UNIQUE(field_name) FROM {tb_name | stb_name} [WHERE clause]; +``` + +**功能说明**:返回该列的数值首次出现的值。该函数功能与 distinct 相似,但是可以匹配标签和时间戳信息。可以针对除时间列以外的字段进行查询,可以匹配标签和时间戳,其中的标签和时间戳是第一次出现时刻的标签和时间戳。 + +**返回结果数据类型**:同应用的字段。 + +**应用字段**:适合于除时间类型以外的字段。 + +**支持版本**:2.6 开始的版本。 + +**说明**: + +- 该函数可以应用在普通表和超级表上。不能和窗口操作一起使用,例如 interval/state_window/session_window 。 +- 由于返回数据量未知,考虑到内存因素,为了函数可以正常返回结果,建议不重复的数据量在 10 万级别,否则会报错。 + +示例: + +``` +taos> select ts,voltage from unique1; + ts | voltage | +================================================== +2021-10-17 00:31:31.000 | 1 | +2022-01-24 00:31:31.000 | 1 | +2021-10-17 00:31:31.000 | 1 | +2021-12-24 00:31:31.000 | 2 | +2022-01-01 08:00:01.000 | 19 | +2021-10-17 00:31:31.000 | NULL | +2022-01-01 08:00:02.000 | NULL | +2022-01-01 08:00:03.000 | 9 | +Query OK, 8 row(s) in set (0.003018s) + +taos> select unique(voltage) from unique1; +ts | unique(voltage) | +================================================== +2021-10-17 00:31:31.000 | 1 | +2021-10-17 00:31:31.000 | NULL | +2021-12-24 00:31:31.000 | 2 | +2022-01-01 08:00:01.000 | 19 | +2022-01-01 08:00:03.000 | 9 | +Query OK, 5 row(s) in set (0.108458s) +``` + +## 计算函数 + +- **DIFF** + + ```sql + SELECT {DIFF(field_name, ignore_negative) | DIFF(field_name)} FROM tb_name [WHERE clause]; + ``` + + 功能说明:统计表中某列的值与前一行对应值的差。 ignore_negative 取值为 0|1 , 可以不填,默认值为 0. 不忽略负值。ignore_negative 为 1 时表示忽略负数。 + + 返回结果数据类型:同应用字段。 + + 应用字段:不能应用在 timestamp、binary、nchar、bool 类型字段。 + + 适用于:**表、(超级表)**。 + + 说明:输出结果行数是范围内总行数减一,第一行没有结果输出。从 2.1.3.0 版本开始,DIFF 函数可以在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname)。从 2.6.0 开始,DIFF 函数支持 ignore_negative 参数 + + 示例: + + ```sql + taos> SELECT DIFF(current) FROM d1001; + ts | diff(current) | + ================================================= + 2018-10-03 14:38:15.000 | 2.30000 | + 2018-10-03 14:38:16.800 | -0.30000 | + Query OK, 2 row(s) in set (0.001162s) + ``` + +### DERIVATIVE + +``` +SELECT DERIVATIVE(field_name, time_interval, ignore_negative) FROM tb_name [WHERE clause]; +``` + +**功能说明**:统计表中某列数值的单位变化率。其中单位时间区间的长度可以通过 time_interval 参数指定,最小可以是 1 秒(1s);ignore_negative 参数的值可以是 0 或 1,为 1 时表示忽略负值。 + +**返回数据类型**:双精度浮点数。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +适用于:**表、(超级表)**。 + +说明:(从 2.1.3.0 版本开始新增此函数)输出结果行数是范围内总行数减一,第一行没有结果输出。DERIVATIVE 函数可以在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname)。 + +示例: + +``` +taos> select derivative(current, 10m, 0) from t1; + ts | derivative(current, 10m, 0) | +======================================================== + 2021-08-20 10:11:22.790 | 0.500000000 | + 2021-08-20 11:11:22.791 | 0.166666620 | + 2021-08-20 12:11:22.791 | 0.000000000 | + 2021-08-20 13:11:22.792 | 0.166666620 | + 2021-08-20 14:11:22.792 | -0.666666667 | +Query OK, 5 row(s) in set (0.004883s) +``` + +### SPREAD + +``` +SELECT SPREAD(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列的最大值和最小值之差。 + +**返回数据类型**:双精度浮点数。 + +**应用字段**:不能应用在 binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +说明:可用于 TIMESTAMP 字段,此时表示记录的时间覆盖范围。 + +示例: + +``` +taos> SELECT SPREAD(voltage) FROM meters; + spread(voltage) | +============================ + 5.000000000 | +Query OK, 1 row(s) in set (0.001792s) + +taos> SELECT SPREAD(voltage) FROM d1001; + spread(voltage) | +============================ + 3.000000000 | +Query OK, 1 row(s) in set (0.000836s) +``` + +### CEIL + +``` +SELECT CEIL(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:获得指定列的向上取整数的结果。 + +返回结果类型:与指定列的原始数据类型一致。例如,如果指定列的原始数据类型为 Float,那么返回的数据类型也为 Float;如果指定列的原始数据类型为 Double,那么返回的数据类型也为 Double。 + +适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列,无论 tag 列的类型是什么类型。 + +嵌套子查询支持:适用于内层查询和外层查询。 + +说明: +支持 +、-、\*、/ 运算,如 ceil(col1) + ceil(col2)。 +只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 +该函数可以应用在普通表和超级表上。 + +### FLOOR + +``` +SELECT FLOOR(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:获得指定列的向下取整数的结果。 + 其他使用说明参见 CEIL 函数描述。 + +### ROUND + +``` +SELECT ROUND(field_name) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:获得指定列的四舍五入的结果。 + 其他使用说明参见 CEIL 函数描述。 + +### CSUM + + ```sql + SELECT CSUM(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + + **功能说明**:累加和(Cumulative sum),输出行与输入行数相同。 + + **返回结果类型**: 输入列如果是整数类型返回值为长整型 (int64_t),浮点数返回值为双精度浮点数(Double)。无符号整数类型返回值为无符号长整型(uint64_t)。 返回结果中同时带有每行记录对应的时间戳。 + + **适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在标签之上。 + + **嵌套子查询支持**: 适用于内层查询和外层查询。 + + **补充说明**: 不支持 +、-、*、/ 运算,如 csum(col1) + csum(col2)。只能与聚合(Aggregation)函数一起使用。 该函数可以应用在普通表和超级表上。 使用在超级表上的时候,需要搭配 Group by tbname使用,将结果强制规约到单个时间线。 + + **支持版本**: 从2.3.0.x开始支持 + +### MAVG + + ```sql + SELECT MAVG(field_name, K) FROM { tb_name | stb_name } [WHERE clause] + ``` + + **功能说明**: 计算连续 k 个值的移动平均数(moving average)。如果输入行数小于 k,则无结果输出。参数 k 的合法输入范围是 1≤ k ≤ 1000。 + + **返回结果类型**: 返回双精度浮点数类型。 + + **适用数据类型**: 不能应用在 timestamp、binary、nchar、bool 类型上;在超级表查询中使用时,不能应用在标签之上。 + + **嵌套子查询支持**: 适用于内层查询和外层查询。 + + **补充说明**: 不支持 +、-、*、/ 运算,如 mavg(col1, k1) + mavg(col2, k1); 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用;该函数可以应用在普通表和超级表上;使用在超级表上的时候,需要搭配 Group by tbname使用,将结果强制规约到单个时间线。 + + **支持版本**: 从2.3.0.x开始支持 + +### SAMPLE + + ```sql + SELECT SAMPLE(field_name, K) FROM { tb_name | stb_name } [WHERE clause] + ``` + + **功能说明**: 获取数据的 k 个采样值。参数 k 的合法输入范围是 1≤ k ≤ 1000。 + + **返回结果类型**: 同原始数据类型, 返回结果中带有该行记录的时间戳。 + + **适用数据类型**: 在超级表查询中使用时,不能应用在标签之上。 + + **嵌套子查询支持**: 适用于内层查询和外层查询。 + + **补充说明**: 不能参与表达式计算;该函数可以应用在普通表和超级表上;使用在超级表上的时候,需要搭配 Group by tbname 使用,将结果强制规约到单个时间线。 + + **支持版本**: 从2.3.0.x开始支持 + +### ASIN + + ```sql + SELECT ASIN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的反正弦结果 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### ACOS + + ```sql + SELECT ACOS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的反余弦结果 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### ATAN + + ```sql + SELECT ATAN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的反正切结果 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### SIN + + ```sql + SELECT SIN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的正弦结果 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### COS + + ```sql + SELECT COS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的余弦结果 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### TAN + + ```sql + SELECT TAN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的正切结果 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### POW + + ```sql + SELECT POW(field_name, power) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的指数为 power 的幂 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### LOG + + ```sql + SELECT LOG(field_name, base) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列对于底数 base 的对数 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### ABS + + ```sql + SELECT ABS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的绝对值 + +**返回结果类型**:如果输入值为整数,输出值是 UBIGINT 类型。如果输入值是 FLOAT/DOUBLE 数据类型,输出值是 DOUBLE 数据类型。 + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### SQRT + + ```sql + SELECT SQRT(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:获得指定列的平方根 + +**返回结果类型**:DOUBLE。如果输入值为 NULL,输出值也为 NULL + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + +**嵌套子查询支持**:适用于内层查询和外层查询。 + +**使用说明**: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +### CAST + + ```sql + SELECT CAST(expression AS type_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:数据类型转换函数,输入参数 expression 支持普通列、常量、标量函数及它们之间的四则运算,不支持 tag 列,只适用于 select 子句中。 + +**返回结果类型**:CAST 中指定的类型(type_name)。 + +**适用数据类型**:输入参数 expression 的类型可以是除 JSON 外目前所有类型字段(BOOL/TINYINT/SMALLINT/INT/BIGINT/FLOAT/DOUBLE/BINARY(M)/TIMESTAMP/NCHAR(M)/TINYINT UNSIGNED/SMALLINT UNSIGNED/INT UNSIGNED/BIGINT UNSIGNED); 输出目标类型只支持 BIGINT/BINARY(N)/TIMESTAMP/NCHAR(N)/BIGINT UNSIGNED。 + + 说明: + + 对于不能支持的类型转换会直接报错。 + + 如果输入值为NULL则输出值也为NULL。 + + 对于类型支持但某些值无法正确转换的情况对应的转换后的值以转换函数输出为准。目前可能遇到的几种情况: + 1)BINARY/NCHAR转BIGINT/BIGINT UNSIGNED时可能出现的无效字符情况,例如"a"可能转为0。 + 2)有符号数或TIMESTAMP转BIGINT UNSIGNED可能遇到的溢出问题。 + 3)BIGINT UNSIGNED转BIGINT可能遇到的溢出问题。 + 4)FLOAT/DOUBLE转BIGINT/BIGINT UNSIGNED可能遇到的溢出问题。 + 版本2.6.0.x后支持 + +### CONCAT + + ```sql + SELECT CONCAT(str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:字符串连接函数。 + +**返回结果类型**:同输入参数类型,BINARY 或者 NCHAR。 + +**适用数据类型**:输入参数或者全部是 BINARY 格式的字符串或者列,或者全部是 NCHAR 格式的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果输入值为NULL,输出值为NULL。 + 该函数最小参数个数为2个,最大参数个数为8个。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### CONCAT_WS + + ``` + SELECT CONCAT_WS(separator, str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:带分隔符的字符串连接函数。 + +**返回结果类型**:同输入参数类型,BINARY 或者 NCHAR。 + +**适用数据类型**:输入参数或者全部是 BINARY 格式的字符串或者列,或者全部是 NCHAR 格式的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果separator值为NULL,输出值为NULL。如果separator值不为NULL,其他输入为NULL,输出为空串 + 该函数最小参数个数为3个,最大参数个数为9个。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### LENGTH + + ``` + SELECT LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:以字节计数的字符串长度。 + +**返回结果类型**:INT。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明** + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### CHAR_LENGTH + + ``` + SELECT CHAR_LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:以字符计数的字符串长度。 + +**返回结果类型**:INT。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明** + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### LOWER + + ``` + SELECT LOWER(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:将字符串参数值转换为全小写字母。 + +**返回结果类型**:同输入类型。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### UPPER + + ``` + SELECT UPPER(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:将字符串参数值转换为全大写字母。 + +**返回结果类型**:同输入类型。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### LTRIM + + ``` + SELECT LTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:返回清除左边空格后的字符串。 + +**返回结果类型**:同输入类型。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### RTRIM + + ``` + SELECT RTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:返回清除右边空格后的字符串。 + +**返回结果类型**:同输入类型。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### SUBSTR + + ``` + SELECT SUBSTR(str,pos[,len]) FROM { tb_name | stb_name } [WHERE clause] + ``` + +**功能说明**:从源字符串 str 中的指定位置 pos 开始取一个长度为 len 的子串并返回。 + +**返回结果类型**:同输入类型。 + +**适用数据类型**:输入参数是 BINARY 类型或者 NCHAR 类型的字符串或者列。不能应用在 TAG 列。 + +**说明**: + + 如果输入值为NULL,输出值为NULL。 + 输入参数pos可以为正数,也可以为负数。如果pos是正数,表示开始位置从字符串开头正数计算。如果pos为负数,表示开始位置从字符串结尾倒数计算。如果输入参数len被忽略,返回的子串包含从pos开始的整个字串。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +### 四则运算 + +``` +SELECT field_name [+|-|*|/|%][Value|field_name] FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:统计表/超级表中某列或多列间的值加、减、乘、除、取余计算结果。 + +**返回数据类型**:双精度浮点数。 + +**应用字段**:不能应用在 timestamp、binary、nchar、bool 类型字段。 + +**适用于**:表、超级表。 + +**说明**: + +1)支持两列或多列之间进行计算,可使用括号控制计算优先级; + +2)NULL 字段不参与计算,如果参与计算的某行中包含 NULL,该行的计算结果为 NULL。 + +``` +taos> SELECT current + voltage * phase FROM d1001; +(current+(voltage*phase)) | +============================ + 78.190000713 | + 84.540003240 | + 80.810000718 | +Query OK, 3 row(s) in set (0.001046s) +``` + +### STATECOUNT + +``` +SELECT STATECOUNT(field_name, oper, val) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:返回满足某个条件的连续记录的个数,结果作为新的一列追加在每行后面。条件根据参数计算,如果条件为 true 则加 1,条件为 false 则重置为-1,如果数据为 NULL,跳过该条数据。 + +**参数范围**: + +- oper : LT (小于)、GT(大于)、LE(小于等于)、GE(大于等于)、NE(不等于)、EQ(等于),不区分大小写。 +- val : 数值型 + +**返回结果类型**:整形。 + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上。 + +**嵌套子查询支持**:不支持应用在子查询上。 + +**支持的版本**:2.6 开始的版本。 + +**说明**: + +- 该函数可以应用在普通表上,在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname) + +- 不能和窗口操作一起使用,例如 interval/state_window/session_window。 + +**示例**: + +``` +taos> select ts,dbig from statef2; + ts | dbig | +======================================================== +2021-10-15 00:31:33.000000000 | 1 | +2021-10-17 00:31:31.000000000 | NULL | +2021-12-24 00:31:34.000000000 | 2 | +2022-01-01 08:00:05.000000000 | 19 | +2022-01-01 08:00:06.000000000 | NULL | +2022-01-01 08:00:07.000000000 | 9 | +Query OK, 6 row(s) in set (0.002977s) + +taos> select stateCount(dbig,GT,2) from statef2; +ts | dbig | statecount(dbig,gt,2) | +================================================================================ +2021-10-15 00:31:33.000000000 | 1 | -1 | +2021-10-17 00:31:31.000000000 | NULL | NULL | +2021-12-24 00:31:34.000000000 | 2 | -1 | +2022-01-01 08:00:05.000000000 | 19 | 1 | +2022-01-01 08:00:06.000000000 | NULL | NULL | +2022-01-01 08:00:07.000000000 | 9 | 2 | +Query OK, 6 row(s) in set (0.002791s) +``` + +### STATEDURATION + +``` +SELECT stateDuration(field_name, oper, val, unit) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:返回满足某个条件的连续记录的时间长度,结果作为新的一列追加在每行后面。条件根据参数计算,如果条件为 true 则加上两个记录之间的时间长度(第一个满足条件的记录时间长度记为 0),条件为 false 则重置为-1,如果数据为 NULL,跳过该条数据。 + +**参数范围**: + +- oper : LT (小于)、GT(大于)、LE(小于等于)、GE(大于等于)、NE(不等于)、EQ(等于),不区分大小写。 +- val : 数值型 +- unit : 时间长度的单位,范围[1s、1m、1h ],不足一个单位舍去。默认为 1s。 + +**返回结果类型**:整形。 + +**适用数据类型**:不能应用在 timestamp、binary、nchar、bool 类型字段上。 + +**嵌套子查询支持**:不支持应用在子查询上。 + +**支持的版本**:2.6 开始的版本。 + +**说明**: + +- 该函数可以应用在普通表上,在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname) + +- 不能和窗口操作一起使用,例如 interval/state_window/session_window。 + +**示例**: + +``` +taos> select ts,dbig from statef2; + ts | dbig | +======================================================== +2021-10-15 00:31:33.000000000 | 1 | +2021-10-17 00:31:31.000000000 | NULL | +2021-12-24 00:31:34.000000000 | 2 | +2022-01-01 08:00:05.000000000 | 19 | +2022-01-01 08:00:06.000000000 | NULL | +2022-01-01 08:00:07.000000000 | 9 | +Query OK, 6 row(s) in set (0.002407s) + +taos> select stateDuration(dbig,GT,2) from statef2; +ts | dbig | stateduration(dbig,gt,2) | +=================================================================================== +2021-10-15 00:31:33.000000000 | 1 | -1 | +2021-10-17 00:31:31.000000000 | NULL | NULL | +2021-12-24 00:31:34.000000000 | 2 | -1 | +2022-01-01 08:00:05.000000000 | 19 | 0 | +2022-01-01 08:00:06.000000000 | NULL | NULL | +2022-01-01 08:00:07.000000000 | 9 | 2 | +Query OK, 6 row(s) in set (0.002613s) +``` + +## 时间函数 + +从 2.6.0.0 版本开始,TDengine 查询引擎支持以下时间相关函数: + +### NOW + +```sql +SELECT NOW() FROM { tb_name | stb_name } [WHERE clause]; +SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operatior NOW(); +INSERT INTO tb_name VALUES (NOW(), ...); +``` + +**功能说明**:返回客户端当前系统时间。 + +**返回结果数据类型**:TIMESTAMP 时间戳类型。 + +**应用字段**:在 WHERE 或 INSERT 语句中使用时只能作用于 TIMESTAMP 类型的字段。 + +**适用于**:表、超级表。 + +**说明**: +1)支持时间加减操作,如 NOW() + 1s, 支持的时间单位如下: +b(纳秒)、u(微秒)、a(毫秒)、s(秒)、m(分)、h(小时)、d(天)、w(周)。 +2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + +**示例**: + +```sql +taos> SELECT NOW() FROM meters; + now() | +========================== + 2022-02-02 02:02:02.456 | +Query OK, 1 row(s) in set (0.002093s) + +taos> SELECT NOW() + 1h FROM meters; + now() + 1h | +========================== + 2022-02-02 03:02:02.456 | +Query OK, 1 row(s) in set (0.002093s) + +taos> SELECT COUNT(voltage) FROM d1001 WHERE ts < NOW(); + count(voltage) | +============================= + 5 | +Query OK, 5 row(s) in set (0.004475s) + +taos> INSERT INTO d1001 VALUES (NOW(), 10.2, 219, 0.32); +Query OK, 1 of 1 row(s) in database (0.002210s) +``` + +### TODAY + +```sql +SELECT TODAY() FROM { tb_name | stb_name } [WHERE clause]; +SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operatior TODAY()]; +INSERT INTO tb_name VALUES (TODAY(), ...); +``` + +**功能说明**:返回客户端当日零时的系统时间。 + +**返回结果数据类型**:TIMESTAMP 时间戳类型。 + +**应用字段**:在 WHERE 或 INSERT 语句中使用时只能作用于 TIMESTAMP 类型的字段。 + +**适用于**:表、超级表。 + +**说明**: +1)支持时间加减操作,如 TODAY() + 1s, 支持的时间单位如下: +b(纳秒),u(微秒),a(毫秒),s(秒),m(分),h(小时),d(天),w(周)。 +2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + +**示例**: + +```sql +taos> SELECT TODAY() FROM meters; + today() | +========================== + 2022-02-02 00:00:00.000 | +Query OK, 1 row(s) in set (0.002093s) + +taos> SELECT TODAY() + 1h FROM meters; + today() + 1h | +========================== + 2022-02-02 01:00:00.000 | +Query OK, 1 row(s) in set (0.002093s) + +taos> SELECT COUNT(voltage) FROM d1001 WHERE ts < TODAY(); + count(voltage) | +============================= + 5 | +Query OK, 5 row(s) in set (0.004475s) + +taos> INSERT INTO d1001 VALUES (TODAY(), 10.2, 219, 0.32); +Query OK, 1 of 1 row(s) in database (0.002210s) +``` + +### TIMEZONE + +```sql +SELECT TIMEZONE() FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:返回客户端当前时区信息。 + +**返回结果数据类型**:BINARY 类型。 + +**应用字段**:无 + +**适用于**:表、超级表。 + +**示例**: + +```sql +taos> SELECT TIMEZONE() FROM meters; + timezone() | +================================= + UTC (UTC, +0000) | +Query OK, 1 row(s) in set (0.002093s) +``` + +### TO_ISO8601 + +```sql +SELECT TO_ISO8601(ts_val | ts_col) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:将 UNIX 时间戳转换成为 ISO8601 标准的日期时间格式,并附加客户端时区信息。 + +**返回结果数据类型**:BINARY 类型。 + +**应用字段**:UNIX 时间戳常量或是 TIMESTAMP 类型的列 + +**适用于**:表、超级表。 + +**说明**:如果输入是 UNIX 时间戳常量,返回格式精度由时间戳的位数决定,如果输入是 TIMSTAMP 类型的列,返回格式的时间戳精度与当前 DATABASE 设置的时间精度一致。 + +**示例**: + +```sql +taos> SELECT TO_ISO8601(1643738400) FROM meters; + to_iso8601(1643738400) | +============================== + 2022-02-02T02:00:00+0800 | + +taos> SELECT TO_ISO8601(ts) FROM meters; + to_iso8601(ts) | +============================== + 2022-02-02T02:00:00+0800 | + 2022-02-02T02:00:00+0800 | + 2022-02-02T02:00:00+0800 | +``` + +### TO_UNIXTIMESTAMP + +```sql +SELECT TO_UNIXTIMESTAMP(datetime_string | ts_col) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:将日期时间格式的字符串转换成为 UNIX 时间戳。 + +**返回结果数据类型**:长整型 INT64。 + +**应用字段**:字符串常量或是 BINARY/NCHAR 类型的列。 + +**适用于**:表、超级表。 + +**说明**: +1)输入的日期时间字符串须符合 ISO8601/RFC3339 标准,无法转换的字符串格式将返回 0。 +2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + +**示例**: + +```sql +taos> SELECT TO_UNIXTIMESTAMP("2022-02-02T02:00:00.000Z") FROM meters; +to_unixtimestamp("2022-02-02T02:00:00.000Z") | +============================================== + 1643767200000 | + +taos> SELECT TO_UNIXTIMESTAMP(col_binary) FROM meters; + to_unixtimestamp(col_binary) | +======================================== + 1643767200000 | + 1643767200000 | + 1643767200000 | +``` + +### TIMETRUNCATE + +```sql +SELECT TIMETRUNCATE(ts_val | datetime_string | ts_col, time_unit) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:将时间戳按照指定时间单位 time_unit 进行截断。 + +**返回结果数据类型**:TIMESTAMP 时间戳类型。 + +**应用字段**:UNIX 时间戳,日期时间格式的字符串,或者 TIMESTAMP 类型的列。 + +**适用于**:表、超级表。 + +**说明**: +1)支持的时间单位 time_unit 如下: +1u(微秒),1a(毫秒),1s(秒),1m(分),1h(小时),1d(天)。 +2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + +**示例**: + +```sql +taos> SELECT TIMETRUNCATE(1643738522000, 1h) FROM meters; + timetruncate(1643738522000, 1h) | +=================================== + 2022-02-02 02:00:00.000 | +Query OK, 1 row(s) in set (0.001499s) + +taos> SELECT TIMETRUNCATE("2022-02-02 02:02:02", 1h) FROM meters; + timetruncate("2022-02-02 02:02:02", 1h) | +=========================================== + 2022-02-02 02:00:00.000 | +Query OK, 1 row(s) in set (0.003903s) + +taos> SELECT TIMETRUNCATE(ts, 1h) FROM meters; + timetruncate(ts, 1h) | +========================== + 2022-02-02 02:00:00.000 | + 2022-02-02 02:00:00.000 | + 2022-02-02 02:00:00.000 | +Query OK, 3 row(s) in set (0.003903s) +``` + +### TIMEDIFF + +```sql +SELECT TIMEDIFF(ts_val1 | datetime_string1 | ts_col1, ts_val2 | datetime_string2 | ts_col2 [, time_unit]) FROM { tb_name | stb_name } [WHERE clause]; +``` + +**功能说明**:计算两个时间戳之间的差值,并近似到时间单位 time_unit 指定的精度。 + +**返回结果数据类型**:长整型 INT64。 + +**应用字段**:UNIX 时间戳,日期时间格式的字符串,或者 TIMESTAMP 类型的列。 + +**适用于**:表、超级表。 + +**说明**: +1)支持的时间单位 time_unit 如下: +1u(微秒),1a(毫秒),1s(秒),1m(分),1h(小时),1d(天)。 +2)如果时间单位 time_unit 未指定, 返回的时间差值精度与当前 DATABASE 设置的时间精度一致。 + +**示例**: + +```sql +taos> SELECT TIMEDIFF(1643738400000, 1643742000000) FROM meters; + timediff(1643738400000, 1643742000000) | +========================================= + 3600000 | +Query OK, 1 row(s) in set (0.002553s) +taos> SELECT TIMEDIFF(1643738400000, 1643742000000, 1h) FROM meters; + timediff(1643738400000, 1643742000000, 1h) | +============================================= + 1 | +Query OK, 1 row(s) in set (0.003726s) + +taos> SELECT TIMEDIFF("2022-02-02 03:00:00", "2022-02-02 02:00:00", 1h) FROM meters; + timediff("2022-02-02 03:00:00", "2022-02-02 02:00:00", 1h) | +============================================================= + 1 | +Query OK, 1 row(s) in set (0.001937s) + +taos> SELECT TIMEDIFF(ts_col1, ts_col2, 1h) FROM meters; + timediff(ts_col1, ts_col2, 1h) | +=================================== + 1 | +Query OK, 1 row(s) in set (0.001937s) +``` diff --git a/docs-cn/14-reference/01-taos-sql/08-interval.md b/docs-cn/14-reference/01-taos-sql/08-interval.md new file mode 100644 index 0000000000000000000000000000000000000000..362ca1bef6ffa2b1e01d739907da5ebff726a500 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/08-interval.md @@ -0,0 +1,113 @@ +--- +sidebar_label: 按窗口切分聚合 +--- + +# 按窗口切分聚合 + +TDengine 支持按时间段窗口切分方式进行聚合结果查询,比如温度传感器每秒采集一次数据,但需查询每隔 10 分钟的温度平均值。这种场景下可以使用窗口子句来获得需要的查询结果。 +窗口子句用于针对查询的数据集合进行按照窗口切分成为查询子集并进行聚合,窗口包含时间窗口(time window)、状态窗口(status window)、会话窗口(session window)三种窗口。其中时间窗口又可划分为滑动时间窗口和翻转时间窗口。 + +## 时间窗口 + +INTERVAL 子句用于产生相等时间周期的窗口,SLIDING 用以指定窗口向前滑动的时间。每次执行的查询是一个时间窗口,时间窗口随着时间流动向前滑动。在定义连续查询的时候需要指定时间窗口(time window )大小和每次前向增量时间(forward sliding times)。如图,[t0s, t0e] ,[t1s , t1e], [t2s, t2e] 是分别是执行三次连续查询的时间窗口范围,窗口的前向滑动的时间范围 sliding time 标识 。查询过滤、聚合等操作按照每个时间窗口为独立的单位执行。当 SLIDING 与 INTERVAL 相等的时候,滑动窗口即为翻转窗口。 + +![时间窗口示意图](/img/sql/timewindow-1.png) + +INTERVAL 和 SLIDING 子句需要配合聚合和选择函数来使用。以下 SQL 语句非法: + +``` +SELECT * FROM temp_table INTERVAL(1S) +``` + +SLIDING 的向前滑动的时间不能超过一个窗口的时间范围。以下语句非法: + +``` +SELECT COUNT(*) FROM temp_table INTERVAL(1D) SLIDING(2D) +``` + +当 SLIDING 与 INTERVAL 取值相等的时候,滑动窗口即为翻转窗口。 +_ 聚合时间段的窗口宽度由关键词 INTERVAL 指定,最短时间间隔 10 毫秒(10a);并且支持偏移 offset(偏移必须小于间隔),也即时间窗口划分与“UTC 时刻 0”相比的偏移量。SLIDING 语句用于指定聚合时间段的前向增量,也即每次窗口向前滑动的时长。 +_ 从 2.1.5.0 版本开始,INTERVAL 语句允许的最短时间间隔调整为 1 微秒(1u),当然如果所查询的 DATABASE 的时间精度设置为毫秒级,那么允许的最短时间间隔为 1 毫秒(1a)。 \* **注意**:用到 INTERVAL 语句时,除非极特殊的情况,都要求把客户端和服务端的 taos.cfg 配置文件中的 timezone 参数配置为相同的取值,以避免时间处理函数频繁进行跨时区转换而导致的严重性能影响。 + +## 状态窗口 + +使用整数(布尔值)或字符串来标识产生记录时候设备的状态量。产生的记录如果具有相同的状态量数值则归属于同一个状态窗口,数值改变后该窗口关闭。如下图所示,根据状态量确定的状态窗口分别是[2019-04-28 14:22:07,2019-04-28 14:22:10]和[2019-04-28 14:22:11,2019-04-28 14:22:12]两个。(状态窗口暂不支持对超级表使用) + +![时间窗口示意图](/img/sql/timewindow-3.png) + +使用 STATE_WINDOW 来确定状态窗口划分的列。例如: + +``` +SELECT COUNT(*), FIRST(ts), status FROM temp_tb_1 STATE_WINDOW(status) +``` + +## 会话窗口 + +会话窗口根据记录的时间戳主键的值来确定是否属于同一个会话。如下图所示,如果设置时间戳的连续的间隔小于等于 12 秒,则以下 6 条记录构成 2 个会话窗口,分别是:[2019-04-28 14:22:10,2019-04-28 14:22:30]和[2019-04-28 14:23:10,2019-04-28 14:23:30]。因为 2019-04-28 14:22:30 与 2019-04-28 14:23:10 之间的时间间隔是 40 秒,超过了连续时间间隔(12 秒)。 + +![时间窗口示意图](/img/sql/timewindow-2.png) + +在 tol_value 时间间隔范围内的结果都认为归属于同一个窗口,如果连续的两条记录的时间超过 tol_val,则自动开启下一个窗口。(会话窗口暂不支持对超级表使用) + +``` + +SELECT COUNT(*), FIRST(ts) FROM temp_tb_1 SESSION(ts, tol_val) +``` + +这种类型的查询语法如下: + +``` +SELECT function_list FROM tb_name + [WHERE where_condition] + [SESSION(ts_col, tol_val)] + [STATE_WINDOW(col)] + [INTERVAL(interval [, offset]) [SLIDING sliding]] + [FILL({NONE | VALUE | PREV | NULL | LINEAR | NEXT})] + +SELECT function_list FROM stb_name + [WHERE where_condition] + [INTERVAL(interval [, offset]) [SLIDING sliding]] + [FILL({NONE | VALUE | PREV | NULL | LINEAR | NEXT})] + [GROUP BY tags] +``` + +- 在聚合查询中,function_list 位置允许使用聚合和选择函数,并要求每个函数仅输出单个结果(例如:COUNT、AVG、SUM、STDDEV、LEASTSQUARES、PERCENTILE、MIN、MAX、FIRST、LAST),而不能使用具有多行输出结果的函数(例如:DIFF 以及四则运算)。 +- 此外也 LAST_ROW 查询也不能与窗口聚合同时出现。 +- 标量函数(如:CEIL/FLOOR 等)也不能使用在窗口聚合查询中。 +- + +- WHERE 语句可以指定查询的起止时间和其他过滤条件。 +- FILL 语句指定某一窗口区间数据缺失的情况下的填充模式。填充模式包括以下几种: + 1. 不进行填充:NONE(默认填充模式)。 + 2. VALUE 填充:固定值填充,此时需要指定填充的数值。例如:FILL(VALUE, 1.23)。 + 3. PREV 填充:使用前一个非 NULL 值填充数据。例如:FILL(PREV)。 + 4. NULL 填充:使用 NULL 填充数据。例如:FILL(NULL)。 + 5. LINEAR 填充:根据前后距离最近的非 NULL 值做线性插值填充。例如:FILL(LINEAR)。 + 6. NEXT 填充:使用下一个非 NULL 值填充数据。例如:FILL(NEXT)。 + +:::info + +1. 使用 FILL 语句的时候可能生成大量的填充输出,务必指定查询的时间区间。针对每次查询,系统可返回不超过 1 千万条具有插值的结果。 +2. 在时间维度聚合中,返回的结果中时间序列严格单调递增。 +3. 如果查询对象是超级表,则聚合函数会作用于该超级表下满足值过滤条件的所有表的数据。如果查询中没有使用 GROUP BY 语句,则返回的结果按照时间序列严格单调递增;如果查询中使用了 GROUP BY 语句分组,则返回结果中每个 GROUP 内不按照时间序列严格单调递增。 + +::: + +时间聚合也常被用于连续查询场景,可以参考文档 [连续查询(Continuous Query)](https://www.taosdata.com/cn/documentation/advanced-features#continuous-query)。 + +## 示例 + +智能电表的建表语句如下: + +``` +CREATE TABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT); +``` + +针对智能电表采集的数据,以 10 分钟为一个阶段,计算过去 24 小时的电流数据的平均值、最大值、电流的中位数。如果没有计算值,用前一个非 NULL 值填充。使用的查询语句如下: + +``` +SELECT AVG(current), MAX(current), APERCENTILE(current, 50) FROM meters + WHERE ts>=NOW-1d and ts<=now + INTERVAL(10m) + FILL(PREV); +``` diff --git a/docs-cn/14-reference/01-taos-sql/09-limit.md b/docs-cn/14-reference/01-taos-sql/09-limit.md new file mode 100644 index 0000000000000000000000000000000000000000..c4e7c6b2f03f3a3f469d32f713bf15bba32f54bc --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/09-limit.md @@ -0,0 +1,51 @@ +--- +sidebar_label: 边界限制 +--- + +# 边界限制 + +## 一般限制 + +- 数据库名最大长度为 32。 +- 表名最大长度为 192,每行数据最大长度 16k 个字符, 从 2.1.7.0 版本开始,每行数据最大长度 48k 个字符(注意:数据行内每个 BINARY/NCHAR 类型的列还会额外占用 2 个字节的存储位置)。 +- 列名最大长度为 64,最多允许 1024 列,最少需要 2 列,第一列必须是时间戳。(从 2.1.7.0 版本开始,改为最多允许 4096 列) +- 标签名最大长度为 64,最多允许 128 个,可以 1 个,一个表中标签值的总长度不超过 16k 个字符。 +- SQL 语句最大长度 1048576 个字符,也可通过客户端配置参数 maxSQLLength 修改,取值范围 65480 ~ 1048576。 +- SELECT 语句的查询结果,最多允许返回 1024 列(语句中的函数调用可能也会占用一些列空间),超限时需要显式指定较少的返回数据列,以避免语句执行报错。(从 2.1.7.0 版本开始,改为最多允许 4096 列) +- 库的数目,超级表的数目、表的数目,系统不做限制,仅受系统资源限制。 + +## GROUP BY 的限制 + +TAOS SQL 支持对标签、TBNAME 进行 GROUP BY 操作,也支持普通列进行 GROUP BY,前提是:仅限一列且该列的唯一值小于 10 万个。注意:group by 不支持 float,double 类型。 + +## IS NOT NULL 的限制 + +IS NOT NULL 与不为空的表达式适用范围。 + +IS NOT NULL 支持所有类型的列。不为空的表达式为 <\>"",仅对非数值类型的列适用。 + +## ORDER BY 的限制 + +- 非超级表只能有一个 order by. +- 超级表最多两个 order by, 并且第二个必须为 ts. +- order by tag,必须和 group by tag 一起,并且是同一个 tag。 tbname 和 tag 一样逻辑。 只适用于超级表 +- order by 普通列,必须和 group by 一起或者和 top/bottom 一起,并且是同一个普通列。 适用于超级表和普通表。如果同时存在 group by 和 top/bottom 一起,order by 优先必须和 group by 同一列。 +- order by ts. 适用于超级表和普通表。 +- order by ts 同时含有 group by 时 针对 group 内部用 ts 排序 + +## 表(列)名合法性说明 + +TDengine 中的表(列)名命名规则如下: +只能由字母、数字、下划线构成,数字不能在首位,长度不能超过 192 字节,不区分大小写。这里表名称不包括数据库名的前缀和分隔符。 + +转移后表(列)名规则: +为了兼容支持更多形式的表(列)名,TDengine 引入新的转义符 "`"。可用让表名与关键词不冲突,同时不受限于上述表名称合法性约束检查,转义符不计入表名称的长度。 +转义后的表(列)名同样受到长度限制要求,且长度计算的时候不计算转义符。使用转义字符以后,不再对转义字符中的内容进行大小写统一。 + +例如: +\`aBc\` 和 \`abc\` 是不同的表(列)名,但是 abc 和 aBc 是相同的表(列)名。 + +需要注意的是转义字符中的内容必须是可打印字符。 + +支持版本 +支持转义符的功能从 2.3.0.1 版本开始。 \ No newline at end of file diff --git a/docs-cn/14-reference/01-taos-sql/10-json.md b/docs-cn/14-reference/01-taos-sql/10-json.md new file mode 100644 index 0000000000000000000000000000000000000000..6a06bd30ea9eec9eb8e1471d60f74416f6e45e96 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/10-json.md @@ -0,0 +1,91 @@ +--- +sidebar_label: JSON 类型使用说明 +--- + +# JSON 类型使用说明 + +## 语法说明 + +1. 创建 json 类型 tag + + ``` + create stable s1 (ts timestamp, v1 int) tags (info json) + + create table s1_1 using s1 tags ('{"k1": "v1"}') + ``` + +2. json 取值操作符 -> + + ``` + select * from s1 where info->'k1' = 'v1' + + select info->'k1' from s1 + ``` + +3. json key 是否存在操作符 contains + + ``` + select * from s1 where info contains 'k2' + + select * from s1 where info contains 'k1' + ``` + +## 支持的操作 + +1. 在 where 条件中时,支持函数 match/nmatch/between and/like/and/or/is null/is no null,不支持 in + + ``` + select * from s1 where info->'k1' match 'v*'; + + select * from s1 where info->'k1' like 'v%' and info contains 'k2'; + + select * from s1 where info is null; + + select * from s1 where info->'k1' is not null + ``` + +2. 支持 json tag 放在 group by、order by、join 子句、union all 以及子查询中,比如 group by json->'key' + +3. 支持 distinct 操作. + + ``` + select distinct info->'k1' from s1 + ``` + +4. 标签操作 + + 支持修改 json 标签值(全量覆盖) + + 支持修改 json 标签名 + + 不支持添加 json 标签、删除 json 标签、修改 json 标签列宽 + +## 其他约束条件 + +1. 只有标签列可以使用 json 类型,如果用 json 标签,标签列只能有一个。 + +2. 长度限制:json 中 key 的长度不能超过 256,并且 key 必须为可打印 ascii 字符;json 字符串总长度不超过 4096 个字节。 + +3. json 格式限制: + + 1. json 输入字符串可以为空("","\t"," "或 null)或 object,不能为非空的字符串,布尔型和数组。 + 2. object 可为{},如果 object 为{},则整个 json 串记为空。key 可为"",若 key 为"",则 json 串中忽略该 k-v 对。 + 3. value 可以为数字(int/double)或字符串或 bool 或 null,暂不可以为数组。不允许嵌套。 + 4. 若 json 字符串中出现两个相同的 key,则第一个生效。 + 5. json 字符串里暂不支持转义。 + +4. 当查询 json 中不存在的 key 时,返回 NULL + +5. 当 json tag 作为子查询结果时,不再支持上层查询继续对子查询中的 json 串做解析查询。 + + 比如暂不支持 + + ``` + select jtag->'key' from (select jtag from stable) + ``` + + 不支持 + + ``` + select jtag->'key' from (select jtag from stable) where jtag->'key'>0 + ``` diff --git a/docs-cn/14-reference/01-taos-sql/11-escape.md b/docs-cn/14-reference/01-taos-sql/11-escape.md new file mode 100644 index 0000000000000000000000000000000000000000..be27dd4e7b6dd59264d8740f47d4baaf4182a678 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/11-escape.md @@ -0,0 +1,28 @@ +# 转义字符说明 + +## 转义字符表 + +| 字符序列 | **代表的字符** | +| :------: | -------------- | +| `\'` | 单引号' | +| `\"` | 双引号" | +| \n | 换行符 | +| \r | 回车符 | +| \t | tab 符 | +| `\\` | 斜杠\ | +| `\%` | % 规则见下 | +| `\_` | \_ 规则见下 | + +:::note +转义符的功能从 2.4.0.4 版本开始 + +::: + +## 转义字符使用规则 + +1. 标识符里有转义字符(数据库名、表名、列名) + 1. 普通标识符: 直接提示错误的标识符,因为标识符规定必须是数字、字母和下划线,并且不能以数字开头。 + 2. 反引号``标识符: 保持原样,不转义 +2. 数据里有转义字符 + 1. 遇到上面定义的转义字符会转义(%和\_见下面说明),如果没有匹配的转义字符会忽略掉转义符\。 + 2. 对于%和*,因为在 like 里这两个字符是通配符,所以在模式匹配 like 里用`\%`%和`\_`表示字符里本身的%和*,如果在 like 模式匹配上下文之外使用`\%`或`\_`,则它们的计算结果为字符串`\%`和`\_`,而不是%和\_。 diff --git a/docs-cn/14-reference/01-taos-sql/12-errorcode.md b/docs-cn/14-reference/01-taos-sql/12-errorcode.md new file mode 100644 index 0000000000000000000000000000000000000000..2013e1e640d10bbd09572ca1d9c4ba12a38620d8 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/12-errorcode.md @@ -0,0 +1,176 @@ +--- +sidebar_label: 错误码 +--- + +# 错误码以及对应的十进制码 + +| 状态码 | 模 | 错误码(十六进制) | 错误描述 | 错误码(十进制) | +| :-------------------------------------- | :-: | :----------------: | :------------------------------------------- | :--------------- | +| TSDB_CODE_RPC_ACTION_IN_PROGRESS | 0 | 0x0001 | "Action in progress" | -2147483647 | +| TSDB_CODE_RPC_AUTH_REQUIRED | 0 | 0x0002 | "Authentication required" | -2147483646 | +| TSDB_CODE_RPC_AUTH_FAILURE | 0 | 0x0003 | "Authentication failure" | -2147483645 | +| TSDB_CODE_RPC_REDIRECT | 0 | 0x0004 | "Redirect" | -2147483644 | +| TSDB_CODE_RPC_NOT_READY | 0 | 0x0005 | "System not ready" | -2147483643 | +| TSDB_CODE_RPC_ALREADY_PROCESSED | 0 | 0x0006 | "Message already processed" | -2147483642 | +| TSDB_CODE_RPC_LAST_SESSION_NOT_FINISHED | 0 | 0x0007 | "Last session not finished" | -2147483641 | +| TSDB_CODE_RPC_MISMATCHED_LINK_ID | 0 | 0x0008 | "Mismatched meter id" | -2147483640 | +| TSDB_CODE_RPC_TOO_SLOW | 0 | 0x0009 | "Processing of request timed out" | -2147483639 | +| TSDB_CODE_RPC_MAX_SESSIONS | 0 | 0x000A | "Number of sessions reached limit" | -2147483638 | +| TSDB_CODE_RPC_NETWORK_UNAVAIL | 0 | 0x000B | "Unable to establish connection" | -2147483637 | +| TSDB_CODE_RPC_APP_ERROR | 0 | 0x000C | "Unexpected generic error in RPC" | -2147483636 | +| TSDB_CODE_RPC_UNEXPECTED_RESPONSE | 0 | 0x000D | "Unexpected response" | -2147483635 | +| TSDB_CODE_RPC_INVALID_VALUE | 0 | 0x000E | "Invalid value" | -2147483634 | +| TSDB_CODE_RPC_INVALID_TRAN_ID | 0 | 0x000F | "Invalid transaction id" | -2147483633 | +| TSDB_CODE_RPC_INVALID_SESSION_ID | 0 | 0x0010 | "Invalid session id" | -2147483632 | +| TSDB_CODE_RPC_INVALID_MSG_TYPE | 0 | 0x0011 | "Invalid message type" | -2147483631 | +| TSDB_CODE_RPC_INVALID_RESPONSE_TYPE | 0 | 0x0012 | "Invalid response type" | -2147483630 | +| TSDB_CODE_RPC_INVALID_TIME_STAMP | 0 | 0x0013 | "Invalid timestamp" | -2147483629 | +| TSDB_CODE_COM_OPS_NOT_SUPPORT | 0 | 0x0100 | "Operation not supported" | -2147483392 | +| TSDB_CODE_COM_MEMORY_CORRUPTED | 0 | 0x0101 | "Memory corrupted" | -2147483391 | +| TSDB_CODE_COM_OUT_OF_MEMORY | 0 | 0x0102 | "Out of memory" | -2147483390 | +| TSDB_CODE_COM_INVALID_CFG_MSG | 0 | 0x0103 | "Invalid config message" | -2147483389 | +| TSDB_CODE_COM_FILE_CORRUPTED | 0 | 0x0104 | "Data file corrupted" | -2147483388 | +| TSDB_CODE_TSC_INVALID_OPERATION | 0 | 0x0200 | "Invalid SQL statement" | -2147483136 | +| TSDB_CODE_TSC_INVALID_QHANDLE | 0 | 0x0201 | "Invalid qhandle" | -2147483135 | +| TSDB_CODE_TSC_INVALID_TIME_STAMP | 0 | 0x0202 | "Invalid combination of client/service time" | -2147483134 | +| TSDB_CODE_TSC_INVALID_VALUE | 0 | 0x0203 | "Invalid value in client" | -2147483133 | +| TSDB_CODE_TSC_INVALID_VERSION | 0 | 0x0204 | "Invalid client version" | -2147483132 | +| TSDB_CODE_TSC_INVALID_IE | 0 | 0x0205 | "Invalid client ie" | -2147483131 | +| TSDB_CODE_TSC_INVALID_FQDN | 0 | 0x0206 | "Invalid host name" | -2147483130 | +| TSDB_CODE_TSC_INVALID_USER_LENGTH | 0 | 0x0207 | "Invalid user name" | -2147483129 | +| TSDB_CODE_TSC_INVALID_PASS_LENGTH | 0 | 0x0208 | "Invalid password" | -2147483128 | +| TSDB_CODE_TSC_INVALID_DB_LENGTH | 0 | 0x0209 | "Database name too long" | -2147483127 | +| TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH | 0 | 0x020A | "Table name too long" | -2147483126 | +| TSDB_CODE_TSC_INVALID_CONNECTION | 0 | 0x020B | "Invalid connection" | -2147483125 | +| TSDB_CODE_TSC_OUT_OF_MEMORY | 0 | 0x020C | "System out of memory" | -2147483124 | +| TSDB_CODE_TSC_NO_DISKSPACE | 0 | 0x020D | "System out of disk space" | -2147483123 | +| TSDB_CODE_TSC_QUERY_CACHE_ERASED | 0 | 0x020E | "Query cache erased" | -2147483122 | +| TSDB_CODE_TSC_QUERY_CANCELLED | 0 | 0x020F | "Query terminated" | -2147483121 | +| TSDB_CODE_TSC_SORTED_RES_TOO_MANY | 0 | 0x0210 | "Result set too large to be sorted" | -2147483120 | +| TSDB_CODE_TSC_APP_ERROR | 0 | 0x0211 | "Application error" | -2147483119 | +| TSDB_CODE_TSC_ACTION_IN_PROGRESS | 0 | 0x0212 | "Action in progress" | -2147483118 | +| TSDB_CODE_TSC_DISCONNECTED | 0 | 0x0213 | "Disconnected from service" | -2147483117 | +| TSDB_CODE_TSC_NO_WRITE_AUTH | 0 | 0x0214 | "No write permission" | -2147483116 | +| TSDB_CODE_MND_MSG_NOT_PROCESSED | 0 | 0x0300 | "Message not processed" | -2147482880 | +| TSDB_CODE_MND_ACTION_IN_PROGRESS | 0 | 0x0301 | "Message is progressing" | -2147482879 | +| TSDB_CODE_MND_ACTION_NEED_REPROCESSED | 0 | 0x0302 | "Messag need to be reprocessed" | -2147482878 | +| TSDB_CODE_MND_NO_RIGHTS | 0 | 0x0303 | "Insufficient privilege for operation" | -2147482877 | +| TSDB_CODE_MND_APP_ERROR | 0 | 0x0304 | "Unexpected generic error in mnode" | -2147482876 | +| TSDB_CODE_MND_INVALID_CONNECTION | 0 | 0x0305 | "Invalid message connection" | -2147482875 | +| TSDB_CODE_MND_INVALID_MSG_VERSION | 0 | 0x0306 | "Incompatible protocol version" | -2147482874 | +| TSDB_CODE_MND_INVALID_MSG_LEN | 0 | 0x0307 | "Invalid message length" | -2147482873 | +| TSDB_CODE_MND_INVALID_MSG_TYPE | 0 | 0x0308 | "Invalid message type" | -2147482872 | +| TSDB_CODE_MND_TOO_MANY_SHELL_CONNS | 0 | 0x0309 | "Too many connections" | -2147482871 | +| TSDB_CODE_MND_OUT_OF_MEMORY | 0 | 0x030A | "Out of memory in mnode" | -2147482870 | +| TSDB_CODE_MND_INVALID_SHOWOBJ | 0 | 0x030B | "Data expired" | -2147482869 | +| TSDB_CODE_MND_INVALID_QUERY_ID | 0 | 0x030C | "Invalid query id" | -2147482868 | +| TSDB_CODE_MND_INVALID_STREAM_ID | 0 | 0x030D | "Invalid stream id" | -2147482867 | +| TSDB_CODE_MND_INVALID_CONN_ID | 0 | 0x030E | "Invalid connection id" | -2147482866 | +| TSDB_CODE_MND_SDB_OBJ_ALREADY_THERE | 0 | 0x0320 | "Object already there" | -2147482848 | +| TSDB_CODE_MND_SDB_ERROR | 0 | 0x0321 | "Unexpected generic error in sdb" | -2147482847 | +| TSDB_CODE_MND_SDB_INVALID_TABLE_TYPE | 0 | 0x0322 | "Invalid table type" | -2147482846 | +| TSDB_CODE_MND_SDB_OBJ_NOT_THERE | 0 | 0x0323 | "Object not there" | -2147482845 | +| TSDB_CODE_MND_SDB_INVAID_META_ROW | 0 | 0x0324 | "Invalid meta row" | -2147482844 | +| TSDB_CODE_MND_SDB_INVAID_KEY_TYPE | 0 | 0x0325 | "Invalid key type" | -2147482843 | +| TSDB_CODE_MND_DNODE_ALREADY_EXIST | 0 | 0x0330 | "DNode already exists" | -2147482832 | +| TSDB_CODE_MND_DNODE_NOT_EXIST | 0 | 0x0331 | "DNode does not exist" | -2147482831 | +| TSDB_CODE_MND_VGROUP_NOT_EXIST | 0 | 0x0332 | "VGroup does not exist" | -2147482830 | +| TSDB_CODE_MND_NO_REMOVE_MASTER | 0 | 0x0333 | "Master DNode cannot be removed" | -2147482829 | +| TSDB_CODE_MND_NO_ENOUGH_DNODES | 0 | 0x0334 | "Out of DNodes" | -2147482828 | +| TSDB_CODE_MND_CLUSTER_CFG_INCONSISTENT | 0 | 0x0335 | "Cluster cfg inconsistent" | -2147482827 | +| TSDB_CODE_MND_INVALID_DNODE_CFG_OPTION | 0 | 0x0336 | "Invalid dnode cfg option" | -2147482826 | +| TSDB_CODE_MND_BALANCE_ENABLED | 0 | 0x0337 | "Balance already enabled" | -2147482825 | +| TSDB_CODE_MND_VGROUP_NOT_IN_DNODE | 0 | 0x0338 | "Vgroup not in dnode" | -2147482824 | +| TSDB_CODE_MND_VGROUP_ALREADY_IN_DNODE | 0 | 0x0339 | "Vgroup already in dnode" | -2147482823 | +| TSDB_CODE_MND_DNODE_NOT_FREE | 0 | 0x033A | "Dnode not avaliable" | -2147482822 | +| TSDB_CODE_MND_INVALID_CLUSTER_ID | 0 | 0x033B | "Cluster id not match" | -2147482821 | +| TSDB_CODE_MND_NOT_READY | 0 | 0x033C | "Cluster not ready" | -2147482820 | +| TSDB_CODE_MND_ACCT_ALREADY_EXIST | 0 | 0x0340 | "Account already exists" | -2147482816 | +| TSDB_CODE_MND_INVALID_ACCT | 0 | 0x0341 | "Invalid account" | -2147482815 | +| TSDB_CODE_MND_INVALID_ACCT_OPTION | 0 | 0x0342 | "Invalid account options" | -2147482814 | +| TSDB_CODE_MND_USER_ALREADY_EXIST | 0 | 0x0350 | "User already exists" | -2147482800 | +| TSDB_CODE_MND_INVALID_USER | 0 | 0x0351 | "Invalid user" | -2147482799 | +| TSDB_CODE_MND_INVALID_USER_FORMAT | 0 | 0x0352 | "Invalid user format" | -2147482798 | +| TSDB_CODE_MND_INVALID_PASS_FORMAT | 0 | 0x0353 | "Invalid password format" | -2147482797 | +| TSDB_CODE_MND_NO_USER_FROM_CONN | 0 | 0x0354 | "Can not get user from conn" | -2147482796 | +| TSDB_CODE_MND_TOO_MANY_USERS | 0 | 0x0355 | "Too many users" | -2147482795 | +| TSDB_CODE_MND_TABLE_ALREADY_EXIST | 0 | 0x0360 | "Table already exists" | -2147482784 | +| TSDB_CODE_MND_INVALID_TABLE_ID | 0 | 0x0361 | "Table name too long" | -2147482783 | +| TSDB_CODE_MND_INVALID_TABLE_NAME | 0 | 0x0362 | "Table does not exist" | -2147482782 | +| TSDB_CODE_MND_INVALID_TABLE_TYPE | 0 | 0x0363 | "Invalid table type in tsdb" | -2147482781 | +| TSDB_CODE_MND_TOO_MANY_TAGS | 0 | 0x0364 | "Too many tags" | -2147482780 | +| TSDB_CODE_MND_TOO_MANY_TIMESERIES | 0 | 0x0366 | "Too many time series" | -2147482778 | +| TSDB_CODE_MND_NOT_SUPER_TABLE | 0 | 0x0367 | "Not super table" | -2147482777 | +| TSDB_CODE_MND_COL_NAME_TOO_LONG | 0 | 0x0368 | "Tag name too long" | -2147482776 | +| TSDB_CODE_MND_TAG_ALREAY_EXIST | 0 | 0x0369 | "Tag already exists" | -2147482775 | +| TSDB_CODE_MND_TAG_NOT_EXIST | 0 | 0x036A | "Tag does not exist" | -2147482774 | +| TSDB_CODE_MND_FIELD_ALREAY_EXIST | 0 | 0x036B | "Field already exists" | -2147482773 | +| TSDB_CODE_MND_FIELD_NOT_EXIST | 0 | 0x036C | "Field does not exist" | -2147482772 | +| TSDB_CODE_MND_INVALID_STABLE_NAME | 0 | 0x036D | "Super table does not exist" | -2147482771 | +| TSDB_CODE_MND_DB_NOT_SELECTED | 0 | 0x0380 | "Database not specified or available" | -2147482752 | +| TSDB_CODE_MND_DB_ALREADY_EXIST | 0 | 0x0381 | "Database already exists" | -2147482751 | +| TSDB_CODE_MND_INVALID_DB_OPTION | 0 | 0x0382 | "Invalid database options" | -2147482750 | +| TSDB_CODE_MND_INVALID_DB | 0 | 0x0383 | "Invalid database name" | -2147482749 | +| TSDB_CODE_MND_MONITOR_DB_FORBIDDEN | 0 | 0x0384 | "Cannot delete monitor database" | -2147482748 | +| TSDB_CODE_MND_TOO_MANY_DATABASES | 0 | 0x0385 | "Too many databases for account" | -2147482747 | +| TSDB_CODE_MND_DB_IN_DROPPING | 0 | 0x0386 | "Database not available" | -2147482746 | +| TSDB_CODE_DND_MSG_NOT_PROCESSED | 0 | 0x0400 | "Message not processed" | -2147482624 | +| TSDB_CODE_DND_OUT_OF_MEMORY | 0 | 0x0401 | "Dnode out of memory" | -2147482623 | +| TSDB_CODE_DND_NO_WRITE_ACCESS | 0 | 0x0402 | "No permission for disk files in dnode" | -2147482622 | +| TSDB_CODE_DND_INVALID_MSG_LEN | 0 | 0x0403 | "Invalid message length" | -2147482621 | +| TSDB_CODE_VND_ACTION_IN_PROGRESS | 0 | 0x0500 | "Action in progress" | -2147482368 | +| TSDB_CODE_VND_MSG_NOT_PROCESSED | 0 | 0x0501 | "Message not processed" | -2147482367 | +| TSDB_CODE_VND_ACTION_NEED_REPROCESSED | 0 | 0x0502 | "Action need to be reprocessed" | -2147482366 | +| TSDB_CODE_VND_INVALID_VGROUP_ID | 0 | 0x0503 | "Invalid Vgroup ID" | -2147482365 | +| TSDB_CODE_VND_INIT_FAILED | 0 | 0x0504 | "Vnode initialization failed" | -2147482364 | +| TSDB_CODE_VND_NO_DISKSPACE | 0 | 0x0505 | "System out of disk space" | -2147482363 | +| TSDB_CODE_VND_NO_DISK_PERMISSIONS | 0 | 0x0506 | "No write permission for disk files" | -2147482362 | +| TSDB_CODE_VND_NO_SUCH_FILE_OR_DIR | 0 | 0x0507 | "Missing data file" | -2147482361 | +| TSDB_CODE_VND_OUT_OF_MEMORY | 0 | 0x0508 | "Out of memory" | -2147482360 | +| TSDB_CODE_VND_APP_ERROR | 0 | 0x0509 | "Unexpected generic error in vnode" | -2147482359 | +| TSDB_CODE_VND_INVALID_STATUS | 0 | 0x0510 | "Database not ready" | -2147482352 | +| TSDB_CODE_VND_NOT_SYNCED | 0 | 0x0511 | "Database suspended" | -2147482351 | +| TSDB_CODE_VND_NO_WRITE_AUTH | 0 | 0x0512 | "Write operation denied" | -2147482350 | +| TSDB_CODE_TDB_INVALID_TABLE_ID | 0 | 0x0600 | "Invalid table ID" | -2147482112 | +| TSDB_CODE_TDB_INVALID_TABLE_TYPE | 0 | 0x0601 | "Invalid table type" | -2147482111 | +| TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION | 0 | 0x0602 | "Invalid table schema version" | -2147482110 | +| TSDB_CODE_TDB_TABLE_ALREADY_EXIST | 0 | 0x0603 | "Table already exists" | -2147482109 | +| TSDB_CODE_TDB_INVALID_CONFIG | 0 | 0x0604 | "Invalid configuration" | -2147482108 | +| TSDB_CODE_TDB_INIT_FAILED | 0 | 0x0605 | "Tsdb init failed" | -2147482107 | +| TSDB_CODE_TDB_NO_DISKSPACE | 0 | 0x0606 | "No diskspace for tsdb" | -2147482106 | +| TSDB_CODE_TDB_NO_DISK_PERMISSIONS | 0 | 0x0607 | "No permission for disk files" | -2147482105 | +| TSDB_CODE_TDB_FILE_CORRUPTED | 0 | 0x0608 | "Data file(s) corrupted" | -2147482104 | +| TSDB_CODE_TDB_OUT_OF_MEMORY | 0 | 0x0609 | "Out of memory" | -2147482103 | +| TSDB_CODE_TDB_TAG_VER_OUT_OF_DATE | 0 | 0x060A | "Tag too old" | -2147482102 | +| TSDB_CODE_TDB_TIMESTAMP_OUT_OF_RANGE | 0 | 0x060B | "Timestamp data out of range" | -2147482101 | +| TSDB_CODE_TDB_SUBMIT_MSG_MSSED_UP | 0 | 0x060C | "Submit message is messed up" | -2147482100 | +| TSDB_CODE_TDB_INVALID_ACTION | 0 | 0x060D | "Invalid operation" | -2147482099 | +| TSDB_CODE_TDB_INVALID_CREATE_TB_MSG | 0 | 0x060E | "Invalid creation of table" | -2147482098 | +| TSDB_CODE_TDB_NO_TABLE_DATA_IN_MEM | 0 | 0x060F | "No table data in memory skiplist" | -2147482097 | +| TSDB_CODE_TDB_FILE_ALREADY_EXISTS | 0 | 0x0610 | "File already exists" | -2147482096 | +| TSDB_CODE_TDB_TABLE_RECONFIGURE | 0 | 0x0611 | "Need to reconfigure table" | -2147482095 | +| TSDB_CODE_TDB_IVD_CREATE_TABLE_INFO | 0 | 0x0612 | "Invalid information to create table" | -2147482094 | +| TSDB_CODE_QRY_INVALID_QHANDLE | 0 | 0x0700 | "Invalid handle" | -2147481856 | +| TSDB_CODE_QRY_INVALID_MSG | 0 | 0x0701 | "Invalid message" | -2147481855 | +| TSDB_CODE_QRY_NO_DISKSPACE | 0 | 0x0702 | "No diskspace for query" | -2147481854 | +| TSDB_CODE_QRY_OUT_OF_MEMORY | 0 | 0x0703 | "System out of memory" | -2147481853 | +| TSDB_CODE_QRY_APP_ERROR | 0 | 0x0704 | "Unexpected generic error in query" | -2147481852 | +| TSDB_CODE_QRY_DUP_JOIN_KEY | 0 | 0x0705 | "Duplicated join key" | -2147481851 | +| TSDB_CODE_QRY_EXCEED_TAGS_LIMIT | 0 | 0x0706 | "Tag conditon too many" | -2147481850 | +| TSDB_CODE_QRY_NOT_READY | 0 | 0x0707 | "Query not ready" | -2147481849 | +| TSDB_CODE_QRY_HAS_RSP | 0 | 0x0708 | "Query should response" | -2147481848 | +| TSDB_CODE_GRANT_EXPIRED | 0 | 0x0800 | "License expired" | -2147481600 | +| TSDB_CODE_GRANT_DNODE_LIMITED | 0 | 0x0801 | "DNode creation limited by licence" | -2147481599 | +| TSDB_CODE_GRANT_ACCT_LIMITED | 0 | 0x0802 | "Account creation limited by license" | -2147481598 | +| TSDB_CODE_GRANT_TIMESERIES_LIMITED | 0 | 0x0803 | "Table creation limited by license" | -2147481597 | +| TSDB_CODE_GRANT_DB_LIMITED | 0 | 0x0804 | "DB creation limited by license" | -2147481596 | +| TSDB_CODE_GRANT_USER_LIMITED | 0 | 0x0805 | "User creation limited by license" | -2147481595 | +| TSDB_CODE_GRANT_CONN_LIMITED | 0 | 0x0806 | "Conn creation limited by license" | -2147481594 | +| TSDB_CODE_GRANT_STREAM_LIMITED | 0 | 0x0807 | "Stream creation limited by license" | -2147481593 | +| TSDB_CODE_GRANT_SPEED_LIMITED | 0 | 0x0808 | "Write speed limited by license" | -2147481592 | +| TSDB_CODE_GRANT_STORAGE_LIMITED | 0 | 0x0809 | "Storage capacity limited by license" | -2147481591 | +| TSDB_CODE_GRANT_QUERYTIME_LIMITED | 0 | 0x080A | "Query time limited by license" | -2147481590 | +| TSDB_CODE_GRANT_CPU_LIMITED | 0 | 0x080B | "CPU cores limited by license" | -2147481589 | +| TSDB_CODE_SYN_INVALID_CONFIG | 0 | 0x0900 | "Invalid Sync Configuration" | -2147481344 | +| TSDB_CODE_SYN_NOT_ENABLED | 0 | 0x0901 | "Sync module not enabled" | -2147481343 | +| TSDB_CODE_WAL_APP_ERROR | 0 | 0x1000 | "Unexpected generic error in wal" | -2147479552 | diff --git a/docs-cn/14-reference/01-taos-sql/_category_.yml b/docs-cn/14-reference/01-taos-sql/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..62290997ece68ce1a61d391c3976e338033c0dd1 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/_category_.yml @@ -0,0 +1 @@ +label: SQL 手册 diff --git a/docs-cn/14-reference/01-taos-sql/index.md b/docs-cn/14-reference/01-taos-sql/index.md new file mode 100644 index 0000000000000000000000000000000000000000..2c8d11288e55fd007b62b0a5fecc7dc7f2dc2737 --- /dev/null +++ b/docs-cn/14-reference/01-taos-sql/index.md @@ -0,0 +1,30 @@ +# TAOS SQL + +本文档说明 TAOS SQL 支持的语法规则、主要查询功能、支持的 SQL 查询函数,以及常用技巧等内容。阅读本文档需要读者具有基本的 SQL 语言的基础。 + +TAOS SQL 是用户对 TDengine 进行数据写入和查询的主要工具。TAOS SQL 为了便于用户快速上手,在一定程度上提供类似于标准 SQL 类似的风格和模式。严格意义上,TAOS SQL 并不是也不试图提供 SQL 标准的语法。此外,由于 TDengine 针对的时序性结构化数据不提供删除功能,因此在 TAO SQL 中不提供数据删除的相关功能。 + +TAOS SQL 不支持关键字的缩写,例如 DESCRIBE 不能缩写为 DESC。 + +本章节 SQL 语法遵循如下约定: + +- <\> 里的内容是用户需要输入的,但不要输入 <\> 本身 +- \[ \] 表示内容为可选项,但不能输入 [] 本身 +- | 表示多选一,选择其中一个即可,但不能输入 | 本身 +- … 表示前面的项可重复多个 + +为更好地说明 SQL 语法的规则及其特点,本文假设存在一个数据集。以智能电表(meters)为例,假设每个智能电表采集电流、电压、相位三个量。其建模如下: + +``` +taos> DESCRIBE meters; + Field | Type | Length | Note | +================================================================================= + ts | TIMESTAMP | 8 | | + current | FLOAT | 4 | | + voltage | INT | 4 | | + phase | FLOAT | 4 | | + location | BINARY | 64 | TAG | + groupid | INT | 4 | TAG | +``` + +数据集包含 4 个智能电表的数据,按照 TDengine 的建模规则,对应 4 个子表,其名称分别是 d1001, d1002, d1003, d1004。 \ No newline at end of file diff --git a/docs-cn/14-reference/02-restful-api/02-restful-api.mdx b/docs-cn/14-reference/02-restful-api/02-restful-api.mdx new file mode 100644 index 0000000000000000000000000000000000000000..6173c3215ac5a5dccc1caa206f89b77d101a6e70 --- /dev/null +++ b/docs-cn/14-reference/02-restful-api/02-restful-api.mdx @@ -0,0 +1,302 @@ +# RESTful API + +为支持各种不同类型平台的开发,TDengine 提供符合 REST 设计标准的 API,即 RESTful API。为最大程度降低学习成本,不同于其他数据库 RESTful API 的设计方法,TDengine 直接通过 HTTP POST 请求 BODY 中包含的 SQL 语句来操作数据库,仅需要一个 URL。RESTful 连接器的使用参见[视频教程](https://www.taosdata.com/blog/2020/11/11/1965.html)。 + +注意:与原生连接器的一个区别是,RESTful 接口是无状态的,因此 `USE db_name` 指令没有效果,所有对表名、超级表名的引用都需要指定数据库名前缀。(从 2.2.0.0 版本开始,支持在 RESTful url 中指定 db_name,这时如果 SQL 语句中没有指定数据库名前缀的话,会使用 url 中指定的这个 db_name。从 2.4.0.0 版本开始,RESTful 默认由 taosAdapter 提供,要求必须在 url 中指定 db_name。) + +## 安装 + +RESTful 接口不依赖于任何 TDengine 的库,因此客户端不需要安装任何 TDengine 的库,只要客户端的开发语言支持 HTTP 协议即可。 + +## 验证 + +在已经安装 TDengine 服务器端的情况下,可以按照如下方式进行验证。 + +下面以 Ubuntu 环境中使用 curl 工具(确认已经安装)来验证 RESTful 接口的正常。 + +下面示例是列出所有的数据库,请把 h1.taosdata.com 和 6041(缺省值)替换为实际运行的 TDengine 服务 fqdn 和端口号: + +```html +curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'show databases;' +h1.taosdata.com:6041/rest/sql +``` + +返回值结果如下表示验证通过: + +```json +{ + "status": "succ", + "head": [ + "name", + "created_time", + "ntables", + "vgroups", + "replica", + "quorum", + "days", + "keep1,keep2,keep(D)", + "cache(MB)", + "blocks", + "minrows", + "maxrows", + "wallevel", + "fsync", + "comp", + "precision", + "status" + ], + "data": [ + [ + "log", + "2020-09-02 17:23:00.039", + 4, + 1, + 1, + 1, + 10, + "30,30,30", + 1, + 3, + 100, + 4096, + 1, + 3000, + 2, + "us", + "ready" + ] + ], + "rows": 1 +} +``` + +## RESTful 连接器的使用 + +### HTTP 请求格式 + +``` +http://:/rest/sql/[db_name] +``` + +参数说明: + +- fqnd: 集群中的任一台主机 FQDN 或 IP 地址 +- port: 配置文件中 httpPort 配置项,缺省为 6041 +- db_name: 可选参数,指定本次所执行的 SQL 语句的默认数据库库名。(从 2.2.0.0 版本开始支持) + +例如:http://h1.taos.com:6041/rest/sql/test 是指向地址为 h1.taos.com:6041 的 url,并将默认使用的数据库库名设置为 test。 + +HTTP 请求的 Header 里需带有身份认证信息,TDengine 支持 Basic 认证与自定义认证两种机制,后续版本将提供标准安全的数字签名机制来做身份验证。 + +- 自定义身份认证信息如下所示(token 稍后介绍) + +``` +Authorization: Taosd +``` + +- Basic 身份认证信息如下所示 + +``` +Authorization: Basic +``` + +HTTP 请求的 BODY 里就是一个完整的 SQL 语句,SQL 语句中的数据表应提供数据库前缀,例如 \.\。如果表名不带数据库前缀,又没有在 url 中指定数据库名的话,系统会返回错误。因为 HTTP 模块只是一个简单的转发,没有当前 DB 的概念。 + +使用 curl 通过自定义身份认证方式来发起一个 HTTP Request,语法如下: + +```bash +curl -H 'Authorization: Basic ' -d '' :/rest/sql/[db_name] +``` + +或者 + +```bash +curl -u username:password -d '' :/rest/sql/[db_name] +``` + +其中,`TOKEN` 为 `{username}:{password}` 经过 Base64 编码之后的字符串,例如 `root:taosdata` 编码后为 `cm9vdDp0YW9zZGF0YQ==` + +## HTTP 返回格式 + +返回值为 JSON 格式,如下: + +```json +{ + "status": "succ", + "head": ["ts","current", …], + "column_meta": [["ts",9,8],["current",6,4], …], + "data": [ + ["2018-10-03 14:38:05.000", 10.3, …], + ["2018-10-03 14:38:15.000", 12.6, …] + ], + "rows": 2 +} +``` + +说明: + +- status: 告知操作结果是成功还是失败。 +- head: 表的定义,如果不返回结果集,则仅有一列 “affected_rows”。(从 2.0.17.0 版本开始,建议不要依赖 head 返回值来判断数据列类型,而推荐使用 column_meta。在未来版本中,有可能会从返回值中去掉 head 这一项。) +- column_meta: 从 2.0.17.0 版本开始,返回值中增加这一项来说明 data 里每一列的数据类型。具体每个列会用三个值来说明,分别为:列名、列类型、类型长度。例如`["current",6,4]`表示列名为“current”;列类型为 6,也即 float 类型;类型长度为 4,也即对应 4 个字节表示的 float。如果列类型为 binary 或 nchar,则类型长度表示该列最多可以保存的内容长度,而不是本次返回值中的具体数据长度。当列类型是 nchar 的时候,其类型长度表示可以保存的 unicode 字符数量,而不是 bytes。 +- data: 具体返回的数据,一行一行的呈现,如果不返回结果集,那么就仅有 [[affected_rows]]。data 中每一行的数据列顺序,与 column_meta 中描述数据列的顺序完全一致。 +- rows: 表明总共多少行数据。 + +column_meta 中的列类型说明: + +- 1:BOOL +- 2:TINYINT +- 3:SMALLINT +- 4:INT +- 5:BIGINT +- 6:FLOAT +- 7:DOUBLE +- 8:BINARY +- 9:TIMESTAMP +- 10:NCHAR + +## 自定义授权码 + +HTTP 请求中需要带有授权码 ``,用于身份识别。授权码通常由管理员提供,可简单的通过发送 `HTTP GET` 请求来获取授权码,操作如下: + +```bash +curl http://:/rest/login// +``` + +其中,`fqdn` 是 TDengine 数据库的 fqdn 或 ip 地址,port 是 TDengine 服务的端口号,`username` 为数据库用户名,`password` 为数据库密码,返回值为 `JSON` 格式,各字段含义如下: + +- status:请求结果的标志位 + +- code:返回值代码 + +- desc:授权码 + +获取授权码示例: + +```bash +curl http://192.168.0.1:6041/rest/login/root/taosdata +``` + +返回值: + +```json +{ + "status": "succ", + "code": 0, + "desc": "/KfeAzX/f9na8qdtNZmtONryp201ma04bEl8LcvLUd7a8qdtNZmtONryp201ma04" +} +``` + +## 使用示例 + +- 在 demo 库里查询表 d1001 的所有记录: + +```bash +curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'select * from demo.d1001' 192.168.0.1:6041/rest/sql +``` + +返回值: + +```json +{ + "status": "succ", + "head": ["ts", "current", "voltage", "phase"], + "column_meta": [ + ["ts", 9, 8], + ["current", 6, 4], + ["voltage", 4, 4], + ["phase", 6, 4] + ], + "data": [ + ["2018-10-03 14:38:05.000", 10.3, 219, 0.31], + ["2018-10-03 14:38:15.000", 12.6, 218, 0.33] + ], + "rows": 2 +} +``` + +- 创建库 demo: + +```bash +curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'create database demo' 192.168.0.1:6041/rest/sql +``` + +返回值: + +```json +{ + "status": "succ", + "head": ["affected_rows"], + "column_meta": [["affected_rows", 4, 4]], + "data": [[1]], + "rows": 1 +} +``` + +## 其他用法 + +### 结果集采用 Unix 时间戳 + +HTTP 请求 URL 采用 `sqlt` 时,返回结果集的时间戳将采用 Unix 时间戳格式表示,例如 + +```bash +curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'select * from demo.d1001' 192.168.0.1:6041/rest/sqlt +``` + +返回值: + +```json +{ + "status": "succ", + "head": ["ts", "current", "voltage", "phase"], + "column_meta": [ + ["ts", 9, 8], + ["current", 6, 4], + ["voltage", 4, 4], + ["phase", 6, 4] + ], + "data": [ + [1538548685000, 10.3, 219, 0.31], + [1538548695000, 12.6, 218, 0.33] + ], + "rows": 2 +} +``` + +### 结果集采用 UTC 时间字符串 + +HTTP 请求 URL 采用 `sqlutc` 时,返回结果集的时间戳将采用 UTC 时间字符串表示,例如 + +```bash + curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'select * from demo.t1' 192.168.0.1:6041/rest/sqlutc +``` + +返回值: + +```json +{ + "status": "succ", + "head": ["ts", "current", "voltage", "phase"], + "column_meta": [ + ["ts", 9, 8], + ["current", 6, 4], + ["voltage", 4, 4], + ["phase", 6, 4] + ], + "data": [ + ["2018-10-03T14:38:05.000+0800", 10.3, 219, 0.31], + ["2018-10-03T14:38:15.000+0800", 12.6, 218, 0.33] + ], + "rows": 2 +} +``` + +## 重要配置项 + +下面仅列出一些与 RESTful 接口有关的配置参数,其他系统参数请看配置文件里的说明。(注意:配置修改后,需要重启 taosd 服务才能生效) + +- 对外提供 RESTful 服务的端口号,默认绑定到 6041(实际取值是 serverPort + 11,因此可以通过修改 serverPort 参数的设置来修改)。 +- httpMaxThreads: 启动的线程数量,默认为 2(2.0.17.0 版本开始,默认值改为 CPU 核数的一半向下取整)。 +- restfulRowLimit: 返回结果集(JSON 格式)的最大条数,默认值为 10240。 +- httpEnableCompress: 是否支持压缩,默认不支持,目前 TDengine 仅支持 gzip 压缩格式。 +- httpDebugFlag: 日志开关,默认 131。131:仅错误和报警信息,135:调试信息,143:非常详细的调试信息,默认 131。 +- httpDbNameMandatory: 是否必须在 RESTful url 中指定默认的数据库名。默认为 0,即关闭此检查。如果设置为 1,那么每个 RESTful url 中都必须设置一个默认数据库名,否则无论此时执行的 SQL 语句是否需要指定数据库,都会返回一个执行错误,拒绝执行此 SQL 语句。 diff --git a/docs-cn/14-reference/02-restful-api/_category_.yml b/docs-cn/14-reference/02-restful-api/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..736836846eef118e51ab802811151e26646684e9 --- /dev/null +++ b/docs-cn/14-reference/02-restful-api/_category_.yml @@ -0,0 +1 @@ +label: RESTful API diff --git a/docs-cn/14-reference/03-connector/03-connector.mdx b/docs-cn/14-reference/03-connector/03-connector.mdx new file mode 100644 index 0000000000000000000000000000000000000000..2036a591ff1f6f579dfec4e2e014573900d3c21d --- /dev/null +++ b/docs-cn/14-reference/03-connector/03-connector.mdx @@ -0,0 +1,93 @@ +# 连接器 + +TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java、Python、Go、Node.js、C# 、RESTful 等,便于用户快速开发应用。 + +![image-connecotr](/img/connector.png) + +## 支持的系统 + +目前 TDengine 的连接器可支持的平台广泛,包括:X64/X86/ARM64/ARM32/MIPS/Alpha 等硬件平台,以及 Linux/Win64/Win32 等开发环境。对照矩阵如下: + +| **CPU** | **OS** | **JDBC** | **Python** | **Go** | **Node.js** | **C#** | **Rust** | **RESTful** | +| -------------- | --------- | -------- | ---------- | ------ | ----------- | ------ | -------- | ----------- | +| **X86 64bit** | **Linux** | ● | ● | ● | ● | ● | ● | ● | +| **X86 64bit** | **Win64** | ● | ● | ● | ● | ● | ● | ● | +| **X86 64bit** | **Win32** | ● | ● | ● | ● | ○ | ○ | ● | +| **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ○ | ● | +| **ARM64** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● | +| **ARM32** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● | +| **MIPS 龙芯** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○ | +| **Alpha 申威** | **Linux** | ○ | ○ | -- | -- | -- | -- | ○ | +| **X86 海光** | **Linux** | ○ | ○ | ○ | -- | -- | -- | ○ | + +其中 ● 表示官方测试验证通过,○ 表示非官方测试验证通过,-- 表示未经验证。 + +## 特性矩阵 + +连接器对 TDengine 特性的支持对照矩阵如下[1]: + +| **Feature** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** | +| ------------------ | --------- | ---------- | -------- | -------- | ----------- | -------- | +| **连接管理** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **同步查询** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **异步查询** | 不支持[2] | 支持 | 支持 | 支持 | 支持 | 暂不支持 | +| **参数绑定** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **获取系统信息** | 暂不支持 | 支持 | 暂不支持 | 暂不支持 | 支持 | 暂不支持 | +| **错误信息** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **订阅功能** | 支持 | 支持 | 支持 | 支持 | 支持 | 暂不支持 | +| **Schemaless** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **RESTful 连接** | 支持 | 支持 | 支持 | 暂不支持 | 支持 | 支持 | +| **批量拉取(WS)** | 支持 | 暂不支持 | 暂不支持 | 暂不支持 | 暂不支持 | 暂不支持 | + +备注: + +[1]: 由于不同语言数据库框架规范不同,并不意味着所有 C/C++ 接口都需要对应支持。 + +[2]: JDBC 标准为同步查询。 + +:::warning + +- 在没有安装 TDengine 服务端软件的系统中使用连接器(除 RESTful 外)访问 TDengine 数据库,需要安装相应版本的客户端安装包来使应用驱动(Linux 系统中文件名为 libtaos.so,Windows 系统中为 taos.dll)被安装在系统中,否则会产生无法找到相应库文件的错误。 +- 所有执行 SQL 语句的 API,例如 C/C++ Connector 中的 `tao_query`、`taos_query_a`、`taos_subscribe` 等,以及其它语言中与它们对应的 API,每次都只能执行一条 SQL 语句,如果实际参数中包含了多条语句,它们的行为是未定义的。 +- 升级 TDengine 到 2.0.8.0 版本的用户,必须更新 JDBC。连接 TDengine 必须升级 taos-jdbcdriver 到 2.0.12 及以上。详细的版本依赖关系请参见 [taos-jdbcdriver 文档](https://www.taosdata.com/cn/documentation/connector/java#version)。 +- 无论选用何种编程语言的连接器,2.0 及以上版本的 TDengine 推荐数据库应用的每个线程都建立一个独立的连接,或基于线程建立连接池,以避免连接内的“USE statement”状态量在线程之间相互干扰(但连接的查询和写入操作都是线程安全的)。 + +::: + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import InstallOnWindows from "./_linux_install.mdx"; +import InstallOnLinux from "./_windows_install.mdx"; +import VarifyWindows from "./_varify_linux.mdx"; +import VarifyLinux from "./_varify_windows.mdx"; + +## 安装客户端驱动 + +:::info +只有在没有安装 TDengine 服务端软件的系统上使用非 RESTFful 连接器才需要安装客户端驱动。 + +::: + +### 安装步骤 + + + + + + + + + + +### 安装验证 + +以上安装和配置完成后,并确认 TDengine 服务已经正常启动运行,此时可以执行 taos 客户端进行登录。 + + + + + + + + + diff --git a/docs-cn/14-reference/03-connector/_category_.yml b/docs-cn/14-reference/03-connector/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..abd3f666f3b93697fde59931ffd7b10a0308b6b7 --- /dev/null +++ b/docs-cn/14-reference/03-connector/_category_.yml @@ -0,0 +1 @@ +label: "连接器" \ No newline at end of file diff --git a/docs-cn/14-reference/03-connector/_linux_install.mdx b/docs-cn/14-reference/03-connector/_linux_install.mdx new file mode 100644 index 0000000000000000000000000000000000000000..21dacdfdb8f64364bb7aae0567a424bc98e2ef96 --- /dev/null +++ b/docs-cn/14-reference/03-connector/_linux_install.mdx @@ -0,0 +1,27 @@ +1. 从[涛思官网](https://www.taosdata.com/cn/all-downloads/)下载: + - X64 硬件环境:TDengine-client-2.x.x.x-Linux-x64.tar.gz + - ARM64 硬件环境:TDengine-client-2.x.x.x-Linux-aarch64.tar.gz + - ARM32 硬件环境:TDengine-client-2.x.x.x-Linux-aarch32.tar.gz +2. 解压缩软件包 + + 将软件包放置在当前用户可读写的任意目录下,然后执行下面的命令:`tar -xzvf TDengine-client-xxxxxxxxx.tar.gz` + 其中 xxxxxxxxx 需要替换为实际版本的字符串。 +3. 执行安装脚本 + + 解压软件包之后,会在解压目录下看到以下文件(目录): + ​ - _ install_client.sh_:安装脚本,用于应用驱动程序 + ​ - _ taos.tar.gz_:应用驱动安装包 + ​ - _ driver_:TDengine 应用驱动 driver + ​ - _connector_: 各种编程语言连接器(go/nodejs/python/JDBC) + ​ - _examples_: 各种编程语言的示例程序(c/C#/go/JDBC/MATLAB/python/R) + 运行 install_client.sh 进行安装。 +4. 配置 taos.cfg + + 编辑 taos.cfg 文件(默认路径/etc/taos/taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:`h1.taos.com:6030` + +:::tip + +1. 如本机没有部署 TDengine 服务,仅安装了应用驱动,则 taos.cfg 中仅需配置 firstEP,无需配置 FQDN。 +2. 为防止与服务器端连接时出现“unable to resolve FQDN”错误,建议确认客户端的 hosts 文件已经配置正确的 FQDN 值。 + +::: diff --git a/docs-cn/14-reference/03-connector/_varify_linux.mdx b/docs-cn/14-reference/03-connector/_varify_linux.mdx new file mode 100644 index 0000000000000000000000000000000000000000..b7340a7ef131cefc78aa9555eadba9a72d43fcb9 --- /dev/null +++ b/docs-cn/14-reference/03-connector/_varify_linux.mdx @@ -0,0 +1,14 @@ +在 Linux shell 下直接执行 taos,应该就能正常连接到 TDegine 服务,进入到 taos shell 界面,示例如下: + +```sql +$ taos +Welcome to the TDengine shell from Linux, Client Version:2.0.5.0 +Copyright (c) 2017 by TAOS Data, Inc. All rights reserved. +taos> show databases; +name | created_time | ntables | vgroups | replica | quorum | days | keep1,keep2,keep(D) | cache(MB)| blocks | minrows | maxrows | wallevel | fsync | comp | precision | status | +========================================================================================================================================================================================================================= +test | 2020-10-14 10:35:48.617 | 10 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16| 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready | +log | 2020-10-12 09:08:21.651 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1| 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready | +Query OK, 2 row(s) in set (0.001198s) +taos> +``` diff --git a/docs-cn/14-reference/03-connector/_varify_windows.mdx b/docs-cn/14-reference/03-connector/_varify_windows.mdx new file mode 100644 index 0000000000000000000000000000000000000000..4f61bef9a22806f61b4b056ca319ab606c348b1d --- /dev/null +++ b/docs-cn/14-reference/03-connector/_varify_windows.mdx @@ -0,0 +1,14 @@ +在 cmd 下进入到 c:\TDengine 目录下直接执行 taos.exe,应该就能正常链接到 tdegine 服务,进入到 taos shell 界面,示例如下: + +```sql + C:\TDengine>taos + Welcome to the TDengine shell from Linux, Client Version:2.0.5.0 + Copyright (c) 2017 by TAOS Data, Inc. All rights reserved. + taos> show databases; + name | created_time | ntables | vgroups | replica | quorum | days | keep1,keep2,keep(D) | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | precision | status | + =================================================================================================================================================================================================================================================================== + test | 2020-10-14 10:35:48.617 | 10 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready | + log | 2020-10-12 09:08:21.651 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready | + Query OK, 2 row(s) in set (0.045000s) + taos> +``` diff --git a/docs-cn/14-reference/03-connector/_windows_install.mdx b/docs-cn/14-reference/03-connector/_windows_install.mdx new file mode 100644 index 0000000000000000000000000000000000000000..67b04607172d5cd6e00b44d21b60c2c1a28d738a --- /dev/null +++ b/docs-cn/14-reference/03-connector/_windows_install.mdx @@ -0,0 +1,26 @@ +1. 从[涛思官网](https://www.taosdata.com/cn/all-downloads/)下载 + - X64 硬件环境:TDengine-client-2.X.X.X-Windows-x64.exe + - X86 硬件环境:TDengine-client-2.X.X.X-Windows-x86.exe +2. 执行安装程序,按提示选择默认值,完成安装 +3. 安装路径 + + 默认安装路径为:C:\TDengine,其中包括以下文件(目录): + + - _taos.exe_:taos shell 命令行程序 + - _cfg_ : 配置文件目录 + - _driver_: 应用驱动动态链接库 + - _examples_: 示例程序 bash/C/C#/go/JDBC/Python/Node.js + - _include_: 头文件 + - _log_ : 日志文件 + - _unins000.exe_: 卸载程序 + +4. 配置 taos.cfg + + 编辑 taos.cfg 文件(默认路径 C:\TDengine\cfg\taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:`h1.taos.com:6030`。 + +:::tip + +1. 如利用 FQDN 连接服务器,必须确认本机网络环境 DNS 已配置好,或在 hosts 文件中添加 FQDN 寻址记录,如编辑 C:\Windows\system32\drivers\etc\hosts,添加如下的记录:`192.168.1.99 h1.taos.com` +2. 卸载:运行 unins000.exe 可卸载 TDengine 应用驱动。 + +::: diff --git a/docs-cn/14-reference/03-connector/cpp.mdx b/docs-cn/14-reference/03-connector/cpp.mdx new file mode 100644 index 0000000000000000000000000000000000000000..6ff6b413b9fcfb5d9c4552ef06184a4db2777a08 --- /dev/null +++ b/docs-cn/14-reference/03-connector/cpp.mdx @@ -0,0 +1,414 @@ +--- +sidebar_position: 1 +--- + +# C/C++ Connector + +**C/C++连接器支持的系统有**: + +| **CPU 类型** | x64(64bit) | | | ARM64 | ARM32 | +| ------------ | ------------ | -------- | -------- | -------- | -------- | +| **OS 类型** | Linux | Win64 | Win32 | Linux | Linux | +| **支持与否** | **支持** | **支持** | **支持** | **支持** | **支持** | + +C/C++的 API 类似于 MySQL 的 C API。应用程序使用时,需要包含 TDengine 头文件 _taos.h_,里面列出了提供的 API 的函数原型。安装后,taos.h 位于: + +- Linux:`/usr/local/taos/include` +- Windows:`C:\TDengine\include` + +```c +#include +``` + +注意: + +- 在编译时需要链接 TDengine 动态库。Linux 为 _libtaos.so_ ,安装后,位于 _/usr/local/taos/driver_。Windows 为 taos.dll,安装后位于 _C:\TDengine_。 +- 如未特别说明,当 API 的返回值是整数时,_0_ 代表成功,其它是代表失败原因的错误码,当返回值是指针时, _NULL_ 表示失败。 +- 在 taoserror.h 中有所有的错误码,以及对应的原因描述。 + +### 示例程序 + +使用 C/C++连接器的示例代码请参见 https://github.com/taosdata/TDengine/tree/develop/examples/c 。 + +示例程序源码也可以在安装目录下的 examples/c 路径下找到: + +**apitest.c、asyncdemo.c、demo.c、prepare.c、stream.c、subscribe.c** + +该目录下有 makefile,在 Linux 环境下,直接执行 make 就可以编译得到执行文件。 + +在一台机器上启动 TDengine 服务,执行这些示例程序,按照提示输入 TDengine 服务的 FQDN,就可以正常运行,并打印出信息。 + +**提示:**在 ARM 环境下编译时,请将 makefile 中的-msse4.2 打开,这个选项只有在 x64/x86 硬件平台上才能支持。 + +### 基础 API + +基础 API 用于完成创建数据库连接等工作,为其它 API 的执行提供运行时环境。 + +- `void taos_init()` + + 初始化运行环境。如果应用没有主动调用该 API,那么应用在调用`taos_connect`时将自动调用,故应用程序一般无需手动调用该 API。 + +- `void taos_cleanup()` + + 清理运行环境,应用退出前应调用此 API。 + +- `int taos_options(TSDB_OPTION option, const void * arg, ...)` + + 设置客户端选项,目前支持区域设置(`TSDB_OPTION_LOCALE`)、字符集设置(`TSDB_OPTION_CHARSET`)、时区设置(`TSDB_OPTION_TIMEZONE`)、配置文件路径设置(`TSDB_OPTION_CONFIGDIR`)。区域设置、字符集、时区默认为操作系统当前设置。 + +- `char *taos_get_client_info()` + + 获取客户端版本信息。 + +- `TAOS *taos_connect(const char *host, const char *user, const char *pass, const char *db, int port)` + + 创建数据库连接,初始化连接上下文。其中需要用户提供的参数包含: + + - host:TDengine 管理主节点的 FQDN + - user:用户名 + - pass:密码 + - db:数据库名字,如果用户没有提供,也可以正常连接,用户可以通过该连接创建新的数据库,如果用户提供了数据库名字,则说明该数据库用户已经创建好,缺省使用该数据库 + - port:TDengine 管理主节点的端口号 + + 返回值为空表示失败。应用程序需要保存返回的参数,以便后续 API 调用。 + + :::info + 同一进程可以根据不同的 host/port 连接多个 taosd 集群 + + ::: + +- `char *taos_get_server_info(TAOS *taos)` + + 获取服务端版本信息。 + +- `int taos_select_db(TAOS *taos, const char *db)` + + 将当前的缺省数据库设置为`db`。 + +- `void taos_close(TAOS *taos)` + + 关闭连接,其中`taos`是`taos_connect`函数返回的指针。 + +### 同步查询 API + +传统的数据库操作 API,都属于同步操作。应用调用 API 后,一直处于阻塞状态,直到服务器返回结果。TDengine 支持如下 API: + +- `TAOS_RES* taos_query(TAOS *taos, const char *sql)` + + 该 API 用来执行 SQL 语句,可以是 DQL、DML 或 DDL 语句。 其中的`taos`参数是通过`taos_connect`获得的指针。不能通过返回值是否是 NULL 来判断执行结果是否失败,而是需要用`taos_errno`函数解析结果集中的错误代码来进行判断。 + +- `int taos_result_precision(TAOS_RES *res)` + + 返回结果集时间戳字段的精度,`0` 代表毫秒,`1` 代表微秒,`2` 代表纳秒。 + +- `TAOS_ROW taos_fetch_row(TAOS_RES *res)` + + 按行获取查询结果集中的数据。 + +- `int taos_fetch_block(TAOS_RES *res, TAOS_ROW *rows)` + + 批量获取查询结果集中的数据,返回值为获取到的数据的行数。 + +- `int taos_num_fields(TAOS_RES *res)` 和 `int taos_field_count(TAOS_RES *res)` + + 这两个 API 等价,用于获取查询结果集中的列数。 + +- `int* taos_fetch_lengths(TAOS_RES *res)` + + 获取结果集中每个字段的长度。 返回值是一个数组,其长度为结果集的列数。 + +- `int taos_affected_rows(TAOS_RES *res)` + + 获取被所执行的 SQL 语句影响的行数。 + +- `TAOS_FIELD *taos_fetch_fields(TAOS_RES *res)` + + 获取查询结果集每列数据的属性(列的名称、列的数据类型、列的长度),与 taos_num_fileds 配合使用,可用来解析`taos_fetch_row`返回的一个元组(一行)的数据。 `TAOS_FIELD` 的结构如下: + +```c +typedef struct taosField { + char name[65]; // 列名 + uint8_t type; // 数据类型 + int16_t bytes; // 长度,单位是字节 +} TAOS_FIELD; +``` + +- `void taos_stop_query(TAOS_RES *res)` + + 停止一个查询的执行。 + +- `void taos_free_result(TAOS_RES *res)` + + 释放查询结果集以及相关的资源。查询完成后,务必调用该 API 释放资源,否则可能导致应用内存泄露。但也需注意,释放资源后,如果再调用`taos_consume`等获取查询结果的函数,将导致应用 Crash。 + +- `char *taos_errstr(TAOS_RES *res)` + + 获取最近一次 API 调用失败的原因,返回值为字符串。 + +- `int taos_errno(TAOS_RES *res)` + + 获取最近一次 API 调用失败的原因,返回值为错误代码。 + +:::note +2.0 及以上版本 TDengine 推荐数据库应用的每个线程都建立一个独立的连接,或基于线程建立连接池。而不推荐在应用中将该连接 (TAOS\*) 结构体传递到不同的线程共享使用。基于 TAOS 结构体发出的查询、写入等操作具有多线程安全性,但 “USE statement” 等状态量有可能在线程之间相互干扰。此外,C 语言的连接器可以按照需求动态建立面向数据库的新连接(该过程对用户不可见),同时建议只有在程序最后退出的时候才调用 taos_close 关闭连接。 + +::: + +### 异步查询 API + +同步 API 之外,TDengine 还提供性能更高的异步调用 API 处理数据插入、查询操作。在软硬件环境相同的情况下,异步 API 处理数据插入的速度比同步 API 快 2 ~ 4 倍。异步 API 采用非阻塞式的调用方式,在系统真正完成某个具体数据库操作前,立即返回。调用的线程可以去处理其他工作,从而可以提升整个应用的性能。异步 API 在网络延迟严重的情况下,优点尤为突出。 + +异步 API 都需要应用提供相应的回调函数,回调函数参数设置如下:前两个参数都是一致的,第三个参数依不同的 API 而定。第一个参数 param 是应用调用异步 API 时提供给系统的,用于回调时,应用能够找回具体操作的上下文,依具体实现而定。第二个参数是 SQL 操作的结果集,如果为空,比如 insert 操作,表示没有记录返回,如果不为空,比如 select 操作,表示有记录返回。 + +异步 API 对于使用者的要求相对较高,用户可根据具体应用场景选择性使用。下面是两个重要的异步 API: + +- `void taos_query_a(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, int code), void *param);` + + 异步执行 SQL 语句。 + + - taos:调用 taos_connect 返回的数据库连接 + - sql:需要执行的 SQL 语句 + - fp:用户定义的回调函数,其第三个参数`code`用于指示操作是否成功,`0`表示成功,负数表示失败(调用`taos_errstr`获取失败原因)。应用在定义回调函数的时候,主要处理第二个参数`TAOS_RES *`,该参数是查询返回的结果集 + - param:应用提供一个用于回调的参数 + +- `void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);` + + 批量获取异步查询的结果集,只能与`taos_query_a`配合使用。其中: + + - res:`taos_query_a`回调时返回的结果集 + - fp:回调函数。其参数`param`是用户可定义的传递给回调函数的参数结构体;`numOfRows`是获取到的数据的行数(不是整个查询结果集的函数)。 在回调函数中,应用可以通过调用`taos_fetch_row`前向迭代获取批量记录中每一行记录。读完一块内的所有记录后,应用需要在回调函数中继续调用`taos_fetch_rows_a`获取下一批记录进行处理,直到返回的记录数(numOfRows)为零(结果返回完成)或记录数为负值(查询出错)。 + +TDengine 的异步 API 均采用非阻塞调用模式。应用程序可以用多线程同时打开多张表,并可以同时对每张打开的表进行查询或者插入操作。需要指出的是,**客户端应用必须确保对同一张表的操作完全串行化**,即对同一个表的插入或查询操作未完成时(未返回时),不能够执行第二个插入或查询操作。 + +### 参数绑定 API + +除了直接调用 `taos_query` 进行查询,TDengine 也提供了支持参数绑定的 Prepare API,与 MySQL 一样,这些 API 目前也仅支持用问号 `?` 来代表待绑定的参数。文档中有时也会把此功能称为“原生接口写入”。 + +从 2.1.1.0 和 2.1.2.0 版本开始,TDengine 大幅改进了参数绑定接口对数据写入(INSERT)场景的支持。这样在通过参数绑定接口写入数据时,就避免了 SQL 语法解析的资源消耗,从而在绝大多数情况下显著提升写入性能。此时的典型操作步骤如下: + +1. 调用 `taos_stmt_init` 创建参数绑定对象; +2. 调用 `taos_stmt_prepare` 解析 INSERT 语句; +3. 如果 INSERT 语句中预留了表名但没有预留 TAGS,那么调用 `taos_stmt_set_tbname` 来设置表名; +4. 如果 INSERT 语句中既预留了表名又预留了 TAGS(例如 INSERT 语句采取的是自动建表的方式),那么调用 `taos_stmt_set_tbname_tags` 来设置表名和 TAGS 的值; +5. 调用 `taos_stmt_bind_param_batch` 以多列的方式设置 VALUES 的值,或者调用 `taos_stmt_bind_param` 以单行的方式设置 VALUES 的值; +6. 调用 `taos_stmt_add_batch` 把当前绑定的参数加入批处理; +7. 可以重复第 3 ~ 6 步,为批处理加入更多的数据行; +8. 调用 `taos_stmt_execute` 执行已经准备好的批处理指令; +9. 执行完毕,调用 `taos_stmt_close` 释放所有资源。 + +说明:如果 `taos_stmt_execute` 执行成功,假如不需要改变 SQL 语句的话,那么是可以复用 `taos_stmt_prepare` 的解析结果,直接进行第 3 ~ 6 步绑定新数据的。但如果执行出错,那么并不建议继续在当前的环境上下文下继续工作,而是建议释放资源,然后从 `taos_stmt_init` 步骤重新开始。 + +除 C/C++ 语言外,TDengine 的 Java 语言 JNI Connector 也提供参数绑定接口支持,具体请另外参见:[参数绑定接口的 Java 用法](https://www.taosdata.com/cn/documentation/connector/java#stmt-java)。 + +接口相关的具体函数如下(也可以参考 [prepare.c](https://github.com/taosdata/TDengine/blob/develop/examples/c/prepare.c) 文件中使用对应函数的方式): + +- `TAOS_STMT* taos_stmt_init(TAOS *taos)` + + 创建一个 TAOS_STMT 对象用于后续调用。 + +- `int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length)` + + 解析一条 SQL 语句,将解析结果和参数信息绑定到 stmt 上,如果参数 length 大于 0,将使用此参数作为 SQL 语句的长度,如等于 0,将自动判断 SQL 语句的长度。 + +- `int taos_stmt_bind_param(TAOS_STMT *stmt, TAOS_BIND *bind)` + + 不如 `taos_stmt_bind_param_batch` 效率高,但可以支持非 INSERT 类型的 SQL 语句。 + 进行参数绑定,bind 指向一个数组(代表所要绑定的一行数据),需保证此数组中的元素数量和顺序与 SQL 语句中的参数完全一致。TAOS_BIND 的使用方法与 MySQL 中的 MYSQL_BIND 一致,具体定义如下: + +```c +typedef struct TAOS_BIND { + int buffer_type; + void * buffer; + unsigned long buffer_length; // 未实际使用 + unsigned long *length; + int * is_null; + int is_unsigned; // 未实际使用 + int * error; // 未实际使用 +} TAOS_BIND; +``` + +- `int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name)` + + (2.1.1.0 版本新增,仅支持用于替换 INSERT 语句中的参数值) + 当 SQL 语句中的表名使用了 `?` 占位时,可以使用此函数绑定一个具体的表名。 + +- `int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags)` + + (2.1.2.0 版本新增,仅支持用于替换 INSERT 语句中的参数值) + 当 SQL 语句中的表名和 TAGS 都使用了 `?` 占位时,可以使用此函数绑定具体的表名和具体的 TAGS 取值。最典型的使用场景是使用了自动建表功能的 INSERT 语句(目前版本不支持指定具体的 TAGS 列)。tags 参数中的列数量需要与 SQL 语句中要求的 TAGS 数量完全一致。 + +- `int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind)` + + (2.1.1.0 版本新增,仅支持用于替换 INSERT 语句中的参数值) + 以多列的方式传递待绑定的数据,需要保证这里传递的数据列的顺序、列的数量与 SQL 语句中的 VALUES 参数完全一致。TAOS_MULTI_BIND 的具体定义如下: + +```c +typedef struct TAOS_MULTI_BIND { + int buffer_type; + void * buffer; + uintptr_t buffer_length; + int32_t * length; + char * is_null; + int num; // 列的个数,即 buffer 中的参数个数 +} TAOS_MULTI_BIND; +``` + +- `int taos_stmt_add_batch(TAOS_STMT *stmt)` + + 将当前绑定的参数加入批处理中,调用此函数后,可以再次调用 `taos_stmt_bind_param` 或 `taos_stmt_bind_param_batch` 绑定新的参数。需要注意,此函数仅支持 INSERT/IMPORT 语句,如果是 SELECT 等其他 SQL 语句,将返回错误。 + +- `int taos_stmt_execute(TAOS_STMT *stmt)` + + 执行准备好的语句。目前,一条语句只能执行一次。 + +- `TAOS_RES* taos_stmt_use_result(TAOS_STMT *stmt)` + + 获取语句的结果集。结果集的使用方式与非参数化调用时一致,使用完成后,应对此结果集调用 `taos_free_result` 以释放资源。 + +- `int taos_stmt_close(TAOS_STMT *stmt)` + + 执行完毕,释放所有资源。 + +- `char * taos_stmt_errstr(TAOS_STMT *stmt)` + + (2.1.3.0 版本新增) + 用于在其他 stmt API 返回错误(返回错误码或空指针)时获取错误信息。 + +### Schemaless 方式写入接口 + +除了使用 SQL 方式或者使用参数绑定 API 写入数据外,还可以使用 Schemaless 的方式完成写入。Schemaless 可以免于预先创建超级表/数据子表的数据结构,而是可以直接写入数据,TDengine 系统会根据写入的数据内容自动创建和维护所需要的表结构。Schemaless 的使用方式详见 [Schemaless 写入](https://www.taosdata.com/cn/documentation/insert#schemaless) 章节,这里介绍与之配套使用的 C/C++ API。 + +- `TAOS_RES* taos_schemaless_insert(TAOS* taos, const char* lines[], int numLines, int protocol, int precision)` + + **功能说明** + 该接口将行协议的文本数据写入到 TDengine 中。 + + **参数说明** + taos: 数据库连接,通过 taos_connect 函数建立的数据库连接。 + lines:文本数据。满足解析格式要求的无模式文本字符串。 + numLines:文本数据的行数,不能为 0 。 + protocol: 行协议类型,用于标识文本数据格式。 + precision:文本数据中的时间戳精度字符串。 + + **返回值** + TAOS_RES 结构体,应用可以通过使用 taos_errstr 获得错误信息,也可以使用 taos_errno 获得错误码。 + 在某些情况下,返回的 TAOS_RES 为 NULL,此时仍然可以调用 taos_errno 来安全地获得错误码信息。 + 返回的 TAOS_RES 需要调用方来负责释放,否则会出现内存泄漏。 + + **说明** + 协议类型是枚举类型,包含以下三种格式: + TSDB_SML_LINE_PROTOCOL:InfluxDB 行协议(Line Protocol) + TSDB_SML_TELNET_PROTOCOL: OpenTSDB 文本行协议 + TSDB_SML_JSON_PROTOCOL: OpenTSDB Json 协议格式 + + 时间戳分辨率的定义,定义在 taos.h 文件中,具体内容如下: + TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0, + TSDB_SML_TIMESTAMP_HOURS, + TSDB_SML_TIMESTAMP_MINUTES, + TSDB_SML_TIMESTAMP_SECONDS, + TSDB_SML_TIMESTAMP_MILLI_SECONDS, + TSDB_SML_TIMESTAMP_MICRO_SECONDS, + TSDB_SML_TIMESTAMP_NANO_SECONDS + + 需要注意的是,时间戳分辨率参数只在协议类型为 SML_LINE_PROTOCOL 的时候生效。 + 对于 OpenTSDB 的文本协议,时间戳的解析遵循其官方解析规则 — 按照时间戳包含的字符的数量来确认时间精度。 + + **支持版本** + 该功能接口从 2.3.0.0 版本开始支持。 + +```c +#include +#include +#include + +int main() { + const char* host = "127.0.0.1"; + const char* user = "root"; + const char* passwd = "taosdata"; + + // connect to server + TAOS* taos = taos_connect(host, user, passwd, "test", 0); + + // prepare the line string + char* lines1[] = { + "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", + "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000" + }; + + // schema-less insert + TAOS_RES* res = taos_schemaless_insert(taos, lines1, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + if (taos_errno(res) != 0) { + printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res)); + } + + taos_free_result(res); + + // close the connection + taos_close(taos); + return (code); +} +``` + +### 连续查询接口 + +TDengine 提供时间驱动的实时流式计算 API。可以每隔一指定的时间段,对一张或多张数据库的表(数据流)进行各种实时聚合计算操作。操作简单,仅有打开、关闭流的 API。具体如下: + +- `TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, TAOS_ROW row), int64_t stime, void *param, void (*callback)(void *))` + + 该 API 用来创建数据流,其中: + + - taos:已经建立好的数据库连接。 + - sql:SQL 查询语句(仅能使用查询语句)。 + - fp:用户定义的回调函数指针,每次流式计算完成后,TDengine 将查询的结果(TAOS_ROW)、查询状态(TAOS_RES)、用户定义参数(PARAM)传递给回调函数,在回调函数内,用户可以使用 taos_num_fields 获取结果集列数,taos_fetch_fields 获取结果集每列数据的类型。 + - stime:是流式计算开始的时间。如果是“64 位整数最小值”,表示从现在开始;如果不为“64 位整数最小值”,表示从指定的时间开始计算(UTC 时间从 1970/1/1 算起的毫秒数)。 + - param:是应用提供的用于回调的一个参数,回调时,提供给应用。 + - callback: 第二个回调函数,会在连续查询自动停止时被调用。 + + 返回值为 NULL,表示创建失败;返回值不为空,表示成功。 + +- `void taos_close_stream (TAOS_STREAM *tstr)` + + 关闭数据流,其中提供的参数是 taos_open_stream 的返回值。用户停止流式计算的时候,务必关闭该数据流。 + +### 数据订阅接口 + +订阅 API 目前支持订阅一张或多张表,并通过定期轮询的方式不断获取写入表中的最新数据。 + +- `TAOS_SUB *taos_subscribe(TAOS* taos, int restart, const char* topic, const char *sql, TAOS_SUBSCRIBE_CALLBACK fp, void *param, int interval)` + + 该函数负责启动订阅服务,成功时返回订阅对象,失败时返回 `NULL`,其参数为: + + - taos:已经建立好的数据库连接 + - restart:如果订阅已经存在,是重新开始,还是继续之前的订阅 + - topic:订阅的主题(即名称),此参数是订阅的唯一标识 + - sql:订阅的查询语句,此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据 + - fp:收到查询结果时的回调函数(稍后介绍函数原型),只在异步调用时使用,同步调用时此参数应该传 `NULL` + - param:调用回调函数时的附加参数,系统 API 将其原样传递到回调函数,不进行任何处理 + - interval:轮询周期,单位为毫秒。异步调用时,将根据此参数周期性的调用回调函数,为避免对系统性能造成影响,不建议将此参数设置的过小;同步调用时,如两次调用`taos_consume`的间隔小于此周期,API 将会阻塞,直到时间间隔超过此周期。 + +- `typedef void (*TAOS_SUBSCRIBE_CALLBACK)(TAOS_SUB* tsub, TAOS_RES *res, void* param, int code)` + + 异步模式下,回调函数的原型,其参数为: + + - tsub:订阅对象 + - res:查询结果集,注意结果集中可能没有记录 + - param:调用 `taos_subscribe`时客户程序提供的附加参数 + - code:错误码 + + :::note + 在这个回调函数里不可以做耗时过长的处理,尤其是对于返回的结果集中数据较多的情况,否则有可能导致客户端阻塞等异常状态。如果必须进行复杂计算,则建议在另外的线程中进行处理。 + + ::: + +- `TAOS_RES *taos_consume(TAOS_SUB *tsub)` + + 同步模式下,该函数用来获取订阅的结果。 用户应用程序将其置于一个循环之中。 如两次调用`taos_consume`的间隔小于订阅的轮询周期,API 将会阻塞,直到时间间隔超过此周期。 如果数据库有新记录到达,该 API 将返回该最新的记录,否则返回一个没有记录的空结果集。 如果返回值为 `NULL`,说明系统出错。 异步模式下,用户程序不应调用此 API。 + + :::note + 在调用 `taos_consume()` 之后,用户应用应确保尽快调用 `taos_fetch_row()` 或 `taos_fetch_block()` 来处理订阅结果,否则服务端会持续缓存查询结果数据等待客户端读取,极端情况下会导致服务端内存消耗殆尽,影响服务稳定性。 + + ::: + +- `void taos_unsubscribe(TAOS_SUB *tsub, int keepProgress)` + + 取消订阅。 如参数 `keepProgress` 不为 0,API 会保留订阅的进度信息,后续调用 `taos_subscribe` 时可以基于此进度继续;否则将删除进度信息,后续只能重新开始读取数据。 diff --git a/docs-cn/14-reference/03-connector/csharp.mdx b/docs-cn/14-reference/03-connector/csharp.mdx new file mode 100644 index 0000000000000000000000000000000000000000..d5fd1fddf37f2ab2a1acf4e547169b0432d2feb3 --- /dev/null +++ b/docs-cn/14-reference/03-connector/csharp.mdx @@ -0,0 +1,81 @@ +--- +sidebar_position: 7 +sidebar_label: C# +--- + +# C# 连接器 + +- C# 连接器支持的系统有:Linux 64/Windows x64/Windows x86 + +- C# 连接器现在也支持从 [Nuget 下载引用](https://www.nuget.org/packages/TDengine.Connector/) + +- 在 Windows 系统上,C# 应用程序可以使用 TDengine 的原生 C 接口来执行所有数据库操作,后续版本将提供 ORM(Dapper)框架驱动。 + +## 安装准备 + +- 应用驱动安装请参考[安装连接器驱动步骤](/reference/connector/#安装客户端驱动)。 +- 接口文件 TDengineDrivercs.cs 和参考程序示例 TDengineTest.cs 均位于 Windows 客户端 install_directory/examples/C# 目录下。 +- 安装 [.NET SDK](https://dotnet.microsoft.com/download) + +## 示例程序 + +示例程序源码位于 + +- {client_install_directory}/examples/C# +- [C# example source code on GitHub](https://github.com/taosdata/TDengine/tree/develop/examples/C%23) + +:::note +TDengineTest.cs C# 示例源程序,包含了数据库连接参数,以及如何执行数据插入、查询等操作。 + +::: + +## 安装验证 + +需要先安装 .NET SDK + +```cmd +cd {client_install_directory}/examples/C#/C#Checker +//运行测试 +dotnet run -- -h . // 此步骤会先build,然后再运行。 +``` + +## C# 连接器的使用 + +在 Windows 系统上,C# 应用程序可以使用 TDengine 的 C# 连接器接口来执行所有数据库的操作。使用的具体步骤如下所示: + +- 创建一个 C# project(需要 .NET SDK). + + ```cmd + mkdir test + cd test + dotnet new console + ``` + +- 通过 Nuget 引用 TDengineDriver 包 + + ```cmd + dotnet add package TDengine.Connector + ``` + +- 在项目中需要用到 TDengineConnector 的地方引用 TDengineDriver namespace。 + + ```cs + using TDengineDriver; + ``` + +- 用户可以参考[TDengineTest.cs](https://github.com/taosdata/TDengine/tree/develop/examples/C%2523/TDengineTest)来定义数据库连接参数,以及如何执行数据插入、查询等操作。 + +:::note + +- TDengine V2.0.3.0 之后同时支持 32 位和 64 位 Windows 系统,所以 C# 项目在生成 .exe 文件时,“解决方案”/“项目”的“平台”请选择对应的 x86 或 x64。 +- 此接口目前已经在 Visual Studio 2015/2017 中验证过,其它 Visual Studio 版本尚待验证。 +- 此连接器需要用到 taos.dll 文件,所以在未安装客户端时需要在执行应用程序前,拷贝 Windows{client_install_directory}/driver 目录中的 taos.dll 文件到项目最后生成 .exe 可执行文件所在的文件夹。之后运行 exe 文件,即可访问 TDengine 数据库并做插入、查询等操作。 + +::: + +## 第三方驱动 + +Maikebing.Data.Taos 是一个 TDengine 的 ADO.NET 提供器,支持 Linux,Windows。该开发包由热心贡献者`麦壳饼@@maikebing`提供,具体请参考: + +- 接口下载:https://github.com/maikebing/Maikebing.EntityFrameworkCore.Taos +- 用法说明:https://www.taosdata.com/blog/2020/11/02/1901.html diff --git a/docs-cn/14-reference/03-connector/go.mdx b/docs-cn/14-reference/03-connector/go.mdx new file mode 100644 index 0000000000000000000000000000000000000000..859775500e0a4e23de621d144fee243b9eb6c76e --- /dev/null +++ b/docs-cn/14-reference/03-connector/go.mdx @@ -0,0 +1,211 @@ +--- +sidebar_position: 4 +--- + +# Go Connector + +## 安装准备 + +Go 连接器支持的系统有: + +| **CPU 类型** | x64(64bit) | | | aarch64 | aarch32 | +| ------------ | ------------ | -------- | -------- | -------- | ---------- | +| **OS 类型** | Linux | Win64 | Win32 | Linux | Linux | +| **支持与否** | **支持** | **支持** | **支持** | **支持** | **开发中** | + +安装前准备:已安装好 TDengine 应用驱动,参考[安装连接器驱动步骤](/reference/connector)。 + +## 示例程序 + +使用 Go 连接器的示例代码请参考 [https://github.com/taosdata/TDengine/tree/develop/examples/go](https://github.com/taosdata/TDengine/tree/develop/examples/go) 以及[视频教程](https://www.taosdata.com/blog/2020/11/11/1951.html)。 + +示例程序源码也位于安装目录下的 examples/go/taosdemo.go 文件中。 + +:::tip +建议 Go 版本是 1.13 及以上,并开启模块支持: +::: + +```sh +go env -w GO111MODULE=on +go env -w GOPROXY=https://goproxy.io,direct +``` + +在 taosdemo.go 所在目录下进行编译和执行: + +```sh +go mod init taosdemo +go get github.com/taosdata/driver-go/taosSql +# use win branch in Windows platform. +#go get github.com/taosdata/driver-go/taosSql@win +go build +./taosdemo -h fqdn -p serverPort +``` + +## Go 连接器的使用 + +TDengine 提供了 GO 驱动程序包`taosSql`。`taosSql` 实现了 GO 语言的内置接口 `database/sql/driver`。用户只需按如下方式引入包就可以在应用程序中访问 TDengine。 + +```go +import ( + "database/sql" + _ "github.com/taosdata/driver-go/v2/taosSql" +) +``` + +:::tip +下划线与双引号之间必须有一个空格。 + +::: + +`taosSql` 的 v2 版本进行了重构,分离出内置数据库操作接口 `database/sql/driver` 到目录 `taosSql`;订阅、 stmt 等其他功能放到目录 `af`。 + +## 常用 API + +- `sql.Open(DRIVER_NAME string, dataSourceName string) *DB` + + 该 API 用来打开 DB,返回一个类型为\*DB 的对象,一般情况下,DRIVER_NAME 设置为字符串 `taosSql`,dataSourceName 设置为字符串 `user:password@/tcp(host:port)/dbname`,如果客户想要用多个 goroutine 并发访问 TDengine, 那么需要在各个 goroutine 中分别创建一个 sql.Open 对象并用之访问 TDengine。 + + **注意**: 该 API 成功创建的时候,并没有做权限等检查,只有在真正执行 Query 或者 Exec 的时候才能真正的去创建连接,并同时检查 user/password/host/port 是不是合法。另外,由于整个驱动程序大部分实现都下沉到 taosSql 所依赖的 libtaos 动态库中。所以,sql.Open 本身特别轻量。 + +- `func (db *DB) Exec(query string, args ...interface{}) (Result, error)` + +sql.Open 内置的方法,用来执行非查询相关 SQL + +- `func (db *DB) Query(query string, args ...interface{}) (*Rows, error)` + +sql.Open 内置的方法,用来执行查询语句 + +- `func (db *DB) Prepare(query string) (*Stmt, error)` + + sql.Open 内置的方法,Prepare creates a prepared statement for later queries or executions. + +- `func (s *Stmt) Exec(args ...interface{}) (Result, error)` + + sql.Open 内置的方法,executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement. + +- `func (s *Stmt) Query(args ...interface{}) (*Rows, error)` + + sql.Open 内置的方法,Query executes a prepared query statement with the given arguments and returns the query results as a \*Rows. + +- `func (s *Stmt) Close() error` + + sql.Open 内置的方法,Close closes the statement. + +## 其他代码示例 + +[Consume Messages from Kafka](https://github.com/taosdata/go-demo-kafka) 是一个通过 Go 语言实现消费 Kafka 队列写入 TDengine 的示例程序,也可以作为通过 Go 连接 TDengine 的写法参考。 + +## Go RESTful 的使用 + +### 引入 + +```go restful +import ( + "database/sql" + _ "github.com/taosdata/driver-go/v2/taosRestful" +) +``` + +`go.mod ` 的文件 require 块使用  github.com/taosdata/driver-go/v2 develop  之后执行  `go mod tidy ` + +`sql.Open `的 driverName 为  `taosRestful` + +### DSN + +格式为: + +数据库用户名:数据库密码@连接方式(域名或 ip:端口)/[数据库][?参数] + +样例: + +`root:taosdata@http(localhost:6041)/test?readBufferSize=52428800` + +参数: + +`disableCompression` 是否接受压缩数据,默认为 true 不接受压缩数据,如果传输数据使用 gzip 压缩设置为 false。 + +`readBufferSize` 读取数据的缓存区大小默认为 4K(4096),当查询结果数据量多时可以适当调大该值。 + +### 使用限制 + +由于 RESTful 接口无状态所以 `use db` 语法不会生效,需要将 db 名称放到 SQL 语句中,如:`create table if not exists tb1 (ts timestamp, a int)`改为`create table if not exists test.tb1 (ts timestamp, a int)`否则将报错`[0x217] Database not specified or available`。 + +也可以将 db 名称放到 DSN 中,将 `root:taosdata@http(localhost:6041)/` 改为 `root:taosdata@http(localhost:6041)/test`,此方法在 TDengine 2.4.0.5 版本的 taosAdapter 开始支持。当指定的 db 不存在时执行 `create database` 语句不会报错,而执行针对该 db 的其他查询或写入操作会报错。完整示例如下: + +```go restful demo +package main + +import ( + "database/sql" + "fmt" + "time" + + _ "github.com/taosdata/driver-go/v2/taosRestful" +) + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/test" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + fmt.Println("failed to connect TDengine, err:", err) + return + } + defer taos.Close() + taos.Exec("create database if not exists test") + taos.Exec("create table if not exists tb1 (ts timestamp, a int)") + _, err = taos.Exec("insert into tb1 values(now, 0)(now+1s,1)(now+2s,2)(now+3s,3)") + if err != nil { + fmt.Println("failed to insert, err:", err) + return + } + rows, err := taos.Query("select * from tb1") + if err != nil { + fmt.Println("failed to select from table, err:", err) + return + } + + defer rows.Close() + for rows.Next() { + var r struct { + ts time.Time + a int + } + err := rows.Scan(&r.ts, &r.a) + if err != nil { + fmt.Println("scan error:\n", err) + return + } + fmt.Println(r.ts, r.a) + } +} +``` + +### 常见问题 + +- 无法找到包`github.com/taosdata/driver-go/v2/taosRestful` + + 将 `go.mod` 中 require 块对`github.com/taosdata/driver-go/v2`的引用改为`github.com/taosdata/driver-go/v2 develop`,之后执行 `go mod tidy`。 + +- stmt 相关接口崩溃 + + RESTful 不支持 stmt 相关接口,建议使用`db.Exec`和`db.Query`。 + +- 使用 `use db` 语句后执行其他语句报错 `[0x217] Database not specified or available` + + 在 RESTful 接口中 SQL 语句的执行无上下文关联,使用 `use db` 语句不会生效,解决办法见上方使用限制章节。 + +- 使用 taosSql 不报错使用 taosRestful 报错 `[0x217] Database not specified or available` + + 因为 RESTful 接口无状态,使用 `use db` 语句不会生效,解决办法见上方使用限制章节。 + +- 升级 `github.com/taosdata/driver-go/v2/taosRestful` + + 将 `go.mod` 文件中对 `github.com/taosdata/driver-go/v2` 的引用改为 `github.com/taosdata/driver-go/v2 develop`,之后执行 `go mod tidy`。 + +- readBufferSize 参数调大后无明显效果 + + readBufferSize 调大后会减少获取结果时 syscall 的调用。如果查询结果的数据量不大,修改该参数不会带来明显提升,如果该参数修改过大,瓶颈会在解析 JSON 数据。如果需要优化查询速度,需要根据实际情况调整该值来达到查询效果最优。 + +- disableCompression 参数设置为 false 时查询效率降低 + + 当 disableCompression 参数设置为 false 时查询结果会 gzip 压缩后传输,拿到数据后要先进行 gzip 解压。 diff --git a/docs-cn/14-reference/03-connector/java.mdx b/docs-cn/14-reference/03-connector/java.mdx new file mode 100644 index 0000000000000000000000000000000000000000..81718009c404d3190057cb51f79ab94de86ba986 --- /dev/null +++ b/docs-cn/14-reference/03-connector/java.mdx @@ -0,0 +1,892 @@ +--- +sidebar_position: 2 +--- + +# Java Connector + +## 总体介绍 + +`taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTful(taos-jdbcdriver-2.0.18 开始支持 JDBC-RESTful)。 JDBC-JNI 通过调用客户端 libtaos.so(或 taos.dll )的本地方法实现, JDBC-RESTful 则在内部封装了 RESTful 接口实现。 + +![tdengine-connector](/img/tdengine-jdbc-connector.png) + +上图显示了 3 种 Java 应用使用连接器访问 TDengine 的方式: + +- JDBC-JNI:Java 应用在物理节点 1(pnode1)上使用 JDBC-JNI 的 API ,直接调用客户端 API(libtaos.so 或 taos.dll)将写入和查询请求发送到位于物理节点 2(pnode2)上的 taosd 实例。 +- RESTful:应用将 SQL 发送给位于物理节点 2(pnode2)上的 RESTful 连接器,再调用客户端 API(libtaos.so)。 +- JDBC-RESTful:Java 应用通过 JDBC-RESTful 的 API ,将 SQL 封装成一个 RESTful 请求,发送给物理节点 2 的 RESTful 连接器。 + +TDengine 的 JDBC 驱动实现尽可能与关系型数据库驱动保持一致,但 TDengine 与关系对象型数据库的使用场景和技术特征存在差异,导致 `taos-jdbcdriver` 与传统的 JDBC driver 也存在一定差异。在使用时需要注意以下几点: + +- TDengine 目前不支持针对单条数据记录的删除操作。 +- 目前不支持事务操作。 + +### JDBC-JNI 和 JDBC-RESTful 的对比 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
对比项JDBC-JNIJDBC-RESTful
支持的操作系统linux、windows全平台
是否需要安装 client需要不需要
server 升级后是否需要升级 client需要不需要
写入性能JDBC-RESTful 是 JDBC-JNI 的 50%~90%
查询性能JDBC-RESTful 与 JDBC-JNI 没有差别
+ +注意: + +- 与 JNI 方式不同,RESTful 接口是无状态的。在使用 JDBC-RESTful 时,需要在 sql 中指定表、超级表的数据库名称。例如: + +```sql +INSERT INTO test.t1 USING test.weather (ts, temperature) TAGS('beijing') VALUES(now, 24.6); +``` + +- 从 taos-jdbcdriver-2.0.36 和 TDengine 2.2.0.0 版本开始,如果在 url 中指定了 dbname,那么,JDBC-RESTful 会默认使用/rest/sql/dbname 作为 resful 请求的 url,在 sql 中不需要指定 dbname。例如:url 为 jdbc:TAOS-RS://127.0.0.1:6041/test,那么,可以执行 sql:insert into t1 using weather(ts, temperatrue) tags('beijing') values(now, 24.6); + +## 版本支持 + +| taos-jdbcdriver 版本 | TDengine 2.0.x.x 版本 | TDengine 2.2.x.x 版本 | TDengine 2.4.x.x 版本 | JDK 版本 | +| -------------------- | --------------------- | --------------------- | --------------------- | -------- | +| 2.0.37 | X | X | 2.4.0.6 以上 | 1.8.x | +| 2.0.36 | X | 2.2.2.11 以上 | 2.4.0.0 - 2.4.0.5 | 1.8.x | +| 2.0.35 | X | 2.2.2.11 以上 | 2.3.0.0 - 2.4.0.5 | 1.8.x | +| 2.0.33 - 2.0.34 | 2.0.3.0 以上 | 2.2.0.0 以上 | 2.4.0.0 - 2.4.0.5 | 1.8.x | +| 2.0.31 - 2.0.32 | 2.1.3.0 - 2.1.7.7 | X | X | 1.8.x | +| 2.0.22 - 2.0.30 | 2.0.18.0 - 2.1.2.1 | X | X | 1.8.x | +| 2.0.12 - 2.0.21 | 2.0.8.0 - 2.0.17.4 | X | X | 1.8.x | +| 2.0.4 - 2.0.11 | 2.0.0.0 - 2.0.7.3 | X | X | 1.8.x | + +## TDengine DataType 和 Java DataType + +TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对应类型转换如下: + +| TDengine DataType | JDBCType (driver 版本 < 2.0.24) | JDBCType (driver 版本 >= 2.0.24) | +| ----------------- | --------------------------------- | ---------------------------------- | +| TIMESTAMP | java.lang.Long | java.sql.Timestamp | +| INT | java.lang.Integer | java.lang.Integer | +| BIGINT | java.lang.Long | java.lang.Long | +| FLOAT | java.lang.Float | java.lang.Float | +| DOUBLE | java.lang.Double | java.lang.Double | +| SMALLINT | java.lang.Short | java.lang.Short | +| TINYINT | java.lang.Byte | java.lang.Byte | +| BOOL | java.lang.Boolean | java.lang.Boolean | +| BINARY | java.lang.String | byte array | +| NCHAR | java.lang.String | java.lang.String | +| JSON | - | java.lang.String | + +注意:JSON 类型仅在 tag 中支持。 + +## 安装 Java Connector + +### 安装前准备 + +使用 Java Connector 连接数据库前,需要具备以下条件: + +1. Linux 或 Windows 操作系统 +2. Java 1.8 以上运行时环境 +3. TDengine-client(使用 JDBC-JNI 时必须,使用 JDBC-RESTful 时非必须) + +**注意**:由于 TDengine 的应用驱动是使用 C 语言开发的,使用 taos-jdbcdriver 驱动包时需要依赖系统对应的本地函数库。 + +- libtaos.so 在 Linux 系统中成功安装 TDengine 后,依赖的本地函数库 libtaos.so 文件会被自动拷贝至 /usr/lib/libtaos.so,该目录包含在 Linux 自动扫描路径上,无需单独指定。 +- taos.dll 在 Windows 系统中安装完客户端之后,驱动包依赖的 taos.dll 文件会自动拷贝到系统默认搜索路径 C:/Windows/System32 下,同样无需要单独指定。 + +**注意**:在 Windows 环境开发时需要安装 TDengine 对应的 [windows 客户端](https://www.taosdata.com/cn/all-downloads/#TDengine-Windows-Client),Linux 服务器安装完 TDengine 之后默认已安装 client,也可以单独安装 [Linux 客户端](https://www.taosdata.com/cn/getting-started/#快速上手) 连接远程 TDengine Server。 + +### 通过 maven 获取 JDBC driver + +目前 taos-jdbcdriver 已经发布到 [Sonatype Repository](https://search.maven.org/artifact/com.taosdata.jdbc/taos-jdbcdriver) 仓库,且各大仓库都已同步。 + +- [sonatype](https://search.maven.org/artifact/com.taosdata.jdbc/taos-jdbcdriver) +- [mvnrepository](https://mvnrepository.com/artifact/com.taosdata.jdbc/taos-jdbcdriver) +- [maven.aliyun](https://maven.aliyun.com/mvn/search) + +maven 项目中,在 pom.xml 中添加以下依赖: + +```xml-dtd + + com.taosdata.jdbc + taos-jdbcdriver + 2.0.18 + +``` + +### 通过源码编译获取 JDBC driver + +可以通过下载 TDengine 的源码,自己编译最新版本的 java connector + +```shell +git clone https://github.com/taosdata/TDengine.git +cd TDengine/src/connector/jdbc +mvn clean package -Dmaven.test.skip=true +``` + +编译后,在 target 目录下会产生 taos-jdbcdriver-2.0.XX-dist.jar 的 jar 包。 + +## Java 连接器的使用 + +### 获取连接 + +#### 指定 URL 获取连接 + +通过指定 URL 获取连接,如下所示: + +```java +Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); +String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosdata"; +Connection conn = DriverManager.getConnection(jdbcUrl); +``` + +以上示例,使用 **JDBC-RESTful** 的 driver,建立了到 hostname 为 taosdemo.com,端口为 6041,数据库名为 test 的连接。这个 URL 中指定用户名(user)为 root,密码(password)为 taosdata。 + +使用 JDBC-RESTful 接口,不需要依赖本地函数库。与 JDBC-JNI 相比,仅需要: + +1. driverClass 指定为“com.taosdata.jdbc.rs.RestfulDriver”; +2. jdbcUrl 以“jdbc:TAOS-RS://”开头; +3. 使用 6041 作为连接端口。 + +如果希望获得更好的写入和查询性能,Java 应用可以使用 **JDBC-JNI** 的 driver,如下所示: + +```java +Class.forName("com.taosdata.jdbc.TSDBDriver"); +String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata"; +Connection conn = DriverManager.getConnection(jdbcUrl); +``` + +以上示例,使用了 JDBC-JNI 的 driver,建立了到 hostname 为 taosdemo.com,端口为 6030(TDengine 的默认端口),数据库名为 test 的连接。这个 URL 中指定用户名(user)为 root,密码(password)为 taosdata。 + +**注意**:使用 JDBC-JNI 的 driver,taos-jdbcdriver 驱动包时需要依赖系统对应的本地函数库(Linux 下是 libtaos.so;Windows 下是 taos.dll)。 + +> 在 Windows 环境开发时需要安装 TDengine 对应的 [windows 客户端](https://www.taosdata.com/cn/all-downloads/#TDengine-Windows-Client),Linux 服务器安装完 TDengine 之后默认已安装 client,也可以单独安装 [Linux 客户端](https://www.taosdata.com/cn/getting-started/#%E5%AE%A2%E6%88%B7%E7%AB%AF) 连接远程 TDengine Server。 + +JDBC-JNI 的使用请参见[视频教程](https://www.taosdata.com/blog/2020/11/11/1955.html)。 + +TDengine 的 JDBC URL 规范格式为: +`jdbc:[TAOS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}]` + +url 中的配置参数如下: + +- user:登录 TDengine 用户名,默认值 'root'。 +- password:用户登录密码,默认值 'taosdata'。 +- cfgdir:客户端配置文件目录路径,Linux OS 上默认值 `/etc/taos`,Windows OS 上默认值 `C:/TDengine/cfg`。 +- charset:客户端使用的字符集,默认值为系统字符集。 +- locale:客户端语言环境,默认值系统当前 locale。 +- timezone:客户端使用的时区,默认值为系统当前时区。 +- batchfetch: 仅在使用 JDBC-JNI 时生效。true:在执行查询时批量拉取结果集;false:逐行拉取结果集。默认值为:false。 +- timestampFormat: 仅在使用 JDBC-RESTful 时生效. 'TIMESTAMP':结果集中 timestamp 类型的字段为一个 long 值; 'UTC':结果集中 timestamp 类型的字段为一个 UTC 时间格式的字符串; 'STRING':结果集中 timestamp 类型的字段为一个本地时间格式的字符串。默认值为'STRING'。 +- batchErrorIgnore:true:在执行 Statement 的 executeBatch 时,如果中间有一条 sql 执行失败,继续执行下面的 sq 了。false:不再执行失败 sql 后的任何语句。默认值为:false。 + +#### 指定 URL 和 Properties 获取连接 + +除了通过指定的 URL 获取连接,还可以使用 Properties 指定建立连接时的参数,如下所示: + +```java +public Connection getConn() throws Exception{ + Class.forName("com.taosdata.jdbc.TSDBDriver"); + // Class.forName("com.taosdata.jdbc.rs.RestfulDriver"); + String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata"; + // String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + Connection conn = DriverManager.getConnection(jdbcUrl, connProps); + return conn; +} +``` + +以上示例,建立一个到 hostname 为 taosdemo.com,端口为 6030,数据库名为 test 的连接。注释为使用 JDBC-RESTful 时的方法。这个连接在 url 中指定了用户名(user)为 root,密码(password)为 taosdata,并在 connProps 中指定了使用的字符集、语言环境、时区等信息。 + +properties 中的配置参数如下: + +- TSDBDriver.PROPERTY_KEY_USER:登录 TDengine 用户名,默认值 'root'。 +- TSDBDriver.PROPERTY_KEY_PASSWORD:用户登录密码,默认值 'taosdata'。 +- TSDBDriver.PROPERTY_KEY_CONFIG_DIR:客户端配置文件目录路径,Linux OS 上默认值 `/etc/taos`,Windows OS 上默认值 `C:/TDengine/cfg`。 +- TSDBDriver.PROPERTY_KEY_CHARSET:客户端使用的字符集,默认值为系统字符集。 +- TSDBDriver.PROPERTY_KEY_LOCALE:客户端语言环境,默认值系统当前 locale。 +- TSDBDriver.PROPERTY_KEY_TIME_ZONE:客户端使用的时区,默认值为系统当前时区。 +- TSDBDriver.PROPERTY_KEY_BATCH_LOAD: 仅在使用 JDBC-JNI 时生效。true:在执行查询时批量拉取结果集;false:逐行拉取结果集。默认值为:false。 +- TSDBDriver.PROPERTY_KEY_TIMESTAMP_FORMAT: 仅在使用 JDBC-RESTful 时生效. 'TIMESTAMP':结果集中 timestamp 类型的字段为一个 long 值; 'UTC':结果集中 timestamp 类型的字段为一个 UTC 时间格式的字符串; 'STRING':结果集中 timestamp 类型的字段为一个本地时间格式的字符串。默认值为'STRING'。 +- TSDBDriver.PROPERTY_KEY_BATCH_ERROR_IGNORE:true:在执行 Statement 的 executeBatch 时,如果中间有一条 sql 执行失败,继续执行下面的 sq 了。false:不再执行失败 sql 后的任何语句。默认值为:false。 + +#### 使用客户端配置文件建立连接 + +当使用 JDBC-JNI 连接 TDengine 集群时,可以使用客户端配置文件,在客户端配置文件中指定集群的 firstEp、secondEp 参数。如下所示: + +1. 在 Java 应用中不指定 hostname 和 port + +```java +public Connection getConn() throws Exception{ + Class.forName("com.taosdata.jdbc.TSDBDriver"); + String jdbcUrl = "jdbc:TAOS://:/test?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + Connection conn = DriverManager.getConnection(jdbcUrl, connProps); + return conn; +} +``` + +2. 在配置文件中指定 firstEp 和 secondEp + +``` +# first fully qualified domain name (FQDN) for TDengine system +firstEp cluster_node1:6030 + +# second fully qualified domain name (FQDN) for TDengine system, for cluster only +secondEp cluster_node2:6030 + +# default system charset +# charset UTF-8 + +# system locale +# locale en_US.UTF-8 +``` + +以上示例,jdbc 会使用客户端的配置文件,建立到 hostname 为 cluster_node1、端口为 6030、数据库名为 test 的连接。当集群中 firstEp 节点失效时,JDBC 会尝试使用 secondEp 连接集群。 + +TDengine 中,只要保证 firstEp 和 secondEp 中一个节点有效,就可以正常建立到集群的连接。 + +> 注意:这里的配置文件指的是调用 JDBC Connector 的应用程序所在机器上的配置文件,Linux OS 上默认值 /etc/taos/taos.cfg ,Windows OS 上默认值 C://TDengine/cfg/taos.cfg。 + +#### 配置参数的优先级 + +通过以上 3 种方式获取连接,如果配置参数在 url、Properties、客户端配置文件中有重复,则参数的`优先级由高到低`分别如下: + +1. JDBC URL 参数,如上所述,可以在 JDBC URL 的参数中指定。 +2. Properties connProps +3. 客户端配置文件 taos.cfg + +例如:在 url 中指定了 password 为 taosdata,在 Properties 中指定了 password 为 taosdemo,那么,JDBC 会使用 url 中的 password 建立连接。 + +> 更多详细配置请参考[客户端配置](https://www.taosdata.com/cn/documentation/administrator/#client) + +### 创建数据库和表 + +```java +Statement stmt = conn.createStatement(); + +// create database +stmt.executeUpdate("create database if not exists db"); + +// use database +stmt.executeUpdate("use db"); + +// create table +stmt.executeUpdate("create table if not exists tb (ts timestamp, temperature int, humidity float)"); +``` + +> 注意:如果不使用 `use db` 指定数据库,则后续对表的操作都需要增加数据库名称作为前缀,如 db.tb。 + +### 插入数据 + +```java +// insert data +int affectedRows = stmt.executeUpdate("insert into tb values(now, 23, 10.3) (now + 1s, 20, 9.3)"); + +System.out.println("insert " + affectedRows + " rows."); +``` + +> now 为系统内部函数,默认为客户端所在计算机当前时间。 +> `now + 1s` 代表客户端当前时间往后加 1 秒,数字后面代表时间单位:a(毫秒),s(秒),m(分),h(小时),d(天),w(周),n(月),y(年)。 + +### 查询数据 + +```java +// query data +ResultSet resultSet = stmt.executeQuery("select * from tb"); + +Timestamp ts = null; +int temperature = 0; +float humidity = 0; +while(resultSet.next()){ + + ts = resultSet.getTimestamp(1); + temperature = resultSet.getInt(2); + humidity = resultSet.getFloat("humidity"); + + System.out.printf("%s, %d, %s\n", ts, temperature, humidity); +} +``` + +> 查询和操作关系型数据库一致,使用下标获取返回字段内容时从 1 开始,建议使用字段名称获取。 + +### 处理异常 + +在报错后,通过 SQLException 可以获取到错误的信息和错误码: + +```java +try (Statement statement = connection.createStatement()) { + // executeQuery + ResultSet resultSet = statement.executeQuery(sql); + // print result + printResult(resultSet); +} catch (SQLException e) { + System.out.println("ERROR Message: " + e.getMessage()); + System.out.println("ERROR Code: " + e.getErrorCode()); + e.printStackTrace(); +} +``` + +JDBC 连接器可能报错的错误码包括 3 种:JDBC driver 本身的报错(错误码在 0x2301 到 0x2350 之间),JNI 方法的报错(错误码在 0x2351 到 0x2400 之间),TDengine 其他功能模块的报错。 + +具体的错误码请参考: + +- https://github.com/taosdata/TDengine/blob/develop/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java +- https://github.com/taosdata/TDengine/blob/develop/src/inc/taoserror.h + +### 通过参数绑定写入数据 + +从 2.1.2.0 版本开始,TDengine 的 JDBC-JNI 实现大幅改进了参数绑定方式对数据写入(INSERT)场景的支持。采用这种方式写入数据时,能避免 SQL 语法解析的资源消耗,从而在很多情况下显著提升写入性能。 +注意: + +- JDBC-RESTful 实现并不提供参数绑定这种使用方式 +- 以下示例代码基于 taos-jdbcdriver-2.0.36 +- binary 类型数据需要调用 setString 方法,nchar 类型数据需要调用 setNString 方法 +- setString 和 setNString 都要求用户在 size 参数里声明表定义中对应列的列宽 + +示例代码: + +```java +public class ParameterBindingDemo { + + private static final String host = "127.0.0.1"; + private static final Random random = new Random(System.currentTimeMillis()); + private static final int BINARY_COLUMN_SIZE = 20; + private static final String[] schemaList = { + "create table stable1(ts timestamp, f1 tinyint, f2 smallint, f3 int, f4 bigint) tags(t1 tinyint, t2 smallint, t3 int, t4 bigint)", + "create table stable2(ts timestamp, f1 float, f2 double) tags(t1 float, t2 double)", + "create table stable3(ts timestamp, f1 bool) tags(t1 bool)", + "create table stable4(ts timestamp, f1 binary(" + BINARY_COLUMN_SIZE + ")) tags(t1 binary(" + BINARY_COLUMN_SIZE + "))", + "create table stable5(ts timestamp, f1 nchar(" + BINARY_COLUMN_SIZE + ")) tags(t1 nchar(" + BINARY_COLUMN_SIZE + "))" + }; + private static final int numOfSubTable = 10, numOfRow = 10; + + public static void main(String[] args) throws SQLException { + + String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; + Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata"); + + init(conn); + + bindInteger(conn); + + bindFloat(conn); + + bindBoolean(conn); + + bindBytes(conn); + + bindString(conn); + + conn.close(); + } + + private static void init(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists test_parabind"); + stmt.execute("create database if not exists test_parabind"); + stmt.execute("use test_parabind"); + for (int i = 0; i < schemaList.length; i++) { + stmt.execute(schemaList[i]); + } + } + } + + private static void bindInteger(Connection conn) throws SQLException { + String sql = "insert into ? using stable1 tags(?,?,?,?) values(?,?,?,?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t1_" + i); + // set tags + pstmt.setTagByte(0, Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); + pstmt.setTagShort(1, Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); + pstmt.setTagInt(2, random.nextInt(Integer.MAX_VALUE)); + pstmt.setTagLong(3, random.nextLong()); + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f1List.add(Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); + pstmt.setByte(1, f1List); + + ArrayList f2List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f2List.add(Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); + pstmt.setShort(2, f2List); + + ArrayList f3List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f3List.add(random.nextInt(Integer.MAX_VALUE)); + pstmt.setInt(3, f3List); + + ArrayList f4List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f4List.add(random.nextLong()); + pstmt.setLong(4, f4List); + + // add column + pstmt.columnDataAddBatch(); + } + // execute column + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindFloat(Connection conn) throws SQLException { + String sql = "insert into ? using stable2 tags(?,?) values(?,?,?)"; + + TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class); + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t2_" + i); + // set tags + pstmt.setTagFloat(0, random.nextFloat()); + pstmt.setTagDouble(1, random.nextDouble()); + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f1List.add(random.nextFloat()); + pstmt.setFloat(1, f1List); + + ArrayList f2List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f2List.add(random.nextDouble()); + pstmt.setDouble(2, f2List); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + // close if no try-with-catch statement is used + pstmt.close(); + } + + private static void bindBoolean(Connection conn) throws SQLException { + String sql = "insert into ? using stable3 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t3_" + i); + // set tags + pstmt.setTagBoolean(0, random.nextBoolean()); + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f1List.add(random.nextBoolean()); + pstmt.setBoolean(1, f1List); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindBytes(Connection conn) throws SQLException { + String sql = "insert into ? using stable4 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t4_" + i); + // set tags + pstmt.setTagString(0, new String("abc")); + + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) { + f1List.add(new String("abc")); + } + pstmt.setString(1, f1List, BINARY_COLUMN_SIZE); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindString(Connection conn) throws SQLException { + String sql = "insert into ? using stable5 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t5_" + i); + // set tags + pstmt.setTagNString(0, "北京-abc"); + + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) { + f1List.add("北京-abc"); + } + pstmt.setNString(1, f1List, BINARY_COLUMN_SIZE); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } +} +``` + +用于设定 TAGS 取值的方法总共有: + +```java +public void setTagNull(int index, int type) +public void setTagBoolean(int index, boolean value) +public void setTagInt(int index, int value) +public void setTagByte(int index, byte value) +public void setTagShort(int index, short value) +public void setTagLong(int index, long value) +public void setTagTimestamp(int index, long value) +public void setTagFloat(int index, float value) +public void setTagDouble(int index, double value) +public void setTagString(int index, String value) +public void setTagNString(int index, String value) +``` + +用于设定 VALUES 数据列的取值的方法总共有: + +```java +public void setInt(int columnIndex, ArrayList list) throws SQLException +public void setFloat(int columnIndex, ArrayList list) throws SQLException +public void setTimestamp(int columnIndex, ArrayList list) throws SQLException +public void setLong(int columnIndex, ArrayList list) throws SQLException +public void setDouble(int columnIndex, ArrayList list) throws SQLException +public void setBoolean(int columnIndex, ArrayList list) throws SQLException +public void setByte(int columnIndex, ArrayList list) throws SQLException +public void setShort(int columnIndex, ArrayList list) throws SQLException +public void setString(int columnIndex, ArrayList list, int size) throws SQLException +public void setNString(int columnIndex, ArrayList list, int size) throws SQLException +``` + +### 无模式写入 + +从 2.2.0.0 版本开始,TDengine 增加了对无模式写入功能。无模式写入兼容 InfluxDB 的 行协议(Line Protocol)、OpenTSDB 的 telnet 行协议和 OpenTSDB 的 JSON 格式协议。详情请参见[无模式写入](https://www.taosdata.com/docs/cn/v2.0/insert#schemaless)。 + +注意: + +- JDBC-RESTful 实现并不提供无模式写入这种使用方式 +- 以下示例代码基于 taos-jdbcdriver-2.0.36 + +示例代码: + +```java +public class SchemalessInsertTest { + private static final String host = "127.0.0.1"; + private static final String lineDemo = "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000"; + private static final String telnetDemo = "stb0_0 1626006833 4 host=host0 interface=eth0"; + private static final String jsonDemo = "{\"metric\": \"meter_current\",\"timestamp\": 1346846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"Beijing\", \"id\": \"d1001\"}}"; + + public static void main(String[] args) throws SQLException { + final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + try (Connection connection = DriverManager.getConnection(url)) { + init(connection); + + SchemalessWriter writer = new SchemalessWriter(connection); + writer.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.NANO_SECONDS); + writer.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); + writer.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); + } + } + + private static void init(Connection connection) throws SQLException { + try (Statement stmt = connection.createStatement()) { + stmt.executeUpdate("drop database if exists test_schemaless"); + stmt.executeUpdate("create database if not exists test_schemaless"); + stmt.executeUpdate("use test_schemaless"); + } + } +} +``` + +### 设置客户端参数 + +从 TDengine-2.3.5.0 版本开始,jdbc driver 支持在应用的第一次连接中,设置 TDengine 的客户端参数。Driver 支持 JDBC-JNI 方式中,通过 jdbcUrl 和 properties 两种方式设置 client parameter。 +注意: + +- JDBC-RESTful 不支持设置 client parameter 的功能。 +- 应用中设置的 client parameter 为进程级别的,即如果要更新 client 的参数,需要重启应用。这是因为 client parameter 是全局参数,仅在应用程序的第一次设置生效。 +- 以下示例代码基于 taos-jdbcdriver-2.0.36。 + +示例代码: + +```java +public class ClientParameterSetting { + private static final String host = "127.0.0.1"; + + public static void main(String[] args) throws SQLException { + setParameterInJdbcUrl(); + + setParameterInProperties(); + } + + private static void setParameterInJdbcUrl() throws SQLException { + String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?debugFlag=135&asyncLog=0"; + + Connection connection = DriverManager.getConnection(jdbcUrl, "root", "taosdata"); + + printDatabase(connection); + + connection.close(); + } + + private static void setParameterInProperties() throws SQLException { + String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; + Properties properties = new Properties(); + properties.setProperty("user", "root"); + properties.setProperty("password", "taosdata"); + properties.setProperty("debugFlag", "135"); + properties.setProperty("asyncLog", "0"); + properties.setProperty("maxSQLLength", "1048576"); + + try (Connection conn = DriverManager.getConnection(jdbcUrl, properties)) { + printDatabase(conn); + } + } + + private static void printDatabase(Connection connection) throws SQLException { + try (Statement stmt = connection.createStatement()) { + ResultSet rs = stmt.executeQuery("show databases"); + + ResultSetMetaData meta = rs.getMetaData(); + while (rs.next()) { + for (int i = 1; i <= meta.getColumnCount(); i++) { + System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t"); + } + System.out.println(); + } + } + } +} +``` + +## 订阅 + +### 创建 + +```java +TSDBSubscribe sub = ((TSDBConnection)conn).subscribe("topic", "select * from meters", false); +``` + +`subscribe` 方法的三个参数含义如下: + +- topic:订阅的主题(即名称),此参数是订阅的唯一标识 +- sql:订阅的查询语句,此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据 +- restart:如果订阅已经存在,是重新开始,还是继续之前的订阅 + +如上面的例子将使用 SQL 语句 `select * from meters` 创建一个名为 `topic` 的订阅,如果这个订阅已经存在,将继续之前的查询进度,而不是从头开始消费所有的数据。 + +### 消费数据 + +```java +int total = 0; +while(true) { + TSDBResultSet rs = sub.consume(); + int count = 0; + while(rs.next()) { + count++; + } + total += count; + System.out.printf("%d rows consumed, total %d\n", count, total); + Thread.sleep(1000); +} +``` + +`consume` 方法返回一个结果集,其中包含从上次 `consume` 到目前为止的所有新数据。请务必按需选择合理的调用 `consume` 的频率(如例子中的 `Thread.sleep(1000)`),否则会给服务端造成不必要的压力。 + +### 关闭订阅 + +```java +sub.close(true); +``` + +`close` 方法关闭一个订阅。如果其参数为 `true` 表示保留订阅进度信息,后续可以创建同名订阅继续消费数据;如为 `false` 则不保留订阅进度。 + +## 关闭资源 + +```java +resultSet.close(); +stmt.close(); +conn.close(); +``` + +> `注意务必要将 connection 进行关闭`,否则会出现连接泄露。 + +## 与连接池使用 + +### HikariCP + +使用示例如下: + +```java + public static void main(String[] args) throws SQLException { + HikariConfig config = new HikariConfig(); + // jdbc properties + config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log"); + config.setUsername("root"); + config.setPassword("taosdata"); + // connection pool configurations + config.setMinimumIdle(10); //minimum number of idle connection + config.setMaximumPoolSize(10); //maximum number of connection in the pool + config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool + config.setMaxLifetime(0); // maximum life time for each connection + config.setIdleTimeout(0); // max idle time for recycle idle connection + config.setConnectionTestQuery("select server_status()"); //validation query + + HikariDataSource ds = new HikariDataSource(config); //create datasource + + Connection connection = ds.getConnection(); // get connection + Statement statement = connection.createStatement(); // get statement + + //query or insert + // ... + + connection.close(); // put back to conneciton pool +} +``` + +> 通过 HikariDataSource.getConnection() 获取连接后,使用完成后需要调用 close() 方法,实际上它并不会关闭连接,只是放回连接池中。 +> 更多 HikariCP 使用问题请查看[官方说明](https://github.com/brettwooldridge/HikariCP)。 + +### Druid + +使用示例如下: + +```java +public static void main(String[] args) throws Exception { + + DruidDataSource dataSource = new DruidDataSource(); + // jdbc properties + dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); + dataSource.setUrl(url); + dataSource.setUsername("root"); + dataSource.setPassword("taosdata"); + // pool configurations + dataSource.setInitialSize(10); + dataSource.setMinIdle(10); + dataSource.setMaxActive(10); + dataSource.setMaxWait(30000); + dataSource.setValidationQuery("select server_status()"); + + Connection connection = dataSource.getConnection(); // get connection + Statement statement = connection.createStatement(); // get statement + //query or insert + // ... + + connection.close(); // put back to conneciton pool +} +``` + +> 更多 druid 使用问题请查看[官方说明](https://github.com/alibaba/druid)。 + +**注意事项:** + +- TDengine `v1.6.4.1` 版本开始提供了一个专门用于心跳检测的函数 `select server_status()`,所以在使用连接池时推荐使用 `select server_status()` 进行 Validation Query。 + +如下所示,`select server_status()` 执行成功会返回 `1`。 + +```sql +taos> select server_status(); +server_status()| +================ +1 | +Query OK, 1 row(s) in set (0.000141s) +``` + +## 在框架中使用 + +- Spring JdbcTemplate 中使用 taos-jdbcdriver,可参考 [SpringJdbcTemplate](https://github.com/taosdata/TDengine/tree/develop/examples/JDBC/SpringJdbcTemplate) +- Springboot + Mybatis 中使用,可参考 [springbootdemo](https://github.com/taosdata/TDengine/tree/develop/examples/JDBC/springbootdemo) + +## 示例程序 + +示例程序源码位于 TDengine/test/examples/JDBC 下: + +- JDBCDemo:JDBC 示例源程序 +- JDBCConnectorChecker:JDBC 安装校验源程序及 jar 包 +- Springbootdemo:springboot 示例源程序 +- SpringJdbcTemplate:SpringJDBC 模板 + +请参考:[JDBC example](https://github.com/taosdata/TDengine/tree/develop/examples/JDBC) + +## 常见问题 + +- 使用 Statement 的 addBatch 和 executeBatch 来执行“批量写入/更行”,为什么没有带来性能上的提升? + **原因**:TDengine 的 JDBC 实现中,通过 addBatch 方法提交的 sql 语句,会按照添加的顺序,依次执行,这种方式没有减少与服务端的交互次数,不会带来性能上的提升。 + **解决方法**:1. 在一条 insert 语句中拼接多个 values 值;2. 使用多线程的方式并发插入;3. 使用参数绑定的写入方式 +- java.lang.UnsatisfiedLinkError: no taos in java.library.path + **原因**:程序没有找到依赖的本地函数库 taos。 + **解决方法**:Windows 下可以将 C:\TDengine\driver\taos.dll 拷贝到 C:\Windows\System32\ 目录下,Linux 下将建立如下软链 `ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so` 即可。 + +- java.lang.UnsatisfiedLinkError: taos.dll Can't load AMD 64 bit on a IA 32-bit platform + **原因**:目前 TDengine 只支持 64 位 JDK。 + **解决方法**:重新安装 64 位 JDK。 + +- 其它问题请参考 [Issues](https://github.com/taosdata/TDengine/issues) diff --git a/docs-cn/14-reference/03-connector/node.mdx b/docs-cn/14-reference/03-connector/node.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c19038c38d83d01f6da5b707fa2d8fe0e2875b93 --- /dev/null +++ b/docs-cn/14-reference/03-connector/node.mdx @@ -0,0 +1,201 @@ +--- +sidebar_position: 5 +--- + +# Node.js Connector + +Node.js 连接器支持的系统有: + +| **CPU 类型** | x64(64bit) | | | aarch64 | aarch32 | +| ------------ | ------------ | -------- | -------- | -------- | -------- | +| **OS 类型** | Linux | Win64 | Win32 | Linux | Linux | +| **支持与否** | **支持** | **支持** | **支持** | **支持** | **支持** | + +Node.js 连接器的使用参见[视频教程](https://www.taosdata.com/blog/2020/11/11/1957.html)。 + +### 安装准备 + +- 应用驱动安装请参考[安装连接器驱动步骤](/reference/connector/#安装客户端驱动)。 + +### 安装 Node.js 连接器 + +用户可以通过[npm](https://www.npmjs.com/)来进行安装,也可以通过源代码*src/connector/nodejs/* 来进行安装。具体安装步骤如下: + +首先,通过[npm](https://www.npmjs.com/)安装 node.js 连接器。 + +```bash +npm install td2.0-connector +``` + +我们建议用户使用 npm 安装 node.js 连接器。如果您没有安装 npm,可以将*src/connector/nodejs/*拷贝到您的 nodejs 项目目录下。 + +我们使用[node-gyp](https://github.com/nodejs/node-gyp)和 TDengine 服务端进行交互。安装 node.js 连接器之前,还需要根据具体操作系统来安装下文提到的一些依赖工具。 + +### Linux + +- `python` (建议`v2.7` , `v3.x.x` 目前还不支持) +- `node` 2.0.6 支持 v12.x 和 v10.x,2.0.5 及更早版本支持 v10.x 版本,其他版本可能存在包兼容性的问题。 +- `make` +- c 语言编译器比如[GCC](https://gcc.gnu.org) + +### Windows + +#### 安装方法 1 + +使用微软的[windows-build-tools](https://github.com/felixrieseberg/windows-build-tools)在`cmd` 命令行界面执行`npm install --global --production windows-build-tools` 即可安装所有的必备工具。 + +#### 安装方法 2 + +手动安装以下工具: + +- 安装 Visual Studio 相关:[Visual Studio Build 工具](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) 或者 [Visual Studio 2017 Community](https://visualstudio.microsoft.com/pl/thank-you-downloading-visual-studio/?sku=Community) +- 安装 [Python](https://www.python.org/downloads/) 2.7(`v3.x.x` 暂不支持) 并执行 `npm config set python python2.7` +- 进入`cmd`命令行界面,`npm config set msvs_version 2017` + +如果以上步骤不能成功执行,可以参考微软的 node.js 用户手册[Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules)。 + +如果在 Windows 10 ARM 上使用 ARM64 Node.js,还需添加 "Visual C++ compilers and libraries for ARM64" 和 "Visual C++ ATL for ARM64"。 + +### 示例程序 + +示例程序源码位于 install_directory/examples/nodejs,有: + +Node-example.js node.js 示例源程序 +Node-example-raw.js + +### 安装验证 + +在安装好 TDengine 客户端后,使用 nodejsChecker.js 程序能够验证当前环境是否支持 nodejs 方式访问 Tdengine。 + +验证方法: + +1. 新建安装验证目录,例如:`~/tdengine-test`,拷贝 github 上 nodejsChecker.js 源程序。下载地址:(https://github.com/taosdata/TDengine/tree/develop/examples/nodejs/nodejsChecker.js)。 + +2. 在命令行中执行以下命令: + +```bash +npm init -y +npm install td2.0-connector +node nodejsChecker.js host=localhost +``` + +3. 执行以上步骤后,在命令行会输出 nodejs 连接 Tdengine 实例,并执行简答插入和查询的结果。 + +### Node.js 连接器的使用 + +以下是 Node.js 连接器的一些基本使用方法,详细的使用方法可参考[TDengine Node.js connector](https://github.com/taosdata/TDengine/tree/develop/src/connector/nodejs)。 + +#### 建立连接 + +使用 node.js 连接器时,必须先`require td2.0-connector`,然后使用 `taos.connect` 函数建立到服务端的连接。例如如下代码: + +```javascript +const taos = require("td2.0-connector"); +var conn = taos.connect({ + host: "taosdemo.com", + user: "root", + password: "taosdata", + config: "/etc/taos", + port: 6030, +}); +var cursor = conn.cursor(); // Initializing a new cursor +``` + +建立了一个到 hostname 为 taosdemo.com,端口为 6030(Tdengine 的默认端口号)的连接。连接指定了用户名(root)和密码(taosdata)。taos.connect 函数必须提供的参数是`host`,其它参数在没有提供的情况下会使用如下的默认值。taos.connect 返回了`TDengineConnection` 对象,使用 `cursor()` 方法获取`TDengineCursor`对象来执行 sql 语句。 + +#### 执行 SQL 和插入数据 + +对于 DDL 语句(例如 create database、create table、use 等),可以使用 cursor 的 execute 方法。代码如下: + +```js +cursor.execute("create database if not exists test;"); +``` + +以上代码创建了一个名称为 test 的数据库。对于 DDL 语句,一般没有返回值,cursor 的 execute 返回值为 0。 + +对于 Insert 语句,代码如下: + +```js +var affectRows = cursor.execute( + "insert into test.weather values(now, 22.3, 34);" +); +``` + +execute 方法的返回值为该语句影响的行数,上面的 sql 向 test 库的 weather 表中,插入了一条数据,则返回值 affectRows 为 1。 + +TDengine 目前还不支持 delete 语句。但从 2.0.8.0 版本开始,可以通过 `CREATE DATABASE` 时指定的 UPDATE 参数来启用对数据行的 update。 + +#### 查询 + +可通过 `cursor.query` 函数来查询数据库。 + +```javascript +var query = cursor.query("show databases;"); +``` + +查询的结果可以通过 `query.execute()` 函数获取并打印出来。 + +```javascript +var promise = query.execute(); +promise.then(function (result) { + result.pretty(); +}); +``` + +格式化查询语句还可以使用`query`的`bind`方法。如下面的示例:`query`会自动将提供的数值填入查询语句的`?`里。 + +```javascript +var query = cursor + .query("select * from meterinfo.meters where ts <= ? and areaid = ?;") + .bind(new Date(), 5); +query.execute().then(function (result) { + result.pretty(); +}); +``` + +如果在`query`语句里提供第二个参数并设为`true`也可以立即获取查询结果。如下: + +```javascript +var promise = cursor.query( + "select * from meterinfo.meters where v1 = 30;", + true +); +promise.then(function (result) { + result.pretty(); +}); +``` + +#### 关闭连接 + +在完成插入、查询等操作后,要关闭连接。代码如下: + +```js +conn.close(); +``` + +#### 异步函数 + +异步查询数据库的操作和上面类似,只需要在`cursor.execute`, `TaosQuery.execute`等函数后面加上`_a`。 + +```javascript +var promise1 = cursor + .query("select count(*), avg(v1), avg(v2) from meter1;") + .execute_a(); +var promise2 = cursor + .query("select count(*), avg(v1), avg(v2) from meter2;") + .execute_a(); +promise1.then(function (result) { + result.pretty(); +}); +promise2.then(function (result) { + result.pretty(); +}); +``` + +### 示例 + +[node-example.js](https://github.com/taosdata/TDengine/blob/master/examples/nodejs/node-example.js)提供了一个使用 NodeJS 连接器建表,插入天气数据并查询插入的数据的代码示例。 + +[node-example-raw.js](https://github.com/taosdata/tests/tree/master/examples/nodejs/node-example-raw.js)同样是一个使用 NodeJS 连接器建表,插入天气数据并查询插入的数据的代码示例,但和上面不同的是,该示例只使用`cursor`。 + +[所有示例代码](https://github.com/taosdata/TDengine/tree/develop/src/connector/nodejs/examples) diff --git a/docs-cn/14-reference/03-connector/python.mdx b/docs-cn/14-reference/03-connector/python.mdx new file mode 100644 index 0000000000000000000000000000000000000000..9baf9e0edf6f57a24a728ba88ac2a18e187aef46 --- /dev/null +++ b/docs-cn/14-reference/03-connector/python.mdx @@ -0,0 +1,283 @@ +--- +sidebar_position: 3 +--- + +# Python Connector + +Python 连接器的使用参见[视频教程](https://www.taosdata.com/blog/2020/11/11/1963.html) + +- **安装**:参见下面具体步骤 +- **示例程序**:位于 install_directory/examples/python + +### 安装 + +Python 连接器支持的系统有:Linux 64/Windows x64 + +安装前准备: + +- 已安装好 TDengine 应用驱动,请参考[安装连接器驱动步骤](/reference/connector/#安装客户端驱动) +- 已安装 python 2.7 or >= 3.4 +- 已安装 pip + +### Python 连接器安装 + +Python 连接器可以通过 `pip` 从 PyPI 下载安装。注意 TDengine Python 连接器的包名为 `taospy` 而不是 `taos`(这是一个与 TDengine 无关的另一个程序)。但为保持向后兼容性,仍然使用 `import taos` 导入。 + +```bash +pip install taospy +``` + +如果不使用系统默认的 `python` 和 `pip`,则需要指定 `pip` 的版本或路径: + +```bash +pip2 install taospy +pip3 install taospy +``` + +Python 命令行依赖 taos 动态库 `libtaos.so` 或 `taos.dll`, 对于 Windows 客户端,安装 TDengine windows 客户端后,如果不能正常 `import taos`,可以将 `C:\TDengine\driver\taos.dll` 拷贝到 `C:\windows\system32` 目录后重新尝试。 + +对于无法联网用户,可以将 TDengine 客户端中的 `connector/python` 路径(Linux 下其安装路径为 `/usr/local/taos/connector/python/`,Windows 下默认安装路径为 `C:\TDengine\connector\python`)添加到 `PYTHONPATH` 环境变量中使用。 + +### 示例程序 + +示例程序源码位于 `/examples/python`,有: + +- **read_example.py** Python 示例源程序 + +用户可以参考`read_example.py`这个程序来设计用户自己的写入、查询程序。 + +在安装了对应的应用驱动后,通过`import taos`引入 taos 类。主要步骤如下: + +- 通过 taos.connect 获取 TaosConnection 对象,这个对象可以一个程序只申请一个,在多线程中共享。 + +- 通过 TaosConnection 对象的 `.cursor()` 方法获取一个新的游标对象,这个游标对象必须保证每个线程独享。 + +- 通过游标对象的 execute()方法,执行写入或查询的 SQL 语句。 + +- 如果执行的是写入语句,execute 返回的是成功写入的行数信息 affected rows。 + +- 如果执行的是查询语句,则 execute 执行成功后,需要通过 fetchall 方法去拉取结果集。 具体方法可以参考示例代码。 + +### 安装验证 + +运行如下指令: + +```bash +cd {install_directory}/examples/python/PYTHONConnectorChecker/` +python3 PythonChecker.py -host +``` + +验证通过将打印出成功信息。 + +### Python 连接器的使用 + +#### PEP-249 兼容 API + +您可以像其他数据库一样,使用类似 [PEP-249](https://www.python.org/dev/peps/pep-0249/) 数据库 API 规范风格的 API: + +```python +import taos + +conn = taos.connect() +cursor = conn.cursor() + +cursor.execute("show databases") +results = cursor.fetchall() +for row in results: + print(row) +``` + +##### 代码示例 + +1. 导入 TDengine 客户端模块 + + ```python + import taos + ``` + +2. 获取连接并获取游标对象 + + ```python + conn = taos.connect(host="127.0.0.1", user="root", password="taosdata", config="/etc/taos") + c1 = conn.cursor() + ``` + + _host_ 是 TDengine 服务端所在 IP, _config_ 为客户端配置文件所在目录。 + +3. 写入数据 + + ```python + import datetime + + # 创建数据库 + c1.execute('create database db') + c1.execute('use db') + # 建表 + c1.execute('create table tb (ts timestamp, temperature int, humidity float)') + # 插入数据 + start_time = datetime.datetime(2019, 11, 1) + affected_rows = c1.execute('insert into tb values (\'%s\', 0, 0.0)' %start_time) + # 批量插入数据 + time_interval = datetime.timedelta(seconds=60) + sqlcmd = ['insert into tb values'] + for irow in range(1,11): + start_time += time_interval + sqlcmd.append('(\'%s\', %d, %f)' %(start_time, irow, irow*1.2)) + affected_rows = c1.execute(' '.join(sqlcmd)) + ``` + +4. 查询数据 + + ```python + c1.execute('select * from tb') + # 拉取查询结果 + data = c1.fetchall() + # 返回的结果是一个列表,每一行构成列表的一个元素 + numOfRows = c1.rowcount + numOfCols = len(c1.description) + for irow in range(numOfRows): + print("Row%d: ts=%s, temperature=%d, humidity=%f" %(irow, data[irow][0], data[irow][1], data[irow][2])) + + # 直接使用cursor 循环拉取查询结果 + c1.execute('select * from tb') + for data in c1: + print("ts=%s, temperature=%d, humidity=%f" %(data[0], data[1], data[2])) + ``` + +#### Query API + +从 v2.1.0 版本开始, 我们提供另外一种方法:`connection.query` 来操作数据库。 + +```python +import taos + +conn = taos.connect() +conn.execute("create database if not exists pytest") + +result = conn.query("show databases") +num_of_fields = result.field_count +for field in result.fields: + print(field) +for row in result: + print(row) +conn.execute("drop database pytest") +``` + +`query` 方法会返回一个 `TaosResult` 对象,并提供了以下属性或方法: + +属性: + +- `fields`: `TaosFields` 集合类,提供返回数据的列信息。 +- `field_count`: 返回数据的列数. +- `affected_rows`: 插入数据的行数. +- `row_count`: 查询数据结果数. +- `precision`: 当前数据库的时间精度. + +方法: + +- `fetch_all()`: 类似于 `cursor.fetchall()` 返回同样的集合数据 +- `fetch_all_into_dict()`: v2.1.1 新添加的 API,将上面的数据转换成字典类型返回 +- `blocks_iter()` `rows_iter()`: 根据底层 API 提供的两种不同迭代器。 +- `fetch_rows_a`: 异步 API +- `errno`: 错误码 +- `errstr`: 错误信息 +- `close`: 关闭结果对象,一般不需要直接调用 + +#### 订阅 API + +1. 创建一个同步订阅队列: + + ```python + # 创建一个主题为 'test' 消费周期为1000毫秒的订阅 + # 第一个参数为 True 表示重新开始订阅,如为 False 且之前创建过主题为 'test' 的订阅, + # 则表示继续消费此订阅的数据,而不是重新开始消费所有数据 + sub = conn.subscribe(True, "test", "select * from tb;", 1000) + ``` + +2. 消费订阅的数据 + + ```python + data = sub.consume() + for d in data: + print(d) + ``` + +3. 取消订阅 + + ```python + sub.close() + ``` + +4. 关闭连接 + + ```python + conn.close() + ``` + +#### JSON 类型 + +从 `taospy` `v2.2.0` 开始,Python 连接器开始支持 JSON 数据类型的标签(TDengine 版本要求 Beta 版 2.3.5+, 稳定版 2.4.0+)。 + +创建一个使用 JSON 类型标签的超级表及其子表: + +```python +# encoding:UTF-8 +import taos + +conn = taos.connect() +conn.execute("create database if not exists py_test_json_type") +conn.execute("use py_test_json_type") + +conn.execute("create stable s1 (ts timestamp, v1 int) tags (info json)") +conn.execute("create table s1_1 using s1 tags ('{\"k1\": \"v1\"}')") +``` + +查询子表标签及表名: + +```python +tags = conn.query("select info, tbname from s1").fetch_all_into_dict() +tags +``` + +`tags` 内容为: + +```python +[{'info': '{"k1":"v1"}', 'tbname': 's1_1'}] +``` + +获取 JSON 中某值: + +```python +k1 = conn.query("select info->'k1' as k1 from s1").fetch_all_into_dict() +""" +>>> k1 +[{'k1': '"v1"'}] +""" +``` + +更多 JSON 类型的操作方式请参考 [JSON 类型使用说明](https://www.taosdata.com/cn/documentation/taos-sql)。 + +#### 关于纳秒 (nanosecond) 在 Python 连接器中的说明 + +由于目前 Python 对 nanosecond 支持的不完善(参见链接 1. 2. ),目前的实现方式是在 nanosecond 精度时返回整数,而不是 ms 和 us 返回的 datetime 类型,应用开发者需要自行处理,建议使用 pandas 的 to_datetime()。未来如果 Python 正式完整支持了纳秒,涛思数据可能会修改相关接口。 + +1. https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds +2. https://www.python.org/dev/peps/pep-0564/ + +#### 帮助信息 + +用户可通过 python 的帮助信息直接查看模块的使用信息,或者参考 tests/examples/python 中的示例程序。以下为部分常用类和方法: + +- _TaosConnection_ 类 + + 参考 python 中 help(taos.TaosConnection)。 + 这个类对应客户端和 TDengine 建立的一个连接。在客户端多线程的场景下,推荐每个线程申请一个独立的连接实例,而不建议多线程共享一个连接。 + +- _TaosCursor_ 类 + + 参考 python 中 help(taos.TaosCursor)。 + 这个类对应客户端进行的写入、查询操作。在客户端多线程的场景下,这个游标实例必须保持线程独享,不能跨线程共享使用,否则会导致返回结果出现错误。 + +- _connect_ 方法 + + 用于生成 taos.TaosConnection 的实例。 diff --git a/docs-cn/14-reference/03-connector/rust.mdx b/docs-cn/14-reference/03-connector/rust.mdx new file mode 100644 index 0000000000000000000000000000000000000000..ab09f605e82af55ee893951aefae817cf5c423db --- /dev/null +++ b/docs-cn/14-reference/03-connector/rust.mdx @@ -0,0 +1,114 @@ +# Rust Connector + +![Crates.io](https://img.shields.io/crates/v/libtaos) ![Crates.io](https://img.shields.io/crates/d/libtaos) + +> Rust 连接器仍然在快速开发中,版本 API 变动在所难免,在 1.0 之前无法保证其向后兼容,请使用时注意版本及对应的文档。 + +感谢 [@songtianyi](https://github.com/songtianyi) 对 [libtdengine](https://github.com/songtianyi/tdengine-rust-bindings) 的贡献,使 Rust 社区能够使用 Rust 连接[TDengine]. [libtaos-rs] 项目旨在为 Rust 开发者提供官方支持,使用 taosc 接口及 HTTP 接口构建兼容 API 以便于用户切换接口方式。 + +## 依赖 + +- [Rust](https://www.rust-lang.org/learn/get-started) + +默认情况下,[libtaos-rs] 使用 C 接口连接数据库,所以您需要: + +- [TDengine 客户端](https://www.taosdata.com/cn/getting-started/#%E9%80%9A%E8%BF%87%E5%AE%89%E8%A3%85%E5%8C%85%E5%AE%89%E8%A3%85) +- `clang`: `bindgen` 使用 `libclangAST` 来生成对应的 Rust 绑定。 + +## 特性列表 + +- [x] C 接口的 Rust 绑定 +- [x] 使用 `rest` feature 来启用 RESTful API. +- [x] [r2d2] 连接池支持(feature `r2d2`) +- [ ] 迭代器接口 +- [ ] 流式计算接口 +- [ ] 订阅支持 + +## 构建和测试 + +```sh +cargo build +cargo test +``` + +测试使用默认用户名密码和本地连接。您可以根据具体情况设置环境变量: + +- `TEST_TAOS_IP` +- `TEST_TAOS_PORT` +- `TEST_TAOS_USER` +- `TEST_TAOS_PASS` +- `TEST_TAOS_DB` + +## 使用 + +使用默认的 taosc 连接方式,可以在 `Cargo.toml` 中直接添加 `libtaos` 依赖: + +```toml +[dependencies] +libtaos = "v0.3.8" +``` + +添加 feature `r2d2` 来启动连接池: + +```toml +[dependencies] +libtaos = { version = "*", features = ["r2d2"] } +``` + +对于 RESTful 接口,可使用 `rest` 特性来替代 taosc,免去安装 TDengine 客户端。 + +```toml +[dependencies] +libtaos = { version = "*", features = ["rest"] } +``` + +本项目中提供一个 [示例程序](https://github.com/taosdata/libtaos-rs/blob/main/examples/demo.rs) 如下: + +```rust +// ... +#[tokio::main] +async fn main() -> Result<(), Error> { + init(); + let taos = taos_connect()?; + + assert_eq!( + taos.query("drop database if exists demo").await.is_ok(), + true + ); + assert_eq!(taos.query("create database demo").await.is_ok(), true); + assert_eq!(taos.query("use demo").await.is_ok(), true); + assert_eq!( + taos.query("create table m1 (ts timestamp, speed int)") + .await + .is_ok(), + true + ); + + for i in 0..10i32 { + assert_eq!( + taos.query(format!("insert into m1 values (now+{}s, {})", i, i).as_str()) + .await + .is_ok(), + true + ); + } + let rows = taos.query("select * from m1").await?; + + println!("{}", rows.column_meta.into_iter().map(|col| col.name).join(",")); + for row in rows.rows { + println!("{}", row.into_iter().join(",")); + } + Ok(()) +} +``` + +您可以在 [bailongma-rs] - 一个 Rust 编写的 Prometheus 远程存储 API 适配器 - 看到如何在具体应用中使用 Rust 连接器。 + +## API 参考 + +[API 参考手册](https://docs.rs/libtaos/latest/libtaos/) + +[libtaos-rs]: https://github.com/taosdata/libtaos-rs +[tdengine]: https://github.com/taosdata/TDengine +[bailongma-rs]: https://github.com/taosdata/bailongma-rs +[r2d2]: https://crates.io/crates/r2d2 diff --git a/docs-cn/14-reference/05-support-platform/05-support-platform.md b/docs-cn/14-reference/05-support-platform/05-support-platform.md new file mode 100644 index 0000000000000000000000000000000000000000..35fb659b08c6fb9426d76cbb0d854e39a82f226d --- /dev/null +++ b/docs-cn/14-reference/05-support-platform/05-support-platform.md @@ -0,0 +1,37 @@ +# 支持平台列表 + +## TDengine 服务端支持的平台列表 + +| | **CentOS 7/8** | **Ubuntu 16/18/20** | **Other Linux** | **统信 UOS** | **银河/中标麒麟** | **凝思 V60/V80** | **华为 EulerOS** | +| ------------ | -------------- | ------------------- | --------------- | ------------ | ----------------- | ---------------- | ---------------- | +| X64 | ● | ● | | ○ | ● | ● | ● | +| 龙芯 MIPS64 | | | ● | | | | | +| 鲲鹏 ARM64 | | ○ | ○ | | ● | | | +| 申威 Alpha64 | | | ○ | ● | | | | +| 飞腾 ARM64 | | ○ 优麒麟 | | | | | | +| 海光 X64 | ● | ● | ● | ○ | ● | ● | | +| 瑞芯微 ARM64 | | | ○ | | | | | +| 全志 ARM64 | | | ○ | | | | | +| 炬力 ARM64 | | | ○ | | | | | +| 华为云 ARM64 | | | | | | | ● | + +注: ● 表示经过官方测试验证, ○ 表示非官方测试验证。 + +## TDengine 客户端和连接器支持的平台列表 + +目前 TDengine 的连接器可支持的平台广泛,目前包括:X64/X86/ARM64/ARM32/MIPS/Alpha 等硬件平台,以及 Linux/Win64/Win32 等开发环境。 + +对照矩阵如下: + +| **CPU** | **X64 64bit** | | | **X86 32bit** | **ARM64** | **ARM32** | **MIPS 龙芯** | **Alpha 申威** | **X64 海光** | +| ----------- | ------------- | --------- | --------- | ------------- | --------- | --------- | ------------- | -------------- | ------------ | +| **OS** | **Linux** | **Win64** | **Win32** | **Win32** | **Linux** | **Linux** | **Linux** | **Linux** | **Linux** | +| **C/C++** | ● | ● | ● | ○ | ● | ● | ● | ● | ● | +| **JDBC** | ● | ● | ● | ○ | ● | ● | ● | ● | ● | +| **Python** | ● | ● | ● | ○ | ● | ● | ● | -- | ● | +| **Go** | ● | ● | ● | ○ | ● | ● | ○ | -- | -- | +| **NodeJs** | ● | ● | ○ | ○ | ● | ● | ○ | -- | -- | +| **C#** | ● | ● | ○ | ○ | ○ | ○ | ○ | -- | -- | +| **RESTful** | ● | ● | ● | ● | ● | ● | ● | ● | ● | + +注:● 表示官方测试验证通过,○ 表示非官方测试验证通过,-- 表示未经验证。 diff --git a/docs-cn/14-reference/05-support-platform/_category_.yml b/docs-cn/14-reference/05-support-platform/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..ce2aa5213b1e85bbd07b7242d8bb1c1525e5c687 --- /dev/null +++ b/docs-cn/14-reference/05-support-platform/_category_.yml @@ -0,0 +1 @@ +label: 支持平台列表 diff --git a/docs-cn/14-reference/06-keywords/06-keywords.md b/docs-cn/14-reference/06-keywords/06-keywords.md new file mode 100644 index 0000000000000000000000000000000000000000..e43d09e8123b46b51c04c2359d1f43e17d569c4c --- /dev/null +++ b/docs-cn/14-reference/06-keywords/06-keywords.md @@ -0,0 +1,87 @@ +--- +sidebar_label: 参数限制与保留关键字 +--- +# TDengine 参数限制与保留关键字 + +## 名称命名规则 + +1. 合法字符:英文字符、数字和下划线 +2. 允许英文字符或下划线开头,不允许以数字开头 +3. 不区分大小写 +4. 转义后表(列)名规则: + 为了兼容支持更多形式的表(列)名,TDengine 引入新的转义符 "`"。可用让表名与关键词不冲突,同时不受限于上述表名称合法性约束检查。 + 转义后的表(列)名同样受到长度限制要求,且长度计算的时候不计算转义符。使用转义字符以后,不再对转义字符中的内容进行大小写统一。 + + 例如:\`aBc\` 和 \`abc\` 是不同的表(列)名,但是 abc 和 aBc 是相同的表(列)名。 + 需要注意的是转义字符中的内容必须是可打印字符。 + 支持转义符的功能从 2.3.0.1 版本开始。 + +## 密码合法字符集 + +`[a-zA-Z0-9!?$%^&*()_–+={[}]:;@~#|<,>.?/]` + +去掉了 `` ‘“`\ `` (单双引号、撇号、反斜杠、空格) + +- 数据库名:不能包含“.”以及特殊字符,不能超过 32 个字符 +- 表名:不能包含“.”以及特殊字符,与所属数据库名一起,不能超过 192 个字符,每行数据最大长度 16k 个字符 +- 表的列名:不能包含特殊字符,不能超过 64 个字符 +- 数据库名、表名、列名,都不能以数字开头,合法的可用字符集是“英文字符、数字和下划线” +- 表的列数:不能超过 1024 列,最少需要 2 列,第一列必须是时间戳(从 2.1.7.0 版本开始,改为最多支持 4096 列) +- 记录的最大长度:包括时间戳 8 byte,不能超过 16KB(每个 BINARY/NCHAR 类型的列还会额外占用 2 个 byte 的存储位置) +- 单条 SQL 语句默认最大字符串长度:1048576 byte,但可通过系统配置参数 maxSQLLength 修改,取值范围 65480 ~ 1048576 byte +- 数据库副本数:不能超过 3 +- 用户名:不能超过 23 个 byte +- 用户密码:不能超过 15 个 byte +- 标签(Tags)数量:不能超过 128 个,可以 0 个 +- 标签的总长度:不能超过 16K byte +- 记录条数:仅受存储空间限制 +- 表的个数:仅受节点个数限制 +- 库的个数:仅受节点个数限制 +- 单个库上虚拟节点个数:不能超过 64 个 +- 库的数目,超级表的数目、表的数目,系统不做限制,仅受系统资源限制 +- SELECT 语句的查询结果,最多允许返回 1024 列(语句中的函数调用可能也会占用一些列空间),超限时需要显式指定较少的返回数据列,以避免语句执行报错。(从 2.1.7.0 版本开始,改为最多允许 4096 列) + +## 保留关键字 + +目前 TDengine 有将近 200 个内部保留关键字,这些关键字无论大小写均不可以用作库名、表名、STable 名、数据列名及标签列名等。这些关键字列表如下: + +| 关键字列表 | | | | | +| ----------- | ---------- | --------- | ---------- | ------------ | +| ABORT | CREATE | IGNORE | NULL | STAR | +| ACCOUNT | CTIME | IMMEDIATE | OF | STATE | +| ACCOUNTS | DATABASE | IMPORT | OFFSET | STATEMENT | +| ADD | DATABASES | IN | OR | STATE_WINDOW | +| AFTER | DAYS | INITIALLY | ORDER | STORAGE | +| ALL | DBS | INSERT | PARTITIONS | STREAM | +| ALTER | DEFERRED | INSTEAD | PASS | STREAMS | +| AND | DELIMITERS | INT | PLUS | STRING | +| AS | DESC | INTEGER | PPS | SYNCDB | +| ASC | DESCRIBE | INTERVAL | PRECISION | TABLE | +| ATTACH | DETACH | INTO | PREV | TABLES | +| BEFORE | DISTINCT | IS | PRIVILEGE | TAG | +| BEGIN | DIVIDE | ISNULL | QTIME | TAGS | +| BETWEEN | DNODE | JOIN | QUERIES | TBNAME | +| BIGINT | DNODES | KEEP | QUERY | TIMES | +| BINARY | DOT | KEY | QUORUM | TIMESTAMP | +| BITAND | DOUBLE | KILL | RAISE | TINYINT | +| BITNOT | DROP | LE | REM | TOPIC | +| BITOR | EACH | LIKE | REPLACE | TOPICS | +| BLOCKS | END | LIMIT | REPLICA | TRIGGER | +| BOOL | EQ | LINEAR | RESET | TSERIES | +| BY | EXISTS | LOCAL | RESTRICT | UMINUS | +| CACHE | EXPLAIN | LP | ROW | UNION | +| CACHELAST | FAIL | LSHIFT | RP | UNSIGNED | +| CASCADE | FILE | LT | RSHIFT | UPDATE | +| CHANGE | FILL | MATCH | SCORES | UPLUS | +| CLUSTER | FLOAT | MAXROWS | SELECT | USE | +| COLON | FOR | MINROWS | SEMI | USER | +| COLUMN | FROM | MINUS | SESSION | USERS | +| COMMA | FSYNC | MNODES | SET | USING | +| COMP | GE | MODIFY | SHOW | VALUES | +| COMPACT | GLOB | MODULES | SLASH | VARIABLE | +| CONCAT | GRANTS | NCHAR | SLIDING | VARIABLES | +| CONFLICT | GROUP | NE | SLIMIT | VGROUPS | +| CONNECTION | GT | NONE | SMALLINT | VIEW | +| CONNECTIONS | HAVING | NOT | SOFFSET | VNODES | +| CONNS | ID | NOTNULL | STABLE | WAL | +| COPY | IF | NOW | STABLES | WHERE | diff --git a/docs-cn/14-reference/06-keywords/_category_.yml b/docs-cn/14-reference/06-keywords/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..67738650a4564477f017542aea81767b3de72922 --- /dev/null +++ b/docs-cn/14-reference/06-keywords/_category_.yml @@ -0,0 +1 @@ +label: 参数限制与保留关键字 \ No newline at end of file diff --git a/docs-cn/14-reference/07-docker/07-docker.md b/docs-cn/14-reference/07-docker/07-docker.md new file mode 100644 index 0000000000000000000000000000000000000000..3efcd0bace13c0b391f06a312e0affb7991610bd --- /dev/null +++ b/docs-cn/14-reference/07-docker/07-docker.md @@ -0,0 +1,513 @@ +# 用 Docker 部署 TDengine + +本章主要介绍如何在容器中启动 TDengine 服务并访问它。 +注意:可以在 docker run 命令行中或者 docker-compose 文件中使用环境变量来控制容器中服务的行为。 + +## 启动 TDengine + +TDengine 镜像启动时默认激活 HTTP 服务,使用下列命令 + +```shell +docker run -d --name tdengine -p 6041:6041 tdengine/tdengine +``` + +以上命令启动了一个名为“tdengine”的容器,并把其中的 HTTP 服务的端 6041 映射到了主机端口 6041。使用如下命令可以验证该容器中提供的 HTTP 服务是否可用: + +```shell +curl -u root:taosdata -d "show databases" localhost:6041/rest/sql +``` + +使用如下命令可以在该容器中执行 TDengine 的客户端 taos 对 TDengine 进行访问: + +```shell +$ docker exec -it tdengine taos + +Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 +Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. + +taos> show databases; + name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | +==================================================================================================================================================================================================================================================================================== + log | 2022-01-17 13:57:22.270 | 10 | 1 | 1 | 1 | 10 | 30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | 0 | us | 0 | ready | +Query OK, 1 row(s) in set (0.002843s) +``` + +因为运行在容器中的 TDengine 服务端使用容器的 hostname 建立连接,使用 taos shell 或者各种连接器(例如 JDBC-JNI)从容器外访问容器内的 TDengine 比较复杂,所以上述方式是访问容器中 TDengine 服务的最简单的方法,适用于一些简单场景。如果在一些复杂场景下想要从容器化使用 taos shell 或者各种连接器访问容器中的 TDengine 服务,请参考下一节。 + +## 在 host 网络上启动 TDengine + +```shell +docker run -d --name tdengine --network host tdengine/tdengine +``` + +上面的命令在 host 网络上启动 TDengine,并使用主机的 FQDN 建立连接而不是使用容器的 hostname 。这种方式和在主机上使用 `systemctl` 启动 TDengine 效果相同。在主机已安装 TDengine 客户端情况下,可以直接使用下面的命令访问它。 + +```shell +$ taos + +Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 +Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. + +taos> show dnodes; + id | end_point | vnodes | cores | status | role | create_time | offline reason | +====================================================================================================================================== + 1 | myhost:6030 | 1 | 8 | ready | any | 2022-01-17 22:10:32.619 | | +Query OK, 1 row(s) in set (0.003233s) +``` + +## 以指定的 hostname 和 port 启动 TDengine + +利用 `TAOS_FQDN` 环境变量或者 `taos.cfg` 中的 `fqdn` 配置项可以使 TDengine 在指定的 hostname 上建立连接。这种方式可以为部署提供更大的灵活性。 + +```shell +docker run -d \ + --name tdengine \ + -e TAOS_FQDN=tdengine \ + -p 6030-6049:6030-6049 \ + -p 6030-6049:6030-6049/udp \ + tdengine/tdengine +``` + +上面的命令在容器中启动一个 TDengine 服务,其所监听的 hostname 为 tdengine ,并将容器的 6030 到 6049 端口段映射到主机的 6030 到 6049 端口段 (tcp 和 udp 都需要映射)。如果主机上该端口段已经被占用,可以修改上述命令指定一个主机上空闲的端口段。如果 `rpcForceTcp` 被设置为 `1` ,可以只映射 tcp 协议。 + +接下来,要确保 "tdengine" 这个 hostname 在 `/etc/hosts` 中可解析。 + +```shell +echo 127.0.0.1 tdengine |sudo tee -a /etc/hosts +``` + +最后,可以从 taos shell 或者任意连接器以 "tdengine" 为服务端地址访问 TDengine 服务。 + +```shell +taos -h tdengine -P 6030 +``` + +如果 `TAOS_FQDN` 被设置为与所在主机名相同,则效果与 “在 host 网络上启动 TDengine” 相同。 + +## 在指定网络上启动 TDengine + +也可以在指定的特定网络上启动 TDengine。下面是详细步骤: + +1. 首先,创建一个 docker 网络,命名为 td-net + + ```shell + docker network create td-net + ``` + +2. 启动 TDengine + + 以下命令在 td-net 网络上启动 TDengine 服务 + + ```shell + docker run -d --name tdengine --network td-net \ + -e TAOS_FQDN=tdengine \ + tdengine/tdengine + ``` + +3. 在同一网络上的另一容器中启动 TDengine 客户端 + + ```shell + docker run --rm -it --network td-net -e TAOS_FIRST_EP=tdengine tdengine/tdengine taos + # or + #docker run --rm -it --network td-net -e tdengine/tdengine taos -h tdengine + ``` + +## 在容器中启动客户端应用 + +如果想在容器中启动自己的应用的话,需要将相应的对 TDengine 的依赖也要加入到镜像中,例如: + +```docker +FROM ubuntu:20.04 +RUN apt-get update && apt-get install -y wget +ENV TDENGINE_VERSION=2.4.0.0 +RUN wget -c https://www.taosdata.com/assets-download/TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ + && tar xvf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ + && cd TDengine-client-${TDENGINE_VERSION} \ + && ./install_client.sh \ + && cd ../ \ + && rm -rf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz TDengine-client-${TDENGINE_VERSION} +## add your application next, eg. go, build it in builder stage, copy the binary to the runtime +#COPY --from=builder /path/to/build/app /usr/bin/ +#CMD ["app"] +``` + +以下是一个 go 应用程序的示例: + +```go +/* + * In this test program, we'll create a database and insert 4 records then select out. + */ +package main + +import ( + "database/sql" + "flag" + "fmt" + "time" + + _ "github.com/taosdata/driver-go/v2/taosSql" +) + +type config struct { + hostName string + serverPort string + user string + password string +} + +var configPara config +var taosDriverName = "taosSql" +var url string + +func init() { + flag.StringVar(&configPara.hostName, "h", "", "The host to connect to TDengine server.") + flag.StringVar(&configPara.serverPort, "p", "", "The TCP/IP port number to use for the connection to TDengine server.") + flag.StringVar(&configPara.user, "u", "root", "The TDengine user name to use when connecting to the server.") + flag.StringVar(&configPara.password, "P", "taosdata", "The password to use when connecting to the server.") + flag.Parse() +} + +func printAllArgs() { + fmt.Printf("============= args parse result: =============\n") + fmt.Printf("hostName: %v\n", configPara.hostName) + fmt.Printf("serverPort: %v\n", configPara.serverPort) + fmt.Printf("usr: %v\n", configPara.user) + fmt.Printf("password: %v\n", configPara.password) + fmt.Printf("================================================\n") +} + +func main() { + printAllArgs() + + url = "root:taosdata@/tcp(" + configPara.hostName + ":" + configPara.serverPort + ")/" + + taos, err := sql.Open(taosDriverName, url) + checkErr(err, "open database error") + defer taos.Close() + + taos.Exec("create database if not exists test") + taos.Exec("use test") + taos.Exec("create table if not exists tb1 (ts timestamp, a int)") + _, err = taos.Exec("insert into tb1 values(now, 0)(now+1s,1)(now+2s,2)(now+3s,3)") + checkErr(err, "failed to insert") + rows, err := taos.Query("select * from tb1") + checkErr(err, "failed to select") + + defer rows.Close() + for rows.Next() { + var r struct { + ts time.Time + a int + } + err := rows.Scan(&r.ts, &r.a) + if err != nil { + fmt.Println("scan error:\n", err) + return + } + fmt.Println(r.ts, r.a) + } +} + +func checkErr(err error, prompt string) { + if err != nil { + fmt.Println("ERROR: %s\n", prompt) + panic(err) + } +} +``` + +如下是完整版本的 dockerfile + +```docker +FROM golang:1.17.6-buster as builder +ENV TDENGINE_VERSION=2.4.0.0 +RUN wget -c https://www.taosdata.com/assets-download/TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ + && tar xvf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ + && cd TDengine-client-${TDENGINE_VERSION} \ + && ./install_client.sh \ + && cd ../ \ + && rm -rf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz TDengine-client-${TDENGINE_VERSION} +WORKDIR /usr/src/app/ +ENV GOPROXY="https://goproxy.io,direct" +COPY ./main.go ./go.mod ./go.sum /usr/src/app/ +RUN go env +RUN go mod tidy +RUN go build + +FROM ubuntu:20.04 +RUN apt-get update && apt-get install -y wget +ENV TDENGINE_VERSION=2.4.0.0 +RUN wget -c https://www.taosdata.com/assets-download/TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ + && tar xvf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz \ + && cd TDengine-client-${TDENGINE_VERSION} \ + && ./install_client.sh \ + && cd ../ \ + && rm -rf TDengine-client-${TDENGINE_VERSION}-Linux-x64.tar.gz TDengine-client-${TDENGINE_VERSION} + +## add your application next, eg. go, build it in builder stage, copy the binary to the runtime +COPY --from=builder /usr/src/app/app /usr/bin/ +CMD ["app"] +``` + +目前我们已经有了 `main.go`, `go.mod`, `go.sum`, `app.dockerfile`, 现在可以构建出这个应用程序并在 `td-net` 网络上启动它 + +```shell +$ docker build -t app -f app.dockerfile +$ docker run --rm --network td-net app -h tdengine -p 6030 +============= args parse result: ============= +hostName: tdengine +serverPort: 6030 +usr: root +password: taosdata +================================================ +2022-01-17 15:56:55.48 +0000 UTC 0 +2022-01-17 15:56:56.48 +0000 UTC 1 +2022-01-17 15:56:57.48 +0000 UTC 2 +2022-01-17 15:56:58.48 +0000 UTC 3 +2022-01-17 15:58:01.842 +0000 UTC 0 +2022-01-17 15:58:02.842 +0000 UTC 1 +2022-01-17 15:58:03.842 +0000 UTC 2 +2022-01-17 15:58:04.842 +0000 UTC 3 +2022-01-18 01:43:48.029 +0000 UTC 0 +2022-01-18 01:43:49.029 +0000 UTC 1 +2022-01-18 01:43:50.029 +0000 UTC 2 +2022-01-18 01:43:51.029 +0000 UTC 3 +``` + +## 用 docker-compose 启动 TDengine 集群 + +1. 如下 docker-compose 文件启动一个 2 副本、2 管理节点、2 数据节点以及 1 个 arbitrator 的 TDengine 集群。 + + ```docker + version: "3" + services: + arbitrator: + image: tdengine/tdengine:$VERSION + command: tarbitrator + td-1: + image: tdengine/tdengine:$VERSION + environment: + TAOS_FQDN: "td-1" + TAOS_FIRST_EP: "td-1" + TAOS_NUM_OF_MNODES: "2" + TAOS_REPLICA: "2" + TAOS_ARBITRATOR: arbitrator:6042 + volumes: + - taosdata-td1:/var/lib/taos/ + - taoslog-td1:/var/log/taos/ + td-2: + image: tdengine/tdengine:$VERSION + environment: + TAOS_FQDN: "td-2" + TAOS_FIRST_EP: "td-1" + TAOS_NUM_OF_MNODES: "2" + TAOS_REPLICA: "2" + TAOS_ARBITRATOR: arbitrator:6042 + volumes: + - taosdata-td2:/var/lib/taos/ + - taoslog-td2:/var/log/taos/ + volumes: + taosdata-td1: + taoslog-td1: + taosdata-td2: + taoslog-td2: + ``` + + :::note + - `VERSION` 环境变量被用来设置 tdengine image tag + - 在新创建的实例上必须设置 `TAOS_FIRST_EP` 以使其能够加入 TDengine 集群;如果有高可用需求,则需要同时使用 `TAOS_SECOND_EP` + - `TAOS_REPLICA` 用来设置缺省的数据库副本数量,其取值范围为[1,3] + 在双副本环境下,推荐使用 arbitrator, 用 TAOS_ARBITRATOR 来设置 + ::: + + +2. 启动集群 + + ```shell + $ VERSION=2.4.0.0 docker-compose up -d + Creating network "test_default" with the default driver + Creating volume "test_taosdata-td1" with default driver + Creating volume "test_taoslog-td1" with default driver + Creating volume "test_taosdata-td2" with default driver + Creating volume "test_taoslog-td2" with default driver + Creating test_td-1_1 ... done + Creating test_arbitrator_1 ... done + Creating test_td-2_1 ... done + ``` + +3. 查看节点状态 + + ```shell + $ docker-compose ps + Name Command State Ports + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + test_arbitrator_1 /usr/bin/entrypoint.sh tar ... Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp + test_td-1_1 /usr/bin/entrypoint.sh taosd Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp + test_td-2_1 /usr/bin/entrypoint.sh taosd Up 6030/tcp, 6031/tcp, 6032/tcp, 6033/tcp, 6034/tcp, 6035/tcp, 6036/tcp, 6037/tcp, 6038/tcp, 6039/tcp, 6040/tcp, 6041/tcp, 6042/tcp + ``` + +4. 用 taos shell 查看 dnodes + + ```shell + $ docker-compose exec td-1 taos -s "show dnodes" + + Welcome to the TDengine shell from Linux, Client Version:2.4.0.0 + Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. + + taos> show dnodes + id | end_point | vnodes | cores | status | role | create_time | offline reason | + ====================================================================================================================================== + 1 | td-1:6030 | 1 | 8 | ready | any | 2022-01-18 02:47:42.871 | | + 2 | td-2:6030 | 0 | 8 | ready | any | 2022-01-18 02:47:43.518 | | + 0 | arbitrator:6042 | 0 | 0 | ready | arb | 2022-01-18 02:47:43.633 | - | + Query OK, 3 row(s) in set (0.000811s) + ``` + +## taosAdapter + +1. taosAdapter 在 TDengine 容器中默认是启动的。如果想要禁用它,在启动时指定环境变量 `TAOS_DISABLE_ADAPTER=true` + +2. 同时为了部署灵活起见,可以在独立的容器中启动 taosAdapter + + ```docker + services: + # ... + adapter: + image: tdengine/tdengine:$VERSION + command: taosadapter + ``` + + 如果要部署多个 taosAdapter 来提高吞吐量并提供高可用性,推荐配置方式为使用 nginx 等反向代理来提供统一的访问入口。具体配置方法请参考 nginx 的官方文档。如下是示例: + + ```docker + ersion: "3" + + networks: + inter: + api: + + services: + arbitrator: + image: tdengine/tdengine:$VERSION + command: tarbitrator + networks: + - inter + td-1: + image: tdengine/tdengine:$VERSION + networks: + - inter + environment: + TAOS_FQDN: "td-1" + TAOS_FIRST_EP: "td-1" + TAOS_NUM_OF_MNODES: "2" + TAOS_REPLICA: "2" + TAOS_ARBITRATOR: arbitrator:6042 + volumes: + - taosdata-td1:/var/lib/taos/ + - taoslog-td1:/var/log/taos/ + td-2: + image: tdengine/tdengine:$VERSION + networks: + - inter + environment: + TAOS_FQDN: "td-2" + TAOS_FIRST_EP: "td-1" + TAOS_NUM_OF_MNODES: "2" + TAOS_REPLICA: "2" + TAOS_ARBITRATOR: arbitrator:6042 + volumes: + - taosdata-td2:/var/lib/taos/ + - taoslog-td2:/var/log/taos/ + adapter: + image: tdengine/tdengine:$VERSION + command: taosadapter + networks: + - inter + environment: + TAOS_FIRST_EP: "td-1" + TAOS_SECOND_EP: "td-2" + deploy: + replicas: 4 + nginx: + image: nginx + depends_on: + - adapter + networks: + - inter + - api + ports: + - 6041:6041 + - 6044:6044/udp + command: [ + "sh", + "-c", + "while true; + do curl -s http://adapter:6041/-/ping >/dev/null && break; + done; + printf 'server{listen 6041;location /{proxy_pass http://adapter:6041;}}' + > /etc/nginx/conf.d/rest.conf; + printf 'stream{server{listen 6044 udp;proxy_pass adapter:6044;}}' + >> /etc/nginx/nginx.conf;cat /etc/nginx/nginx.conf; + nginx -g 'daemon off;'", + ] + volumes: + taosdata-td1: + taoslog-td1: + taosdata-td2: + taoslog-td2: + ``` + +## 使用 docker swarm 部署 + +如果要想将基于容器的 TDengine 集群部署在多台主机上,可以使用 docker swarm。首先要在这些主机上建立 docke swarm 集群,请参考 docker 官方文档。 + +docker-compose 文件可以参考上节。下面是使用 docker swarm 启动 TDengine 的命令: + +```shell +$ VERSION=2.4.0 docker stack deploy -c docker-compose.yml taos +Creating network taos_inter +Creating network taos_api +Creating service taos_arbitrator +Creating service taos_td-1 +Creating service taos_td-2 +Creating service taos_adapter +Creating service taos_nginx +``` + +查看和管理 + +```shell +$ docker stack ps taos +ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS +79ni8temw59n taos_nginx.1 nginx:latest TM1701 Running Running about a minute ago +3e94u72msiyg taos_adapter.1 tdengine/tdengine:2.4.0 TM1702 Running Running 56 seconds ago +100amjkwzsc6 taos_td-2.1 tdengine/tdengine:2.4.0 TM1703 Running Running about a minute ago +pkjehr2vvaaa taos_td-1.1 tdengine/tdengine:2.4.0 TM1704 Running Running 2 minutes ago +tpzvgpsr1qkt taos_arbitrator.1 tdengine/tdengine:2.4.0 TM1705 Running Running 2 minutes ago +rvss3g5yg6fa taos_adapter.2 tdengine/tdengine:2.4.0 TM1706 Running Running 56 seconds ago +i2augxamfllf taos_adapter.3 tdengine/tdengine:2.4.0 TM1707 Running Running 56 seconds ago +lmjyhzccpvpg taos_adapter.4 tdengine/tdengine:2.4.0 TM1708 Running Running 56 seconds ago +$ docker service ls +ID NAME MODE REPLICAS IMAGE PORTS +561t4lu6nfw6 taos_adapter replicated 4/4 tdengine/tdengine:2.4.0 +3hk5ct3q90sm taos_arbitrator replicated 1/1 tdengine/tdengine:2.4.0 +d8qr52envqzu taos_nginx replicated 1/1 nginx:latest *:6041->6041/tcp, *:6044->6044/udp +2isssfvjk747 taos_td-1 replicated 1/1 tdengine/tdengine:2.4.0 +9pzw7u02ichv taos_td-2 replicated 1/1 tdengine/tdengine:2.4.0 +``` + +从上面的输出可以看到有两个 dnode, 和两个 taosAdapter,以及一个 nginx 反向代理服务。 + +接下来,我们可以减少 taosAdapter 服务的数量 + +```shell +$ docker service scale taos_adapter=1 +taos_adapter scaled to 1 +overall progress: 1 out of 1 tasks +1/1: running [==================================================>] +verify: Service converged + +$ docker service ls -f name=taos_adapter +ID NAME MODE REPLICAS IMAGE PORTS +561t4lu6nfw6 taos_adapter replicated 1/1 tdengine/tdengine:2.4.0 +``` diff --git a/docs-cn/14-reference/07-docker/_category_.yml b/docs-cn/14-reference/07-docker/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..68c16927f4a9098311dec116aab41e8faa07fe81 --- /dev/null +++ b/docs-cn/14-reference/07-docker/_category_.yml @@ -0,0 +1 @@ +label: TDengine Docker 镜像 \ No newline at end of file diff --git a/docs-cn/14-reference/08-server-config/08-server-config.md b/docs-cn/14-reference/08-server-config/08-server-config.md new file mode 100644 index 0000000000000000000000000000000000000000..844aa21c4378e892e1379e28b5501f8eaceb4750 --- /dev/null +++ b/docs-cn/14-reference/08-server-config/08-server-config.md @@ -0,0 +1,1094 @@ +# 服务端配置 + +TDengine 系统后台服务由 taosd 提供,可以在配置文件 taos.cfg 里修改配置参数,以满足不同场景的需求。配置文件的缺省位置在/etc/taos 目录,可以通过 taosd 命令行执行参数 -c 指定配置文件目录。比如,指定配置文件位于`/home/user` 这个目录: + +``` +taosd -c /home/user +``` + +另外可以使用 `-C` 显示当前服务器配置参数: + +``` +taosd -C +``` + +下面仅仅列出一些重要的配置参数,更多的参数请看配置文件里的说明。而且这些参数的缺省配置都是可以工作的,一般无需设置。 + +:::note +配置文件参数修改后,需要重启*taosd*服务,或客户端应用才能生效。 + +::: + +## 首要参数 + +### firstEP + +| 属性 | 说明 | +| -------- | ----------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | taosd 启动时,主动连接的集群中首个 dnode 的 end point | +| 缺省值 | localhost:6030 | + +### fqdn + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 数据节点的 FQDN。如果习惯 IP 地址访问,可设置为该节点的 IP 地址。 | +| 缺省值 | 缺省为操作系统配置的第一个 hostname。 | +| 补充说明 | 这个参数值的长度需要控制在 96 个字符以内。 | + +### serverPort + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | taosd 启动后,对外服务的端口号 | +| 缺省值 | 6030 | +| 补充说明 | RESTful 服务使用的端口号是在此基础上+11,即默认值为 6041(注意 2.4 及后续版本使用 taosAdapter 提供 RESTful 接口)。 | + +:::note +对于端口,TDengine 会使用从 serverPort 起 13 个连续的 TCP 和 UDP 端口号,请务必在防火墙打开。因此如果是缺省配置,需要打开从 6030 到 6042 共 13 个端口,而且必须 TCP 和 UDP 都打开。(详细的端口情况请参见下表) +::: +| 协议 | 默认端口 | 用途说明 | 修改方法 | +| :--- | :-------- | :---------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | +| TCP | 6030 | 客户端与服务端之间通讯。 | 由配置文件设置 serverPort 决定。 | +| TCP | 6035 | 多节点集群的节点间通讯。 | 随 serverPort 端口变化。 | +| TCP | 6040 | 多节点集群的节点间数据同步。 | 随 serverPort 端口变化。 | +| TCP | 6041 | 客户端与服务端之间的 RESTful 通讯。 | 随 serverPort 端口变化。注意 taosAdapter 配置或有不同,请参考相应[文档](https://www.taosdata.com/cn/documentation/tools/adapter)。 | +| TCP | 6042 | Arbitrator 的服务端口。 | 随 Arbitrator 启动参数设置变化。 | +| TCP | 6043 | TaosKeeper 监控服务端口。 | 随 TaosKeeper 启动参数设置变化。 | +| TCP | 6044 | 支持 StatsD 的数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | +| UDP | 6045 | 支持 collectd 数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | +| TCP | 6060 | 企业版内 Monitor 服务的网络端口。 | | +| UDP | 6030-6034 | 客户端与服务端之间通讯。 | 随 serverPort 端口变化。 | +| UDP | 6035-6039 | 多节点集群的节点间通讯。 | 随 serverPort 端口变化。 + + +### logDir + +| 属性 | 说明 | +| -------- | -------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 日志文件目录,客户端和服务器的运行日志将写入该目录 | +| 缺省值 | /var/log/taos | + +### dataDir + +| 属性 | 说明 | +| -------- | ------------------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 数据文件目录,所有的数据文件都将写入该目录 | +| 缺省值 | /var/lib/taos | + +### arbitrator + +| 属性 | 说明 | +| -------- | ------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 系统中裁决器的 end point | +| 缺省值 | 空 | + +## 开关类 + +### monitor + +| 属性 | 说明 | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 服务器内部的系统监控开关。监控主要负责收集物理节点的负载状况,包括 CPU、内存、硬盘、网络带宽、HTTP 请求量的监控记录,记录信息存储在`LOG`库中。 | +| 取值范围 | 0:关闭监控服务, 1:激活监控服务。 | +| 缺省值 | 0 | + +### vnodeBak + +| 属性 | 说明 | +| -------- | -------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 删除 vnode 时是否备份 vnode 目录 | +| 取值范围 | 0:否,1:是 | +| 缺省值 | 1 | + +### elemetryRePorting + +| 属性 | 说明 | +| -------- | ---------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 是否允许 TDengine 采集和上报基本使用信息 | +| 取值范围 | 0:不允许
1:允许 | +| 缺省值 | 1 | + +### balance + +| 属性 | 说明 | +| -------- | ---------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 是否启动负载均衡 | +| 取值范围 | 0,1 | +| 缺省值 | 1 | + +### stream + +| 属性 | 说明 | +| -------- | ------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 是否启用连续查询(流计算功能) | +| 取值范围 | 0:不允许
1:允许 | +| 缺省值 | 1 | + +### enableCoreFile + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 是否开启服务 crash 时生成 core 文件 | +| 取值范围 | 0:否,1:是 | +| 缺省值 | 1 | +| 补充说明 | 不同的启动方式,生成 core 文件的目录如下:1、systemctl start taosd 启动:生成的 core 在根目录下
2、手动启动,就在 taosd 执行目录下。 | + +## 区域相关 + +### timezone + +| 属性 | 说明 | +| -------- | ------------------------------ | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 时区 | +| 缺省值 | 从系统中动态获取当前的时区设置 | + +### locale + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 系统区位信息及编码格式 | +| 缺省值 | 系统中动态获取,如果自动获取失败,需要用户在配置文件设置或通过 API 设置 | + +### charset + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 字符集编码 | +| 缺省值 | 系统中动态获取,如果自动获取失败,需要用户在配置文件设置或通过 API 设置 | + +## 存储相关 + +### cache + +| 属性 | 说明 | +| -------- | ------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 内存块的大小 | +| 单位 | MB | +| 缺省值 | 16 | + +### blocks + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 每个 vnode(tsdb)中有多少 cache 大小的内存块。因此一个 vnode 的用的内存大小粗略为(cache \* blocks) | +| 缺省值 | 6 | + +### days + +| 属性 | 说明 | +| -------- | -------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 数据文件存储数据的时间跨度 | +| 单位 | 天 | +| 缺省值 | 10 | + +### keep + +| 属性 | 说明 | +| -------- | -------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 数据保留的天数 | +| 单位 | 天 | +| 缺省值 | 3650 | + +### minRows + +| 属性 | 说明 | +| -------- | ---------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 文件块中记录的最小条数 | +| 缺省值 | 100 | + +### maxRows + +| 属性 | 说明 | +| -------- | ---------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 文件块中记录的最大条数 | +| 缺省值 | 4096 | + +### walLevel + +| 属性 | 说明 | +| -------- | --------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | WAL 级别 | +| 取值范围 | 1:写 wal, 但不执行 fsync
2:写 wal, 而且执行 fsync | +| 缺省值 | 1 | + +### fsync + +| 属性 | 说明 | +| -------- | -------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 当 wal 设置为 2 时,执行 fsync 的周期 | +| 单位 | 毫秒 | +| 取值范围 | 最小为 0,表示每次写入,立即执行 fsync
最大为 180000(三分钟) | +| 缺省值 | 3000 | + +### update + +| 属性 | 说明 | +| -------- | ---------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 允许更新已存在的数据行 | +| 取值范围 | 0:不允许更新
1:允许整行更新
2:允许部分列更新。(2.1.7.0 版本开始此参数支持设为 2,在此之前取值只能是 [0, 1]) | +| 缺省值 | 0 | +| 补充说明 | 2.0.8.0 版本之前,不支持此参数。 | + +### cacheLast + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 是否在内存中缓存子表的最近数据 | +| 取值范围 | 0:关闭
1:缓存子表最近一行数据
2:缓存子表每一列的最近的非 NULL 值
3:同时打开缓存最近行和列功能。(2.1.2.0 版本开始此参数支持 0 ~ 3 的取值范围,在此之前取值只能是 [0, 1]) | +| 缺省值 | 0 | +| 补充说明 | 2.1.2.0 版本之前、2.0.20.7 版本之前在 taos.cfg 文件中不支持此参数。 + + +### minimalLogDirGB + +| 属性 | 说明 | +| -------- | -------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 当日志文件夹的磁盘大小小于该值时,停止写日志 | +| 单位 | GB | +| 缺省值 | 0.1 | + +### minimalTmpDirGB + +| 属性 | 说明 | +| -------- | ------------------------------------------------ | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 当日志文件夹的磁盘大小小于该值时,停止写临时文件 | +| 单位 | GB | +| 缺省值 | 0.1 | + +### minimalDataDirGB + +| 属性 | 说明 | +| -------- | ------------------------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 当日志文件夹的磁盘大小小于该值时,停止写时序数据 | +| 单位 | GB | +| 缺省值 | 0.1 | + +## 集群相关 + +### replica + +| 属性 | 说明 | +| -------- | ------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 副本个数 | +| 取值范围 | 1-3 | +| 缺省值 | 1 | + +### quorum + +| 属性 | 说明 | +| -------- | -------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 多副本环境下指令执行的确认数要求 | +| 取值范围 | 1,2 | +| 缺省值 | 1 | + +### role + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | dnode 的可选角色 | +| 取值范围 | 0:any(既可作为 mnode,也可分配 vnode)
1:mgmt(只能作为 mnode,不能分配 vnode)
2:dnode(不能作为 mnode,只能分配 vnode) | +| 缺省值 | 0 | + +## 时间相关 + +### rpcTimer + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | rpc 重试时长 | +| 单位 | 毫秒 | +| 取值范围 | 100-3000 | +| 缺省值 | 300 | + +### rpcMaxTime + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | rpc 等待应答最大时长 | +| 单位 | 秒 | +| 取值范围 | 100-7200 | +| 缺省值 | 600 | + +### statusInterval + +| 属性 | 说明 | +| -------- | --------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | dnode 向 mnode 报告状态间隔 | +| 单位 | 秒 | +| 取值范围 | 1-10 | +| 缺省值 | 1 | + +### shellActivityTimer + +| 属性 | 说明 | +| -------- | --------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | shell 客户端向 mnode 发送心跳间隔 | +| 单位 | 秒 | +| 取值范围 | 1-120 | +| 缺省值 | 3 | + +### tableMetaKeepTimer + +| 属性 | 说明 | +| -------- | --------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 表的元数据 cache 时长 | +| 单位 | 秒 | +| 取值范围 | 1-8640000 | +| 缺省值 | 7200 | + +### minSlidingTime + +| 属性 | 说明 | +| -------- | ----------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 最小滑动窗口时长 | +| 单位 | 毫秒 | +| 取值范围 | 10-1000000 | +| 缺省值 | 10 | +| 补充说明 | 支持 us 补值后,这个值就是 1us 了。 | + +### minIntervalTime + +| 属性 | 说明 | +| -------- | -------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 时间窗口最小值 | +| 单位 | 毫秒 | +| 取值范围 | 1-1000000 | +| 缺省值 | 10 | + +### maxTmerCtrl + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 定时器个数 | +| 单位 | 个 | +| 取值范围 | 8-2048 | +| 缺省值 | 512 | + +### monitorInterval + +| 属性 | 说明 | +| -------- | -------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 监控数据库记录系统参数(CPU/内存)的时间间隔 | +| 单位 | 秒 | +| 取值范围 | 1-600 | +| 缺省值 | 30 | + +### offlineThreshold + +| 属性 | 说明 | +| -------- | ------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | dnode 离线阈值,超过该时间将导致 dnode 离线 | +| 单位 | 秒 | +| 取值范围 | 5-7200000 | +| 缺省值 | 86400\*10(10 天) | + +### maxStreamCompDelay + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 连续查询启动最大延迟 | +| 单位 | 毫秒 | +| 取值范围 | 10-1000000000 | +| 缺省值 | 20000 | +| 补充说明 | 为避免多个 stream 同时执行占用太多系统资源,程序中对 stream 的执行时间人为增加了一些随机的延时。
maxFirstStreamCompDelay 是 stream 第一次执行前最少要等待的时间。
streamCompDelayRatio 是延迟时间的计算系数,它乘以查询的 interval 后为延迟时间基准。
maxStreamCompDelay 是延迟时间基准的上限。
实际延迟时间为一个不超过延迟时间基准的随机值。
stream 某次计算失败后需要重试,retryStreamCompDelay 是重试的等待时间基准。
实际重试等待时间为不超过等待时间基准的随机值。 | + +### maxFirstStreamCompDelay + +| 属性 | 说明 | +| -------- | -------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 第一次连续查询启动最大延迟 | +| 单位 | 毫秒 | +| 取值范围 | 10-1000000000 | +| 缺省值 | 10000 | + +### retryStreamCompDelay + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 连续查询重试等待间隔 | +| 单位 | 毫秒 | +| 取值范围 | 10-1000000000 | +| 缺省值 | 10 | + +### streamCompDelayRatio + +| 属性 | 说明 | +| -------- | -------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 连续查询的延迟时间计算系数 | +| 取值范围 | 0.1-0.9 | +| 缺省值 | 0.1 | + +## 数量相关 + +### numOfThreadsPerCore + +| 属性 | 说明 | +| -------- | ----------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 每个 CPU 核生成的队列消费者线程数量 | +| 缺省值 | 1.0 | + +### ratioOfQueryThreads + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 设置查询线程的最大数量 | +| 取值范围 | 0:表示只有 1 个查询线程
1:表示最大和 CPU 核数相等的查询线程
2:表示最大建立 2 倍 CPU 核数的查询线程。 | +| 缺省值 | 1 | +| 补充说明 | 该值可以为小数,即 0.5 表示最大建立 CPU 核数一半的查询线程。 | + +### numOfMnodes + +| 属性 | 说明 | +| -------- | ------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 系统中管理节点个数 | +| 缺省值 | 3 | + +### maxVgroupsPerDb + +| 属性 | 说明 | +| -------- | ------------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 每个 DB 中 能够使用的最大 vnode 个数 | +| 取值范围 | 0-8192 | +| 缺省值 | | + +### maxTablesPerVnode + +| 属性 | 说明 | +| -------- | --------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 每个 vnode 中能够创建的最大表个数 | +| 缺省值 | 1000000 | + +### maxNumOfOrderedRes + +| 属性 | 说明 | +| -------- | -------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 支持超级表时间排序允许的最多记录数限制 | +| 缺省值 | 10 万 | + +### maxShellConns + +| 属性 | 说明 | +| -------- | ----------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 一个 dnode 容许的连接数 | +| 取值范围 | 10-50000000 | +| 缺省值 | 5000 | + +### maxConnections + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 一个数据库连接所容许的 dnode 连接数 | +| 取值范围 | 1-100000 | +| 缺省值 | 5000 | +| 补充说明 | 实际测试下来,如果默认没有配,选 50 个 worker thread 会产生 Network unavailable | + +### mnodeEqualVnodeNum + +| 属性 | 说明 | +| -------- | ---------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 一个 mnode 等同于 vnode 消耗的个数 | +| 缺省值 | 4 | + +## 压缩相关 + +### comp + +| 属性 | 说明 | +| -------- | ----------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 文件压缩标志位 | +| 取值范围 | 0:关闭,1:一阶段压缩,2:两阶段压缩 | +| 缺省值 | 2 | + +### compressMsgSize + +| 属性 | 说明 | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 客户端与服务器之间进行消息通讯过程中,对通讯的消息进行压缩的阈值。如果要压缩消息,建议设置为 64330 字节,即大于 64330 字节的消息体才进行压缩。 | +| 单位 | bytes | +| 取值范围 | `0 `表示对所有的消息均进行压缩 >0: 超过该值的消息才进行压缩 -1: 不压缩 | +| 缺省值 | -1 | + +### compressColData + +| 属性 | 说明 | +| -------- | --------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 客户端与服务器之间进行消息通讯过程中,对服务器端查询结果进行列压缩的阈值。 | +| 单位 | bytes | +| 取值范围 | 0: 对所有查询结果均进行压缩 >0: 查询结果中任意列大小超过该值的消息才进行压缩 -1: 不压缩 | +| 缺省值 | -1 | +| 补充说明 | 2.3.0.0 版本新增。 | + +### lossyColumns + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 适用范围 | 服务器端 | +| 含义 | 配置要进行有损压缩的浮点数据类型 | +| 取值范围 | 空字符串:关闭有损压缩
float:只对 float 类型进行有损压缩
double:只对 double 类型进行有损压缩
float \| double:float double 都进行有损压缩 | +| 缺省值 | 128 | +| 补充说明 | 有损压缩默认为关闭状态,只有配置后才生效 | + +### fPrecision + +| 属性 | 说明 | +| -------- | -------------------------------- | +| 适用范围 | 服务器端 | +| 含义 | 设置 float 类型浮点数压缩精度 | +| 取值范围 | 0.1 ~ 0.00000001 | +| 缺省值 | 0.00000001 | +| 补充说明 | 小于此值的浮点数尾数部分将被截取 | + +### dPrecision + +| 属性 | 说明 | +| -------- | -------------------------------- | +| 适用范围 | 服务器端 | +| 含义 | 设置 double 类型浮点数压缩精度 | +| 取值范围 | 0.1 ~ 0.0000000000000001 | +| 缺省值 | 0.0000000000000001 | +| 补充说明 | 小于此值的浮点数尾数部分将被截取 | + +## HTTP 相关 + +### http + +| 属性 | 说明 | +| -------- | --------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 服务器内部的 http 服务开关。 | +| 取值范围 | 0:关闭 http 服务, 1:激活 http 服务。 | +| 缺省值 | 1 | + +### httpEnableRecordSql + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 内部使用,记录通过 RESTFul 接口,产生的 SQL 调用。taosAdapter 配置或有不同,请参考相应[文档](https://www.taosdata.com/cn/documentation/tools/adapter)。 | +| 缺省值 | 0 | +| 补充说明 | 生成的文件(httpnote.0/httpnote.1),与服务端日志所在目录相同。 | + +### httpMaxThreads + +| 属性 | 说明 | +| -------- | --------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | RESTFul 接口的线程数。taosAdapter 配置或有不同,请参考相应[文档](https://www.taosdata.com/cn/documentation/tools/adapter)。 | +| 缺省值 | 2 | + +### restfulRowLimit + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | RESTFul 接口单次返回的记录条数。taosAdapter 配置或有不同,请参考相应[文档](https://www.taosdata.com/cn/documentation/tools/adapter)。 | +| 缺省值 | 10240 | +| 补充说明 | 最大 10,000,000 | + +### httpDBNameMandatory + +| 属性 | 说明 | +| -------- | ---------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 是否在 URL 中输入 数据库名称 | +| 取值范围 | 0:不开启,1:开启 | +| 缺省值 | 0 | +| 补充说明 | 2.3 版本新增。 | + +## 日志相关 + +### numOfLogLines + +| 属性 | 说明 | +| -------- | ---------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 单个日志文件允许的最大行数。 | +| 缺省值 | 10,000,000 | + +### asyncLog + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 日志写入模式 | +| 取值范围 | 0:同步、1:异步 | +| 缺省值 | 1 | + +### logKeepDays + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 日志文件的最长保存时间 | +| 单位 | 天 | +| 缺省值 | 0 | +| 补充说明 | 大于 0 时,日志文件会被重命名为 taosdlog.xxx,其中 xxx 为日志文件最后修改的时间戳。 | + +### debugFlag + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 运行日志开关 | +| 取值范围 | 131(输出错误和警告日志),135(输出错误、警告和调试日志),143(输出错误、警告、调试和跟踪日志) | +| 缺省值 | 131 或 135(不同模块有不同的默认值) | + +### mDebugFlag + +| 属性 | 说明 | +| -------- | ------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 管理模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | 135 | + +### dDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | dnode 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | 135 | + +### sDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | sync 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | 135 | + +### wDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | wal 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | 135 | + +### sdbDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | sdb 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | 135 | + +### rpcDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | rpc 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### tmrDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 定时器模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### cDebugFlag + +| 属性 | 说明 | +| -------- | --------------------- | +| 适用范围 | 仅客户端适用 | +| 含义 | client 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### jniDebugFlag + +| 属性 | 说明 | +| -------- | ------------------ | +| 适用范围 | 仅客户端适用 | +| 含义 | jni 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### odbcDebugFlag + +| 属性 | 说明 | +| -------- | ------------------- | +| 适用范围 | 仅客户端适用 | +| 含义 | odbc 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### uDebugFlag + +| 属性 | 说明 | +| -------- | ---------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 共用功能模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### httpDebugFlag + +| 属性 | 说明 | +| -------- | ------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | http 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### mqttDebugFlag + +| 属性 | 说明 | +| -------- | ------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | mqtt 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### monitorDebugFlag + +| 属性 | 说明 | +| -------- | ------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 监控模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### qDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 查询模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### vDebugFlag + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | vnode 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### tsdbDebugFlag + +| 属性 | 说明 | +| -------- | ------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | TSDB 模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +### cqDebugFlag + +| 属性 | 说明 | +| -------- | ---------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 连续查询模块的日志开关 | +| 取值范围 | 同上 | +| 缺省值 | | + +## 内部配置 + +### secondEP + +| 属性 | 说明 | +| -------- | ---------------------------------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | taosd 启动时,如果 firstEp 连接不上,尝试连接集群中第二个 dnode 的 end point | +| 缺省值 | 无 | + +### scriptDir + +| 属性 | 说明 | +| -------- | ------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | | +| 缺省值 | | + +### balanceInterval + +| 属性 | 说明 | +| -------- | ------------------------------------------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | 管理节点在正常运行状态下,检查负载均衡的时间间隔 | +| 单位 | 秒 | +| 取值范围 | 1-30000 | +| 缺省值 | 300 | + +### minTablesPerVnode + +| 属性 | 说明 | +| -------- | --------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 每个 vnode 中必须创建的最小表个数 | +| 缺省值 | 1000 | + +### tableIncStepPerVnode + +| 属性 | 说明 | +| -------- | ----------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 每个 vnode 中超过最小表数后递增步长 | +| 缺省值 | 1000 | + +### mqttHostName + +| 属性 | 说明 | +| -------- | -------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | mqtt uri | +| 缺省值 | | +| 补充说明 | mqtt://username:password@hostname:1883/taos/ | + +### mqttPort + +| 属性 | 说明 | +| -------- | ---------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | mqtt client name | +| 缺省值 | | +| 补充说明 | 1883 | + +### mqttTopic + +| 属性 | 说明 | +| -------- | ------------ | +| 适用范围 | 仅服务端适用 | +| 含义 | | +| 缺省值 | | +| 补充说明 | /test | + +### mqtt + +| 属性 | 说明 | +| -------- | --------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 服务器内部的 mqtt 服务开关。 | +| 取值范围 | 0:关闭 mqtt 服务, 1:激活 mqtt 服务。 | +| 缺省值 | 0 | + +### telegrafUseFieldNum + +| 属性 | 说明 | +| -------- | ---- | +| 适用范围 | | +| 含义 | | +| 缺省值 | | + +### gitinfo + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | | +| 取值范围 | 1 | +| 缺省值 | | + +### gitinfoofInternal + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | | +| 取值范围 | 2 | +| 缺省值 | | + +### Buildinfo + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | | +| 取值范围 | 3 | +| 缺省值 | | + +### version + +| 属性 | 说明 | +| -------- | -------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | | +| 取值范围 | 4 | +| 缺省值 | | + +### numOfCommitThreads + +| 属性 | 说明 | +| -------- | ---------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 设置写入线程的最大数量 | +| 缺省值 | | + +## 仅客户端适用 + +### maxSQLLength + +| 属性 | 说明 | +| -------- | --------------------------- | +| 适用范围 | 仅客户端适用 | +| 含义 | 单条 SQL 语句允许的最长限制 | +| 单位 | bytes | +| 取值范围 | 65480-1048576 | +| 缺省值 | 1048576 | + +### tscEnableRecordSql + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------------------- | +| 含义 | 是否记录客户端 sql 语句到文件 | +| 取值范围 | 0:否,1:是 | +| 缺省值 | 0 | +| 补充说明 | 生成的文件(tscnote-xxxx.0/tscnote-xxx.1,xxxx 是 pid),与客户端日志所在目录相同。 | + +### maxBinaryDisplayWidth + +| 属性 | 说明 | +| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 含义 | Taos shell 中 binary 和 nchar 字段的显示宽度上限,超过此限制的部分将被隐藏 | +| 取值范围 | 5 - | +| 缺省值 | 30 | +| 补充说明 | 实际上限按以下规则计算:如果字段值的长度大于 maxBinaryDisplayWidth,则显示上限为 **字段名长度** 和 **maxBinaryDisplayWidth** 的较大者。
否则,上限为 **字段名长度** 和 **字段值长度** 的较大者。
可在 shell 中通过命令 set max_binary_display_width nn 动态修改此选项 | + +### maxWildCardsLength + +| 属性 | 说明 | +| -------- | ------------------------------------------ | +| 含义 | 设定 LIKE 算子的通配符字符串允许的最大长度 | +| 单位 | bytes | +| 取值范围 | 0-16384 | +| 缺省值 | 100 | +| 补充说明 | 2.1.6.1 版本新增。 | + +### tsdbMetaCompactRatio + +| 属性 | 说明 | +| -------- | -------------------------------------------------------------- | +| 含义 | tsdb meta 文件中冗余数据超过多少阈值,开启 meta 文件的压缩功能 | +| 取值范围 | 0:不开启,[1-100]:冗余数据比例 | +| 缺省值 | 0 | + +### clientMerge + +| 属性 | 说明 | +| -------- | ---------------------------- | +| 含义 | 是否允许客户端对写入数据去重 | +| 取值范围 | 0:不开启,1:开启 | +| 缺省值 | 0 | +| 补充说明 | 2.3 版本新增。 | + +### maxRegexStringLen + +| 属性 | 说明 | +| -------- | -------------------------- | +| 含义 | 正则表达式最大允许长度 | +| 取值范围 | 默认值 128,最大长度 16384 | +| 缺省值 | 128 | +| 补充说明 | 2.3 版本新增。 | + +## 其他 + +### queryBufferSize + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 为所有并发查询占用保留的内存大小。 | +| 单位 | MB | +| 缺省值 | | +| 补充说明 | 计算规则可以根据实际应用可能的最大并发数和表的数字相乘,再乘 170 。
(2.0.15 以前的版本中,此参数的单位是字节) | + +### ratioOfQueryCores + +| 属性 | 说明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | +| 适用范围 | 仅服务端适用 | +| 含义 | 设置查询线程的最大数量。 | +| 缺省值 | | +| 补充说明 | 最小值 0 表示只有 1 个查询线程
最大值 2 表示最大建立 2 倍 CPU 核数的查询线程。
默认为 1,表示最大和 CPU 核数相等的查询线程。
该值可以为小数,即 0.5 表示最大建立 CPU 核数一半的查询线程。 | | + +### rpcForceTcp + +| 属性 | 说明 | +| -------- | --------------------------------------------------- | +| 适用范围 | 服务端和客户端均适用 | +| 含义 | 强制使用 TCP 传输 | +| 取值范围 | 0: 不开启 1: 开启 | +| 缺省值 | 0 | +| 补充说明 | 在网络比较差的环境中,建议开启。
2.0 版本新增。 | + +### maxNumOfDistinctRes + +| 属性 | 说明 | +| -------- | -------------------------------- | +| 适用范围 | 仅服务端适用 | +| 含义 | 允许返回的 distinct 结果最大行数 | +| 取值范围 | 默认值为 10 万,最大值 1 亿 | +| 缺省值 | 10 万 | +| 补充说明 | 2.3 版本新增。 | + diff --git a/docs-cn/14-reference/08-server-config/_category_.yml b/docs-cn/14-reference/08-server-config/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..e05fbeb578ceb525ae80f3d50c3e018df13bfa56 --- /dev/null +++ b/docs-cn/14-reference/08-server-config/_category_.yml @@ -0,0 +1 @@ +label: 服务端配置 \ No newline at end of file diff --git a/docs-cn/14-reference/09-client-config/09-client-config.md b/docs-cn/14-reference/09-client-config/09-client-config.md new file mode 100644 index 0000000000000000000000000000000000000000..15ca79b029d8194c5af0c43ab579aac8727b06d4 --- /dev/null +++ b/docs-cn/14-reference/09-client-config/09-client-config.md @@ -0,0 +1,105 @@ +# 客户端及应用驱动配置 + +TDengine 系统的前台交互客户端应用程序为 taos,以及应用驱动,它与 taosd 共享同一个配置文件 taos.cfg。运行 taos 时,使用参数-c 指定配置文件目录,如 taos -c /home/cfg,表示使用/home/cfg/目录下的 taos.cfg 配置文件中的参数,缺省目录是/etc/taos。更多 taos 的使用方法请见帮助信息 `taos --help`。本节主要说明 taos 客户端应用在配置文件 taos.cfg 文件中使用到的参数。 + +**2.0.10.0 之后版本支持命令行以下参数显示当前客户端参数的配置** + +```bash +taos -C 或 taos --dump-config +``` + +客户端及应用驱动配置参数列表及解释 + +- firstEp: taos 启动时,主动连接的集群中第一个 taosd 实例的 end point, 缺省值为 localhost:6030。 + +- secondEp: taos 启动时,如果 firstEp 连不上,将尝试连接 secondEp。 + +- locale:系统区位信息及编码格式。 + + 默认值:系统中动态获取,如果自动获取失败,需要用户在配置文件设置或通过 API 设置。 + + TDengine 为存储中文、日文、韩文等非 ASCII 编码的宽字符,提供一种专门的字段类型 nchar。写入 nchar 字段的数据将统一采用 UCS4-LE 格式进行编码并发送到服务器。需要注意的是,编码正确性是客户端来保证。因此,如果用户想要正常使用 nchar 字段来存储诸如中文、日文、韩文等非 ASCII 字符,需要正确设置客户端的编码格式。 + + 客户端的输入的字符均采用操作系统当前默认的编码格式,在 Linux 系统上多为 UTF-8,部分中文系统编码则可能是 GB18030 或 GBK 等。在 docker 环境中默认的编码是 POSIX。在中文版 Windows 系统中,编码则是 CP936。客户端需要确保正确设置自己所使用的字符集,即客户端运行的操作系统当前编码字符集,才能保证 nchar 中的数据正确转换为 UCS4-LE 编码格式。 + + 在 Linux 中 locale 的命名规则为: <语言>\_<地区>.<字符集编码> 如:zh_CN.UTF-8,zh 代表中文,CN 代表大陆地区,UTF-8 表示字符集。字符集编码为客户端正确解析本地字符串提供编码转换的说明。Linux 系统与 Mac OSX 系统可以通过设置 locale 来确定系统的字符编码,由于 Windows 使用的 locale 中不是 POSIX 标准的 locale 格式,因此在 Windows 下需要采用另一个配置参数 charset 来指定字符编码。在 Linux 系统中也可以使用 charset 来指定字符编码。 + +- charset:字符集编码。 + + 默认值:系统中动态获取,如果自动获取失败,需要用户在配置文件设置或通过 API 设置。 + + 如果配置文件中不设置 charset,在 Linux 系统中,taos 在启动时候,自动读取系统当前的 locale 信息,并从 locale 信息中解析提取 charset 编码格式。如果自动读取 locale 信息失败,则尝试读取 charset 配置,如果读取 charset 配置也失败,则中断启动过程。 + + 在 Linux 系统中,locale 信息包含了字符编码信息,因此正确设置了 Linux 系统 locale 以后可以不用再单独设置 charset。例如: + + ``` + locale zh_CN.UTF-8 + ``` + + 在 Windows 系统中,无法从 locale 获取系统当前编码。如果无法从配置文件中读取字符串编码信息,taos 默认设置为字符编码为 CP936。其等效在配置文件中添加如下配置: + + ``` + charset CP936 + ``` + + 如果需要调整字符编码,请查阅当前操作系统使用的编码,并在配置文件中正确设置。 + + 在 Linux 系统中,如果用户同时设置了 locale 和字符集编码 charset,并且 locale 和 charset 的不一致,后设置的值将覆盖前面设置的值。 + + ``` + locale zh_CN.UTF-8 + charset GBK + ``` + + 则 charset 的有效值是 GBK。 + + ``` + charset GBK + locale zh_CN.UTF-8 + ``` + + charset 的有效值是 UTF-8。 + + 日志的配置参数,与 server 的配置参数完全一样。 + +- timezone + + 默认值:动态获取当前客户端运行系统所在的时区。 + + 为应对多时区的数据写入和查询问题,TDengine 采用 Unix 时间戳(Unix Timestamp)来记录和存储时间戳。Unix 时间戳的特点决定了任一时刻不论在任何时区,产生的时间戳均一致。需要注意的是,Unix 时间戳是在客户端完成转换和记录。为了确保客户端其他形式的时间转换为正确的 Unix 时间戳,需要设置正确的时区。 + + 在 Linux 系统中,客户端会自动读取系统设置的时区信息。用户也可以采用多种方式在配置文件设置时区。例如: + + ``` + timezone UTC-8 + timezone GMT-8 + timezone Asia/Shanghai + ``` + + 均是合法的设置东八区时区的格式。但需注意,Windows 下并不支持 `timezone Asia/Shanghai` 这样的写法,而必须写成 `timezone UTC-8`。 + + 时区的设置对于查询和写入 SQL 语句中非 Unix 时间戳的内容(时间戳字符串、关键词 now 的解析)产生影响。例如: + + ```sql + SELECT count(*) FROM table_name WHERE TS<'2019-04-11 12:01:08'; + ``` + + 在东八区,SQL 语句等效于 + + ```sql + SELECT count(*) FROM table_name WHERE TS<1554955268000; + ``` + + 在 UTC 时区,SQL 语句等效于 + + ```sql + SELECT count(*) FROM table_name WHERE TS<1554984068000; + ``` + + 为了避免使用字符串时间格式带来的不确定性,也可以直接使用 Unix 时间戳。此外,还可以在 SQL 语句中使用带有时区的时间戳字符串,例如:RFC3339 格式的时间戳字符串,2013-04-12T15:52:01.123+08:00 或者 ISO-8601 格式时间戳字符串 2013-04-12T15:52:01.123+0800。上述两个字符串转化为 Unix 时间戳不受系统所在时区的影响。 + + 启动 taos 时,也可以从命令行指定一个 taosd 实例的 end point,否则就从 taos.cfg 读取。 + +- maxBinaryDisplayWidth + + Shell 中 binary 和 nchar 字段的显示宽度上限,超过此限制的部分将被隐藏。默认值:30。可在 taos shell 中通过命令 set max_binary_display_width nn 动态修改此选项。 diff --git a/docs-cn/14-reference/09-client-config/_category_.yml b/docs-cn/14-reference/09-client-config/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..ad6e70b96dd031cc3d2607565f91d554e19addeb --- /dev/null +++ b/docs-cn/14-reference/09-client-config/_category_.yml @@ -0,0 +1 @@ +label: 客户端配置 diff --git a/docs-cn/14-reference/12-direcotry.md b/docs-cn/14-reference/12-direcotry.md new file mode 100644 index 0000000000000000000000000000000000000000..c2746de1c1dd98f9ffa715680d4a1048cd3e8c02 --- /dev/null +++ b/docs-cn/14-reference/12-direcotry.md @@ -0,0 +1,34 @@ +# 文件目录结构 + +安装 TDengine 后,默认会在操作系统中生成下列目录或文件: + +| 目录/文件 | 说明 | +| ------------------------- | -------------------------------------------------------------------- | +| /usr/local/taos/bin | TDengine 可执行文件目录。其中的执行文件都会软链接到/usr/bin 目录下。 | +| /usr/local/taos/connector | TDengine 各种连接器目录。 | +| /usr/local/taos/driver | TDengine 动态链接库目录。会软链接到/usr/lib 目录下。 | +| /usr/local/taos/examples | TDengine 各种语言应用示例目录。 | +| /usr/local/taos/include | TDengine 对外提供的 C 语言接口的头文件。 | +| /etc/taos/taos.cfg | TDengine 默认[配置文件] | +| /var/lib/taos | TDengine 默认数据文件目录。可通过[配置文件]修改位置。 | +| /var/log/taos | TDengine 默认日志文件目录。可通过[配置文件]修改位置。 | + +## 可执行文件 + +TDengine 的所有可执行文件默认存放在 _/usr/local/taos/bin_ 目录下。其中包括: + +- _taosd_:TDengine 服务端可执行文件 +- _taos_:TDengine Shell 可执行文件 +- _taosdump_:数据导入导出工具 +- _taosBenchmark_:TDengine 测试工具 +- remove.sh:卸载 TDengine 的脚本,请谨慎执行,链接到/usr/bin 目录下的**rmtaos**命令。会删除 TDengine 的安装目录/usr/local/taos,但会保留/etc/taos、/var/lib/taos、/var/log/taos。 + +:::note +2.4.0.0 版本之后的 taosBenchmark 和 taosdump 需要安装独立安装包 taosTools。 + +::: + +:::tip +您可以通过修改系统配置文件 taos.cfg 来配置不同的数据目录和日志目录。 + +::: diff --git a/docs-cn/14-reference/13-schemaless/13-schemaless.md b/docs-cn/14-reference/13-schemaless/13-schemaless.md new file mode 100644 index 0000000000000000000000000000000000000000..1c5fbea726eb5153d4db0ef6d42ef53b478232f5 --- /dev/null +++ b/docs-cn/14-reference/13-schemaless/13-schemaless.md @@ -0,0 +1,164 @@ +# Schemaless 写入 + +## 前言 + +在物联网应用中,常会采集比较多的数据项,用于实现智能控制、业务分析、设备监控等。由于应用逻辑的版本升级,或者设备自身的硬件调整等原因,数据采集项就有可能比较频繁地出现变动。为了在这种情况下方便地完成数据记录工作,TDengine +从 2.2.0.0 版本开始,提供调用 Schemaless 写入方式,可以免于预先创建超级表/子表的步骤,随着数据写入接口能够自动创建与数据对应的存储结构。并且在必要时,Schemaless +将自动增加必要的数据列,保证用户写入的数据可以被正确存储。 + +无模式写入方式建立的超级表及其对应的子表与通过 SQL 直接建立的超级表和子表完全没有区别,你也可以通过,SQL 语句直接向其中写入数据。需要注意的是,通过无模式写入方式建立的表,其表名是基于标签值按照固定的映射规则生成,所以无法明确地进行表意,缺乏可读性。 + +## 无模式写入行协议 + +TDengine 的无模式写入的行协议兼容 InfluxDB 的 行协议(Line Protocol)、OpenTSDB 的 telnet 行协议、OpenTSDB 的 JSON 格式协议。但是使用这三种协议的时候,需要在 API 中指定输入内容使用解析协议的标准。 + +对于 InfluxDB、OpenTSDB 的标准写入协议请参考各自的文档。下面首先以 InfluxDB 的行协议为基础,介绍 TDengine 扩展的协议内容,允许用户采用更加精细的方式控制(超级表)模式。 + +Schemaless 采用一个字符串来表达一个数据行(可以向写入 API 中一次传入多行字符串来实现多个数据行的批量写入),其格式约定如下: + +```json +measurement,tag_set field_set timestamp +``` + +其中: + +- measurement 将作为数据表名。它与 tag_set 之间使用一个英文逗号来分隔。 +- tag_set 将作为标签数据,其格式形如 `=,=`,也即可以使用英文逗号来分隔多个标签数据。它与 field_set 之间使用一个半角空格来分隔。 +- field_set 将作为普通列数据,其格式形如 `=,=`,同样是使用英文逗号来分隔多个普通列的数据。它与 timestamp 之间使用一个半角空格来分隔。 +- timestamp 即本行数据对应的主键时间戳。 + +tag_set 中的所有的数据自动转化为 nchar 数据类型,并不需要使用双引号(")。 + +在无模式写入数据行协议中,field_set 中的每个数据项都需要对自身的数据类型进行描述。具体来说: + +- 如果两边有英文双引号,表示 BIANRY(32) 类型。例如 `"abc"`。 +- 如果两边有英文双引号而且带有 L 前缀,表示 NCHAR(32) 类型。例如 `L"报错信息"`。 +- 对空格、等号(=)、逗号(,)、双引号("),前面需要使用反斜杠(\)进行转义。(都指的是英文半角符号) +- 数值类型将通过后缀来区分数据类型: + +| **序号** | **后缀** | **映射类型** | **大小(字节)** | +| -------- | -------- | ------------ | -------------- | +| 1 | 无或 f64 | double | 8 | +| 2 | f32 | float | 4 | +| 3 | i8 | TinyInt | 1 | +| 4 | i16 | SmallInt | 2 | +| 5 | i32 | Int | 4 | +| 6 | i64 或 i | Bigint | 8 | + +- t, T, true, True, TRUE, f, F, false, False 将直接作为 BOOL 型来处理。 + +例如如下数据行表示:向名为 st 的超级表下的 t1 标签为 "3"(NCHAR)、t2 标签为 "4"(NCHAR)、t3 +标签为 "t3"(NCHAR)的数据子表,写入 c1 列为 3(BIGINT)、c2 列为 false(BOOL)、c3 +列为 "passit"(BINARY)、c4 列为 4(DOUBLE)、主键时间戳为 1626006833639000000 的一行数据。 + +```json +st,t1=3,t2=4,t3=t3 c1=3i64,c3="passit",c2=false,c4=4f64 1626006833639000000 +``` + +需要注意的是,如果描述数据类型后缀时使用了错误的大小写,或者为数据指定的数据类型有误,均可能引发报错提示而导致数据写入失败。 + +## 无模式写入的主要处理逻辑 + +无模式写入按照如下原则来处理行数据: + +1. 将使用如下规则来生成子表名:首先将 measurement 的名称和标签的 key 和 value 组合成为如下的字符串 + +```json +"measurement,tag_key1=tag_value1,tag_key2=tag_value2" +``` + +需要注意的是,这里的 tag*key1, tag_key2 并不是用户输入的标签的原始顺序,而是使用了标签名称按照字符串升序排列后的结果。所以,tag_key1 并不是在行协议中输入的第一个标签。 +排列完成以后计算该字符串的 MD5 散列值 "md5_val"。然后将计算的结果与字符串组合生成表名:“t_md5_val”。其中的 “t*” 是固定的前缀,每个通过该映射关系自动生成的表都具有该前缀。 + +2. 如果解析行协议获得的超级表不存在,则会创建这个超级表。 +3. 如果解析行协议获得子表不存在,则 Schemaless 会按照步骤 1 或 2 确定的子表名来创建子表。 +4. 如果数据行中指定的标签列或普通列不存在,则在超级表中增加对应的标签列或普通列(只增不减)。 +5. 如果超级表中存在一些标签列或普通列未在一个数据行中被指定取值,那么这些列的值在这一行中会被置为 + NULL。 +6. 对 BINARY 或 NCHAR 列,如果数据行中所提供值的长度超出了列类型的限制,自动增加该列允许存储的字符长度上限(只增不减),以保证数据的完整保存。 +7. 如果指定的数据子表已经存在,而且本次指定的标签列取值跟已保存的值不一样,那么最新的数据行中的值会覆盖旧的标签列取值。 +8. 整个处理过程中遇到的错误会中断写入过程,并返回错误代码。 + +:::tip +无模式所有的处理逻辑,仍会遵循 TDengine 对数据结构的底层限制,例如每行数据的总长度不能超过 +16k 字节。这方面的具体限制约束请参见 [TAOS SQL 边界限制](https://www.taosdata.com/cn/documentation/taos-sql#limitation) + +::: + +## 时间分辨率识别 + +无模式写入过程中支持三个指定的模式,具体如下 + +| **序号** | **值** | **说明** | +| -------- | ------------------- | ------------------------------- | +| 1 | SML_LINE_PROTOCOL | InfluxDB 行协议(Line Protocol) | +| 2 | SML_TELNET_PROTOCOL | OpenTSDB 文本行协议 | +| 3 | SML_JSON_PROTOCOL | JSON 协议格式 | + +在 SML_LINE_PROTOCOL 解析模式下,需要用户指定输入的时间戳的时间分辨率。可用的时间分辨率如下表所示: + +| **序号** | **时间分辨率定义** | **含义** | +| -------- | --------------------------------- | -------------- | +| 1 | TSDB_SML_TIMESTAMP_NOT_CONFIGURED | 未定义(无效) | +| 2 | TSDB_SML_TIMESTAMP_HOURS | 小时 | +| 3 | TSDB_SML_TIMESTAMP_MINUTES | 分钟 | +| 4 | TSDB_SML_TIMESTAMP_SECONDS | 秒 | +| 5 | TSDB_SML_TIMESTAMP_MILLI_SECONDS | 毫秒 | +| 6 | TSDB_SML_TIMESTAMP_MICRO_SECONDS | 微秒 | +| 7 | TSDB_SML_TIMESTAMP_NANO_SECONDS | 纳秒 | + +在 SML_TELNET_PROTOCOL 和 SML_JSON_PROTOCOL 模式下,根据时间戳的长度来确定时间精度(与 OpenTSDB 标准操作方式相同),此时会忽略用户指定的时间分辨率。 + +## 数据模式映射规则 + +本节将说明行协议的数据如何映射成为具有模式的数据。每个行协议中数据 measurement 映射为 +超级表名称。tag_set 中的 标签名称为 数据模式中的标签名,field_set 中的名称为列名称。以如下数据为例,说明映射规则: + +```json +st,t1=3,t2=4,t3=t3 c1=3i64,c3="passit",c2=false,c4=4f64 1626006833639000000 +``` + +该行数据映射生成一个超级表: st, 其包含了 3 个类型为 nchar 的标签,分别是:t1, t2, t3。五个数据列,分别是 ts(timestamp),c1 (bigint),c3(binary),c2 (bool), c4 (bigint)。映射成为如下 SQL 语句: + +```json +create stable st (_ts timestamp, c1 bigint, c2 bool, c3 binary(6), c4 bigint) tags(t1 nchar(1), t2 nchar(1), t3 nchar(2)) +``` + +## 数据模式变更处理 + +本节将说明不同行数据写入情况下,对于数据模式的影响。 + +在使用行协议写入一个明确的标识的字段类型的时候,后续更改该字段的类型定义,会出现明确的数据模式错误,即会触发写入 API 报告错误。如下所示, + +```json +st,t1=3,t2=4,t3=t3 c1=3i64,c3="passit",c2=false,c4=4 1626006833639000000 +st,t1=3,t2=4,t3=t3 c1=3i64,c3="passit",c2=false,c4=4i 1626006833640000000 +``` + +第一行的数据类型映射将 c4 列定义为 Double, 但是第二行的数据又通过数值后缀方式声明该列为 BigInt, 由此会触发无模式写入的解析错误。 + +如果列前面的行协议将数据列声明为了 binary, 后续的要求长度更长的 binary 长度,此时会触发超级表模式的变更。 + +```json +st,t1=3,t2=4,t3=t3 c1=3i64,c5="pass" 1626006833639000000 +st,t1=3,t2=4,t3=t3 c1=3i64,c5="passit" 1626006833640000000 +``` + +第一行中行协议解析会声明 c5 列是一个 binary(4)的字段,第二次行数据写入会提取列 c5 仍然是 binary 列,但是其宽度为 6,此时需要将 binary 的宽度增加到能够容纳 新字符串的宽度。 + +```json +st,t1=3,t2=4,t3=t3 c1=3i64 1626006833639000000 +st,t1=3,t2=4,t3=t3 c1=3i64,c6="passit" 1626006833640000000 +``` + +第二行数据相对于第一行来说增加了一个列 c6,类型为 binary(6)。那么此时会自动增加一个列 c6, 类型为 binary(6)。 + +## 写入完整性 + +TDengine 提供数据写入的幂等性保证,即您可以反复调用 API 进行出错数据的写入操作。但是不提供多行数据写入的原子性保证。即在多行数据一批次写入过程中,会出现部分数据写入成功,部分数据写入失败的情况。 + +## 错误码 + +如果是无模式写入过程中的数据本身错误,应用会得到 TSDB_CODE_TSC_LINE_SYNTAX_ERROR +错误信息,该错误信息表明错误发生在写入文本中。其他的错误码与原系统一致,可以通过 +taos_errstr 获取具体的错误原因。 diff --git a/docs-cn/14-reference/13-schemaless/_category_.yml b/docs-cn/14-reference/13-schemaless/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..2e93df8b366a0d60d4af35ff35076b8345a1ad6a --- /dev/null +++ b/docs-cn/14-reference/13-schemaless/_category_.yml @@ -0,0 +1 @@ +label: Schemaless 写入 diff --git a/docs-cn/14-reference/_category_.yml b/docs-cn/14-reference/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..f8031c35755f5912110136e8fdf3b176ddf5d6b0 --- /dev/null +++ b/docs-cn/14-reference/_category_.yml @@ -0,0 +1,4 @@ +label: 参考指南 +link: + slug: /reference/ + type: generated-index \ No newline at end of file diff --git a/docs-cn/15-application/01-telegraf.md b/docs-cn/15-application/01-telegraf.md new file mode 100644 index 0000000000000000000000000000000000000000..a23240debebbbf4a9da023f904562f04276f5b12 --- /dev/null +++ b/docs-cn/15-application/01-telegraf.md @@ -0,0 +1,83 @@ +--- +sidebar_label: TDengine + Telegraf + Grafana +--- + +# 使用 TDengine + Telegraf + Grafana 快速搭建 IT 运维展示系统 + +## 背景介绍 + +TDengine 是涛思数据专为物联网、车联网、工业互联网、IT 运维等设计和优化的大数据平台。自从 2019 年 7 月开源以来,凭借创新的数据建模设计、快捷的安装方式、易用的编程接口和强大的数据写入查询性能博得了大量时序数据开发者的青睐。 + +IT 运维监测数据通常都是对时间特性比较敏感的数据,例如: + +- 系统资源指标:CPU、内存、IO、带宽等。 +- 软件系统指标:存活状态、连接数目、请求数目、超时数目、错误数目、响应时间、服务类型及其他与业务有关的指标。 + +当前主流的 IT 运维系统通常包含一个数据采集模块,一个数据存储模块,和一个可视化显示模块。Telegraf 和 Grafana 分别是当前最流行的数据采集模块和可视化显示模块之一。而数据存储模块可供选择的软件比较多,其中 OpenTSDB 或 InfluxDB 比较流行。而 TDengine 作为新兴的时序大数据平台,具备极强的高性能、高可靠、易管理、易维护的优势。 + +本文介绍不需要写一行代码,通过简单修改几行配置文件,就可以快速搭建一个基于 TDengine + Telegraf + Grafana 的 IT 运维系统。架构如下图: + +![IT-DevOps-Solutions-Telegraf.png](/img/IT-DevOps-Solutions-Telegraf.png) + +## 安装步骤 + +### 安装 Telegraf,Grafana 和 TDengine + +安装 Telegraf、Grafana 和 TDengine 请参考相关官方文档。 + +### Telegraf + +请参考[官方文档](https://portal.influxdata.com/downloads/)。 + +### Grafana + +请参考[官方文档](https://grafana.com/grafana/download)。 + +### TDengine + +从涛思数据官网[下载](http://taosdata.com/cn/all-downloads/)页面下载最新 TDengine-server 2.3.0.0 或以上版本安装。 + +## 数据链路设置 + +### 下载 TDengine 插件到 grafana 插件目录 + +```bash +1. wget -c https://github.com/taosdata/grafanaplugin/releases/download/v3.1.3/tdengine-datasource-3.1.3.zip +2. sudo unzip tdengine-datasource-3.1.3.zip -d /var/lib/grafana/plugins/ +3. sudo chown grafana:grafana -R /var/lib/grafana/plugins/tdengine +4. echo -e "[plugins]\nallow_loading_unsigned_plugins = tdengine-datasource\n" | sudo tee -a /etc/grafana/grafana.ini +5. sudo systemctl restart grafana-server.service +``` + +### 修改 /etc/telegraf/telegraf.conf + +配置方法,在 /etc/telegraf/telegraf.conf 增加如下文字,其中 database name 请填写希望在 TDengine 保存 Telegraf 数据的数据库名,TDengine server/cluster host、username 和 password 填写 TDengine 实际值: + +``` +[[outputs.http]] + url = "http://:6041/influxdb/v1/write?db=" + method = "POST" + timeout = "5s" + username = "" + password = "" + data_format = "influx" + influx_max_line_bytes = 250 +``` + +然后重启 telegraf: + +```bash +sudo systemctl start telegraf +``` + +### 导入 Dashboard + +使用 Web 浏览器访问 IP:3000 登录 Grafana 界面,系统初始用户名密码为 admin/admin。 +点击左侧齿轮图标并选择 Plugins,应该可以找到 TDengine data source 插件图标。 +点击左侧加号图标并选择 Import,从 `https://github.com/taosdata/grafanaplugin/blob/master/examples/telegraf/grafana/dashboards/telegraf-dashboard-v0.1.0.json` 下载 dashboard JSON 文件后导入。之后可以看到如下界面的仪表盘: + +![IT-DevOps-Solutions-telegraf-dashboard.png](/img/IT-DevOps-Solutions-telegraf-dashboard.png) + +## 总结 + +以上演示如何快速搭建一个完整的 IT 运维展示系统。得力于 TDengine 2.3.0.0 版本中新增的 schemaless 协议解析功能,以及强大的生态软件适配能力,用户可以短短数分钟就可以搭建一个高效易用的 IT 运维系统。TDengine 强大的数据写入查询性能和其他丰富功能请参考官方文档和产品落地案例。 diff --git a/docs-cn/15-application/02-collectd.md b/docs-cn/15-application/02-collectd.md new file mode 100644 index 0000000000000000000000000000000000000000..10f8eff8b7ade5a66357fb095a600fa453f53731 --- /dev/null +++ b/docs-cn/15-application/02-collectd.md @@ -0,0 +1,96 @@ +--- +sidebar_label: TDengine + collectd/StatsD + Grafana +--- + +# 使用 TDengine + collectd/StatsD + Grafana 快速搭建 IT 运维监控系统 + +## 背景介绍 + +TDengine 是涛思数据专为物联网、车联网、工业互联网、IT 运维等设计和优化的大数据平台。自从 2019 年 7 月开源以来,凭借创新的数据建模设计、快捷的安装方式、易用的编程接口和强大的数据写入查询性能博得了大量时序数据开发者的青睐。 + +IT 运维监测数据通常都是对时间特性比较敏感的数据,例如: + +- 系统资源指标:CPU、内存、IO、带宽等。 +- 软件系统指标:存活状态、连接数目、请求数目、超时数目、错误数目、响应时间、服务类型及其他与业务有关的指标。 + +当前主流的 IT 运维系统通常包含一个数据采集模块,一个数据存储模块,和一个可视化显示模块。collectd / statsD 作为老牌开源数据采集工具,具有广泛的用户群。但是 collectd / StatsD 自身功能有限,往往需要配合 Telegraf、Grafana 以及时序数据库组合搭建成为完整的监控系统。而 TDengine 新版本支持多种数据协议接入,可以直接接受 collectd 和 statsD 的数据写入,并提供 Grafana dashboard 进行图形化展示。 + +本文介绍不需要写一行代码,通过简单修改几行配置文件,就可以快速搭建一个基于 TDengine + collectd / statsD + Grafana 的 IT 运维系统。架构如下图: + +![IT-DevOps-Solutions-Collectd-StatsD.png](/img/IT-DevOps-Solutions-Collectd-StatsD.png) + +## 安装步骤 + +安装 collectd, StatsD, Grafana 和 TDengine 请参考相关官方文档。 + +### 安装 collectd + +请参考[官方文档](https://collectd.org/documentation.shtml)。 + +### 安装 StatsD + +请参考[官方文档](https://github.com/statsd/statsd)。 + +### 安装 Grafana + +请参考[官方文档](https://grafana.com/grafana/download)。 + +### 安装 TDengine + +从涛思数据官网[下载](http://taosdata.com/cn/all-downloads/)页面下载最新 TDengine-server 2.3.0.0 或以上版本安装。 + +## 数据链路设置 + +### 复制 TDengine 插件到 grafana 插件目录 + +```bash +1. wget -c https://github.com/taosdata/grafanaplugin/releases/download/v3.1.3/tdengine-datasource-3.1.3.zip +2. sudo unzip tdengine-datasource-3.1.3.zip -d /var/lib/grafana/plugins/ +3. sudo chown grafana:grafana -R /var/lib/grafana/plugins/tdengine +4. echo -e "[plugins]\nallow_loading_unsigned_plugins = tdengine-datasource\n" | sudo tee -a /etc/grafana/grafana.ini +5. sudo systemctl restart grafana-server.service +``` + +### 配置 collectd + +在 /etc/collectd/collectd.conf 文件中增加如下内容,其中 host 和 port 请填写 TDengine 和 taosAdapter 配置的实际值: + +``` +LoadPlugin network + + Server "" "" + + +sudo systemctl start collectd +``` + +### 配置 StatsD + +在 config.js 文件中增加如下内容后启动 StatsD,其中 host 和 port 请填写 TDengine 和 taosAdapter 配置的实际值: + +``` +backends 部分添加 "./backends/repeater" +repeater 部分添加 { host:'', port: } +``` + +### 导入 Dashboard + +使用 Web 浏览器访问运行 Grafana 的服务器的 3000 端口 host:3000 登录 Grafana 界面,系统初始用户名密码为 admin/admin。 +点击左侧齿轮图标并选择 Plugins,应该可以找到 TDengine data source 插件图标。 + +#### 导入 collectd 仪表盘 + +从 https://github.com/taosdata/grafanaplugin/blob/master/examples/collectd/grafana/dashboards/collect-metrics-with-tdengine-v0.1.0.json 下载 dashboard json 文件,点击左侧加号图标并选择 Import,按照界面提示选择 JSON 文件导入。之后可以看到如下界面的仪表盘: + +![IT-DevOps-Solutions-collectd-dashboard.png](/img/IT-DevOps-Solutions-collectd-dashboard.png) + +#### 导入 StatsD 仪表盘 + +从 https://github.com/taosdata/grafanaplugin/blob/master/examples/statsd/dashboards/statsd-with-tdengine-v0.1.0.json 下载 dashboard json 文件,点击左侧加号图标并选择 Import,按照界面提示导入 JSON 文件。之后可以看到如下界面的仪表盘: +![IT-DevOps-Solutions-statsd-dashboard.png](/img/IT-DevOps-Solutions-statsd-dashboard.png) + +## 总结 + +TDengine 作为新兴的时序大数据平台,具备极强的高性能、高可靠、易管理、易维护的优势。得力于 TDengine 2.3.0.0 版本中新增的 schemaless 协议解析功能,以及强大的生态软件适配能力,用户可以短短数分钟就可以搭建一个高效易用的 IT 运维系统或者适配一个已存在的系统。 + +TDengine 强大的数据写入查询性能和其他丰富功能请参考官方文档和产品成功落地案例。 diff --git a/docs-cn/15-application/03-immigrate.md b/docs-cn/15-application/03-immigrate.md new file mode 100644 index 0000000000000000000000000000000000000000..1e3087c06f40ae393ad55f71b534ca0cf424cb74 --- /dev/null +++ b/docs-cn/15-application/03-immigrate.md @@ -0,0 +1,401 @@ +--- +sidebar_label: OpenTSDB 迁移到 TDengine +--- + +# OpenTSDB 应用迁移到 TDengine 的最佳实践 + +作为一个分布式、可伸缩、基于 HBase 的分布式时序数据库系统,得益于其先发优势,OpenTSDB 被 DevOps 领域的人员引入并广泛地应用在了运维监控领域。但最近几年,随着云计算、微服务、容器化等新技术快速落地发展,企业级服务种类变得越来越多,架构也越来越复杂,应用运行基础环境日益多样化,给系统和运行监控带来的压力也越来越大。从这一现状出发,使用 OpenTSDB 作为 DevOps 的监控后端存储,越来越受困于其性能问题以及迟缓的功能升级,以及由此而衍生出来的应用部署成本上升和运行效率降低等问题,这些问题随着系统规模的扩大日益严重。 + +在这一背景下,为满足高速增长的物联网大数据市场和技术需求,在吸取众多传统关系型数据库、NoSQL 数据库、流计算引擎、消息队列等软件的优点之后,涛思数据自主开发出创新型大数据处理产品 TDengine。在时序大数据处理上,TDengine 有着自己独特的优势。就 OpenTSDB 当前遇到的问题来说,TDengine 能够有效解决。 + +相对于 OpenTSDB,TDengine 具有如下显著特点: + +- 数据写入和查询的性能远超 OpenTSDB; +- 针对时序数据的高效压缩机制,压缩后在磁盘上的存储空间不到 1/5; +- 安装部署非常简单,单一安装包完成安装部署,不依赖其他的第三方软件,整个安装部署过程秒级搞定; +- 提供的内建函数覆盖 OpenTSDB 支持的全部查询函数,还支持更多的时序数据查询函数、标量函数及聚合函数,支持多种时间窗口聚合、连接查询、表达式运算、多种分组聚合、用户定义排序、以及用户定义函数等高级查询功能。采用类 SQL 的语法规则,更加简单易学,基本上没有学习成本。 +- 支持多达 128 个标签,标签总长度可达到 16 KB; +- 除 HTTP 之外,还提供 Java、Python、C、Rust、Go 等多种语言的接口,支持 JDBC 等多种企业级标准连接器协议。 + +如果我们将原本运行在 OpenTSDB 上的应用迁移到 TDengine 上,不仅可以有效地降低计算和存储资源的占用、减少部署服务器的规模,还能够极大减少运行维护的成本的输出,让运维管理工作更简单、更轻松,大幅降低总拥有成本。与 OpenTSDB 一样,TDengine 也已经进行了开源,不同的是,除了单机版,后者还实现了集群版开源,被厂商绑定的顾虑一扫而空。 + +在下文中我们将就“使用最典型并广泛应用的运维监控(DevOps)场景”来说明,如何在不编码的情况下将 OpenTSDB 的应用快速、安全、可靠地迁移到 TDengine 之上。后续的章节会做更深度的介绍,以便于进行非 DevOps 场景的迁移。 + +## DevOps 应用快速迁移 + +### 1、典型应用场景 + +一个典型的 DevOps 应用场景的系统整体的架构如下图(图 1) 所示。 + +**图 1. DevOps 场景中典型架构** +![IT-DevOps-Solutions-Immigrate-OpenTSDB-Arch](/img/IT-DevOps-Solutions-Immigrate-OpenTSDB-Arch.jpg "图1. DevOps 场景中典型架构") + +在该应用场景中,包含了部署在应用环境中负责收集机器度量(Metrics)、网络度量(Metrics)以及应用度量(Metrics)的 Agent 工具、汇聚 agent 收集信息的数据收集器,数据持久化存储和管理的系统以及监控数据可视化工具(例如:Grafana 等)。 + +其中,部署在应用节点的 Agents 负责向 collectd/Statsd 提供不同来源的运行指标,collectd/StatsD 则负责将汇聚的数据推送到 OpenTSDB 集群系统,然后使用可视化看板 Grafana 将数据可视化呈现出来。 + +### 2、迁移服务 + +- **TDengine 安装部署** + +首先是 TDengine 的安装,从官网上下载 TDengine 最新稳定版,解压缩后运行 install.sh 进行安装。各种安装包的使用帮助请参见博客[《TDengine 多种安装包的安装和卸载》](https://www.taosdata.com/blog/2019/08/09/566.html)。 + +注意,安装完成以后,不要立即启动 taosd 服务,在正确配置完成参数以后再启动。 + +- **调整数据收集器配置** + +在 TDengine 2.3 版本中,我们发布了 taosAdapter ,taosAdapter 是一个无状态、可快速弹性伸缩的组件,它可以兼容 Influxdb 的 Line Protocol 和 OpenTSDB 的 telnet/JSON 写入协议规范,提供了丰富的数据接入能力,有效的节省用户迁移成本,降低用户应用迁移的难度。 + +用户可以根据需求弹性部署 taosAdapter 实例,结合场景的需要,快速提升数据写入的吞吐量,为不同应用场景下的数据写入提供保障。 + +通过 taosAdapter,用户可以将 collectd 和 StatsD 收集的数据直接推送到 TDengine ,实现应用场景的无缝迁移,非常的轻松便捷。taosAdapter 还支持 Telegraf、Icinga、TCollector 、node_exporter 的数据接入,使用详情参考[taosAdapter](https://www.taosdata.com/cn/documentation/tools/adapter)。 + +如果使用 collectd,修改其默认位置 `/etc/collectd/collectd.conf` 的配置文件为指向 taosAdapter 部署的节点 IP 地址和端口。假设 taosAdapter 的 IP 地址为 192.168.1.130,端口为 6046,配置如下: + +```html +LoadPlugin write_tsdb + + + Host "192.168.1.130" Port "6046" HostTags "status=production" StoreRates + false AlwaysAppendDS false + + +``` + +即可让 collectd 将数据使用推送到 OpenTSDB 的插件方式推送到 taosAdapter, taosAdapter 将调用 API 将数据写入到 taosd 中,从而完成数据的写入工作。如果你使用的是 StatsD 相应地调整配置文件信息。 + +- **调整看板(Dashborad)系统** + +在数据能够正常写入 TDengine 后,可以调整适配 Grafana 将写入 TDengine 的数据可视化呈现出来。获取和使用 TDengine 提供的 Grafana 插件请参考[与其他工具的连接](https://www.taosdata.com/cn/documentation/connections#grafana)。 + +TDengine 提供了默认的两套 Dashboard 模板,用户只需要将 Grafana 目录下的模板导入到 Grafana 中即可激活使用。 + +**图 2. 导入 Grafana 模板** +![](/img/IT-DevOps-Solutions-Immigrate-OpenTSDB-Dashboard.jpg "图2. 导入 Grafana 模板") + +操作完以上步骤后,就完成了将 OpenTSDB 替换成为 TDengine 的迁移工作。可以看到整个流程非常简单,不需要写代码,只需要对某些配置文件进行调整即可完成全部的迁移工作。 + +### 3、迁移后架构 + +完成迁移以后,此时的系统整体的架构如下图(图 3)所示,而整个过程中采集端、数据写入端、以及监控呈现端均保持了稳定,除了极少的配置调整外,不涉及任何重要的更改和变动。OpenTSDB 大量的应用场景均为 DevOps ,这种场景下,简单的参数设置即可完成 OpenTSDB 到 TDengine 迁移动作,使用上 TDengine 更加强大的处理能力和查询性能。 + +在绝大多数的 DevOps 场景中,如果你拥有一个小规模的 OpenTSDB 集群(3 台及以下的节点)作为 DevOps 的存储端,依赖于 OpenTSDB 为系统持久化层提供数据存储和查询功能,那么你可以安全地将其替换为 TDengine,并节约更多的计算和存储资源。在同等计算资源配置情况下,单台 TDengine 即可满足 3 ~ 5 台 OpenTSDB 节点提供的服务能力。如果规模比较大,那便需要采用 TDengine 集群。 + +如果你的应用特别复杂,或者应用领域并不是 DevOps 场景,你可以继续阅读后续的章节,更加全面深入地了解将 OpenTSDB 的应用迁移到 TDengine 的高级话题。 + +**图 3. 迁移完成后的系统架构** +![IT-DevOps-Solutions-Immigrate-TDengine-Arch](/img/IT-DevOps-Solutions-Immigrate-TDengine-Arch.jpg "图 3. 迁移完成后的系统架构") + +## 其他场景的迁移评估与策略 + +### 1、TDengine 与 OpenTSDB 的差异 + +本章将详细介绍 OpenTSDB 与 TDengine 在系统功能层面上存在的差异。阅读完本章的内容,你可以全面地评估是否能够将某些基于 OpenTSDB 的复杂应用迁移到 TDengine 上,以及迁移之后应该注意的问题。 + +TDengine 当前只支持 Grafana 的可视化看板呈现,所以如果你的应用中使用了 Grafana 以外的前端看板(例如[TSDash](https://github.com/facebook/tsdash)、[Status Wolf](https://github.com/box/StatusWolf)等),那么前端看板将无法直接迁移到 TDengine,需要将前端看板重新适配到 Grafana 才可以正常运行。 + +截止到 2.3.0.x 版本,TDengine 只能够支持 collectd 和 StatsD 作为数据收集汇聚软件,当然后面会陆续提供更多的数据收集聚合软件的接入支持。如果您的收集端使用了其他类型的数据汇聚器,您的应用需要适配到这两个数据汇聚端系统,才能够将数据正常写入。除了上述两个数据汇聚端软件协议以外,TDengine 还支持通过 InfluxDB 的行协议和 OpenTSDB 的数据写入协议、JSON 格式将数据直接写入,您可以重写数据推送端的逻辑,使用 TDengine 支持的行协议来写入数据。 + +此外,如果你的应用中使用了 OpenTSDB 以下特性,在将应用迁移到 TDengine 之前你还需要了解以下注意事项: + +1. ` /api/stats`:如果你的应用中使用了该项特性来监控 OpenTSDB 的服务状态,并在应用中建立了相关的逻辑来联动处理,那么这部分状态读取和获取的逻辑需要重新适配到 TDengine。TDengine 提供了全新的处理集群状态监控机制,来满足你的应用对其进行的监控和维护的需求。 +2. `/api/tree`:如果你依赖于 OpenTSDB 的该项特性来进行时间线的层级化组织和维护,那么便无法将其直接迁移至 TDengine。TDengine 采用了数据库->超级表->子表这样的层级来组织和维护时间线,归属于同一个超级表的所有的时间线在系统中同一个层级,但是可以通过不同标签值的特殊构造来模拟应用逻辑上的多级结构。 +3. `Rollup And PreAggregates`:采用了 Rollup 和 PreAggregates 需要应用来决定在合适的地方访问 Rollup 的结果,在某些场景下又要访问原始的结果,这种结构的不透明性让应用处理逻辑变得极为复杂而且完全不具有移植性。我们认为这种策略是时序数据库无法提供高性能聚合情况下的妥协与折中。TDengine 暂不支持多个时间线的自动降采样和(时间段范围的)预聚合,由于 其拥有的高性能查询处理逻辑,即使不依赖于 Rollup 和 (时间段)预聚合计算结果,也能够提供很高性能的查询响应,而且让你的应用查询处理逻辑更加简单。 +4. `Rate`: TDengine 提供了两个计算数值变化率的函数,分别是 Derivative(其计算结果与 InfluxDB 的 Derivative 行为一致)和 IRate(其计算结果与 Prometheus 中的 IRate 函数计算结果一致)。但是这两个函数的计算结果与 Rate 有细微的差别,但整体上功能更强大。此外,**OpenTSDB 提供的所有计算函数,TDengine 均有对应的查询函数支持,并且 TDengine 的查询函数功能远超过 OpenTSDB 支持的查询函数,**可以极大地简化你的应用处理逻辑。 + +通过上面的介绍,相信你应该能够了解 OpenTSDB 迁移到 TDengine 带来的变化,这些信息也有助于你正确地判断是否可以接受将应用 迁移到 TDengine 之上,体验 TDengine 提供的强大的时序数据处理能力和便捷的使用体验。 + +### 2、迁移策略 + +首先将基于 OpenTSDB 的系统进行迁移涉及到的数据模式设计、系统规模估算、数据写入端改造,进行数据分流、应用适配工作;之后将两个系统并行运行一段时间,再将历史数据迁移到 TDengine 中。当然如果你的应用中有部分功能强依赖于上述 OpenTSDB 特性,同时又不希望停止使用,可以考虑保持原有的 OpenTSDB 系统运行,同时启动 TDengine 来提供主要的服务。 + +## 数据模型设计 + +一方面,TDengine 要求其入库的数据具有严格的模式定义。另一方面,TDengine 的数据模型相对于 OpenTSDB 来说又更加丰富,多值模型能够兼容全部的单值模型的建立需求。 + +现在让我们假设一个 DevOps 的场景,我们使用了 collectd 收集设备的基础度量(metrics),包含了 memory 、swap、disk 等几个度量,其在 OpenTSDB 中的模式如下: + +| 序号 | 测量(metric) | 值名称 | 类型 | tag1 | tag2 | tag3 | tag4 | tag5 | +| ---- | -------------- | ------ | ------ | ---- | ----------- | -------------------- | --------- | ------ | +| 1 | memory | value | double | host | memory_type | memory_type_instance | source | n/a | +| 2 | swap | value | double | host | swap_type | swap_type_instance | source | n/a | +| 3 | disk | value | double | host | disk_point | disk_instance | disk_type | source | + +TDengine 要求存储的数据具有数据模式,即写入数据之前需创建超级表并指定超级表的模式。对于数据模式的建立,你有两种方式来完成此项工作:1)充分利用 TDengine 对 OpenTSDB 的数据原生写入的支持,调用 TDengine 提供的 API 将(文本行或 JSON 格式)数据写入,并自动化地建立单值模型。采用这种方式不需要对数据写入应用进行较大的调整,也不需要对写入的数据格式进行转换。 + +在 C 语言层面,TDengine 提供了 taos_insert_lines() 函数来直接写入 OpenTSDB 格式的数据(在 2.3.x 版本中该函数对应的是 taos_schemaless_insert())。其代码参考示例请参见安装包目录下示例代码 schemaless.c。 + +2)在充分理解 TDengine 的数据模型基础上,结合生成数据的特点,手动方式建立 OpenTSDB 到 TDengine 的数据模型调整的映射关系。TDengine 能够支持多值模型和单值模型,考虑到 OpenTSDB 均为单值映射模型,这里推荐使用单值模型在 TDengine 中进行建模。 + +- **单值模型**。 + +具体步骤如下:将度量(metrics)的名称作为 TDengine 超级表的名称,该超级表建成后具有两个基础的数据列—时间戳(timestamp)和值(value),超级表的标签等效于 度量 的标签信息,标签数量等同于度量 的标签的数量。子表的表名采用具有固定规则的方式进行命名:`metric + '_' + tags1_value + '_' + tag2_value + '_' + tag3_value ... `作为子表名称。 + +在 TDengine 中建立 3 个超级表: + +```sql +create stable memory(ts timestamp, val float) tags(host binary(12),memory_type binary(20), memory_type_instance binary(20), source binary(20)); +create stable swap(ts timestamp, val double) tags(host binary(12), swap_type binary(20), swap_type_binary binary(20), source binary(20)); +create stable disk(ts timestamp, val double) tags(host binary(12), disk_point binary(20), disk_instance binary(20), disk_type binary(20), source binary(20)); +``` + +对于子表使用动态建表的方式创建如下所示: + +```sql +insert into memory_vm130_memory_bufferred_collectd using memory tags(‘vm130’, ‘memory’, 'buffer', 'collectd') values(1632979445, 3.0656); +``` + +最终系统中会建立 340 个左右的子表,3 个超级表。需要注意的是,如果采用串联标签值的方式导致子表名称超过系统限制(191 字节),那么需要采用一定的编码方式(例如 MD5)将其转化为可接受长度。 + +- **多值模型** + +如果你想要利用 TDengine 的多值模型能力,需要首先满足以下要求:不同的采集量具有相同的采集频率,且能够通过消息队列**同时到达**数据写入端,从而确保使用 SQL 语句将多个指标一次性写入。将度量的名称作为超级表的名称,建立具有相同采集频率且能够同时到达的数据多列模型。子表的表名采用具有固定规则的方式进行命名。上述每个度量均只包含一个测量值,因此无法将其转化为多值模型。 + +## 数据分流与应用适配 + +从消息队列中订阅数据,并启动调整后的写入程序写入数据。 + +数据开始写入持续一段时间后,可以采用 SQL 语句检查写入的数据量是否符合预计的写入要求。统计数据量使用如下 SQL 语句: + +```sql +select count(*) from memory +``` + +完成查询后,如果写入的数据与预期的相比没有差别,同时写入程序本身没有异常的报错信息,那么可用确认数据写入是完整有效的。 + +TDengine 不支持采用 OpenTSDB 的查询语法进行查询或数据获取处理,但是针对 OpenTSDB 的每种查询都提供对应的支持。可以用检查附录 1 获取对应的查询处理的调整和应用使用的方式,如果需要全面了解 TDengine 支持的查询类型,请参阅 TDengine 的用户手册。 + +TDengine 支持标准的 JDBC 3.0 接口操纵数据库,你也可以使用其他类型的高级语言的连接器来查询读取数据,以适配你的应用。具体的操作和使用帮助也请参阅用户手册。 + +## 历史数据迁移 + +### 1、使用工具自动迁移数据 + +为了方便历史数据的迁移工作,我们为数据同步工具 DataX 提供了插件,能够将数据自动写入到 TDengine 中,需要注意的是 DataX 的自动化数据迁移只能够支持单值模型的数据迁移过程。 + +DataX 具体的使用方式及如何使用 DataX 将数据写入 TDengine 请参见[基于 DataX 的 TDeninge 数据迁移工具](https://www.taosdata.com/blog/2021/10/26/3156.html)。 + +在对 DataX 进行迁移实践后,我们发现通过启动多个进程,同时迁移多个 metric 的方式,可以大幅度的提高迁移历史数据的效率,下面是迁移过程中的部分记录,希望这些能为应用迁移工作带来参考。 + +| datax 实例个数 (并发进程个数) | 迁移记录速度 (条/秒) | +| ----------------------------- | --------------------- | +| 1 | 约 13.9 万 | +| 2 | 约 21.8 万 | +| 3 | 约 24.9 万 | +| 5 | 约 29.5 万 | +| 10 | 约 33 万 | + +
(注:测试数据源自 单节点 Intel(R) Core(TM) i7-10700 CPU@2.90GHz 16 核 64G 硬件设备,channel 和 batchSize 分别为 8 和 1000,每条记录包含 10 个 tag) + +### 2、手动迁移数据 + +如果你需要使用多值模型进行数据写入,就需要自行开发一个将数据从 OpenTSDB 导出的工具,然后确认哪些时间线能够合并导入到同一个时间线,再将可以同时导入的时间通过 SQL 语句的写入到数据库中。 + +手动迁移数据需要注意以下两个问题: + +1)在磁盘中存储导出数据时,磁盘需要有足够的存储空间以便能够充分容纳导出的数据文件。为了避免全量数据导出后导致磁盘文件存储紧张,可以采用部分导入的模式,对于归属于同一个超级表的时间线优先导出,然后将导出部分的数据文件导入到 TDengine 系统中。 + +2)在系统全负载运行下,如果有足够的剩余计算和 IO 资源,可以建立多线程的导入机制,最大限度地提升数据迁移的效率。考虑到数据解析对于 CPU 带来的巨大负载,需要控制最大的并行任务数量,以避免因导入历史数据而触发的系统整体过载。 + +由于 TDegnine 本身操作简易性,所以不需要在整个过程中进行索引维护、数据格式的变化处理等工作,整个过程只需要顺序执行即可。 + +当历史数据完全导入到 TDengine 以后,此时两个系统处于同时运行的状态,之后便可以将查询请求切换到 TDengine 上,从而实现无缝的应用切换。 + +## 附录 1: OpenTSDB 查询函数对应表 + +**Avg** + +等效函数:avg + +示例: + +SELECT avg(val) FROM (SELECT first(val) FROM super_table WHERE ts >= startTime and ts <= endTime INTERVAL(20s) Fill(linear)) INTERVAL(20s) + +备注: + +1. Interval 内的数值与外层查询的 interval 数值需要相同。 +2. 在 TDengine 中插值处理需要使用子查询来协助完成,如上所示,在内层查询中指明插值类型即可,由于 OpenTSDB 中数值的插值使用了线性插值,因此在插值子句中使用 fill(linear) 来声明插值类型。以下有相同插值计算需求的函数,均采用该方法处理。 +3. Interval 中参数 20s 表示将内层查询按照 20 秒一个时间窗口生成结果。在真实的查询中,需要调整为不同的记录之间的时间间隔。这样可确保等效于原始数据生成了插值结果。 +4. 由于 OpenTSDB 特殊的插值策略和机制,聚合查询(Aggregate)中先插值再计算的方式导致其计算结果与 TDengine 不可能完全一致。但是在降采样(Downsample)的情况下,TDengine 和 OpenTSDB 能够获得一致的结果(由于 OpenTSDB 在聚合查询和降采样查询中采用了完全不同的插值策略)。 + +**Count** + +等效函数:count + +示例: + +select count(\*) from super_table_name; + +**Dev** + +等效函数:stddev + +示例: + +Select stddev(val) from table_name + +**Estimated percentiles** + +等效函数:apercentile + +示例: + +Select apercentile(col1, 50, “t-digest”) from table_name + +备注: + +1. 近似查询处理过程中,OpenTSDB 默认采用 t-digest 算法,所以为了获得相同的计算结果,需要在 apercentile 函数中指明使用的算法。TDengine 能够支持两种不同的近似处理算法,分别通过“default”和“t-digest”来声明。 + +**First** + +等效函数:first + +示例: + +Select first(col1) from table_name + +**Last** + +等效函数:last + +示例: + +Select last(col1) from table_name + +**Max** + +等效函数:max + +示例: + +Select max(value) from (select first(val) value from table_name interval(10s) fill(linear)) interval(10s) + +备注:Max 函数需要插值,原因见上。 + +**Min** + +等效函数:min + +示例: + +Select min(value) from (select first(val) value from table_name interval(10s) fill(linear)) interval(10s); + +**MinMax** + +等效函数:max + +Select max(val) from table_name + +备注:该函数无插值需求,因此可用直接计算。 + +**MimMin** + +等效函数:min + +Select min(val) from table_name + +备注:该函数无插值需求,因此可用直接计算。 + +**Percentile** + +等效函数:percentile + +备注: + +**Sum** + +等效函数:sum + +Select max(value) from (select first(val) value from table_name interval(10s) fill(linear)) interval(10s) + +备注:该函数无插值需求,因此可用直接计算。 + +**Zimsum** + +等效函数:sum + +Select sum(val) from table_name + +备注:该函数无插值需求,因此可用直接计算。 + +完整示例: + +```json +// OpenTSDB 查询 JSON +query = { +“start”:1510560000, +“end”: 1515000009, +“queries”:[{ +“aggregator”: “count”, +“metric”:”cpu.usage_user”, +}] +} + +//等效查询 SQL: +SELECT count(*) +FROM `cpu.usage_user` +WHERE ts>=1510560000 AND ts<=1515000009 +``` + +## 附录 2: 资源估算方法 + +### 数据生成环境 + +我们仍然使用第 4 章中的假设环境,3 个测量值。分别是:温度和湿度的数据写入的速率是每 5 秒一条记录,时间线 10 万个。空气质量的写入速率是 10 秒一条记录,时间线 1 万个,查询的请求频率 500 QPS。 + +### 存储资源估算 + +假设产生数据并需要存储的传感器设备数量为 `n`,数据生成的频率为`t`条/秒,每条记录的长度为 `L` bytes,则每天产生的数据规模为 `n×t×L` bytes。假设压缩比为 C,则每日产生数据规模为 `(n×t×L)/C` bytes。存储资源预估为能够容纳 1.5 年的数据规模,生产环境下 TDengine 的压缩比 C 一般在 5 ~ 7 之间,同时为最后结果增加 20% 的冗余,可计算得到需要存储资源: + +```matlab +(n×t×L)×(365×1.5)×(1+20%)/C +``` + +结合以上的计算公式,将参数带入计算公式,在不考虑标签信息的情况下,每年产生的原始数据规模是 11.8TB。需要注意的是,由于标签信息在 TDengine 中关联到每个时间线,并不是每条记录。所以需要记录的数据量规模相对于产生的数据有一定的降低,而这部分标签数据整体上可以忽略不记。假设压缩比为 5,则保留的数据规模最终为 2.56 TB。 + +### 存储设备选型考虑 + +硬盘应该选用具有较好随机读性能的硬盘设备,如果能够有 SSD,尽可能考虑使用 SSD。较好的随机读性能的磁盘对于提升系统查询性能具有极大的帮助,能够整体上提升系统的查询响应性能。为了获得较好的查询性能,硬盘设备的单线程随机读 IOPS 的性能指标不应该低于 1000,能够达到 5000 IOPS 以上为佳。为了获得当前的设备随机读取的 IO 性能的评估,建议使用 fio 软件对其进行运行性能评估(具体的使用方式请参阅附录 1),确认其是否能够满足大文件随机读性能要求。 + +硬盘写性能对于 TDengine 的影响不大。TDengine 写入过程采用了追加写的模式,所以只要有较好的顺序写性能即可,一般意义上的 SAS 硬盘和 SSD 均能够很好地满足 TDengine 对于磁盘写入性能的要求。 + +### 计算资源估算 + +由于物联网数据的特殊性,数据产生的频率固定以后,TDengine 写入的过程对于(计算和存储)资源消耗都保持一个相对固定的量。《[TDengine 的运营与维护](https://www.taosdata.com/cn/documentation/administrator)》上的描述,该系统中每秒 22000 个写入,消耗 CPU 不到 1 个核。 + +在针对查询所需要消耗的 CPU 资源的估算上,假设应用要求数据库提供的 QPS 为 10000,每次查询消耗的 CPU 时间约 1 ms,那么每个核每秒提供的查询为 1000 QPS,满足 10000 QPS 的查询请求,至少需要 10 个核。为了让系统整体上 CPU 负载小于 50%,整个集群需要 10 个核的两倍,即 20 个核。 + +### 内存资源估算 + +数据库默认为每个 Vnode 分配内存 16MB\*3 缓冲区,集群系统包括 22 个 CPU 核,则默认会建立 22 个虚拟节点 Vnode,每个 Vnode 包含 1000 张表,则可以容纳所有的表。则约 1 个半小时写满一个 block,从而触发落盘,可以不做调整。22 个 Vnode 共计需要内存缓存约 1GB。考虑到查询所需要的内存,假设每次查询的内存开销约 50MB,则 500 个查询并发需要的内存约 25GB。 + +综上所述,可使用单台 16 核 32GB 的机器,或者使用 2 台 8 核 16GB 机器构成的集群。 + +## 附录 3: 集群部署及启动 + +TDengine 提供了丰富的帮助文档说明集群安装、部署的诸多方面的内容,这里提供响应的文档索引,供你参考。 + +### 集群部署 + +首先是安装 TDengine,从官网上下载 TDengine 最新稳定版,解压缩后运行 install.sh 进行安装。各种安装包的使用帮助请参见博客[《TDengine 多种安装包的安装和卸载》](https://www.taosdata.com/blog/2019/08/09/566.html)。 + +注意安装完成以后,不要立即启动 taosd 服务,在正确配置完成参数以后才启动 taosd 服务。 + +### 设置运行参数并启动服务 + +为确保系统能够正常获取运行的必要信息。请在服务端正确设置以下关键参数: + +FQDN、firstEp、secondEP、dataDir、logDir、tmpDir、serverPort。各参数的具体含义及设置的要求,可参见文档《[TDengine 集群安装、管理](https://www.taosdata.com/cn/documentation/cluster)》 + +按照相同的步骤,在需要运行的节点上设置参数,并启动 taosd 服务,然后添加 Dnode 到集群中。 + +最后启动 taos,执行命令 show dnodes,如果能看到所有的加入集群的节点,那么集群顺利搭建完成。具体的操作流程及注意事项,请参阅文档《[TDengine 集群安装、管理](https://www.taosdata.com/cn/documentation/cluster)》 + +## 附录 4: 超级表名称 + +由于 OpenTSDB 的 metric 名称中带有点号(“.“),例如“cpu.usage_user”这种名称的 metric。但是点号在 TDengine 中具有特殊含义,是用来分隔数据库和表名称的分隔符。TDengine 也提供转义符,以允许用户在(超级)表名称中使用关键词或特殊分隔符(如:点号)。为了使用特殊字符,需要采用转义字符将表的名称括起来,例如:`cpu.usage_user`这样就是合法的(超级)表名称。 + +## 附录 5:参考文章 + +1. [使用 TDengine + collectd/StatsD + Grafana 快速搭建 IT 运维监控系统](https://www.taosdata.com/cn/documentation20/devops/collectd) +2. [通过 collectd 将采集数据直接写入 TDengine](https://www.taosdata.com/cn/documentation20/insert#collectd) diff --git a/docs-cn/15-application/_category_.yml b/docs-cn/15-application/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..141c9269b50a2155391543ecea1dfe5c918e113c --- /dev/null +++ b/docs-cn/15-application/_category_.yml @@ -0,0 +1,4 @@ +label: 应用实践 +link: + slug: /application/ + type: generated-index diff --git a/docs-cn/16-iot-big-data/_category_.yml b/docs-cn/16-iot-big-data/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..0c389d56780a0eab585f4f0cee0311852037bc1f --- /dev/null +++ b/docs-cn/16-iot-big-data/_category_.yml @@ -0,0 +1 @@ +label: 物联网大数据 \ No newline at end of file diff --git a/docs-cn/16-iot-big-data/index.md b/docs-cn/16-iot-big-data/index.md new file mode 100644 index 0000000000000000000000000000000000000000..5687dd3fda161c426108dba298b73fc4db949c28 --- /dev/null +++ b/docs-cn/16-iot-big-data/index.md @@ -0,0 +1,7 @@ +# 物联网大数据 + + +- [物联网、工业互联网大数据的特点](https://www.taosdata.com/blog/2019/07/09/105.html) +- [物联网大数据平台应具备的功能和特点](https://www.taosdata.com/blog/2019/07/29/542.html) +- [通用大数据架构为什么不适合处理物联网数据?](https://www.taosdata.com/blog/2019/07/09/107.html) +- [物联网、车联网、工业互联网大数据平台,为什么推荐使用 TDengine?](https://www.taosdata.com/blog/2019/07/09/109.html) diff --git a/docs-cn/17-train-fqa/01-faq.md b/docs-cn/17-train-fqa/01-faq.md new file mode 100644 index 0000000000000000000000000000000000000000..9f3baccf7f765325129ac72bd4e62ede0c7e8e87 --- /dev/null +++ b/docs-cn/17-train-fqa/01-faq.md @@ -0,0 +1,222 @@ +# 常见问题及反馈 + +## 问题反馈 + +如果 FAQ 中的信息不能够帮到您,需要 TDengine 技术团队的技术支持与协助,请将以下两个目录中内容打包: + +1. /var/log/taos (如果没有修改过默认路径) +2. /etc/taos + +附上必要的问题描述,包括使用的 TDengine 版本信息、平台环境信息、发生该问题的执行操作、出现问题的表征及大概的时间,在 [GitHub](https://github.com/taosdata/TDengine) 提交 issue。 + +为了保证有足够的 debug 信息,如果问题能够重复,请修改/etc/taos/taos.cfg 文件,最后面添加一行“debugFlag 135"(不带引号本身),然后重启 taosd, 重复问题,然后再递交。也可以通过如下 SQL 语句,临时设置 taosd 的日志级别。 + +``` + alter dnode debugFlag 135; +``` + +但系统正常运行时,请一定将 debugFlag 设置为 131,否则会产生大量的日志信息,降低系统效率。 + +## 常见问题列表 + +**1. TDengine2.0 之前的版本升级到 2.0 及以上的版本应该注意什么?☆☆☆** + +2.0 版在之前版本的基础上,进行了完全的重构,配置文件和数据文件是不兼容的。在升级之前务必进行如下操作: + +1. 删除配置文件,执行 `sudo rm -rf /etc/taos/taos.cfg` +2. 删除日志文件,执行 `sudo rm -rf /var/log/taos/` +3. 确保数据已经不再需要的前提下,删除数据文件,执行 `sudo rm -rf /var/lib/taos/` +4. 安装最新稳定版本的 TDengine +5. 如果需要迁移数据或者数据文件损坏,请联系涛思数据官方技术支持团队,进行协助解决 + +**2. Windows 平台下 JDBCDriver 找不到动态链接库,怎么办?** + +请看为此问题撰写的[技术博客](https://www.taosdata.com/blog/2019/12/03/950.html)。 + +**3. 创建数据表时提示 more dnodes are needed** + +请看为此问题撰写的[技术博客](https://www.taosdata.com/blog/2019/12/03/965.html)。 + +**4. 如何让 TDengine crash 时生成 core 文件?** + +请看为此问题撰写的[技术博客](https://www.taosdata.com/blog/2019/12/06/974.html)。 + +**5. 遇到错误“Unable to establish connection”, 我怎么办?** + +客户端遇到连接故障,请按照下面的步骤进行检查: + +1. 检查网络环境 + + - 云服务器:检查云服务器的安全组是否打开 TCP/UDP 端口 6030-6042 的访问权限 + - 本地虚拟机:检查网络能否 ping 通,尽量避免使用`localhost` 作为 hostname + - 公司服务器:如果为 NAT 网络环境,请务必检查服务器能否将消息返回值客户端 + +2. 确保客户端与服务端版本号是完全一致的,开源社区版和企业版也不能混用 + +3. 在服务器,执行 `systemctl status taosd` 检查*taosd*运行状态。如果没有运行,启动*taosd* + +4. 确认客户端连接时指定了正确的服务器 FQDN (Fully Qualified Domain Name —— 可在服务器上执行 Linux 命令 hostname -f 获得),FQDN 配置参考:[一篇文章说清楚 TDengine 的 FQDN](https://www.taosdata.com/blog/2020/09/11/1824.html)。 + +5. ping 服务器 FQDN,如果没有反应,请检查你的网络,DNS 设置,或客户端所在计算机的系统 hosts 文件。如果部署的是 TDengine 集群,客户端需要能 ping 通所有集群节点的 FQDN。 + +6. 检查防火墙设置(Ubuntu 使用 ufw status,CentOS 使用 firewall-cmd --list-port),确认 TCP/UDP 端口 6030-6042 是打开的 + +7. 对于 Linux 上的 JDBC(ODBC, Python, Go 等接口类似)连接, 确保*libtaos.so*在目录*/usr/local/taos/driver*里, 并且*/usr/local/taos/driver*在系统库函数搜索路径*LD_LIBRARY_PATH*里 + +8. 对于 Windows 上的 JDBC, ODBC, Python, Go 等连接,确保*C:\TDengine\driver\taos.dll*在你的系统库函数搜索目录里 (建议*taos.dll*放在目录 _C:\Windows\System32_) + +9. 如果仍不能排除连接故障 + + - Linux 系统请使用命令行工具 nc 来分别判断指定端口的 TCP 和 UDP 连接是否通畅 + 检查 UDP 端口连接是否工作:`nc -vuz {hostIP} {port} ` + 检查服务器侧 TCP 端口连接是否工作:`nc -l {port}` + 检查客户端侧 TCP 端口连接是否工作:`nc {hostIP} {port}` + + - Windows 系统请使用 PowerShell 命令 Net-TestConnection -ComputerName {fqdn} -Port {port} 检测服务段端口是否访问 + +10. 也可以使用 taos 程序内嵌的网络连通检测功能,来验证服务器和客户端之间指定的端口连接是否通畅(包括 TCP 和 UDP):[TDengine 内嵌网络检测工具使用指南](https://www.taosdata.com/blog/2020/09/08/1816.html)。 + +**6. 遇到错误“Unexpected generic error in RPC”或者“Unable to resolve FQDN”,我怎么办?** + +产生这个错误,是由于客户端或数据节点无法解析 FQDN(Fully Qualified Domain Name)导致。对于 TAOS Shell 或客户端应用,请做如下检查: + +1. 请检查连接的服务器的 FQDN 是否正确,FQDN 配置参考:[一篇文章说清楚 TDengine 的 FQDN](https://www.taosdata.com/blog/2020/09/11/1824.html) +2. 如果网络配置有 DNS server,请检查是否正常工作 +3. 如果网络没有配置 DNS server,请检查客户端所在机器的 hosts 文件,查看该 FQDN 是否配置,并是否有正确的 IP 地址 +4. 如果网络配置 OK,从客户端所在机器,你需要能 Ping 该连接的 FQDN,否则客户端是无法连接服务器的 +5. 如果服务器曾经使用过 TDengine,且更改过 hostname,建议检查 data 目录的 dnodeEps.json 是否符合当前配置的 EP,路径默认为/var/lib/taos/dnode。正常情况下,建议更换新的数据目录或者备份后删除以前的数据目录,这样可以避免该问题。 +6. 检查/etc/hosts 和/etc/hostname 是否是预配置的 FQDN + +**7. 虽然语法正确,为什么我还是得到 "Invalid SQL" 错误** + +如果你确认语法正确,2.0 之前版本,请检查 SQL 语句长度是否超过 64K。如果超过,也会返回这个错误。 + +**8. 是否支持 validation queries?** + +TDengine 还没有一组专用的 validation queries。然而建议你使用系统监测的数据库”log"来做。 + + + +**9. 我可以删除或更新一条记录吗?** + +TDengine 目前尚不支持删除功能,未来根据用户需求可能会支持。 + +从 2.0.8.0 开始,TDengine 支持更新已经写入数据的功能。使用更新功能需要在创建数据库时使用 UPDATE 1 参数,之后可以使用 INSERT INTO 命令更新已经写入的相同时间戳数据。UPDATE 参数不支持 ALTER DATABASE 命令修改。没有使用 UPDATE 1 参数创建的数据库,写入相同时间戳的数据不会修改之前的数据,也不会报错。 + +另需注意,在 UPDATE 设置为 0 时,后发送的相同时间戳的数据会被直接丢弃,但并不会报错,而且仍然会被计入 affected rows (所以不能利用 INSERT 指令的返回信息进行时间戳查重)。这样设计的主要原因是,TDengine 把写入的数据看做一个数据流,无论时间戳是否出现冲突,TDengine 都认为产生数据的原始设备真实地产生了这样的数据。UPDATE 参数只是控制这样的流数据在进行持久化时要怎样处理——UPDATE 为 0 时,表示先写入的数据覆盖后写入的数据;而 UPDATE 为 1 时,表示后写入的数据覆盖先写入的数据。这种覆盖关系如何选择,取决于对数据的后续使用和统计中,希望以先还是后生成的数据为准。 + +此外,从 2.1.7.0 版本开始,支持将 UPDATE 参数设为 2,表示“支持部分列更新”。也即,当 UPDATE 设为 1 时,如果更新一个数据行,其中某些列没有提供取值,那么这些列会被设为 NULL;而当 UPDATE 设为 2 时,如果更新一个数据行,其中某些列没有提供取值,那么这些列会保持原有数据行中的对应值。 + +**10. 我怎么创建超过 1024 列的表?** + +使用 2.0 及其以上版本,默认支持 1024 列;2.0 之前的版本,TDengine 最大允许创建 250 列的表。但是如果确实超过限值,建议按照数据特性,逻辑地将这个宽表分解成几个小表。(从 2.1.7.0 版本开始,表的最大列数增加到了 4096 列。) + +**11. 最有效的写入数据的方法是什么?** + +批量插入。每条写入语句可以一张表同时插入多条记录,也可以同时插入多张表的多条记录。 + +**12. Windows 系统下插入的 nchar 类数据中的汉字被解析成了乱码如何解决?** + +Windows 下插入 nchar 类的数据中如果有中文,请先确认系统的地区设置成了中国(在 Control Panel 里可以设置),这时 cmd 中的`taos`客户端应该已经可以正常工作了;如果是在 IDE 里开发 Java 应用,比如 Eclipse, Intellij,请确认 IDE 里的文件编码为 GBK(这是 Java 默认的编码类型),然后在生成 Connection 时,初始化客户端的配置,具体语句如下: + +```JAVA +Class.forName("com.taosdata.jdbc.TSDBDriver"); +Properties properties = new Properties(); +properties.setProperty(TSDBDriver.LOCALE_KEY, "UTF-8"); +Connection = DriverManager.getConnection(url, properties); +``` + +**13.JDBC 报错: the excuted SQL is not a DML or a DDL?** + +请更新至最新的 JDBC 驱动 + +```xml + + com.taosdata.jdbc + taos-jdbcdriver + 2.0.27 + +``` + +**14. taos connect failed, reason: invalid timestamp** + +常见原因是服务器和客户端时间没有校准,可以通过和时间服务器同步的方式(Linux 下使用 ntpdate 命令,Windows 在系统时间设置中选择自动同步)校准。 + +**15. 表名显示不全** + +由于 taos shell 在终端中显示宽度有限,有可能比较长的表名显示不全,如果按照显示的不全的表名进行相关操作会发生 Table does not exist 错误。解决方法可以是通过修改 taos.cfg 文件中的设置项 maxBinaryDisplayWidth, 或者直接输入命令 set max_binary_display_width 100。或者在命令结尾使用 \G 参数来调整结果的显示方式。 + +**16. 如何进行数据迁移?** + +TDengine 是根据 hostname 唯一标志一台机器的,在数据文件从机器 A 移动机器 B 时,注意如下两件事: + +- 2.0.0.0 至 2.0.6.x 的版本,重新配置机器 B 的 hostname 为机器 A 的 hostname。 +- 2.0.7.0 及以后的版本,到/var/lib/taos/dnode 下,修复 dnodeEps.json 的 dnodeId 对应的 FQDN,重启。确保机器内所有机器的此文件是完全相同的。 +- 1.x 和 2.x 版本的存储结构不兼容,需要使用迁移工具或者自己开发应用导出导入数据。 + +**17. 如何在命令行程序 taos 中临时调整日志级别** + +为了调试方便,从 2.0.16 版本开始,命令行程序 taos 新增了与日志记录相关的两条指令: + +```sql +ALTER LOCAL flag_name flag_value; +``` + +其含义是,在当前的命令行程序下,修改一个特定模块的日志记录级别(只对当前命令行程序有效,如果 taos 命令行程序重启,则需要重新设置): + +- flag_name 的取值可以是:debugFlag,cDebugFlag,tmrDebugFlag,uDebugFlag,rpcDebugFlag +- flag_value 的取值可以是:131(输出错误和警告日志),135( 输出错误、警告和调试日志),143( 输出错误、警告、调试和跟踪日志) + +```sql +ALTER LOCAL RESETLOG; +``` + +其含义是,清空本机所有由客户端生成的日志文件。 + + + +**18. 时间戳的时区信息是怎样处理的?** + +TDengine 中时间戳的时区总是由客户端进行处理,而与服务端无关。具体来说,客户端会对 SQL 语句中的时间戳进行时区转换,转为 UTC 时区(即 Unix 时间戳——Unix Timestamp)再交由服务端进行写入和查询;在读取数据时,服务端也是采用 UTC 时区提供原始数据,客户端收到后再根据本地设置,把时间戳转换为本地系统所要求的时区进行显示。 + +客户端在处理时间戳字符串时,会采取如下逻辑: + +1. 在未做特殊设置的情况下,客户端默认使用所在操作系统的时区设置。 +2. 如果在 taos.cfg 中设置了 timezone 参数,则客户端会以这个配置文件中的设置为准。 +3. 如果在 C/C++/Java/Python 等各种编程语言的 Connector Driver 中,在建立数据库连接时显式指定了 timezone,那么会以这个指定的时区设置为准。例如 Java Connector 的 JDBC URL 中就有 timezone 参数。 +4. 在书写 SQL 语句时,也可以直接使用 Unix 时间戳(例如 `1554984068000`)或带有时区的时间戳字符串,也即以 RFC 3339 格式(例如 `2013-04-12T15:52:01.123+08:00`)或 ISO-8601 格式(例如 `2013-04-12T15:52:01.123+0800`)来书写时间戳,此时这些时间戳的取值将不再受其他时区设置的影响。 + + + +**19. TDengine 都会用到哪些网络端口?** + +在 TDengine 2.0 版本中,会用到以下这些网络端口(以默认端口 6030 为前提进行说明,如果修改了配置文件中的设置,那么这里列举的端口都会出现变化),管理员可以参考这里的信息调整防火墙设置: + +| 协议 | 默认端口 | 用途说明 | 修改方法 | +| :--- | :-------- | :---------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | +| TCP | 6030 | 客户端与服务端之间通讯。 | 由配置文件设置 serverPort 决定。 | +| TCP | 6035 | 多节点集群的节点间通讯。 | 随 serverPort 端口变化。 | +| TCP | 6040 | 多节点集群的节点间数据同步。 | 随 serverPort 端口变化。 | +| TCP | 6041 | 客户端与服务端之间的 RESTful 通讯。 | 随 serverPort 端口变化。注意 taosAdapter 配置或有不同,请参考相应[文档](https://www.taosdata.com/cn/documentation/tools/adapter)。 | +| TCP | 6042 | Arbitrator 的服务端口。 | 随 Arbitrator 启动参数设置变化。 | +| TCP | 6043 | TaosKeeper 监控服务端口。 | 随 TaosKeeper 启动参数设置变化。 | +| TCP | 6044 | 支持 StatsD 的数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | +| TCP | 6045 | 支持 collectd 数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | +| TCP | 6060 | 企业版内 Monitor 服务的网络端口。 | | +| UDP | 6030-6034 | 客户端与服务端之间通讯。 | 随 serverPort 端口变化。 | +| UDP | 6035-6039 | 多节点集群的节点间通讯。 | 随 serverPort 端口变化。 | + +**20. go 语言编写组件编译失败怎样解决?** + +新版本 TDengine 2.3.0.0 包含一个使用 go 语言开发的 taosAdapter 独立组件,需要单独运行,取代之前 taosd 内置的 httpd ,提供包含原 httpd 功能以及支持多种其他软件(Prometheus、Telegraf、collectd、StatsD 等)的数据接入功能。 +使用最新 develop 分支代码编译需要先 `git submodule update --init --recursive` 下载 taosAdapter 仓库代码后再编译。 + +目前编译方式默认自动编译 taosAdapter。go 语言版本要求 1.14 以上,如果发生 go 编译错误,往往是国内访问 go mod 问题,可以通过设置 go 环境变量来解决: + +```sh +go env -w GO111MODULE=on +go env -w GOPROXY=https://goproxy.cn,direct +``` + +如果希望继续使用之前的内置 httpd,可以关闭 taosAdapter 编译,使用 +`cmake .. -DBUILD_HTTP=true` 使用原来内置的 httpd。 diff --git a/docs-cn/17-train-fqa/02-video.mdx b/docs-cn/17-train-fqa/02-video.mdx new file mode 100644 index 0000000000000000000000000000000000000000..767b154fd34f3898a269bb505999a9de2bf11799 --- /dev/null +++ b/docs-cn/17-train-fqa/02-video.mdx @@ -0,0 +1,25 @@ +# 视频教程 + +## + +## 技术公开课 + +- [技术公开课:开源、高效的物联网大数据平台,TDengine 内核技术剖析](https://www.taosdata.com/blog/2020/12/25/2126.html) + +## 视频教程 + +- [TDengine 视频教程 - 快速上手](https://www.taosdata.com/blog/2020/11/11/1941.html) +- [TDengine 视频教程 - 数据建模](https://www.taosdata.com/blog/2020/11/11/1945.html) +- [TDengine 视频教程 - 集群搭建](https://www.taosdata.com/blog/2020/11/11/1961.html) +- [TDengine 视频教程 - Go Connector](https://www.taosdata.com/blog/2020/11/11/1951.html) +- [TDengine 视频教程 - JDBC Connector](https://www.taosdata.com/blog/2020/11/11/1955.html) +- [TDengine 视频教程 - Node.js Connector](https://www.taosdata.com/blog/2020/11/11/1957.html) +- [TDengine 视频教程 - Python Connector](https://www.taosdata.com/blog/2020/11/11/1963.html) +- [TDengine 视频教程 - RESTful Connector](https://www.taosdata.com/blog/2020/11/11/1965.html) +- [TDengine 视频教程 - “零”代码运维监控](https://www.taosdata.com/blog/2020/11/11/1959.html) + +## 微课堂 + +关注 TDengine 视频号, 有精心制作的微课堂。 + + diff --git a/docs-cn/17-train-fqa/03-docker.md b/docs-cn/17-train-fqa/03-docker.md new file mode 100644 index 0000000000000000000000000000000000000000..54b94c9abae50d5a6581ed4bce321bc5d5e761f3 --- /dev/null +++ b/docs-cn/17-train-fqa/03-docker.md @@ -0,0 +1,328 @@ +# 通过 Docker 快速体验 TDengine + +虽然并不推荐在生产环境中通过 Docker 来部署 TDengine 服务,但 Docker 工具能够很好地屏蔽底层操作系统的环境差异,很适合在开发测试或初次体验时用于安装运行 TDengine 的工具集。特别是,借助 Docker,能够比较方便地在 macOS 和 Windows 系统上尝试 TDengine,而无需安装虚拟机或额外租用 Linux 服务器。另外,从 2.0.14.0 版本开始,TDengine 提供的镜像已经可以同时支持 X86-64、X86、arm64、arm32 平台,像 NAS、树莓派、嵌入式开发板之类可以运行 docker 的非主流计算机也可以基于本文档轻松体验 TDengine。 + +下文通过 Step by Step 风格的介绍,讲解如何通过 Docker 快速建立 TDengine 的单节点运行环境,以支持开发和测试。 + +## 下载 Docker + +Docker 工具自身的下载请参考 [Docker 官网文档](https://docs.docker.com/get-docker/)。 + +安装完毕后可以在命令行终端查看 Docker 版本。如果版本号正常输出,则说明 Docker 环境已经安装成功。 + +```bash +$ docker -v +Docker version 20.10.3, build 48d30b5 +``` + +## 使用 Docker 在容器中运行 TDengine + +### 在 Docker 容器中运行 TDengine server + +```bash +$ docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp tdengine/tdengine +526aa188da767ae94b244226a2b2eec2b5f17dd8eff592893d9ec0cd0f3a1ccd +``` + +这条命令,启动一个运行了 TDengine server 的 docker 容器,并且将容器的 6030 到 6049 端口映射到宿主机的 6030 到 6049 端口上。如果宿主机已经运行了 TDengine server 并占用了相同端口,需要映射容器的端口到不同的未使用端口段。(详情参见 [TDengine 2.0 端口说明](https://www.taosdata.com/cn/documentation/faq#port))。为了支持 TDengine 客户端操作 TDengine server 服务, TCP 和 UDP 端口都需要打开。 + +- **docker run**:通过 Docker 运行一个容器 +- **-d**:让容器在后台运行 +- **-p**:指定映射端口。注意:如果不是用端口映射,依然可以进入 Docker 容器内部使用 TDengine 服务或进行应用开发,只是不能对容器外部提供服务 +- **tdengine/tdengine**:拉取的 TDengine 官方发布的应用镜像 +- **526aa188da767ae94b244226a2b2eec2b5f17dd8eff592893d9ec0cd0f3a1ccd**:这个返回的长字符是容器 ID,我们也可以通过容器 ID 来查看对应的容器 + +进一步,还可以使用 docker run 命令启动运行 TDengine server 的 docker 容器,并使用 `--name` 命令行参数将容器命名为 `tdengine`,使用 `--hostname` 指定 hostname 为 `tdengine-server`,通过 `-v` 挂载本地目录到容器,实现宿主机与容器内部的数据同步,防止容器删除后,数据丢失。 + +```bash +docker run -d --name tdengine --hostname="tdengine-server" -v ~/work/taos/log:/var/log/taos -v ~/work/taos/data:/var/lib/taos -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp tdengine/tdengine +``` + +- **--name tdengine**:设置容器名称,我们可以通过容器名称来访问对应的容器 +- **--hostname=tdengine-server**:设置容器内 Linux 系统的 hostname,我们可以通过映射 hostname 和 IP 来解决容器 IP 可能变化的问题。 +- **-v**:设置宿主机文件目录映射到容器内目录,避免容器删除后数据丢失。 + +### 使用 docker ps 命令确认容器是否已经正确运行 + +```bash +docker ps +``` + +输出示例如下: + +``` +CONTAINER ID IMAGE COMMAND CREATED STATUS ··· +c452519b0f9b tdengine/tdengine "taosd" 14 minutes ago Up 14 minutes ··· +``` + +- **docker ps**:列出所有正在运行状态的容器信息。 +- **CONTAINER ID**:容器 ID。 +- **IMAGE**:使用的镜像。 +- **COMMAND**:启动容器时运行的命令。 +- **CREATED**:容器创建时间。 +- **STATUS**:容器状态。UP 表示运行中。 + +### 通过 docker exec 命令,进入到 docker 容器中去做开发 + +```bash +$ docker exec -it tdengine /bin/bash +root@tdengine-server:~/TDengine-server-2.4.0.4# +``` + +- **docker exec**:通过 docker exec 命令进入容器,如果退出,容器不会停止。 +- **-i**:进入交互模式。 +- **-t**:指定一个终端。 +- **tdengine**:容器名称,需要根据 docker ps 指令返回的值进行修改。 +- **/bin/bash**:载入容器后运行 bash 来进行交互。 + +进入容器后,执行 taos shell 客户端程序。 + +```bash +root@tdengine-server:~/TDengine-server-2.4.0.4# taos + +Welcome to the TDengine shell from Linux, Client Version:2.4.0.4 +Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. + +taos> +``` + +TDengine 终端成功连接服务端,打印出了欢迎消息和版本信息。如果失败,会有错误信息打印出来。 + +在 TDengine 终端中,可以通过 SQL 命令来创建/删除数据库、表、超级表等,并可以进行插入和查询操作。具体可以参考 [TAOS SQL 说明文档](https://www.taosdata.com/cn/documentation/taos-sql)。 + +### 在宿主机访问 Docker 容器中的 TDengine server + +在使用了 -p 命令行参数映射了正确的端口启动了 TDengine Docker 容器后,就在宿主机使用 taos shell 命令即可访问运行在 Docker 容器中的 TDengine。 + +``` +$ taos + +Welcome to the TDengine shell from Linux, Client Version:2.4.0.4 +Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. + +taos> +``` + +也可以在宿主机使用 curl 通过 RESTful 端口访问 Docker 容器内的 TDengine server。 + +``` +curl -u root:taosdata -d 'show databases' 127.0.0.1:6041/rest/sql +``` + +输出示例如下: + +``` +{"status":"succ","head":["name","created_time","ntables","vgroups","replica","quorum","days","keep0,keep1,keep(D)","cache(MB)","blocks","minrows","maxrows","wallevel","fsync","comp","cachelast","precision","update","status"],"column_meta":[["name",8,32],["created_time",9,8],["ntables",4,4],["vgroups",4,4],["replica",3,2],["quorum",3,2],["days",3,2],["keep0,keep1,keep(D)",8,24],["cache(MB)",4,4],["blocks",4,4],["minrows",4,4],["maxrows",4,4],["wallevel",2,1],["fsync",4,4],["comp",2,1],["cachelast",2,1],["precision",8,3],["update",2,1],["status",8,10]],"data":[["test","2021-08-18 06:01:11.021",10000,4,1,1,10,"3650,3650,3650",16,6,100,4096,1,3000,2,0,"ms",0,"ready"],["log","2021-08-18 05:51:51.065",4,1,1,1,10,"30,30,30",1,3,100,4096,1,3000,2,0,"us",0,"ready"]],"rows":2} +``` + +这条命令,通过 RESTful 接口访问 TDengine server,这时连接的是本机的 6041 端口,可见连接成功。 + +TDengine RESTful 接口详情请参考[官方文档](https://www.taosdata.com/cn/documentation/connector#restful)。 + +### 使用 Docker 容器运行 TDengine server 和 taosAdapter + +在 TDegnine 2.4.0.0 之后版本的 Docker 容器,开始提供一个独立运行的组件 taosAdapter,代替之前版本 TDengine 中 taosd 进程中内置的 http server。taosAdapter 支持通过 RESTful 接口对 TDengine server 的数据写入和查询能力,并提供和 InfluxDB/OpenTSDB 兼容的数据摄取接口,允许 InfluxDB/OpenTSDB 应用程序无缝移植到 TDengine。在新版本 Docker 镜像中,默认启用了 taosAdapter,也可以使用 docker run 命令中设置 TAOS_DISABLE_ADAPTER=true 来禁用 taosAdapter;也可以在 docker run 命令中单独使用 taosAdapter,而不运行 taosd 。 + +注意:如果容器中运行 taosAdapter,需要根据需要映射其他端口,具体端口默认配置和修改方法请参考[taosAdapter 文档](https://github.com/taosdata/taosadapter/blob/develop/README-CN.md)。 + +使用 docker 运行 TDengine 2.4.0.4 版本镜像(taosd + taosAdapter): + +```bash +docker run -d --name tdengine-all -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp tdengine/tdengine:2.4.0.4 +``` + +使用 docker 运行 TDengine 2.4.0.4 版本镜像(仅 taosAdapter,需要设置 firstEp 配置项 或 TAOS_FIRST_EP 环境变量): + +```bash +docker run -d --name tdengine-taosa -p 6041-6049:6041-6049 -p 6041-6049:6041-6049/udp -e TAOS_FIRST_EP=tdengine-all tdengine/tdengine:2.4.0.4 taosadapter +``` + +使用 docker 运行 TDengine 2.4.0.4 版本镜像(仅 taosd): + +```bash +docker run -d --name tdengine-taosd -p 6030-6042:6030-6042 -p 6030-6042:6030-6042/udp -e TAOS_DISABLE_ADAPTER=true tdengine/tdengine:2.4.0.4 +``` + +使用 curl 命令验证 RESTful 接口可以正常工作: + +```bash +curl -H 'Authorization: Basic cm9vdDp0YW9zZGF0YQ==' -d 'show databases;' 127.0.0.1:6041/rest/sql +``` + +输出示例如下: + +``` +{"status":"succ","head":["name","created_time","ntables","vgroups","replica","quorum","days","keep","cache(MB)","blocks","minrows","maxrows","wallevel","fsync","comp","cachelast","precision","update","status"],"column_meta":[["name",8,32],["created_time",9,8],["ntables",4,4],["vgroups",4,4],["replica",3,2],["quorum",3,2],["days",3,2],["keep",8,24],["cache(MB)",4,4],["blocks",4,4],["minrows",4,4],["maxrows",4,4],["wallevel",2,1],["fsync",4,4],["comp",2,1],["cachelast",2,1],["precision",8,3],["update",2,1],["status",8,10]],"data":[["log","2021-12-28 09:18:55.765",10,1,1,1,10,"30",1,3,100,4096,1,3000,2,0,"us",0,"ready"]],"rows":1} +``` + +### 应用示例:在宿主机使用 taosBenchmark 写入数据到 Docker 容器中的 TDengine server + +1. 在宿主机命令行界面执行 taosBenchmark (曾命名为 taosdemo)写入数据到 Docker 容器中的 TDengine server + + ```bash + $ taosBenchmark + + taosBenchmark is simulating data generated by power equipments monitoring... + + host: 127.0.0.1:6030 + user: root + password: taosdata + configDir: + resultFile: ./output.txt + thread num of insert data: 10 + thread num of create table: 10 + top insert interval: 0 + number of records per req: 30000 + max sql length: 1048576 + database count: 1 + database[0]: + database[0] name: test + drop: yes + replica: 1 + precision: ms + super table count: 1 + super table[0]: + stbName: meters + autoCreateTable: no + childTblExists: no + childTblCount: 10000 + childTblPrefix: d + dataSource: rand + iface: taosc + insertRows: 10000 + interlaceRows: 0 + disorderRange: 1000 + disorderRatio: 0 + maxSqlLen: 1048576 + timeStampStep: 1 + startTimestamp: 2017-07-14 10:40:00.000 + sampleFormat: + sampleFile: + tagsFile: + columnCount: 3 + column[0]:FLOAT column[1]:INT column[2]:FLOAT + tagCount: 2 + tag[0]:INT tag[1]:BINARY(16) + + Press enter key to continue or Ctrl-C to stop + ``` + + 回车后,该命令将在数据库 test 下面自动创建一张超级表 meters,该超级表下有 1 万张表,表名为 "d0" 到 "d9999",每张表有 1 万条记录,每条记录有 (ts, current, voltage, phase) 四个字段,时间戳从 "2017-07-14 10:40:00 000" 到 "2017-07-14 10:40:09 999",每张表带有标签 location 和 groupId,groupId 被设置为 1 到 10, location 被设置为 "beijing" 或者 "shanghai"。 + + 最后共插入 1 亿条记录。 + +2. 进入 TDengine 终端,查看 taosBenchmark 生成的数据。 + + - **进入命令行。** + + ```bash + $ root@c452519b0f9b:~/TDengine-server-2.4.0.4# taos + + Welcome to the TDengine shell from Linux, Client Version:2.4.0.4 + Copyright (c) 2020 by TAOS Data, Inc. All rights reserved. + + taos> + ``` + + - **查看数据库。** + + ```bash + $ taos> show databases; + name | created_time | ntables | vgroups | ··· + test | 2021-08-18 06:01:11.021 | 10000 | 6 | ··· + log | 2021-08-18 05:51:51.065 | 4 | 1 | ··· + + ``` + + - **查看超级表。** + + ```bash + $ taos> use test; + Database changed. + + $ taos> show stables; + name | created_time | columns | tags | tables | + ============================================================================================ + meters | 2021-08-18 06:01:11.116 | 4 | 2 | 10000 | + Query OK, 1 row(s) in set (0.003259s) + + ``` + + - **查看表,限制输出十条。** + + ```bash + $ taos> select * from test.t0 limit 10; + + DB error: Table does not exist (0.002857s) + taos> select * from test.d0 limit 10; + ts | current | voltage | phase | + ====================================================================================== + 2017-07-14 10:40:00.000 | 10.12072 | 223 | 0.34167 | + 2017-07-14 10:40:00.001 | 10.16103 | 224 | 0.34445 | + 2017-07-14 10:40:00.002 | 10.00204 | 220 | 0.33334 | + 2017-07-14 10:40:00.003 | 10.00030 | 220 | 0.33333 | + 2017-07-14 10:40:00.004 | 9.84029 | 216 | 0.32222 | + 2017-07-14 10:40:00.005 | 9.88028 | 217 | 0.32500 | + 2017-07-14 10:40:00.006 | 9.88110 | 217 | 0.32500 | + 2017-07-14 10:40:00.007 | 10.08137 | 222 | 0.33889 | + 2017-07-14 10:40:00.008 | 10.12063 | 223 | 0.34167 | + 2017-07-14 10:40:00.009 | 10.16086 | 224 | 0.34445 | + Query OK, 10 row(s) in set (0.016791s) + + ``` + + - **查看 d0 表的标签值。** + + ```bash + $ taos> select groupid, location from test.d0; + groupid | location | + ================================= + 0 | shanghai | + Query OK, 1 row(s) in set (0.003490s) + ``` + +### 应用示例:使用数据收集代理软件写入 TDengine + +taosAdapter 支持多个数据收集代理软件(如 Telegraf、StatsD、collectd 等),这里仅模拟 StasD 写入数据,在宿主机执行命令如下: + +``` +echo "foo:1|c" | nc -u -w0 127.0.0.1 6044 +``` + +然后可以使用 taos shell 查询 taosAdapter 自动创建的数据库 statsd 和 超级表 foo 中的内容: + +``` +taos> show databases; + name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | +==================================================================================================================================================================================================================================================================================== + log | 2021-12-28 09:18:55.765 | 12 | 1 | 1 | 1 | 10 | 30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | 0 | us | 0 | ready | + statsd | 2021-12-28 09:21:48.841 | 1 | 1 | 1 | 1 | 10 | 3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | 0 | ns | 2 | ready | +Query OK, 2 row(s) in set (0.002112s) + +taos> use statsd; +Database changed. + +taos> show stables; + name | created_time | columns | tags | tables | +============================================================================================ + foo | 2021-12-28 09:21:48.894 | 2 | 1 | 1 | +Query OK, 1 row(s) in set (0.001160s) + +taos> select * from foo; + ts | value | metric_type | +======================================================================================= + 2021-12-28 09:21:48.840820836 | 1 | counter | +Query OK, 1 row(s) in set (0.001639s) + +taos> +``` + +可以看到模拟数据已经被写入到 TDengine 中。 + +## 停止正在 Docker 中运行的 TDengine 服务 + +```bash +docker stop tdengine +``` + +- **docker stop**:通过 docker stop 停止指定的正在运行中的 docker 镜像。 diff --git a/docs-cn/17-train-fqa/_category_.yml b/docs-cn/17-train-fqa/_category_.yml new file mode 100644 index 0000000000000000000000000000000000000000..034d5894b9aea00e43caf4df21cb39487d8baf7b --- /dev/null +++ b/docs-cn/17-train-fqa/_category_.yml @@ -0,0 +1,4 @@ +label: FAQ、教程及其它 +link: + slug: /train-faq/ + type: generated-index diff --git a/docs-examples/.gitignore b/docs-examples/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7ed6d403bf5f64c0cb230265b4dffee609dea93b --- /dev/null +++ b/docs-examples/.gitignore @@ -0,0 +1,3 @@ +.vscode +*.lock +.idea \ No newline at end of file diff --git a/docs-examples/.gitignre b/docs-examples/.gitignre new file mode 100644 index 0000000000000000000000000000000000000000..0853156c65c2c6c1b693290e74c3ee630bcaac19 --- /dev/null +++ b/docs-examples/.gitignre @@ -0,0 +1,2 @@ +.vscode +*.lock \ No newline at end of file diff --git a/docs-examples/c/.gitignore b/docs-examples/c/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..afe974314989a1e3aa4eee703738a9a960c18577 --- /dev/null +++ b/docs-examples/c/.gitignore @@ -0,0 +1,3 @@ +* +!*.c +!.gitignore diff --git a/docs-examples/c/connect_example b/docs-examples/c/connect_example new file mode 100644 index 0000000000000000000000000000000000000000..1d9451cbf6724d51dbbc9baeba97d779461b2a5d Binary files /dev/null and b/docs-examples/c/connect_example differ diff --git a/docs-examples/c/connect_example.c b/docs-examples/c/connect_example.c new file mode 100644 index 0000000000000000000000000000000000000000..a64bc43361a05ba91b8637a15c7379fc3a2aef12 --- /dev/null +++ b/docs-examples/c/connect_example.c @@ -0,0 +1,13 @@ +// compile with +// gcc connect_example.c -o connect_example -I /usr/local/taos/include -L /usr/local/taos/driver -ltaos +#include +#include "taos.h" +#include "taoserror.h" + +int main() { + // if don't want to connect to a default db, set it to NULL. + const char *db = NULL; + TAOS *taos = taos_connect("localhost", "root", "taosdata", db, 6030); + printf("Connected\n"); + taos_close(taos); +} diff --git a/docs-examples/c/json_protocol_example.c b/docs-examples/c/json_protocol_example.c new file mode 100644 index 0000000000000000000000000000000000000000..b528770f14b24eb768cb2393d651a1f8bfa1dc79 --- /dev/null +++ b/docs-examples/c/json_protocol_example.c @@ -0,0 +1,67 @@ +// compile with +// gcc connect_example.c -o connect_example -I /usr/local/taos/include -L /usr/local/taos/driver -ltaos +#include +#include "taos.h" +#include "taoserror.h" + +int main() { + // if don't want to connect to a default db, set it to NULL. + const char *db = "test"; + TAOS *taos = taos_connect("localhost", "root", "taosdata", db, 6030); + printf("Connected\n"); + char *message[] = { +"[ \ + { \ + \"metric\":\"cpu_load_1\", \ + \"timestamp\": 1626006833, \ + \"value\": 55.5, \ + \"tags\": \ + { \ + \"host\": \"ubuntu\", \ + \"interface\": \"eth1\", \ + \"Id\": \"tb1\" \ + } \ + }, \ + { \ + \"metric\":\"cpu_load_2\", \ + \"timestamp\": 1626006833, \ + \"value\": 55.5, \ + \"tags\": \ + { \ + \"host\": \"ubuntu\", \ + \"interface\": \"eth2\", \ + \"Id\": \"tb2\" \ + } \ + } \ + ]", + "[ \ + { \ + \"metric\":\"cpu_load_1\", \ + \"timestamp\": 1626006834, \ + \"value\": 56.5, \ + \"tags\": \ + { \ + \"host\": \"ubuntu\", \ + \"interface\": \"eth1\", \ + \"Id\": \"tb1\" \ + } \ + }, \ + { \ + \"metric\":\"cpu_load_2\", \ + \"timestamp\": 1626006834, \ + \"value\": 56.5, \ + \"tags\": \ + { \ + \"host\": \"ubuntu\", \ + \"interface\": \"eth2\", \ + \"Id\": \"tb2\" \ + } \ + } \ + ]" + }; +void* code = taos_schemaless_insert(taos, message, 1, 3, NULL); +if (code) { + printf("payload_1 code: %d, %s.\n", code, tstrerror(code)); +} + taos_close(taos); +} diff --git a/docs-examples/csharp/.gitignore b/docs-examples/csharp/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b3aff79f3706e23aa74199a7f521f7912d2b0e45 --- /dev/null +++ b/docs-examples/csharp/.gitignore @@ -0,0 +1,4 @@ +bin +obj +.vs +*.sln \ No newline at end of file diff --git a/docs-examples/csharp/AsyncQueryExample.cs b/docs-examples/csharp/AsyncQueryExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..152d5fb8227722851f11e122122c35fca164a0a8 --- /dev/null +++ b/docs-examples/csharp/AsyncQueryExample.cs @@ -0,0 +1,237 @@ +using TDengineDriver; +using System.Runtime.InteropServices; + +namespace TDengineExample +{ + public class AsyncQuerySample + { + static void Main() { + IntPtr conn = GetConnection(); + QueryAsyncCallback queryAsyncCallback = new QueryAsyncCallback(QueryCallback); + TDengine.QueryAsync(conn, "select * from meters", queryAsyncCallback, IntPtr.Zero); + Thread.Sleep(2000); + TDengine.Close(conn); + TDengine.Cleanup(); + } + + static void QueryCallback(IntPtr param, IntPtr taosRes, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchRowCallback); + TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param); + } + else + { + Console.WriteLine($"async query data failed, failed code {code}"); + } + } + + static void FetchRowCallback(IntPtr param, IntPtr taosRes, int numOfRows) + { + if (numOfRows > 0) + { + Console.WriteLine($"{numOfRows} rows async retrieved"); + DisplayRes(taosRes); + TDengine.FetchRowAsync(taosRes, FetchRowCallback, param); + } + else + { + if (numOfRows == 0) + { + Console.WriteLine("async retrieve complete."); + + } + else + { + Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}"); + } + TDengine.FreeResult(taosRes); + } + } + + public static void DisplayRes(IntPtr res) + { + if (!IsValidResult(res)) + { + TDengine.Cleanup(); + System.Environment.Exit(1); + } + + List metaList = TDengine.FetchFields(res); + int fieldCount = metaList.Count; + // metaList.ForEach((item) => { Console.Write("{0} ({1}) \t|\t", item.name, item.size); }); + + List dataList = QueryRes(res, metaList); + for (int index = 0; index < dataList.Count; index++) + { + if (index % fieldCount == 0 && index != 0) + { + Console.WriteLine(""); + } + Console.Write("{0} \t|\t", dataList[index].ToString()); + + } + Console.WriteLine(""); + } + + public static bool IsValidResult(IntPtr res) + { + if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) + { + if (res != IntPtr.Zero) + { + Console.Write("reason: " + TDengine.Error(res)); + return false; + } + Console.WriteLine(""); + return false; + } + return true; + } + + private static List QueryRes(IntPtr res, List meta) + { + IntPtr taosRow; + List dataRaw = new(); + while ((taosRow = TDengine.FetchRows(res)) != IntPtr.Zero) + { + dataRaw.AddRange(FetchRow(taosRow, res)); + } + if (TDengine.ErrorNo(res) != 0) + { + Console.Write("Query is not complete, Error {0} {1}", TDengine.ErrorNo(res), TDengine.Error(res)); + } + TDengine.FreeResult(res); + Console.WriteLine(""); + return dataRaw; + } + + public static List FetchRow(IntPtr taosRow, IntPtr taosRes)//, List metaList, int numOfFiled + { + List metaList = TDengine.FetchFields(taosRes); + int numOfFiled = TDengine.FieldCount(taosRes); + + + List dataRaw = new(); + + IntPtr colLengthPrt = TDengine.FetchLengths(taosRes); + int[] colLengthArr = new int[numOfFiled]; + Marshal.Copy(colLengthPrt, colLengthArr, 0, numOfFiled); + + for (int i = 0; i < numOfFiled; i++) + { + TDengineMeta meta = metaList[i]; + IntPtr data = Marshal.ReadIntPtr(taosRow, IntPtr.Size * i); + + if (data == IntPtr.Zero) + { + dataRaw.Add("NULL"); + continue; + } + switch ((TDengineDataType)meta.type) + { + case TDengineDataType.TSDB_DATA_TYPE_BOOL: + bool v1 = Marshal.ReadByte(data) != 0; + dataRaw.Add(v1); + break; + case TDengineDataType.TSDB_DATA_TYPE_TINYINT: + sbyte v2 = (sbyte)Marshal.ReadByte(data); + dataRaw.Add(v2); + break; + case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: + short v3 = Marshal.ReadInt16(data); + dataRaw.Add(v3); + break; + case TDengineDataType.TSDB_DATA_TYPE_INT: + int v4 = Marshal.ReadInt32(data); + dataRaw.Add(v4); + break; + case TDengineDataType.TSDB_DATA_TYPE_BIGINT: + long v5 = Marshal.ReadInt64(data); + dataRaw.Add(v5); + break; + case TDengineDataType.TSDB_DATA_TYPE_FLOAT: + float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); + dataRaw.Add(v6); + break; + case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: + double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); + dataRaw.Add(v7); + break; + case TDengineDataType.TSDB_DATA_TYPE_BINARY: + string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); + dataRaw.Add(v8); + break; + case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: + long v9 = Marshal.ReadInt64(data); + dataRaw.Add(v9); + break; + case TDengineDataType.TSDB_DATA_TYPE_NCHAR: + string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); + dataRaw.Add(v10); + break; + case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: + byte v12 = Marshal.ReadByte(data); + dataRaw.Add(v12.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: + ushort v13 = (ushort)Marshal.ReadInt16(data); + dataRaw.Add(v13); + break; + case TDengineDataType.TSDB_DATA_TYPE_UINT: + uint v14 = (uint)Marshal.ReadInt32(data); + dataRaw.Add(v14); + break; + case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: + ulong v15 = (ulong)Marshal.ReadInt64(data); + dataRaw.Add(v15); + break; + case TDengineDataType.TSDB_DATA_TYPE_JSONTAG: + string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); + dataRaw.Add(v16); + break; + default: + dataRaw.Add("nonsupport data type"); + break; + } + + } + return dataRaw; + } + + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = "power"; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + } +} + +//output: +//Connect to TDengine success +//8 rows async retrieved + +//1538548685000 | 10.3 | 219 | 0.31 | beijing.chaoyang | 2 | +//1538548695000 | 12.6 | 218 | 0.33 | beijing.chaoyang | 2 | +//1538548696800 | 12.3 | 221 | 0.31 | beijing.chaoyang | 2 | +//1538548696650 | 10.3 | 218 | 0.25 | beijing.chaoyang | 3 | +//1538548685500 | 11.8 | 221 | 0.28 | beijing.haidian | 2 | +//1538548696600 | 13.4 | 223 | 0.29 | beijing.haidian | 2 | +//1538548685000 | 10.8 | 223 | 0.29 | beijing.haidian | 3 | +//1538548686500 | 11.5 | 221 | 0.35 | beijing.haidian | 3 | +//async retrieve complete. \ No newline at end of file diff --git a/docs-examples/csharp/ConnectExample.cs b/docs-examples/csharp/ConnectExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..dafc02a7aad1ddf68ea6adf8d7dd4f1ed4c83b1d --- /dev/null +++ b/docs-examples/csharp/ConnectExample.cs @@ -0,0 +1,29 @@ +using TDengineDriver; + +namespace TDengineExample +{ + + internal class ConnectExample + { + static void Main(String[] args) + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + TDengine.Close(conn); + TDengine.Cleanup(); + } + } +} diff --git a/docs-examples/csharp/InfluxDBLineExample.cs b/docs-examples/csharp/InfluxDBLineExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..0c5fbef723ca4d38a571757c93a3d4548ae0a9b4 --- /dev/null +++ b/docs-examples/csharp/InfluxDBLineExample.cs @@ -0,0 +1,75 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class InfluxDBLineExample + { + static void Main() { + IntPtr conn = GetConnection(); + PrepareDatabase(conn); + string[] lines = { + "meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250" + }; + IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + else + { + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows"); + } + TDengine.FreeResult(res); + ExitProgram(conn, 0); + + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + TDengine.Cleanup(); + Environment.Exit(1); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void PrepareDatabase(IntPtr conn) + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE test"); + if (TDengine.ErrorNo(res) != 0) { + Console.WriteLine("failed to create database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + res = TDengine.Query(conn, "USE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to change database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } + +} diff --git a/docs-examples/csharp/OptsJsonExample.cs b/docs-examples/csharp/OptsJsonExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..5e19102139fa13d35b647bb5214b6929e79db9aa --- /dev/null +++ b/docs-examples/csharp/OptsJsonExample.cs @@ -0,0 +1,76 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class OptsJsonExample + { + static void Main() + { + IntPtr conn = GetConnection(); + PrepareDatabase(conn); + string[] lines = { "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}, " + + "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}]" + }; + + IntPtr res = TDengine.SchemalessInsert(conn, lines, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + else + { + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows"); + } + TDengine.FreeResult(res); + ExitProgram(conn, 0); + + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + TDengine.Cleanup(); + Environment.Exit(1); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void PrepareDatabase(IntPtr conn) + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to create database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + res = TDengine.Query(conn, "USE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to change database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } +} diff --git a/docs-examples/csharp/OptsTelnetExample.cs b/docs-examples/csharp/OptsTelnetExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..81608c32213fa0618a2ca6e0769aacf8e9c8e64d --- /dev/null +++ b/docs-examples/csharp/OptsTelnetExample.cs @@ -0,0 +1,80 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class OptsTelnetExample + { + static void Main() + { + IntPtr conn = GetConnection(); + PrepareDatabase(conn); + string[] lines = { + "meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3", + "meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3", + }; + IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + else + { + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows"); + } + TDengine.FreeResult(res); + ExitProgram(conn, 0); + + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + TDengine.Cleanup(); + Environment.Exit(1); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void PrepareDatabase(IntPtr conn) + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to create database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + res = TDengine.Query(conn, "USE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to change database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } +} diff --git a/docs-examples/csharp/QueryExample.cs b/docs-examples/csharp/QueryExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..62fb84673f955c3fca7d55bbdf1ff32ddcd9bcc2 --- /dev/null +++ b/docs-examples/csharp/QueryExample.cs @@ -0,0 +1,126 @@ +using TDengineDriver; +using System.Runtime.InteropServices; + +namespace TDengineExample +{ + internal class QueryExample + { + static void Main() { + IntPtr conn = GetConnection(); + // run query + IntPtr res = TDengine.Query(conn, "SELECT * FROM meters LIMIT 2"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("Failed to query since: " + TDengine.Error(res)); + TDengine.Close(conn); + TDengine.Cleanup(); + return; + } + + // get filed count + int fieldCount = TDengine.FieldCount(res); + Console.WriteLine("fieldCount=" + fieldCount); + + // print column names + List metas = TDengine.FetchFields(res); + for (int i = 0; i < metas.Count; i++) + { + Console.Write(metas[i].name + "\t"); + } + Console.WriteLine(); + + // print values + IntPtr row; + while ((row = TDengine.FetchRows(res)) != IntPtr.Zero) { + for (int i = 0; i < fieldCount; i++) { + var meta = metas[i]; + int offset = IntPtr.Size * i; + IntPtr data = Marshal.ReadIntPtr(row, offset); + if (data == IntPtr.Zero) + { + Console.Write("NULL\t"); + continue; + } + switch ((TDengineDataType)meta.type) + { + case TDengineDataType.TSDB_DATA_TYPE_BOOL: + bool v1 = Marshal.ReadByte(data) == 0 ? false : true; + Console.Write(v1 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_TINYINT: + byte v2 = Marshal.ReadByte(data); + Console.Write(v2 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: + short v3 = Marshal.ReadInt16(data); + Console.Write(v3 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_INT: + int v4 = Marshal.ReadInt32(data); + Console.Write(v4 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_BIGINT: + long v5 = Marshal.ReadInt64(data); + Console.Write(v5 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_FLOAT: + float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); + Console.Write(v6 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: + double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); + Console.WriteLine(v7 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_BINARY: + string v8 = Marshal.PtrToStringAnsi(data); + Console.Write(v8 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: + long v9 = Marshal.ReadInt64(data); + Console.Write(v9 + "\t"); + break; + case TDengineDataType.TSDB_DATA_TYPE_NCHAR: + string v10 = Marshal.PtrToStringAnsi(data); + Console.Write(v10 + "\t"); + break; + } + } + Console.WriteLine(); + } + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine($"Query is not complete, Error { TDengine.ErrorNo(res)} {TDengine.Error(res)}"); + } + // exit + TDengine.FreeResult(res); + TDengine.Close(conn); + TDengine.Cleanup(); + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = "power"; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + System.Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + } +} + +// output: +// Connect to TDengine success +// fieldCount=6 +// ts current voltage phase location groupid +// 1648432611249 10.3 219 0.31 Beijing.Chaoyang 2 +// 1648432611749 12.6 218 0.33 Beijing.Chaoyang 2 \ No newline at end of file diff --git a/docs-examples/csharp/SQLInsertExample.cs b/docs-examples/csharp/SQLInsertExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..3b81a0d0cc06f6c7e5fb6713049f24caebd0cad0 --- /dev/null +++ b/docs-examples/csharp/SQLInsertExample.cs @@ -0,0 +1,67 @@ +using TDengineDriver; + + +namespace TDengineExample +{ + internal class SQLInsertExample + { + + static void Main() + { + IntPtr conn = GetConnection(); + IntPtr res = TDengine.Query(conn, "CREATE DATABASE power"); + CheckRes(conn, res, "failed to create database"); + res = TDengine.Query(conn, "USE power"); + CheckRes(conn, res, "failed to change database"); + res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); + CheckRes(conn, res, "failed to create stable"); + var sql = "INSERT INTO d1001 USING meters TAGS(Beijing.Chaoyang, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) " + + "d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) " + + "d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) " + + "d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000)('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"; + res = TDengine.Query(conn, sql); + CheckRes(conn, res, "failed to insert data"); + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine("affectedRows " + affectedRows); + ExitProgram(conn, 0); + } + + static IntPtr GetConnection() { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void CheckRes(IntPtr conn, IntPtr res, String errorMsg) { + if (TDengine.ErrorNo(res) != 0) + { + Console.Write(errorMsg + " since: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } +} + +// output: +// Connect to TDengine success +// affectedRows 8 diff --git a/docs-examples/csharp/StmtInsertExample.cs b/docs-examples/csharp/StmtInsertExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..c7e5cdfbd7532f897cac83a7616eacb5f6978ab5 --- /dev/null +++ b/docs-examples/csharp/StmtInsertExample.cs @@ -0,0 +1,112 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class StmtInsertExample + { + private static IntPtr conn; + private static IntPtr stmt; + static void Main() + { + conn = GetConnection(); + PrepareSTable(); + // 1. init and prepare + stmt = TDengine.StmtInit(conn); + if (stmt == IntPtr.Zero) { + Console.WriteLine("failed to init stmt, " + TDengine.Error(stmt)); + ExitProgram(); + } + int res = TDengine.StmtPrepare(stmt, "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"); + CheckStmtRes(res, "failed to prepare stmt"); + + // 2. bind table name and tags + TAOS_BIND[] tags = new TAOS_BIND[2] {TaosBind.BindBinary("Beijing.Chaoyang"), TaosBind.BindInt(2) }; + res = TDengine.StmtSetTbnameTags(stmt, "d1001", tags); + CheckStmtRes(res, "failed to bind table name and tags"); + + // 3. bind values + TAOS_MULTI_BIND[] values = new TAOS_MULTI_BIND[4] { + TaosMultiBind.MultiBindTimestamp(new long[2] { 1648432611249, 1648432611749}), + TaosMultiBind.MultiBindFloat(new float?[2] { 10.3f, 12.6f}), + TaosMultiBind.MultiBindInt(new int?[2] { 219, 218}), + TaosMultiBind.MultiBindFloat(new float?[2]{ 0.31f, 0.33f}) + }; + res = TDengine.StmtBindParamBatch(stmt, values); + CheckStmtRes(res, "failed to bind params"); + + // 4. add batch + res = TDengine.StmtAddBatch(stmt); + CheckStmtRes(res, "failed to add batch"); + + // 5. execute + res = TDengine.StmtExecute(stmt); + CheckStmtRes(res, "faild to execute"); + + // 6. free + TaosBind.FreeTaosBind(tags); + TaosMultiBind.FreeTaosBind(values); + TDengine.Close(conn); + TDengine.Cleanup(); + } + + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + + + static void PrepareSTable() { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE power"); + CheckResPtr(res, "failed to create database"); + res = TDengine.Query(conn, "USE power"); + CheckResPtr(res, "failed to change database"); + res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); + CheckResPtr(res, "failed to create stable"); + } + + static void CheckStmtRes(int res, string errorMsg) + { + if (res != 0) + { + Console.WriteLine(errorMsg + ", " + TDengine.StmtErrorStr(stmt)); + int code = TDengine.StmtClose(stmt); + if (code != 0) { + Console.WriteLine($"falied to close stmt, {code} reason: {TDengine.StmtErrorStr(stmt)} "); + } + ExitProgram(); + } + } + + static void CheckResPtr(IntPtr res, string errorMsg) + { + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine(errorMsg + " since:" + TDengine.Error(res)); + ExitProgram(); + } + } + + static void ExitProgram() + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(1); + } + } +} diff --git a/tests/examples/C#/TDengineTest/TDengineTest.csproj b/docs-examples/csharp/csharp.csproj similarity index 51% rename from tests/examples/C#/TDengineTest/TDengineTest.csproj rename to docs-examples/csharp/csharp.csproj index 211c927d3d36df5941291319e3c85707610c6a8f..b1bd83405efb1086b23134a9c875912a9c09e3f8 100644 --- a/tests/examples/C#/TDengineTest/TDengineTest.csproj +++ b/docs-examples/csharp/csharp.csproj @@ -2,11 +2,14 @@ Exe - net5.0 + net6.0 + enable + enable + TDengineExample.OptsJsonExample - + diff --git a/docs-examples/go/.gitignore b/docs-examples/go/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b6128386c306834cddeb425f365720bb9c9ce790 --- /dev/null +++ b/docs-examples/go/.gitignore @@ -0,0 +1,3 @@ +.idea +.vscode +tmp/ \ No newline at end of file diff --git a/docs-examples/go/connect/afconn/main.go b/docs-examples/go/connect/afconn/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2d36ef03ab049a313ed0416f552397ff252e022e --- /dev/null +++ b/docs-examples/go/connect/afconn/main.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + + "github.com/taosdata/driver-go/v2/af" +) + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + defer conn.Close() + if err != nil { + fmt.Println("failed to connect, err:", err) + } else { + fmt.Println("connected") + } +} diff --git a/docs-examples/go/connect/cgoexample/main.go b/docs-examples/go/connect/cgoexample/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8b9aba4ce4217c00605bc8796c788f3dd52805e6 --- /dev/null +++ b/docs-examples/go/connect/cgoexample/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "database/sql" + "fmt" + + _ "github.com/taosdata/driver-go/v2/taosSql" +) + +func main() { + var taosDSN = "root:taosdata@tcp(localhost:6030)/" + taos, err := sql.Open("taosSql", taosDSN) + if err != nil { + fmt.Println("failed to connect TDengine, err:", err) + return + } + fmt.Println("Connected") + defer taos.Close() +} + +// use +// var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName" +// if you want to connect to a default database. diff --git a/docs-examples/go/connect/restexample/main.go b/docs-examples/go/connect/restexample/main.go new file mode 100644 index 0000000000000000000000000000000000000000..9c05e7eed80dee4ae7e6b20637d265f388d7438d --- /dev/null +++ b/docs-examples/go/connect/restexample/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "database/sql" + "fmt" + + _ "github.com/taosdata/driver-go/v2/taosRestful" +) + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + fmt.Println("failed to connect TDengine, err:", err) + return + } + fmt.Println("Connected") + defer taos.Close() +} + +// use +// var taosDSN = "root:taosdata@http(localhost:6041)/dbName" +// if you want to connect to a default database. diff --git a/docs-examples/go/connect/wrapper/main.go b/docs-examples/go/connect/wrapper/main.go new file mode 100644 index 0000000000000000000000000000000000000000..d7e71a8baf229012b6944aad0eaac232924dd667 --- /dev/null +++ b/docs-examples/go/connect/wrapper/main.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + + "github.com/taosdata/driver-go/v2/wrapper" +) + +func main() { + conn, err := wrapper.TaosConnect("localhost", "root", "taosdata", "", 6030) + defer wrapper.TaosClose(conn) + if err != nil { + fmt.Println("fail to connect, err:", err) + } else { + fmt.Println("connected") + } +} diff --git a/docs-examples/go/go.mod b/docs-examples/go/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..d543c0c7a65de69defc646c55c194922694c7dd2 --- /dev/null +++ b/docs-examples/go/go.mod @@ -0,0 +1,11 @@ +module goexample + +go 1.17 + +require github.com/taosdata/driver-go/v2 v2.0.1-0.20220222122038-174cb6c68124 + +require ( + github.com/json-iterator/go v1.1.12 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect +) diff --git a/docs-examples/go/go.sum b/docs-examples/go/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..22e91ce03352936a9a3b2d02392b0c076b68ed67 --- /dev/null +++ b/docs-examples/go/go.sum @@ -0,0 +1,21 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/taosdata/driver-go/v2 v2.0.1-0.20220222122038-174cb6c68124 h1:xDsYj1FnTBhhjMovgg67YtvTcRwICOTtUFkTxTS1LBM= +github.com/taosdata/driver-go/v2 v2.0.1-0.20220222122038-174cb6c68124/go.mod h1:ZAb4yDucTytX1Gy69F3nTRV+lEXmjkyF4J6OiYCR9NI= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/docs-examples/go/insert/json/main.go b/docs-examples/go/insert/json/main.go new file mode 100644 index 0000000000000000000000000000000000000000..47d9e9984adc05896fb9954ad3deffde3764b836 --- /dev/null +++ b/docs-examples/go/insert/json/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + + "github.com/taosdata/driver-go/v2/af" +) + +func prepareDatabase(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE test") + if err != nil { + panic(err) + } + _, err = conn.Exec("USE test") + if err != nil { + panic(err) + } +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + if err != nil { + fmt.Println("fail to connect, err:", err) + } + defer conn.Close() + prepareDatabase(conn) + + payload := `[{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "Beijing.Haidian", "groupid": 1}}, + {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "Beijing.Haidian", "groupid": 1}}]` + + err = conn.OpenTSDBInsertJsonPayload(payload) + if err != nil { + fmt.Println("insert error:", err) + } +} diff --git a/docs-examples/go/insert/line/main.go b/docs-examples/go/insert/line/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bbc41468fe5f13d3e6f896445bb88f3eba584d0f --- /dev/null +++ b/docs-examples/go/insert/line/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + + "github.com/taosdata/driver-go/v2/af" +) + +func prepareDatabase(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE test") + if err != nil { + panic(err) + } + _, err = conn.Exec("USE test") + if err != nil { + panic(err) + } +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + if err != nil { + fmt.Println("fail to connect, err:", err) + } + defer conn.Close() + prepareDatabase(conn) + var lines = []string{ + "meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250", + } + + err = conn.InfluxDBInsertLines(lines, "ms") + if err != nil { + fmt.Println("insert error:", err) + } +} diff --git a/docs-examples/go/insert/sql/main.go b/docs-examples/go/insert/sql/main.go new file mode 100644 index 0000000000000000000000000000000000000000..91386855334c1930af721e0b4f43395c6a6d8e82 --- /dev/null +++ b/docs-examples/go/insert/sql/main.go @@ -0,0 +1,49 @@ +package main + +import ( + "database/sql" + "fmt" + + _ "github.com/taosdata/driver-go/v2/taosRestful" +) + +func createStable(taos *sql.DB) { + _, err := taos.Exec("CREATE DATABASE power") + if err != nil { + fmt.Println("failed to create database, err:", err) + } + _, err = taos.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") + if err != nil { + fmt.Println("failed to create stable, err:", err) + } +} + +func insertData(taos *sql.DB) { + sql := `INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) + power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) + power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)` + result, err := taos.Exec(sql) + if err != nil { + fmt.Println("failed to insert, err:", err) + return + } + rowsAffected, err := result.RowsAffected() + if err != nil { + fmt.Println("failed to get affected rows, err:", err) + return + } + fmt.Println("RowsAffected", rowsAffected) +} + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + fmt.Println("failed to connect TDengine, err:", err) + return + } + defer taos.Close() + createStable(taos) + insertData(taos) +} diff --git a/docs-examples/go/insert/stmt/main.go b/docs-examples/go/insert/stmt/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c50200ebb427c4c64c2737cb8fe4c3d287551a34 --- /dev/null +++ b/docs-examples/go/insert/stmt/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "fmt" + "time" + + "github.com/taosdata/driver-go/v2/af" + "github.com/taosdata/driver-go/v2/af/param" + "github.com/taosdata/driver-go/v2/common" +) + +func checkErr(err error, prompt string) { + if err != nil { + fmt.Printf("%s\n", prompt) + panic(err) + } +} + +func prepareStable(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE power") + checkErr(err, "failed to create database") + _, err = conn.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") + checkErr(err, "failed to create stable") + _, err = conn.Exec("USE power") + checkErr(err, "failed to change database") +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + checkErr(err, "fail to connect") + defer conn.Close() + prepareStable(conn) + // create stmt + stmt := conn.InsertStmt() + defer stmt.Close() + err = stmt.Prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + checkErr(err, "failed to create prepare statement") + + // bind table name and tags + tagParams := param.NewParam(2).AddBinary([]byte("Beijing.Chaoyang")).AddInt(2) + err = stmt.SetTableNameWithTags("d1001", tagParams) + checkErr(err, "failed to execute SetTableNameWithTags") + + // specify ColumnType + var bindType *param.ColumnType = param.NewColumnType(4).AddTimestamp().AddFloat().AddInt().AddFloat() + + // bind values. note: can only bind one row each time. + valueParams := []*param.Param{ + param.NewParam(1).AddTimestamp(time.Unix(1648432611, 249300000), common.PrecisionMilliSecond), + param.NewParam(1).AddFloat(10.3), + param.NewParam(1).AddInt(219), + param.NewParam(1).AddFloat(0.31), + } + err = stmt.BindParam(valueParams, bindType) + checkErr(err, "BindParam error") + err = stmt.AddBatch() + checkErr(err, "AddBatch error") + + // bind one more row + valueParams = []*param.Param{ + param.NewParam(1).AddTimestamp(time.Unix(1648432611, 749300000), common.PrecisionMilliSecond), + param.NewParam(1).AddFloat(12.6), + param.NewParam(1).AddInt(218), + param.NewParam(1).AddFloat(0.33), + } + err = stmt.BindParam(valueParams, bindType) + checkErr(err, "BindParam error") + err = stmt.AddBatch() + checkErr(err, "AddBatch error") + // execute + err = stmt.Execute() + checkErr(err, "Execute batch error") +} diff --git a/docs-examples/go/insert/telnet/main.go b/docs-examples/go/insert/telnet/main.go new file mode 100644 index 0000000000000000000000000000000000000000..879e6d5cece74fd0b7c815dd34614dca3c9d4544 --- /dev/null +++ b/docs-examples/go/insert/telnet/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + + "github.com/taosdata/driver-go/v2/af" +) + +func prepareDatabase(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE test") + if err != nil { + panic(err) + } + _, err = conn.Exec("USE test") + if err != nil { + panic(err) + } +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + if err != nil { + fmt.Println("fail to connect, err:", err) + } + defer conn.Close() + prepareDatabase(conn) + var lines = []string{ + "meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3", + "meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3", + } + + err = conn.OpenTSDBInsertTelnetLines(lines) + if err != nil { + fmt.Println("insert error:", err) + } +} diff --git a/docs-examples/go/query/async/main.go b/docs-examples/go/query/async/main.go new file mode 100644 index 0000000000000000000000000000000000000000..7776ec8d3f268a3ef393d2097b71dc5681cf48d9 --- /dev/null +++ b/docs-examples/go/query/async/main.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("hello world!") +} diff --git a/docs-examples/go/query/sync/main.go b/docs-examples/go/query/sync/main.go new file mode 100644 index 0000000000000000000000000000000000000000..0326c7a7da5da212f66b1421bb46e5972bef9609 --- /dev/null +++ b/docs-examples/go/query/sync/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "database/sql" + "fmt" + "time" + + _ "github.com/taosdata/driver-go/v2/taosRestful" +) + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/power" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + fmt.Println("failed to connect TDengine, err:", err) + return + } + defer taos.Close() + rows, err := taos.Query("SELECT ts, current FROM meters LIMIT 2") + if err != nil { + fmt.Println("failed to select from table, err:", err) + return + } + + defer rows.Close() + for rows.Next() { + var r struct { + ts time.Time + current float32 + } + err := rows.Scan(&r.ts, &r.current) + if err != nil { + fmt.Println("scan error:\n", err) + return + } + fmt.Println(r.ts, r.current) + } +} diff --git a/docs-examples/go/rest/opentsdbjson/main.go b/docs-examples/go/rest/opentsdbjson/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f4f5792e29436e539f301c14ce76607ad3e5593d --- /dev/null +++ b/docs-examples/go/rest/opentsdbjson/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "time" +) + +type Tags struct { + Location string `json:"location"` + Groupid int32 `json:"groupid"` +} + +type Metric struct { + Metric string `json:"metric"` + Timestamp int64 `json:"timestamp"` + Value int32 `json:"value"` + Tags Tags `json:"tags"` +} + +func main() { + client := http.Client{} + for i := 0; i < 10; i++ { + metric := Metric{"voltage", time.Now().UnixMilli(), 1, Tags{"A", 1}} + json, err := json.Marshal(metric) + if err != nil { + panic(err) + } + req, err := http.NewRequest("POST", "http://localhost:6041/opentsdb/v1/put/json/rest_go", bytes.NewBuffer(json)) + if err != nil { + panic(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Basic cm9vdDp0YW9zZGF0YQ==") + resp, err := client.Do(req) + if err != nil { + panic(err) + } + fmt.Printf("%v\n", resp) + time.Sleep(time.Second) + + } +} diff --git a/docs-examples/go/sub/main.go b/docs-examples/go/sub/main.go new file mode 100644 index 0000000000000000000000000000000000000000..d41736bddc6c4fbf1dea8dcd14f691e0c6a5cd68 --- /dev/null +++ b/docs-examples/go/sub/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "database/sql/driver" + "fmt" + "io" + "os" + "time" + + taos "github.com/taosdata/driver-go/v2/af" +) + +func main() { + db, err := taos.Open("", "", "", "log", 0) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + defer db.Close() + topic, err := db.Subscribe(false, "taoslogtail", "select ts, level, ipaddr, content from log", time.Second) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + defer topic.Unsubscribe(true) + for { + func() { + rows, err := topic.Consume() + defer func() { rows.Close(); time.Sleep(time.Second) }() + if err != nil { + fmt.Println(err) + os.Exit(3) + } + for { + values := make([]driver.Value, 4) + err := rows.Next(values) + if err == io.EOF { + break + } else if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(4) + } + ts := values[0].(time.Time) + level := values[1].(int8) + ipaddr := values[2].(string) + content := values[3].(string) + fmt.Printf("%s %d %s %s\n", ts.Format(time.StampMilli), level, ipaddr, content) + } + }() + } +} \ No newline at end of file diff --git a/docs-examples/java/.gitignore b/docs-examples/java/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d48c759d6c990444f193c0043ec9b316029d31bc --- /dev/null +++ b/docs-examples/java/.gitignore @@ -0,0 +1,2 @@ +.idea +.vscode \ No newline at end of file diff --git a/docs-examples/java/pom.xml b/docs-examples/java/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..6bf4e19484e5c2ef233e92528cc99dfe73e9f45b --- /dev/null +++ b/docs-examples/java/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + com.taos + javaexample + 1.0 + + JavaExample + + + UTF-8 + 1.8 + 1.8 + + + + + com.taosdata.jdbc + taos-jdbcdriver + 2.0.37 + + + junit + junit + 4.13.1 + test + + + + diff --git a/docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java b/docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java new file mode 100644 index 0000000000000000000000000000000000000000..c6ce2ef9785a010daa55ad29415f81711760cd57 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java @@ -0,0 +1,25 @@ +package com.taos.example; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +import com.taosdata.jdbc.TSDBDriver; + +public class JNIConnectExample { + public static void main(String[] args) throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + Connection conn = DriverManager.getConnection(jdbcUrl, connProps); + System.out.println("Connected"); + conn.close(); + } +} + +// use +// String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata"; +// if you want to connect to a default database. \ No newline at end of file diff --git a/docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java b/docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java new file mode 100644 index 0000000000000000000000000000000000000000..9e0f4cc4300931928ee225998a013b92cb7a64d7 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java @@ -0,0 +1,40 @@ +package com.taos.example; + +import com.taosdata.jdbc.SchemalessWriter; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class JSONProtocolExample { + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createDatabase(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE test"); + stmt.execute("USE test"); + } + } + + private static String getJSONData() { + return "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}, " + + "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}]"; + } + + public static void main(String[] args) throws SQLException { + try (Connection conn = getConnection()) { + createDatabase(conn); + SchemalessWriter writer = new SchemalessWriter(conn); + String jsonData = getJSONData(); + writer.write(jsonData, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); + } + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java b/docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java new file mode 100644 index 0000000000000000000000000000000000000000..903dc075d8bb618b40112dbb6bc4d8c15c40aad2 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java @@ -0,0 +1,42 @@ +package com.taos.example; + +import com.taosdata.jdbc.SchemalessWriter; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class LineProtocolExample { + // format: measurement,tag_set field_set timestamp + private static String[] lines = { + "meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", // micro + // seconds + "meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500", + "meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300", + "meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800", + }; + + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createDatabase(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + // the default precision is ms (microsecond), but we use us(microsecond) here. + stmt.execute("CREATE DATABASE test precision 'us'"); + stmt.execute("USE test"); + } + } + + public static void main(String[] args) throws SQLException { + try (Connection conn = getConnection()) { + createDatabase(conn); + SchemalessWriter writer = new SchemalessWriter(conn); + writer.write(lines, SchemalessProtocolType.LINE, SchemalessTimestampType.MICRO_SECONDS); + } + } +} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/Printer.java b/docs-examples/java/src/main/java/com/taos/example/QueryExample.java similarity index 57% rename from tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/Printer.java rename to docs-examples/java/src/main/java/com/taos/example/QueryExample.java index a4627463ec5cd1bbccdb64b67506ba38f712de8f..21e00336e898e933e2504bed7c8eed3f8fadc2ef 100644 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/Printer.java +++ b/docs-examples/java/src/main/java/com/taos/example/QueryExample.java @@ -1,12 +1,11 @@ -package com.taosdata.taosdemo.utils; +package com.taos.example; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; -public class Printer { - - public static void printResult(ResultSet resultSet) throws SQLException { +public class QueryExample { + static void printResult(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); while (resultSet.next()) { for (int i = 1; i <= metaData.getColumnCount(); i++) { @@ -17,11 +16,4 @@ public class Printer { System.out.println(); } } - - public static void printSql(String sql, boolean succeed, long cost) { - System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql); - } - - private Printer() { - } } diff --git a/docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java b/docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java new file mode 100644 index 0000000000000000000000000000000000000000..68d81dbbcc00d42fc38e0ba903854b3c03259490 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java @@ -0,0 +1,25 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBDriver; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +public class RESTConnectExample { + public static void main(String[] args) throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + Connection conn = DriverManager.getConnection(jdbcUrl, connProps); + System.out.println("Connected"); + conn.close(); + } +} + +// use +// String jdbcUrl = "jdbc:TAOS-RS://localhost:6041/dbName?user=root&password=taosdata"; +// if you want to connect to a default database. \ No newline at end of file diff --git a/docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java b/docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java new file mode 100644 index 0000000000000000000000000000000000000000..de89f26cbe38f9343d60aeb8d3e9ce7f67c2e764 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java @@ -0,0 +1,74 @@ +package com.taos.example; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; + + +public class RestInsertExample { + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static List getRawData() { + return Arrays.asList( + "d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,Beijing.Chaoyang,2", + "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,Beijing.Chaoyang,2", + "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,Beijing.Chaoyang,2", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,Beijing.Chaoyang,3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,Beijing.Haidian,2", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,Beijing.Haidian,2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,Beijing.Haidian,3", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,Beijing.Haidian,3" + ); + } + + + /** + * The generated SQL is: + * INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:05.000',10.30000,219,0.31000) + * power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:15.000',12.60000,218,0.33000) + * power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:16.800',12.30000,221,0.31000) + * power.d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES('2018-10-03 14:38:16.650',10.30000,218,0.25000) + * power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 14:38:05.500',11.80000,221,0.28000) + * power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 14:38:16.600',13.40000,223,0.29000) + * power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 14:38:05.000',10.80000,223,0.29000) + * power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 14:38:06.500',11.50000,221,0.35000) + */ + private static String getSQL() { + StringBuilder sb = new StringBuilder("INSERT INTO "); + for (String line : getRawData()) { + String[] ps = line.split(","); + sb.append("power." + ps[0]).append(" USING power.meters TAGS(") + .append(ps[5]).append(", ") // tag: location + .append(ps[6]) // tag: groupId + .append(") VALUES(") + .append('\'').append(ps[1]).append('\'').append(",") // ts + .append(ps[2]).append(",") // current + .append(ps[3]).append(",") // voltage + .append(ps[4]).append(") "); // phase + } + return sb.toString(); + } + + public static void insertData() throws SQLException { + try (Connection conn = getConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE power KEEP 3650"); + stmt.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + + "TAGS (location BINARY(64), groupId INT)"); + String sql = getSQL(); + int rowCount = stmt.executeUpdate(sql); + System.out.println("rowCount=" + rowCount); // rowCount=8 + } + } + } + + public static void main(String[] args) throws SQLException { + insertData(); + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java b/docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java new file mode 100644 index 0000000000000000000000000000000000000000..959e003fe81cadaf9c7bdec8d3d337cafdfe6e15 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java @@ -0,0 +1,55 @@ +package com.taos.example; + +import java.sql.*; + +public class RestQueryExample { + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041/power?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void printRow(ResultSet rs) throws SQLException { + ResultSetMetaData meta = rs.getMetaData(); + for (int i = 1; i <= meta.getColumnCount(); i++) { + String value = rs.getString(i); + System.out.print(value); + System.out.print("\t"); + } + System.out.println(); + } + + private static void printColName(ResultSet rs) throws SQLException { + ResultSetMetaData meta = rs.getMetaData(); + for (int i = 1; i <= meta.getColumnCount(); i++) { + String colLabel = meta.getColumnLabel(i); + System.out.print(colLabel); + System.out.print("\t"); + } + System.out.println(); + } + + private static void processResult(ResultSet rs) throws SQLException { + printColName(rs); + while (rs.next()) { + printRow(rs); + } + } + + private static void queryData() throws SQLException { + try (Connection conn = getConnection()) { + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("SELECT AVG(voltage) FROM meters GROUP BY location"); + processResult(rs); + } + } + } + + public static void main(String[] args) throws SQLException { + queryData(); + } +} + +// possible stdout: +// avg(voltage) location +// 222.0 Beijing.Haidian +// 219.0 Beijing.Chaoyang diff --git a/docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java b/docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java new file mode 100644 index 0000000000000000000000000000000000000000..2a7ccebf41cae1a22d7516966e2c6ffb10011b64 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java @@ -0,0 +1,84 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBPreparedStatement; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class StmtInsertExample { + private static ArrayList tsToLongArray(String ts) { + ArrayList result = new ArrayList<>(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + LocalDateTime localDateTime = LocalDateTime.parse(ts, formatter); + result.add(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()); + return result; + } + + private static ArrayList toArray(T v) { + ArrayList result = new ArrayList<>(); + result.add(v); + return result; + } + + private static List getRawData() { + return Arrays.asList( + "d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,Beijing.Chaoyang,2", + "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,Beijing.Chaoyang,2", + "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,Beijing.Chaoyang,2", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,Beijing.Chaoyang,3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,Beijing.Haidian,2", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,Beijing.Haidian,2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,Beijing.Haidian,3", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,Beijing.Haidian,3" + ); + } + + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createTable(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE power KEEP 3650"); + stmt.executeUpdate("USE power"); + stmt.execute("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + + "TAGS (location BINARY(64), groupId INT)"); + } + } + + private static void insertData() throws SQLException { + try (Connection conn = getConnection()) { + createTable(conn); + String psql = "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"; + try (TSDBPreparedStatement pst = (TSDBPreparedStatement) conn.prepareStatement(psql)) { + for (String line : getRawData()) { + String[] ps = line.split(","); + // bind table name and tags + pst.setTableName(ps[0]); + pst.setTagString(0, ps[5]); + pst.setTagInt(1, Integer.valueOf(ps[6])); + // bind values + pst.setTimestamp(0, tsToLongArray(ps[1])); //ps[1] looks like: 2018-10-03 14:38:05.000 + pst.setFloat(1, toArray(Float.valueOf(ps[2]))); + pst.setInt(2, toArray(Integer.valueOf(ps[3]))); + pst.setFloat(3, toArray(Float.valueOf(ps[4]))); + pst.columnDataAddBatch(); + } + pst.columnDataExecuteBatch(); + } + } + } + + public static void main(String[] args) throws SQLException { + insertData(); + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java b/docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java new file mode 100644 index 0000000000000000000000000000000000000000..50ac5294018932026de540ab8f12471ddd39501c --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java @@ -0,0 +1,45 @@ +package com.taos.example; + +import com.taosdata.jdbc.SchemalessWriter; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class TelnetLineProtocolExample { + // format: =[ =] + private static String[] lines = { "meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3", + "meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3", + }; + + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createDatabase(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + // the default precision is ms (microsecond), but we use us(microsecond) here. + stmt.execute("CREATE DATABASE test precision 'us'"); + stmt.execute("USE test"); + } + } + + public static void main(String[] args) throws SQLException { + try (Connection conn = getConnection()) { + createDatabase(conn); + SchemalessWriter writer = new SchemalessWriter(conn); + writer.write(lines, SchemalessProtocolType.TELNET, SchemalessTimestampType.NOT_CONFIGURED); + } + } + +} diff --git a/docs-examples/node/.gitignore b/docs-examples/node/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1071ed2b9f91854f7a51424aa6c05544e803fc08 --- /dev/null +++ b/docs-examples/node/.gitignore @@ -0,0 +1,3 @@ +node_modules +package-lock.json +yarn-lock.json \ No newline at end of file diff --git a/docs-examples/node/nativeexample/async_query_example.js b/docs-examples/node/nativeexample/async_query_example.js new file mode 100644 index 0000000000000000000000000000000000000000..25b78bc48a82454cc0f9db69b77323a00f3852b4 --- /dev/null +++ b/docs-examples/node/nativeexample/async_query_example.js @@ -0,0 +1,21 @@ +const taos = require("td2.0-connector"); +const conn = taos.connect({ host: "localhost", database: "power" }); +const cursor = conn.cursor(); + +function queryExample() { + cursor + .query("SELECT ts, current FROM meters LIMIT 2") + .execute_a() + .then((result) => { + result.pretty(); + }); +} + +try { + queryExample(); +} finally { + setTimeout(() => { + conn.close(); + }, 2000); +} +// bug here: jira 14506 diff --git a/docs-examples/node/nativeexample/connect.js b/docs-examples/node/nativeexample/connect.js new file mode 100644 index 0000000000000000000000000000000000000000..eb804f47b7d27e9482d7c34b1dac13ae219d048e --- /dev/null +++ b/docs-examples/node/nativeexample/connect.js @@ -0,0 +1,13 @@ +const taos = require("td2.0-connector"); + +var conn = taos.connect({ + host: "localhost", + port: 6030, + user: "root", + password: "taosdata", +}); +conn.close(); + +// run with: node connect.js +// stdout: +// Successfully connected to TDengine diff --git a/docs-examples/node/nativeexample/influxdb_line_example.js b/docs-examples/node/nativeexample/influxdb_line_example.js new file mode 100644 index 0000000000000000000000000000000000000000..858cd945d47a002628ba80c5ef3d329bc1857a88 --- /dev/null +++ b/docs-examples/node/nativeexample/influxdb_line_example.js @@ -0,0 +1,34 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function createDatabase() { + cursor.execute("CREATE DATABASE test"); + cursor.execute("USE test"); +} + +function insertData() { + const lines = [ + "meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250", + ]; + cursor.schemalessInsert( + lines, + taos.SCHEMALESS_PROTOCOL.TSDB_SML_LINE_PROTOCOL, + taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_MILLI_SECONDS + ); +} + +try { + createDatabase(); + insertData(); +} finally { + // cursor.close(); // 此处抛异常 + conn.close(); +} diff --git a/docs-examples/node/nativeexample/insert_example.js b/docs-examples/node/nativeexample/insert_example.js new file mode 100644 index 0000000000000000000000000000000000000000..ef78fd41483ce62e946652b005a714cfd3026f00 --- /dev/null +++ b/docs-examples/node/nativeexample/insert_example.js @@ -0,0 +1,31 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); +try { + cursor.execute("CREATE DATABASE power"); + cursor.execute("USE power"); + cursor.execute( + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ); + var sql = `INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) +power.d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) +power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) +power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)`; + cursor.execute(sql); +} finally { + // cursor.close(); + conn.close(); +} + +// run with: node insert_example.js +// stdout: +// Successfully connected to TDengine +// Query OK, 0 row(s) affected (0.00509570s) +// Query OK, 0 row(s) affected (0.00130880s) +// Query OK, 0 row(s) affected (0.00467900s) +// Query OK, 8 row(s) affected (0.04043550s) +// Connection is closed diff --git a/docs-examples/node/nativeexample/multi_bind_example.js b/docs-examples/node/nativeexample/multi_bind_example.js new file mode 100644 index 0000000000000000000000000000000000000000..63d05461bb3af050acff148b2becc845482fbcae --- /dev/null +++ b/docs-examples/node/nativeexample/multi_bind_example.js @@ -0,0 +1,53 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function prepareSTable() { + cursor.execute("CREATE DATABASE power"); + cursor.execute("USE power"); + cursor.execute( + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ); +} + +//ANCHOR: insertData +function insertData() { + // init + cursor.stmtInit(); + // prepare + cursor.stmtPrepare( + "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)" + ); + + // bind table name and tags + let tagBind = new taos.TaosBind(2); + tagBind.bindBinary("Beijing.Chaoyang"); + tagBind.bindInt(2); + cursor.stmtSetTbnameTags("d1001", tagBind.getBind()); + + // bind values + let valueBind = new taos.TaosMultiBindArr(4); + valueBind.multiBindTimestamp([1648432611249, 1648432611749]); + valueBind.multiBindFloat([10.3, 12.6]); + valueBind.multiBindInt([219, 218]); + valueBind.multiBindFloat([0.31, 0.33]); + cursor.stmtBindParamBatch(valueBind.getMultiBindArr()); + cursor.stmtAddBatch(); + + // execute + cursor.stmtExecute(); + cursor.stmtClose(); +} +//ANCHOR_END: insertData + +try { + prepareSTable(); + insertData(); +} finally { + // cursor.close(); // bug here + conn.close(); +} diff --git a/docs-examples/node/nativeexample/opentsdb_json_example.js b/docs-examples/node/nativeexample/opentsdb_json_example.js new file mode 100644 index 0000000000000000000000000000000000000000..7cafec403ff94bafce0abc850b2164575217865b --- /dev/null +++ b/docs-examples/node/nativeexample/opentsdb_json_example.js @@ -0,0 +1,55 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function createDatabase() { + cursor.execute("CREATE DATABASE test"); + cursor.execute("USE test"); +} + +function insertData() { + const lines = [ + { + metric: "meters.current", + timestamp: 1648432611249, + value: 10.3, + tags: { location: "Beijing.Chaoyang", groupid: 2 }, + }, + { + metric: "meters.voltage", + timestamp: 1648432611249, + value: 219, + tags: { location: "Beijing.Haidian", groupid: 1 }, + }, + { + metric: "meters.current", + timestamp: 1648432611250, + value: 12.6, + tags: { location: "Beijing.Chaoyang", groupid: 2 }, + }, + { + metric: "meters.voltage", + timestamp: 1648432611250, + value: 221, + tags: { location: "Beijing.Haidian", groupid: 1 }, + }, + ]; + + cursor.schemalessInsert( + [JSON.stringify(lines)], + taos.SCHEMALESS_PROTOCOL.TSDB_SML_JSON_PROTOCOL, + taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED + ); +} + +try { + createDatabase(); + insertData(); +} finally { + // cursor.close(); // 此处抛异常 + conn.close(); +} diff --git a/docs-examples/node/nativeexample/opentsdb_telnet_example.js b/docs-examples/node/nativeexample/opentsdb_telnet_example.js new file mode 100644 index 0000000000000000000000000000000000000000..670f8f2be7875602c09a8c027ed755c636f66abb --- /dev/null +++ b/docs-examples/node/nativeexample/opentsdb_telnet_example.js @@ -0,0 +1,38 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function createDatabase() { + cursor.execute("CREATE DATABASE test"); + cursor.execute("USE test"); +} + +function insertData() { + const lines = [ + "meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3", + "meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3", + ]; + cursor.schemalessInsert( + lines, + taos.SCHEMALESS_PROTOCOL.TSDB_SML_TELNET_PROTOCOL, + taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED + ); +} + +try { + createDatabase(); + insertData(); +} finally { + // cursor.close(); // 此处抛异常 + conn.close(); +} diff --git a/docs-examples/node/nativeexample/param_bind_example.js b/docs-examples/node/nativeexample/param_bind_example.js new file mode 100644 index 0000000000000000000000000000000000000000..939f8fdd052a1368876d16a03d35701033fe3ab5 --- /dev/null +++ b/docs-examples/node/nativeexample/param_bind_example.js @@ -0,0 +1,57 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function prepareSTable() { + cursor.execute("CREATE DATABASE power"); + cursor.execute("USE power"); + cursor.execute( + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ); +} + +function insertData() { + // init + cursor.stmtInit(); + // prepare + cursor.stmtPrepare( + "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)" + ); + + // bind table name and tags + let tagBind = new taos.TaosBind(2); + tagBind.bindBinary("Beijing.Chaoyang"); + tagBind.bindInt(2); + cursor.stmtSetTbnameTags("d1001", tagBind.getBind()); + + // bind values + let rows = [ + [1648432611249, 10.3, 219, 0.31], + [1648432611749, 12.6, 218, 0.33], + ]; + for (let row of rows) { + let valueBind = new taos.TaosBind(4); + valueBind.bindTimestamp(row[0]); + valueBind.bindFloat(row[1]); + valueBind.bindInt(row[2]); + valueBind.bindFloat(row[3]); + cursor.stmtBindParam(valueBind.getBind()); + cursor.stmtAddBatch(); + } + + // execute + cursor.stmtExecute(); + cursor.stmtClose(); +} + +try { + prepareSTable(); + insertData(); +} finally { + // cursor.close(); // bug here, jira: 14505 + conn.close(); +} diff --git a/docs-examples/node/nativeexample/query_example.js b/docs-examples/node/nativeexample/query_example.js new file mode 100644 index 0000000000000000000000000000000000000000..34fd05bbb331a7c177b928a2f8b7878ec880ddf8 --- /dev/null +++ b/docs-examples/node/nativeexample/query_example.js @@ -0,0 +1,17 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ host: "localhost", database: "power" }); +const cursor = conn.cursor(); +const query = cursor.query("SELECT ts, current FROM meters LIMIT 2"); +query.execute().then(function (result) { + result.pretty(); +}); + +// stdout: +// Successfully connected to TDengine +// Query OK, 2 row(s) in set (0.00317767s) + +// ts | current | +// ======================================================= +// 2018-10-03 14:38:05.000 | 10.3 | +// 2018-10-03 14:38:15.000 | 12.6 | diff --git a/docs-examples/node/package.json b/docs-examples/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5f235bbe34b1b068c35ef877e14138a6498a415c --- /dev/null +++ b/docs-examples/node/package.json @@ -0,0 +1,9 @@ +{ + "name": "examples", + "version": "1.0.0", + "main": "index.js", + "license": "MIT", + "dependencies": { + "td2.0-connector": "^2.0.11" + } +} diff --git a/docs-examples/python/.gitignore b/docs-examples/python/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..723ef36f4e4f32c4560383aa5987c575a30c6535 --- /dev/null +++ b/docs-examples/python/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file diff --git a/docs-examples/python/.gitkeep b/docs-examples/python/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/connector/python/examples/query-async.py b/docs-examples/python/async_query_example.py similarity index 67% rename from src/connector/python/examples/query-async.py rename to docs-examples/python/async_query_example.py index 585db2344eda4c5d38c2868c35f4d91c50926880..28fb2fe7e785125dbd5b5332cc267f51020dddde 100644 --- a/src/connector/python/examples/query-async.py +++ b/docs-examples/python/async_query_example.py @@ -1,6 +1,8 @@ -from taos import * -from ctypes import * import time +from ctypes import * + +from taos import * + def fetch_callback(p_param, p_result, num_of_rows): print("fetched ", num_of_rows, "rows") @@ -10,7 +12,6 @@ def fetch_callback(p_param, p_result, num_of_rows): if num_of_rows == 0: print("fetching completed") p.contents.done = True - # should explicitly close the result in fetch completed or cause error result.close() return if num_of_rows < 0: @@ -18,25 +19,20 @@ def fetch_callback(p_param, p_result, num_of_rows): result.check_error(num_of_rows) result.close() return None - + for row in result.rows_iter(num_of_rows): - # print(row) - None + print(row) p.contents.count += result.row_count result.fetch_rows_a(fetch_callback, p_param) - def query_callback(p_param, p_result, code): - # type: (c_void_p, c_void_p, c_int) -> None if p_result is None: return result = TaosResult(p_result) if code == 0: result.fetch_rows_a(fetch_callback, p_param) result.check_error(code) - # explicitly close result while query failed - result.close() class Counter(Structure): @@ -47,16 +43,30 @@ class Counter(Structure): def test_query(conn): - # type: (TaosConnection) -> None counter = Counter(count=0) - conn.query_a("select * from log.log", query_callback, byref(counter)) + conn.query_a("select ts, current, voltage from power.meters", query_callback, byref(counter)) while not counter.done: - print("wait query callback") + print(counter) time.sleep(1) print(counter) - # conn.close() + conn.close() if __name__ == "__main__": - test_query(connect()) \ No newline at end of file + test_query(connect()) + +# possible stdout: +# { count: 0, done: False } +# fetched 8 rows +# 1538548685000 10.300000 219 +# 1538548695000 12.600000 218 +# 1538548696800 12.300000 221 +# 1538548696650 10.300000 218 +# 1538548685500 11.800000 221 +# 1538548696600 13.400000 223 +# 1538548685500 10.800000 223 +# 1538548686500 11.500000 221 +# fetched 0 rows +# fetching completed +# { count: 8, done: True } diff --git a/docs-examples/python/bind_param_example.py b/docs-examples/python/bind_param_example.py new file mode 100644 index 0000000000000000000000000000000000000000..503a2eb5dd91a3516f87a4d3c1c3218cb6505236 --- /dev/null +++ b/docs-examples/python/bind_param_example.py @@ -0,0 +1,60 @@ +import taos +from datetime import datetime + +# note: lines have already been sorted by table name +lines = [('d1001', '2018-10-03 14:38:05.000', 10.30000, 219, 0.31000, 'Beijing.Chaoyang', 2), + ('d1001', '2018-10-03 14:38:15.000', 12.60000, 218, 0.33000, 'Beijing.Chaoyang', 2), + ('d1001', '2018-10-03 14:38:16.800', 12.30000, 221, 0.31000, 'Beijing.Chaoyang', 2), + ('d1002', '2018-10-03 14:38:16.650', 10.30000, 218, 0.25000, 'Beijing.Chaoyang', 3), + ('d1003', '2018-10-03 14:38:05.500', 11.80000, 221, 0.28000, 'Beijing.Haidian', 2), + ('d1003', '2018-10-03 14:38:16.600', 13.40000, 223, 0.29000, 'Beijing.Haidian', 2), + ('d1004', '2018-10-03 14:38:05.000', 10.80000, 223, 0.29000, 'Beijing.Haidian', 3), + ('d1004', '2018-10-03 14:38:06.500', 11.50000, 221, 0.35000, 'Beijing.Haidian', 3)] + + +def get_ts(ts: str): + dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S.%f') + return int(dt.timestamp() * 1000) + + +def create_stable(): + conn = taos.connect() + try: + conn.execute("CREATE DATABASE power") + conn.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + finally: + conn.close() + + +def bind_row_by_row(stmt: taos.TaosStmt): + tb_name = None + for row in lines: + if tb_name != row[0]: + tb_name = row[0] + tags: taos.TaosBind = taos.new_bind_params(2) # 2 is count of tags + tags[0].binary(row[5]) # location + tags[1].int(row[6]) # groupId + stmt.set_tbname_tags(tb_name, tags) + values: taos.TaosBind = taos.new_bind_params(4) # 4 is count of columns + values[0].timestamp(get_ts(row[1])) + values[1].float(row[2]) + values[2].int(row[3]) + values[3].float(row[4]) + stmt.bind_param(values) + + +def insert_data(): + conn = taos.connect(database="power") + try: + stmt = conn.statement("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + bind_row_by_row(stmt) + stmt.execute() + stmt.close() + finally: + conn.close() + + +if __name__ == '__main__': + create_stable() + insert_data() diff --git a/docs-examples/python/connect_exmaple.py b/docs-examples/python/connect_exmaple.py new file mode 100644 index 0000000000000000000000000000000000000000..5d57ae6815ceda3c51c75d4e12d4ae9a7438469b --- /dev/null +++ b/docs-examples/python/connect_exmaple.py @@ -0,0 +1,20 @@ +import taos + + +def test_connection(): + # all parameters are optional. + # if database is specified, + # then it must exist. + # we use database log here, because it always exists. + conn = taos.connect(host="localhost", + port=6030, + user="root", + password="taosdata", + database="log") + print('client info:', conn.client_info) + print('server info:', conn.server_info) + conn.close() + + +if __name__ == "__main__": + test_connection() diff --git a/docs-examples/python/json_protocol_example.py b/docs-examples/python/json_protocol_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb4d629bccf3d79e74b381d6259de86d6522315 --- /dev/null +++ b/docs-examples/python/json_protocol_example.py @@ -0,0 +1,38 @@ +import json + +import taos +from taos import SmlProtocol, SmlPrecision + +lines = [{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, + "tags": {"location": "Beijing.Haidian", "groupid": 1}}, + {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, + "tags": {"location": "Beijing.Chaoyang", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "Beijing.Haidian", "groupid": 1}}] + + +def get_connection(): + return taos.connect() + + +def create_database(conn): + conn.execute("CREATE DATABASE test") + conn.execute("USE test") + + +def insert_lines(conn): + global lines + lines = json.dumps(lines) + # note: the first parameter must be a list with only one element. + affected_rows = conn.schemaless_insert( + [lines], SmlProtocol.JSON_PROTOCOL, SmlPrecision.NOT_CONFIGURED) + print(affected_rows) # 4 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs-examples/python/line_protocol_example.py b/docs-examples/python/line_protocol_example.py new file mode 100644 index 0000000000000000000000000000000000000000..02baeb2104f9f48984b4d34afb5e67af641d4e32 --- /dev/null +++ b/docs-examples/python/line_protocol_example.py @@ -0,0 +1,34 @@ +import taos +from taos import SmlProtocol, SmlPrecision + +lines = ["meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", + "meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500", + "meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300", + "meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800", + ] + + +def get_connection(): + # create connection use firstEP in taos.cfg. + return taos.connect() + + +def create_database(conn): + # the default precision is ms (microsecond), but we use us(microsecond) here. + conn.execute("CREATE DATABASE test precision 'us'") + conn.execute("USE test") + + +def insert_lines(conn): + affected_rows = conn.schemaless_insert( + lines, SmlProtocol.LINE_PROTOCOL, SmlPrecision.MICRO_SECONDS) + print(affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs-examples/python/multi_bind_example.py b/docs-examples/python/multi_bind_example.py new file mode 100644 index 0000000000000000000000000000000000000000..1714121d72705ab8d619a41f3463af4aa3193871 --- /dev/null +++ b/docs-examples/python/multi_bind_example.py @@ -0,0 +1,88 @@ +import taos +from datetime import datetime + +# ANCHOR: bind_batch +table_tags = { + "d1001": ('Beijing.Chaoyang', 2), + "d1002": ('Beijing.Chaoyang', 3), + "d1003": ('Beijing.Haidian', 2), + "d1004": ('Beijing.Haidian', 3) +} + +table_values = { + "d1001": [ + ['2018-10-03 14:38:05.000', '2018-10-03 14:38:15.000', '2018-10-03 14:38:16.800'], + [10.3, 12.6, 12.3], + [219, 218, 221], + [0.31, 0.33, 0.32] + ], + "d1002": [ + ['2018-10-03 14:38:16.650'], [10.3], [218], [0.25] + ], + "d1003": [ + ['2018-10-03 14:38:05.500', '2018-10-03 14:38:16.600'], + [11.8, 13.4], + [221, 223], + [0.28, 0.29] + ], + "d1004": [ + ['2018-10-03 14:38:05.500', '2018-10-03 14:38:06.500'], + [10.8, 11.5], + [223, 221], + [0.29, 0.35] + ] +} + + +def bind_multi_rows(stmt: taos.TaosStmt): + """ + batch bind example + """ + for tb_name in table_values.keys(): + tags = table_tags[tb_name] + tag_params = taos.new_bind_params(2) + tag_params[0].binary(tags[0]) + tag_params[1].int(tags[1]) + stmt.set_tbname_tags(tb_name, tag_params) + + values = table_values[tb_name] + value_params = taos.new_multi_binds(4) + value_params[0].timestamp([get_ts(t) for t in values[0]]) + value_params[1].float(values[1]) + value_params[2].int(values[2]) + value_params[3].float(values[3]) + stmt.bind_param_batch(value_params) + + +def insert_data(): + conn = taos.connect(database="power") + try: + stmt = conn.statement("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + bind_multi_rows(stmt) + stmt.execute() + stmt.close() + finally: + conn.close() + + +# ANCHOR_END: bind_batch + + +def create_stable(): + conn = taos.connect() + try: + conn.execute("CREATE DATABASE power") + conn.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + finally: + conn.close() + + +def get_ts(ts: str): + dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S.%f') + return int(dt.timestamp() * 1000) + + +if __name__ == '__main__': + create_stable() + insert_data() diff --git a/docs-examples/python/native_insert_example.py b/docs-examples/python/native_insert_example.py new file mode 100644 index 0000000000000000000000000000000000000000..94d4888a8f5330b9e39d5ae051fcb68f9825505f --- /dev/null +++ b/docs-examples/python/native_insert_example.py @@ -0,0 +1,60 @@ +import taos + +lines = ["d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,Beijing.Chaoyang,2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,Beijing.Haidian,3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,Beijing.Haidian,2", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,Beijing.Haidian,3", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,Beijing.Chaoyang,3", + "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,Beijing.Chaoyang,2", + "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,Beijing.Chaoyang,2", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,Beijing.Haidian,2"] + + +def get_connection() -> taos.TaosConnection: + """ + create connection use firstEp in taos.cfg and use default user and password. + """ + return taos.connect() + + +def create_stable(conn: taos.TaosConnection): + conn.execute("CREATE DATABASE power") + conn.execute("USE power") + conn.execute("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + + +# The generated SQL is: +# INSERT INTO d1001 USING meters TAGS(Beijing.Chaoyang, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) +# d1002 USING meters TAGS(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) +# d1003 USING meters TAGS(Beijing.Haidian, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) +# d1004 USING meters TAGS(Beijing.Haidian, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000) + +def get_sql(): + global lines + lines = map(lambda line: line.split(','), lines) # [['d1001', ...]...] + lines = sorted(lines, key=lambda ls: ls[0]) # sort by table name + sql = "INSERT INTO " + tb_name = None + for ps in lines: + tmp_tb_name = ps[0] + if tb_name != tmp_tb_name: + tb_name = tmp_tb_name + sql += f"{tb_name} USING meters TAGS({ps[5]}, {ps[6]}) VALUES " + sql += f"('{ps[1]}', {ps[2]}, {ps[3]}, {ps[4]}) " + return sql + + +def insert_data(conn: taos.TaosConnection): + sql = get_sql() + affected_rows = conn.execute(sql) + print("affected_rows", affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_stable(connection) + insert_data(connection) + finally: + connection.close() diff --git a/docs-examples/python/query_example.py b/docs-examples/python/query_example.py new file mode 100644 index 0000000000000000000000000000000000000000..6d33c49c968d9210b475931b5d8cecca0ceff3e3 --- /dev/null +++ b/docs-examples/python/query_example.py @@ -0,0 +1,42 @@ +import taos + + +# ANCHOR: iter +def query_api_demo(conn: taos.TaosConnection): + result: taos.TaosResult = conn.query("SELECT tbname, * FROM meters LIMIT 2") + print("field count:", result.field_count) + print("meta of fields[1]:", result.fields[1]) + print("======================Iterate on result=========================") + for row in result: + print(row) + + +# field count: 7 +# meta of files[1]: {name: ts, type: 9, bytes: 8} +# ======================Iterate on result========================= +# ('d1001', datetime.datetime(2018, 10, 3, 14, 38, 5), 10.300000190734863, 219, 0.3100000023841858, 'Beijing.Chaoyang', 2) +# ('d1001', datetime.datetime(2018, 10, 3, 14, 38, 15), 12.600000381469727, 218, 0.33000001311302185, 'Beijing.Chaoyang', 2) +# ANCHOR_END: iter + +# ANCHOR: fetch_all +def fetch_all_demo(conn: taos.TaosConnection): + result: taos.TaosResult = conn.query("SELECT ts, current FROM meters LIMIT 2") + rows = result.fetch_all_into_dict() + print("row count:", result.row_count) + print("===============all data===================") + print(rows) + + +# row count: 2 +# ===============all data=================== +# [{'ts': datetime.datetime(2018, 10, 3, 14, 38, 5), 'current': 10.300000190734863}, +# {'ts': datetime.datetime(2018, 10, 3, 14, 38, 15), 'current': 12.600000381469727}] +# ANCHOR_END: fetch_all + +if __name__ == '__main__': + connection = taos.connect(database="power") + try: + query_api_demo(connection) + fetch_all_demo(connection) + finally: + connection.close() diff --git a/docs-examples/python/telnet_line_protocol_example.py b/docs-examples/python/telnet_line_protocol_example.py new file mode 100644 index 0000000000000000000000000000000000000000..072835109ee238940e6fe5880b72b2b04e0157fa --- /dev/null +++ b/docs-examples/python/telnet_line_protocol_example.py @@ -0,0 +1,38 @@ +import taos +from taos import SmlProtocol, SmlPrecision + +# format: =[ =] +lines = ["meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3", + "meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3", + ] + + +# create connection use firstEp in taos.cfg. +def get_connection(): + return taos.connect() + + +def create_database(conn): + conn.execute("CREATE DATABASE test") + conn.execute("USE test") + + +def insert_lines(conn): + affected_rows = conn.schemaless_insert( + lines, SmlProtocol.TELNET_PROTOCOL, SmlPrecision.NOT_CONFIGURED) + print(affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs-examples/rust/Cargo.toml b/docs-examples/rust/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..114407e69edcb94fdeef77e6ae581569c5451160 --- /dev/null +++ b/docs-examples/rust/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["restexample", "nativeexample", "schemalessexample"] diff --git a/docs-examples/rust/nativeexample/Cargo.toml b/docs-examples/rust/nativeexample/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..64fd10a3e915a39c321b56b6f38be51417d8d18e --- /dev/null +++ b/docs-examples/rust/nativeexample/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "nativeexample" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[dependencies] +libtaos = { version = "0.4.3" } +tokio = { version = "*", features = ["rt", "macros", "rt-multi-thread"] } +bstr = { version = "*" } diff --git a/docs-examples/rust/nativeexample/examples/connect.rs b/docs-examples/rust/nativeexample/examples/connect.rs new file mode 100644 index 0000000000000000000000000000000000000000..8e27458de5d428479668a0e5133ca904cf27c213 --- /dev/null +++ b/docs-examples/rust/nativeexample/examples/connect.rs @@ -0,0 +1,19 @@ +use libtaos::*; + +fn taos_connect() -> Result { + TaosCfgBuilder::default() + .ip("localhost") + .user("root") + .pass("taosdata") + // .db("log") // remove comment if you want to connect to database log by default. + .port(6030u16) + .build() + .expect("TaosCfg builder error") + .connect() +} + +fn main() { + #[allow(unused_variables)] + let taos = taos_connect().unwrap(); + println!("Connected") +} diff --git a/docs-examples/rust/nativeexample/examples/stmt_example.rs b/docs-examples/rust/nativeexample/examples/stmt_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..a791a4135984a33dded145e8175d7ade57de8d77 --- /dev/null +++ b/docs-examples/rust/nativeexample/examples/stmt_example.rs @@ -0,0 +1,38 @@ +use bstr::BString; +use libtaos::*; + +#[tokio::main] +async fn main() -> Result<(), Error> { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.create_database("power").await?; + taos.use_database("power").await?; + taos.exec("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?; + let mut stmt = taos.stmt("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")?; + // bind table name and tags + stmt.set_tbname_tags( + "d1001", + [ + Field::Binary(BString::from("Beijing.Chaoyang")), + Field::Int(2), + ], + )?; + // bind values. + let values = vec![ + Field::Timestamp(Timestamp::new(1648432611249, TimestampPrecision::Milli)), + Field::Float(10.3), + Field::Int(219), + Field::Float(0.31), + ]; + stmt.bind(&values)?; + // bind one more row + let values2 = vec![ + Field::Timestamp(Timestamp::new(1648432611749, TimestampPrecision::Milli)), + Field::Float(12.6), + Field::Int(218), + Field::Float(0.33), + ]; + stmt.bind(&values2)?; + // execute + stmt.execute()?; + Ok(()) +} diff --git a/docs-examples/rust/nativeexample/src/main.rs b/docs-examples/rust/nativeexample/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..e7a11a969c037e00a796aafeff6258501ec15e9a --- /dev/null +++ b/docs-examples/rust/nativeexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/docs-examples/rust/restexample/Cargo.toml b/docs-examples/rust/restexample/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5f89f8a3be3baabd298a70947f6c5d3df088aae --- /dev/null +++ b/docs-examples/rust/restexample/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "restexample" +version = "0.1.0" +edition = "2021" + +[dependencies] +libtaos = { version = "0.4.3", features = ["rest"] } +tokio = { version = "*", features = ["rt", "macros", "rt-multi-thread"] } diff --git a/docs-examples/rust/restexample/examples/connect.rs b/docs-examples/rust/restexample/examples/connect.rs new file mode 100644 index 0000000000000000000000000000000000000000..546bc1f3f439e0dd691940b472d15c0104f2c8f9 --- /dev/null +++ b/docs-examples/rust/restexample/examples/connect.rs @@ -0,0 +1,19 @@ +use libtaos::*; + +fn taos_connect() -> Result { + TaosCfgBuilder::default() + .ip("localhost") + .user("root") + .pass("taosdata") + // .db("log") // remove comment if you want to connect to database log by default. + .port(6030u16) + .build() + .expect("TaosCfg builder error") + .connect() +} + +fn main() { + #[allow(unused_variables)] + let taos = taos_connect().expect("connect error"); + println!("Connected") +} diff --git a/docs-examples/rust/restexample/examples/insert_example.rs b/docs-examples/rust/restexample/examples/insert_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..a0ee1eb3dfb86e9f88aaafeefd2b4b58510a333c --- /dev/null +++ b/docs-examples/rust/restexample/examples/insert_example.rs @@ -0,0 +1,18 @@ +use libtaos::*; + +#[tokio::main] +async fn main() -> Result<(), Error> { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.create_database("power").await?; + taos.exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?; + let sql = "INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) + power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) + power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"; + let result = taos.query(sql).await?; + println!("{:?}", result); + Ok(()) +} + +// stdout: +// TaosQueryData { column_meta: [ColumnMeta { name: "affected_rows", type_: Int, bytes: 4 }], rows: [[Int(8)]] } diff --git a/docs-examples/rust/restexample/examples/query_example.rs b/docs-examples/rust/restexample/examples/query_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..8a5c45641d5902e50e2601990a442d60098b7407 --- /dev/null +++ b/docs-examples/rust/restexample/examples/query_example.rs @@ -0,0 +1,39 @@ +use libtaos::*; + +fn taos_connect() -> Result { + TaosCfgBuilder::default() + .ip("localhost") + .user("root") + .pass("taosdata") + .db("power") + .port(6030u16) + .build() + .expect("TaosCfg builder error") + .connect() +} + +#[tokio::main] +async fn main() -> Result<(), Error> { + let taos = taos_connect().expect("connect error"); + let result = taos.query("SELECT ts, current FROM meters LIMIT 2").await?; + // print column names + let meta: Vec = result.column_meta; + for column in meta { + print!("{}\t", column.name) + } + println!(); + // print rows + let rows: Vec> = result.rows; + for row in rows { + for field in row { + print!("{}\t", field); + } + println!(); + } + Ok(()) +} + +// stdout: +// ts current +// 2022-03-28 09:56:51.249 10.3 +// 2022-03-28 09:56:51.749 12.6 diff --git a/docs-examples/rust/restexample/src/main.rs b/docs-examples/rust/restexample/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..e7a11a969c037e00a796aafeff6258501ec15e9a --- /dev/null +++ b/docs-examples/rust/restexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/docs-examples/rust/schemalessexample/Cargo.toml b/docs-examples/rust/schemalessexample/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..32c6a122318d16f488210da54f1600ba8f6a8b7c --- /dev/null +++ b/docs-examples/rust/schemalessexample/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "schemalessexample" +version = "0.1.0" +edition = "2021" + +[dependencies] +libtaos = { version = "0.4.3" } diff --git a/docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs b/docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..e93888cc83d12f3bec7370a66e8a85d38cec42ad --- /dev/null +++ b/docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs @@ -0,0 +1,22 @@ +use libtaos::schemaless::*; +use libtaos::*; + +fn main() { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.raw_query("CREATE DATABASE test").unwrap(); + taos.raw_query("USE test").unwrap(); + let lines = ["meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250"]; + let affected_rows = taos + .schemaless_insert( + &lines, + TSDB_SML_LINE_PROTOCOL, + TSDB_SML_TIMESTAMP_MILLISECONDS, + ) + .unwrap(); + println!("affected_rows={}", affected_rows); +} + +// run with: cargo run --example influxdb_line_example diff --git a/docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs b/docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..1d66bd1f2b1bcbe82dc3ee3e8e25ea4c521c81f0 --- /dev/null +++ b/docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs @@ -0,0 +1,25 @@ +use libtaos::schemaless::*; +use libtaos::*; + +fn main() { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.raw_query("CREATE DATABASE test").unwrap(); + taos.raw_query("USE test").unwrap(); + let lines = [ + r#"[{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "Beijing.Haidian", "groupid": 1}}, + {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "Beijing.Haidian", "groupid": 1}}]"#, + ]; + + let affected_rows = taos + .schemaless_insert( + &lines, + TSDB_SML_JSON_PROTOCOL, + TSDB_SML_TIMESTAMP_NOT_CONFIGURED, + ) + .unwrap(); + println!("affected_rows={}", affected_rows); // affected_rows=4 +} + +// run with: cargo run --example opentsdb_json_example diff --git a/docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs b/docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..18d7500714d9e41b1bebd490199d296ead3dc7c4 --- /dev/null +++ b/docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs @@ -0,0 +1,28 @@ +use libtaos::schemaless::*; +use libtaos::*; + +fn main() { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.raw_query("CREATE DATABASE test").unwrap(); + taos.raw_query("USE test").unwrap(); + let lines = [ + "meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2", + "meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3", + "meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2", + "meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3", + "meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3", + ]; + let affected_rows = taos + .schemaless_insert( + &lines, + TSDB_SML_TELNET_PROTOCOL, + TSDB_SML_TIMESTAMP_NOT_CONFIGURED, + ) + .unwrap(); + println!("affected_rows={}", affected_rows); // affected_rows=8 +} + +// run with: cargo run --example opentsdb_telnet_example diff --git a/docs-examples/rust/schemalessexample/src/main.rs b/docs-examples/rust/schemalessexample/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..e7a11a969c037e00a796aafeff6258501ec15e9a --- /dev/null +++ b/docs-examples/rust/schemalessexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/documentation20/cn/00.index/docs.md b/documentation20/cn/00.index/docs.md index a48ea49f59ce3fbccf5370de2276692f8e367fe3..d426a74da1342a04a3714dc497c13b1dc287dffd 100644 --- a/documentation20/cn/00.index/docs.md +++ b/documentation20/cn/00.index/docs.md @@ -96,6 +96,7 @@ TDengine 是一个高效的存储、查询、分析时序大数据的平台, - [IDEA Database](https://www.taosdata.com/blog/2020/08/27/1767.html):通过 IDEA 数据库管理工具可视化使用 TDengine - [TDengineGUI](https://github.com/skye0207/TDengineGUI):基于 Electron 开发的跨平台 TDengine 图形化管理工具 - [DataX](https://www.taosdata.com/blog/2021/10/26/3156.html):支持 TDengine 和其他数据库之间进行数据迁移的工具 +- [Awesome TDengine](https://github.com/taosdata/awesome-tdengine):与 TDengine 有关的精彩项目精选清单 ## [TDengine 集群的安装、管理](/cluster) diff --git a/documentation20/cn/02.getting-started/01.docker/docs.md b/documentation20/cn/02.getting-started/01.docker/docs.md index 5a9869c60dbbc45681ba0b89d5f02e86a8e7292b..be582aeec345f683836f3f2740cafa99a3dd990a 100644 --- a/documentation20/cn/02.getting-started/01.docker/docs.md +++ b/documentation20/cn/02.getting-started/01.docker/docs.md @@ -121,7 +121,7 @@ TDengine RESTful 接口详情请参考[官方文档](https://www.taosdata.com/cn ### 使用 Docker 容器运行 TDengine server 和 taosAdapter -在 TDegnine 2.4.0.0 之后版本的 Docker 容器,开始提供一个独立运行的组件 taosAdapter,代替之前版本 TDengine 中 taosd 进程中内置的 http server。taosAdapter 支持通过 RESTful 接口对 TDengine server 的数据写入和查询能力,并提供和 InfluxDB/OpenTSDB 兼容的数据摄取接口,允许 InfluxDB/OpenTSDB 应用程序无缝移植到 TDengine。在新版本 Docker 镜像中,默认启用了 taosAdapter,也可以使用 docker run 命令中设置 TAOS_DISABLE_ADAPTER=true 来禁用 taosAdapter;也可以在 docker run 命令中单独使用taosAdapter,而不运行 taosd 。 +在 TDengine 2.4.0.0 之后版本的 Docker 容器,开始提供一个独立运行的组件 taosAdapter,代替之前版本 TDengine 中 taosd 进程中内置的 http server。taosAdapter 支持通过 RESTful 接口对 TDengine server 的数据写入和查询能力,并提供和 InfluxDB/OpenTSDB 兼容的数据摄取接口,允许 InfluxDB/OpenTSDB 应用程序无缝移植到 TDengine。在新版本 Docker 镜像中,默认启用了 taosAdapter,也可以使用 docker run 命令中设置 TAOS_DISABLE_ADAPTER=true 来禁用 taosAdapter;也可以在 docker run 命令中单独使用taosAdapter,而不运行 taosd 。 注意:如果容器中运行 taosAdapter,需要根据需要映射其他端口,具体端口默认配置和修改方法请参考[taosAdapter文档](https://github.com/taosdata/taosadapter/blob/develop/README-CN.md)。 @@ -227,7 +227,7 @@ taos> - **查看数据库。** ```bash -$ taos> show databases; +$ taos> SHOW DATABASES; name | created_time | ntables | vgroups | ··· test | 2021-08-18 06:01:11.021 | 10000 | 6 | ··· log | 2021-08-18 05:51:51.065 | 4 | 1 | ··· @@ -240,7 +240,7 @@ $ taos> show databases; $ taos> use test; Database changed. -$ taos> show stables; +$ taos> SHOW STABLES; name | created_time | columns | tags | tables | ============================================================================================ meters | 2021-08-18 06:01:11.116 | 4 | 2 | 10000 | @@ -251,10 +251,7 @@ Query OK, 1 row(s) in set (0.003259s) - **查看表,限制输出十条。** ```bash -$ taos> select * from test.t0 limit 10; - -DB error: Table does not exist (0.002857s) -taos> select * from test.d0 limit 10; +taos> SELECT * FROM test.d0 LIMIT 10; ts | current | voltage | phase | ====================================================================================== 2017-07-14 10:40:00.000 | 10.12072 | 223 | 0.34167 | @@ -274,7 +271,7 @@ Query OK, 10 row(s) in set (0.016791s) - **查看 d0 表的标签值。** ```bash -$ taos> select groupid, location from test.d0; +$ taos> SELECT groupid, location FROM test.d0; groupid | location | ================================= 0 | shanghai | @@ -292,7 +289,7 @@ echo "foo:1|c" | nc -u -w0 127.0.0.1 6044 然后可以使用 taos shell 查询 taosAdapter 自动创建的数据库 statsd 和 超级表 foo 中的内容: ``` -taos> show databases; +taos> SHOW DATABASES; name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | ==================================================================================================================================================================================================================================================================================== log | 2021-12-28 09:18:55.765 | 12 | 1 | 1 | 1 | 10 | 30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | 0 | us | 0 | ready | @@ -302,13 +299,13 @@ Query OK, 2 row(s) in set (0.002112s) taos> use statsd; Database changed. -taos> show stables; +taos> SHOW STABLES; name | created_time | columns | tags | tables | ============================================================================================ foo | 2021-12-28 09:21:48.894 | 2 | 1 | 1 | Query OK, 1 row(s) in set (0.001160s) -taos> select * from foo; +taos> SELECT * FROM foo; ts | value | metric_type | ======================================================================================= 2021-12-28 09:21:48.840820836 | 1 | counter | diff --git a/documentation20/cn/02.getting-started/02.taosdemo/docs.md b/documentation20/cn/02.getting-started/02.taosdemo/docs.md index 8d555c4778187394b8849113d68afff6d1158a4d..015e79599ecea0ad6d96dc46602491c393960725 100644 --- a/documentation20/cn/02.getting-started/02.taosdemo/docs.md +++ b/documentation20/cn/02.getting-started/02.taosdemo/docs.md @@ -1,6 +1,6 @@ # 如何使用 taosBenchmark 进行性能测试 -自从 TDengine 2019年 7 月开源以来,凭借创新的数据建模设计、快捷的安装方式、易用的编程接口和强大的数据写入查询性能博得了大量时序数据开发者的青睐。其中写入和查询性能往往令刚接触 TDengine 的用户称叹不已。为了便于用户在最短时间内就可以体验到 TDengine 的高性能特点,我们专门开发了一个应用程序 taosBenchmark (曾命名为 taosdemo)用于对 TDengine 进行写入和查询的性能测试,用户可以通过 taosBenchmark 轻松模拟大量设备产生海量数据的场景,并且可以通过 taosBenchmark 参数灵活控制表的列数、数据类型、乱序比例以及并发线程数量。 +自从 TDengine 2019年 7 月开源以来,凭借创新的数据建模设计、快捷的安装方式、易用的编程接口和强大的数据写入查询性能博得了大量时序数据开发者的青睐。其中写入和查询性能往往令刚接触 TDengine 的用户称叹不已。为了便于用户在最短时间内就可以体验到 TDengine 的高性能特点,我们专门开发了一个应用程序 taosBenchmark (曾命名为 taosdemo)用于对 TDengine 进行写入和查询的性能测试,用户可以通过 taosBenchmark 轻松模拟大量设备产生海量数据的场景,并且可以通过 taosBenchmark 参数灵活按照实际场景定制表的个数(对应设备数)、表的列数(对应每个设备采样点)、数据类型、乱序数据比例、顺序或轮询插入方式、以及并发线程数量。 运行 taosBenchmark 很简单,通过下载 [TDengine 安装包](https://www.taosdata.com/cn/all-downloads/)或者自行下载 [TDengine 代码](https://github.com/taosdata/TDengine)编译都可以在安装目录或者编译结果目录中找到并运行。 @@ -153,41 +153,70 @@ insert delay, avg: 8.31ms, max: 860.12ms, min: 2.00ms ``` $ taosBenchmark --help --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. --p, --password The password to use when connecting to the server. --c, --config-dir=CONFIG_DIR Configuration directory. --h, --host=HOST TDengine server FQDN to connect. The default host is localhost. --P, --port=PORT The TCP/IP port number to use for the connection. --I, --interface=INTERFACE The interface (taosc, rest, and stmt) taosBenchmark uses. By default use 'taosc'. --d, --database=DATABASE Destination database. By default is 'test'. --a, --replica=REPLICA Set the replica parameters of the database, By default use 1, min: 1, max: 3. --m, --table-prefix=TABLEPREFIX Table prefix name. By default use 'd'. --s, --sql-file=FILE The select sql file. --N, --normal-table Use normal table flag. --o, --output=FILE Direct output to the named file. By default use './output.txt'. --q, --query-mode=MODE Query mode -- 0: SYNC, 1: ASYNC. By default use SYNC. --b, --data-type=DATATYPE The data_type of columns, By default use: FLOAT, INT, FLOAT. --w, --binwidth=WIDTH The width of data_type 'BINARY' or 'NCHAR'. By default use 64 --l, --columns=COLUMNS The number of columns per record. Demo mode by default is 1 (float, int, float). Max values is 4095 -All of the new column(s) type is INT. If use -b to specify column type, -l will be ignored. --T, --threads=NUMBER The number of threads. By default use 8. --i, --insert-interval=NUMBER The sleep time (ms) between insertion. By default is 0. --S, --time-step=TIME_STEP The timestamp step between insertion. By default is 1. --B, --interlace-rows=NUMBER The interlace rows of insertion. By default is 0. --r, --rec-per-req=NUMBER The number of records per request. By default is 30000. --t, --tables=NUMBER The number of tables. By default is 10000. --n, --records=NUMBER The number of records per table. By default is 10000. --M, --random The value of records generated are totally random. -By default to simulate power equipment scenario. --x, --aggr-func Test aggregation functions after insertion. --y, --answer-yes Input yes for prompt. --O, --disorder=NUMBER Insert order mode--0: In order, 1 ~ 50: disorder ratio. By default is in order. --R, --disorder-range=NUMBER Out of order data's range. Unit is ms. By default is 1000. --g, --debug Print debug info. --?, --help Give this help list ---usage Give a short usage message --V, --version Print program version. +Usage: taosBenchmark [OPTION...] + + -f, --file=FILE (**IMPORTANT**) Set JSON configuration file(all + options are going to read from this JSON file), + which is mutually exclusive with other commandline + options + -a, --replia=NUMBER The number of replica when create database, + default is 1. + -A, --tag-type=TAG_TYPE Data type of tables' tags, default is + INT,BINARY(16). + -b, --data-type=COL_TYPE Data type of tables' cols, default is + FLOAT,INT,FLOAT. + -B, --interlace-rows=NUMBER The number of interlace rows insert into + tables, default is 0 + -c, --config-dir=CONFIG_DIR Configuration directory. + -C, --chinese Nchar and binary are basic unicode chinese + characters, optional. + -d, --database=DATABASE Name of database, default is test. + -E, --escape-character Use escape character in stable and child table + name, optional. + -F, --prepared_rand=NUMBER Random data source size, default is 10000. + -g, --debug Debug mode, optional. + -G, --performance Performance mode, optional. + -h, --host=HOST TDengine server FQDN to connect, default is + localhost. + -i, --insert-interval=NUMBER Insert interval for interlace mode in + milliseconds, default is 0. + -I, --interface=IFACE insert mode, default is taosc, options: + taosc|rest|stmt|sml + -l, --columns=NUMBER Number of INT data type columns in table, default + is 0. + -m, --table-prefix=TABLE_PREFIX + Prefix of child table name, default is d. + -M, --random Data source is randomly generated, optional. + -n, --records=NUMBER Number of records for each table, default is + 10000. + -N, --normal-table Only create normal table without super table, + optional. + -o, --output=FILE The path of result output file, default is + ./output.txt. + -O, --disorder=NUMBER Ratio of inserting data with disorder timestamp, + default is 0. + -p, --password=PASSWORD The password to use when connecting to the server, + default is taosdata. + -P, --port=PORT The TCP/IP port number to use for the connection, + default is 6030. + -r, --rec-per-req=NUMBER Number of records in each insert request, default + is 30000. + -R, --disorder-range=NUMBER Range of disordered timestamp, default is 1000. + + -S, --time-step=NUMBER Timestamp step in milliseconds, default is 1. + -t, --tables=NUMBER Number of child tables, default is 10000. + -T, --threads=NUMBER The number of thread when insert data, default is + 8. + -u, --user=USER The user name to use when connecting to the + server, default is root. + -w, --binwidth=NUMBER The default length of nchar and binary if not + specified, default is 64. + -x, --aggr-func Query aggregation function after insertion, + optional. + -y, --answer-yes Pass confirmation prompt to continue, optional. + -?, --help Give this help list + --usage Give a short usage message + -V, --version Print program version Mandatory or optional arguments to long options are also mandatory or optional for any corresponding short options. @@ -198,7 +227,7 @@ Report bugs to . taosBenchmark 的参数是为了满足数据模拟的需求来设计的。下面介绍几个常用的参数: ``` --I, --interface=INTERFACE The interface (taosc, rest, and stmt) taosBenchmark uses. Default is 'taosc'. +-I, --interface=IFACE The interface (taosc, rest, and stmt) taosBenchmark uses. Default is 'taosc'. ``` 前面介绍 taosBenchmark 不同接口的性能差异已经提到, -I 参数为选择不同的接口,目前支持 taosc、stmt 和 rest 几种。其中 taosc 为使用 SQL 语句方式进行数据写入;stmt 为使用参数绑定接口进行数据写入;rest 为使用 RESTful 协议进行数据写入。 @@ -339,6 +368,7 @@ select first(current) took 0.024105 second(s) "start_timestamp": "2020-10-01 00:00:00.000", "sample_format": "csv", "sample_file": "./sample.csv", + "use_sample_ts": "no", "tags_file": "", "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] @@ -347,7 +377,7 @@ select first(current) took 0.024105 second(s) } ``` -例如:我们可以通过 "thread_count" 和 "thread_count_create_tbl" 来为建表和插入数据指定不同数量的线程。可以通过 "child_table_exists"、"childtable_limit" 和 "childtable_offset" 的组合来使用多个 taosBenchmark 进程(甚至可以在不同的电脑上)对同一个超级表的不同范围子表进行同时写入。也可以通过 "data_source" 和 "sample_file" 来指定数据来源为 csv 文件,来实现导入已有数据的功能。 +例如:我们可以通过 "thread_count" 和 "thread_count_create_tbl" 来为建表和插入数据指定不同数量的线程。可以通过 "child_table_exists"、"childtable_limit" 和 "childtable_offset" 的组合来使用多个 taosBenchmark 进程(甚至可以在不同的电脑上)对同一个超级表的不同范围子表进行同时写入。也可以通过 "data_source" 和 "sample_file" 来指定数据来源为 CSV 文件,来实现导入已有数据的功能。CSV 为半角逗号分隔的数据文件,每行数据列数需要和表的数据列数(如果是标签数据,是和标签数)相同。 ## 使用 taosBenchmark 进行查询和订阅测试 @@ -401,16 +431,16 @@ taosBenchmark 不仅仅可以进行数据写入,也可以执行查询和订阅 "query_times": 每种查询类型的查询次数 "query_mode": 查询数据接口,"taosc":调用TDengine的c接口;“restful”:使用 RESTful 接口。可选项。缺省是“taosc”。 "specified_table_query": { 指定表的查询 -"query_interval": 执行sqls的间隔,单位是秒。可选项,缺省是0。 -"concurrent": 并发执行sqls的线程数,可选项,缺省是1。每个线程都执行所有的sqls。 -"sqls": 可以添加多个sql语句,最多支持100条。 +"query_interval": 执行 sqls 的间隔,单位是秒。可选项,缺省是0。 +"concurrent": 并发执行 sqls 的线程数,可选项,缺省是1。每个线程都执行所有的 sqls。 +"sqls": 可以添加多个 SQL 语句,最多支持 100 条。 "sql": 查询语句。必选项。 "result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 "super_table_query": { 对超级表中所有子表的查询 "stblname": 超级表名称。必选项。 -"query_interval": 执行sqls的间隔,单位是秒。可选项,缺省是0。 -"threads": 并发执行sqls的线程数,可选项,缺省是1。每个线程负责一部分子表,执行所有的sqls。 -"sql": "select count(*) from xxxx"。查询超级表内所有子表的查询语句,其中表名必须写成 “xxxx”,实例会自动替换成子表名。 +"query_interval": 执行 sqls 的间隔,单位是秒。可选项,缺省是0。 +"threads": 并发执行 sqls 的线程数,可选项,缺省是1。每个线程负责一部分子表,执行所有的 sqls。 +"sql": "SELECT COUNT(*) FROM xxxx"。查询超级表内所有子表的查询语句,其中表名必须写成 “xxxx”,实例会自动替换成子表名。 "result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 ``` @@ -463,7 +493,7 @@ taosBenchmark 不仅仅可以进行数据写入,也可以执行查询和订阅 "restart": 订阅重启。"yes":如果订阅已经存在,重新开始,"no": 继续之前的订阅。(请注意执行用户需要对 dataDir 目录有读写权限) "keepProgress": 保留订阅信息进度。yes表示保留订阅信息,no表示不保留。该值为yes,restart为no时,才能继续之前的订阅。 "resubAfterConsume": 配合 keepProgress 使用,在订阅消费了相应次数后调用 unsubscribe 取消订阅并再次订阅。 -"result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 注意:每条sql语句后的保存结果的文件不能重名,且生成结果文件时,文件名会附加线程号。 +"result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 注意:每条 SQL 语句后的保存结果的文件不能重名,且生成结果文件时,文件名会附加线程号。 ``` ## 结语 @@ -478,7 +508,7 @@ taosBenchmark支持两种配置参数的模式,一种是命令行参数,一 一、命令行参数 --f:指定taosBenchmark所需参数的meta文件。当使用该参数时,其他所有命令行参数都失效。可选项,缺省是NULL。目前仅支持不含 BOM(byte-order mark)的标准 UTF-8 编码文件。 +-f:指定 taosBenchmark 所需参数的 JSON 配置文件。当使用该参数时,其他所有命令行参数都失效。可选项,缺省是 NULL。目前仅支持不含 BOM(byte-order mark)的标准 UTF-8 编码文件。 -u: 用户名。可选项,缺省是“root“。 @@ -512,7 +542,7 @@ taosBenchmark支持两种配置参数的模式,一种是命令行参数,一 -T:并发线程数。可选项,缺省是10。 --i:两次sql插入的休眠时间间隔,缺省是0。 +-i:两次 SQL 插入的休眠时间间隔,缺省是0。 -S:两次插入间隔时间戳步长,缺省是1。 @@ -601,7 +631,7 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "start_timestamp": "2020-10-01 00:00:00.000", "sample_format": "csv", "sample_file": "./sample.csv", - "use_sample_ts": "no", + "use_sample_ts": "no", "tags_file": "", "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] @@ -632,9 +662,9 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "insert_interval": 两次发送请求的间隔时间。可选项,缺省是0,代表无人工设置的时间间隔,单位为ms。。 -"interlace_rows": 设置轮询插入每个单表数据的条目数,如果interlace_rows*childtable_count*supertable_num小于num_of_records_per_req时,则请求插入的数目以interlace_rows*childtable_count*supertable_num为准。可选项,缺省是0。 +"interlace_rows": 设置轮询插入每个单表数据的条目数,如果 interlace_rows * childtable_count * supertable_num 小于 num_of_records_per_req 时,则请求插入的数目以 interlace_rows * childtable_count * supertable_num 为准。可选项,缺省是 0。 -"num_of_records_per_req": 每条请求数据内容包含的插入数据记录数目,该数据组成的sql不能大于maxsqllen,如果过大,则取taosd限制的1M长度(1048576)。0代表不插入数据,建议配置大于0。 +"num_of_records_per_req": 每条请求数据内容包含的插入数据记录数目,该数据组成的 SQL 不能大于 maxSqlLen,如果过大,则取 taosd 限制的1M长度(1048576)。0 代表不插入数据,建议配置大于 0。 "databases": [{ @@ -680,7 +710,7 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "auto_create_table": 子表的创建方式,“yes”:自动建表;"no":提前建表。可选项,缺省是“no”。当 child_table_exists 为 “yes” 时此参数将自动置为 no 。 -"batch_create_tbl_num": 一个sql批量创建子表的数目。 +"batch_create_tbl_num": 一个 SQL 批量创建子表的数目。 "data_source": 插入数据来源,"rand":实例随机生成;“sample”:从样例文件中读取。可选项。缺省是“rand”。 @@ -706,31 +736,31 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "start_timestamp": 子表中记录时间戳的起始值,支持"2020-10-01 00:00:00.000"和“now”两种格式,可选项,缺省是“now”。 -"sample_format": 当插入数据源选择“sample”时,sample文件的格式,"csv":csv格式,每列的值与子表的columns保持一致,但不包含第1列的时间戳。可选项,缺省是”csv”。目前仅仅支持csv格式的sample文件。 +"sample_format": 当插入数据源选择“sample”时,sample文件的格式,"csv":CSV 格式,每列的值与子表的 columns 保持一致,但不包含第1列的时间戳。可选项,缺省是”csv”。目前仅仅支持 CSV 格式的 sample 文件。 "sample_file":sample文件,包含路径和文件名。当插入数据源选择“sample”时,该项为必选项。 -"use_sample_ts":sample文件是否包含第一列时间戳,可选项: "yes" 和 "no", 默认 "no"。(注意:若为yes,则disorder_ratio 和 disorder_range失效) +"use_sample_ts":sample 文件是否包含第一列时间戳,可选项: "yes" 和 "no", 默认 "no"。(注意:若为 yes,则 disorder_ratio 和 disorder_range 失效) -"tags_file": 子表tags值文件,只能是csv文件格式,且必须与超级表的tags保持一致。当该项为非空时,表示子表的tags值从文件中获取;为空时,实例随机生成。可选项,缺省是空。 +"tags_file": 子表 tags 值文件,只能是 CSV 文件格式,且必须与超级表的tags保持一致。当该项为非空时,表示子表的tags值从文件中获取;为空时,实例随机生成。可选项,缺省是空。 -"columns": [{ 超级表的column列表,最大支持1024列(指所有普通列+超级列总和)。默认的第一列为时间类型,程序自动添加,不需要手工添加。 +"columns": [{ 超级表的 column 列表,最大支持 4096 列(指所有普通列+超级列总和)。默认的第一列为时间类型,程序自动添加,不需要手工添加。 "type": 该列的数据类型 ,必选项。 -"len": 该列的长度,只有type是BINARY或NCHAR时有效,可选项,缺省值是8。 +"len": 该列的长度,只有 type 是 BINARY 或 NCHAR 时有效,可选项,缺省值是 8。 -"count":该类型的连续列个数,可选项,缺省是1。 +"count":该类型的连续列个数,可选项,缺省是 1。 }], -"tags": [{ 超级表的tags列表,type不能是timestamp类型, 最大支持128个。 +"tags": [{ 超级表的 tags 列表,type不能是 TIMESTAMP 类型, 最大支持 128 个。 "type": 该列的数据类型 ,必选项。 -"len": 该列的长度,只有type是BINARY或NCHAR时有效,可选项,缺省值是8。 +"len": 该列的长度,只有 type 是 BINARY 或 NCHAR 时有效,可选项,缺省值是 8。 -"count":该类型的连续列个数,可选项,缺省是1。 +"count":该类型的连续列个数,可选项,缺省是 1。 }] @@ -798,11 +828,11 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "specified_table_query": { 指定表的查询 -"query_interval": 执行sqls的间隔,单位是秒。可选项,缺省是0。 +"query_interval": 执行 sqls 的间隔,单位是秒。可选项,缺省是0。 -"concurrent": 并发执行sqls的线程数,可选项,缺省是1。每个线程都执行所有的sqls。 +"concurrent": 并发执行 sqls 的线程数,可选项,缺省是1。每个线程都执行所有的 sqls。 -"sqls": 可以添加多个sql语句,最多支持100条。 +"sqls": 可以添加多个 SQL 语句,最多支持100条。 "sql": 查询语句。必选项。 @@ -812,15 +842,15 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "stblname": 超级表名称。必选项。 -"query_interval": 执行sqls的间隔,单位是秒。可选项,缺省是0。 +"query_interval": 执行 sqls 的间隔,单位是秒。可选项,缺省是0。 -"threads": 并发执行sqls的线程数,可选项,缺省是1。每个线程负责一部分子表,执行所有的sqls。 +"threads": 并发执行 sqls 的线程数,可选项,缺省是1。每个线程负责一部分子表,执行所有的 sqls。 "sql": "select count(*) from xxxx"。查询超级表内所有子表的查询语句,其中表名必须写成 “xxxx”,实例会自动替换成子表名。 "result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 -注意:每条sql语句后的保存结果的文件不能重名,且生成结果文件时,文件名会附加线程号。 +注意:每条 SQL 语句后的保存结果的文件不能重名,且生成结果文件时,文件名会附加线程号。 查询结果显示:如果查询线程结束一次查询距开始执行时间超过30秒打印一次查询次数、用时和QPS。所有查询结束时,汇总打印总的查询次数和QPS。 @@ -882,11 +912,11 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "confirm_parameter_prompt": 执行过程中提示是否确认,为no时,执行过程无需手工输入enter。可选项,缺省是no。 -注意:这里的订阅查询sql目前只支持select * ,其余不支持。 +注意:这里的订阅查询 SQL 目前只支持 SELECT * ,其余不支持。 "specified_table_query": 指定表的订阅。 -"concurrent": 并发执行sqls的线程数,可选项,缺省是1。每个线程都执行所有的sqls。 +"concurrent": 并发执行 sqls 的线程数,可选项,缺省是1。每个线程都执行所有的 sqls。 "mode": 订阅模式。目前支持同步和异步订阅,缺省是sync。 @@ -906,11 +936,11 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "stblname": 超级表名称。必选项。 -"threads": 并发执行sqls的线程数,可选项,缺省是1。每个线程都执行所有的sqls。 +"threads": 并发执行 sqls 的线程数,可选项,缺省是1。每个线程都执行所有的 sqls。 "mode": 订阅模式。 -"interval": 执行sqls的间隔,单位是秒。可选项,缺省是0。 +"interval": 执行 sqls 的间隔,单位是秒。可选项,缺省是 0。 "restart": 订阅重启。"yes":如果订阅已经存在,重新开始,"no": 继续之前的订阅。 @@ -918,6 +948,6 @@ taosBenchmark支持3种功能的测试,包括插入、查询、订阅。但一 "resubAfterConsume": 配合 keepProgress 使用,在订阅消费了相应次数后调用 unsubscribe 取消订阅并再次订阅。 -"sql": " select count(*) from xxxx "。查询语句,其中表名必须写成 “xxxx”,实例会自动替换成子表名。 +"sql": " SELECT COUNT(*) FROM xxxx "。查询语句,其中表名必须写成 “xxxx”,实例会自动替换成子表名。 -"result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 注意:每条sql语句后的保存结果的文件不能重名,且生成结果文件时,文件名会附加线程号。 +"result": 查询结果写入的文件名。可选项,缺省是空,表示查询结果不写入文件。 注意:每条 SQL 语句后的保存结果的文件不能重名,且生成结果文件时,文件名会附加线程号。 diff --git a/documentation20/cn/05.insert/docs.md b/documentation20/cn/05.insert/docs.md index 7e28d6de1a25c7f516472097caef28d05a97854f..aa8371d513f64edf3998d67c7192b5cdbd438099 100644 --- a/documentation20/cn/05.insert/docs.md +++ b/documentation20/cn/05.insert/docs.md @@ -35,7 +35,7 @@ INSERT INTO d1001 VALUES (1538548685000, 10.3, 219, 0.31) (1538548695000, 12.6, **前言**
在物联网应用中,常会采集比较多的数据项,用于实现智能控制、业务分析、设备监控等。由于应用逻辑的版本升级,或者设备自身的硬件调整等原因,数据采集项就有可能比较频繁地出现变动。为了在这种情况下方便地完成数据记录工作,TDengine 从 2.2.0.0 版本开始,提供调用 Schemaless 写入方式,可以免于预先创建超级表/子表的步骤,随着数据写入接口能够自动创建与数据对应的存储结构。并且在必要时,Schemaless 将自动增加必要的数据列,保证用户写入的数据可以被正确存储。 -
目前,TDengine 的 C/C++ Connector 提供支持 Schemaless 的操作接口,详情请参见 [Schemaless 方式写入接口](https://www.taosdata.com/cn/documentation/connector#schemaless)章节。这里对 Schemaless 的数据表达格式进行了描述。 +
目前,TDengine 的所有官方支持的连接器支持 Schemaless 的操作接口,详情请参见 [Schemaless 方式写入接口](https://www.taosdata.com/cn/documentation/connector#schemaless)章节。这里对 Schemaless 的数据表达格式进行了描述。
无模式写入方式建立的超级表及其对应的子表与通过 SQL 直接建立的超级表和子表完全没有区别,您也可以通过 SQL 语句直接向其中写入数据。需要注意的是,通过无模式写入方式建立的表,其表名是基于标签值按照固定的映射规则生成,所以无法明确地进行表意,缺乏可读性。 **无模式写入行协议** @@ -175,8 +175,7 @@ st,t1=3,t2=4,t3=t3 c1=3i64,c6="passit" 1626006833640000000 **错误码**
如果是无模式写入过程中的数据本身错误,应用会得到 TSDB_CODE_TSC_LINE_SYNTAX_ERROR 错误信息,该错误信息表明错误发生在写入文本中。其他的错误码与原系统一致,可以通过 `taos_errstr()` 获取具体的错误原因。 -**后续升级计划** -
当前版本只提供了 C 版本的 API,后续将提供 其他高级语言的 API,例如 Java/Go/Python/C# 等。此外,在TDengine v2.3及后续版本中,您还可以通过 taosAdapter 采用 REST 的方式直接写入无模式数据。 +
除使用 C 版本的 API,也可以使用官网连接器,包括 Java/Go/Python/C#/Node.js/Rust 等。此外,在 TDengine v2.4 及后续版本中,您还可以通过 taosAdapter 采用 RESTful 的方式直接写入无模式数据。 ## Prometheus 直接写入(通过 taosAdapter) diff --git a/documentation20/cn/08.connector/docs.md b/documentation20/cn/08.connector/docs.md index ac9d93f983e8338eb048a77f2ab9688bac4b288f..1051933cce100065a81aea01e112e6d75f40f48e 100644 --- a/documentation20/cn/08.connector/docs.md +++ b/documentation20/cn/08.connector/docs.md @@ -2,7 +2,7 @@ TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java、Python、Go、Node.js、C# 、RESTful 等,便于用户快速开发应用。 -![image-connecotr](../images/connector.png) +![image-connector](../images/connector.png) 目前 TDengine 的连接器可支持的平台广泛,包括:X64/X86/ARM64/ARM32/MIPS/Alpha 等硬件平台,以及 Linux/Win64/Win32 等开发环境。对照矩阵如下: @@ -13,7 +13,7 @@ TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java | **JDBC** | ● | ● | ● | ○ | ● | ● | ○ | ○ | ○ | | **Python** | ● | ● | ● | ○ | ● | ● | ○ | -- | ○ | | **Go** | ● | ● | ● | ○ | ● | ● | ○ | -- | -- | -| **NodeJs** | ● | ● | ○ | ○ | ● | ● | ○ | -- | -- | +| **Node.js** | ● | ● | ○ | ○ | ● | ● | ○ | -- | -- | | **C#** | ● | ● | ○ | ○ | ○ | ○ | ○ | -- | -- | | **RESTful** | ● | ● | ● | ● | ● | ● | ○ | ○ | ○ | @@ -22,7 +22,7 @@ TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java 注意: * 在没有安装 TDengine 服务端软件的系统中使用连接器(除 RESTful 外)访问 TDengine 数据库,需要安装相应版本的客户端安装包来使应用驱动(Linux 系统中文件名为 libtaos.so,Windows 系统中为 taos.dll)被安装在系统中,否则会产生无法找到相应库文件的错误。 -* 所有执行 SQL 语句的 API,例如 C/C++ Connector 中的 `tao_query`、`taos_query_a`、`taos_subscribe` 等,以及其它语言中与它们对应的 API,每次都只能执行一条 SQL 语句,如果实际参数中包含了多条语句,它们的行为是未定义的。 +* 所有执行 SQL 语句的 API,例如 C/C++ Connector 中的 `taos_query`、`taos_query_a`、`taos_subscribe` 等,以及其它语言中与它们对应的 API,每次都只能执行一条 SQL 语句,如果实际参数中包含了多条语句,它们的行为是未定义的。 * 升级 TDengine 到 2.0.8.0 版本的用户,必须更新 JDBC。连接 TDengine 必须升级 taos-jdbcdriver 到 2.0.12 及以上。详细的版本依赖关系请参见 [taos-jdbcdriver 文档](https://www.taosdata.com/cn/documentation/connector/java#version)。 * 无论选用何种编程语言的连接器,2.0 及以上版本的 TDengine 推荐数据库应用的每个线程都建立一个独立的连接,或基于线程建立连接池,以避免连接内的“USE statement”状态量在线程之间相互干扰(但连接的查询和写入操作都是线程安全的)。 @@ -434,9 +434,9 @@ typedef struct TAOS_MULTI_BIND { **说明** 协议类型是枚举类型,包含以下三种格式: - TSDB_SML_LINE_PROTOCOL:InfluxDB行协议(Line Protocol) - TSDB_SML_TELNET_PROTOCOL: OpenTSDB文本行协议 - TSDB_SML_JSON_PROTOCOL: OpenTSDB Json协议格式 + TSDB_SML_LINE_PROTOCOL:InfluxDB 行协议(Line Protocol) + TSDB_SML_TELNET_PROTOCOL: OpenTSDB 文本行协议 + TSDB_SML_JSON_PROTOCOL: OpenTSDB JSON 协议格式 时间戳分辨率的定义,定义在 taos.h 文件中,具体内容如下: TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0, @@ -451,7 +451,7 @@ typedef struct TAOS_MULTI_BIND { 对于 OpenTSDB 的文本协议,时间戳的解析遵循其官方解析规则 — 按照时间戳包含的字符的数量来确认时间精度。 **支持版本** - 该功能接口从2.3.0.0版本开始支持。 + 该功能接口从 2.3.0.0 版本开始支持。 ```c #include @@ -486,26 +486,6 @@ int main() { } ``` -### 连续查询接口 - -TDengine 提供时间驱动的实时流式计算 API。可以每隔一指定的时间段,对一张或多张数据库的表(数据流)进行各种实时聚合计算操作。操作简单,仅有打开、关闭流的 API。具体如下: - -- `TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, TAOS_ROW row), int64_t stime, void *param, void (*callback)(void *))` - - 该 API 用来创建数据流,其中: - * taos:已经建立好的数据库连接。 - * sql:SQL查询语句(仅能使用查询语句)。 - * fp:用户定义的回调函数指针,每次流式计算完成后,TDengine将查询的结果(TAOS_ROW)、查询状态(TAOS_RES)、用户定义参数(PARAM)传递给回调函数,在回调函数内,用户可以使用taos_num_fields获取结果集列数,taos_fetch_fields获取结果集每列数据的类型。 - * stime:是流式计算开始的时间。如果是“64位整数最小值”,表示从现在开始;如果不为“64位整数最小值”,表示从指定的时间开始计算(UTC时间从1970/1/1算起的毫秒数)。 - * param:是应用提供的用于回调的一个参数,回调时,提供给应用。 - * callback: 第二个回调函数,会在连续查询自动停止时被调用。 - - 返回值为 NULL,表示创建失败;返回值不为空,表示成功。 - -- `void taos_close_stream (TAOS_STREAM *tstr)` - - 关闭数据流,其中提供的参数是 taos_open_stream 的返回值。用户停止流式计算的时候,务必关闭该数据流。 - ### 数据订阅接口 订阅 API 目前支持订阅一张或多张表,并通过定期轮询的方式不断获取写入表中的最新数据。 diff --git a/documentation20/cn/11.administrator/docs.md b/documentation20/cn/11.administrator/docs.md index d8be0e8fddbf2bfc00ca9f44b2e7dba29a0274c8..96a4c067d1bc647b3782c78c376176d657473b47 100644 --- a/documentation20/cn/11.administrator/docs.md +++ b/documentation20/cn/11.administrator/docs.md @@ -1239,7 +1239,7 @@ taosd -C | 内部配置 | No | | 适用范围 | 仅服务端适用 | | 含义 | 配置要进行有损压缩的浮点数据类型 | - | 取值范围 | float:只对float类型进行有损压缩
double:只对double类型进行有损压缩
float|double:float double都进行有损压缩 | + | 取值范围 | float:只对float类型进行有损压缩
double:只对double类型进行有损压缩
float\|double:float double都进行有损压缩 | | 缺省值 | 默认为空字符串,关闭有损压缩 | | 补充说明 | 2.4.0.10版本新增。| @@ -1324,7 +1324,7 @@ taosd -C | create time | | | | | ntables | | | | | vgroups | | | | -| replica | **YES** | 在线 dnode 数目为 1:1-1;2:1-2;>=3:1-3 | ALTER DATABASE REPLICA *n* | +| replica | **YES** | 在线 dnode 数目为:
1:1-1;
2:1-2;
>=3:1-3 | ALTER DATABASE REPLICA *n* | | quorum | **YES** | 1-2 | ALTER DATABASE QUORUM *n* | | days | | | | | keep | **YES** | days-365000 | ALTER DATABASE KEEP *n* | diff --git a/documentation20/cn/12.taos-sql/docs.md b/documentation20/cn/12.taos-sql/docs.md index 025065fe9e82e6e98aeba436834e9eb3487b2f4b..28a5675e4d90d2ef7fbfaa894af8ad823e0b6bcf 100755 --- a/documentation20/cn/12.taos-sql/docs.md +++ b/documentation20/cn/12.taos-sql/docs.md @@ -86,7 +86,7 @@ CREATE DATABASE db_name PRECISION 'ns'; 4) 更多关于UPDATE参数的用法,请参考[FAQ](https://www.taosdata.com/cn/documentation/faq)。 - 3) 数据库名最大长度为33; + 3) 数据库名最大长度为32; 4) 一条SQL 语句的最大长度为65480个字符; @@ -733,6 +733,8 @@ summary: > TBNAME: 在超级表查询中可视为一个特殊的标签,代表查询涉及的子表名
\_c0: 表示表(超级表)的第一列 + \_qstart,\_qstop,\_qduration: 表示查询过滤窗口的起始,结束以及持续时间(从 2.6.0.0 版本开始支持) + \_wstart,\_wstop,\_wduration: 窗口切分聚合查询(例如 interval/session window/state window)中表示每个切分窗口的起始,结束以及持续时间(从 2.6.0.0 版本开始支持) #### 小技巧 @@ -801,21 +803,54 @@ Query OK, 1 row(s) in set (0.001091s) 6. 从 2.1.4.0 版本开始,条件过滤开始支持 IN 算子,例如 `WHERE city IN ('Beijing', 'Shanghai')`。说明:BOOL 类型写作 `{true, false}` 或 `{0, 1}` 均可,但不能写作 0、1 之外的整数;FLOAT 和 DOUBLE 类型会受到浮点数精度影响,集合内的值在精度范围内认为和数据行的值完全相等才能匹配成功;TIMESTAMP 类型支持非主键的列。 -7. 从2.3.0.0版本开始,条件过滤开始支持正则表达式,关键字match/nmatch,不区分大小写。 +7. 从2.3.0.0版本开始,条件过滤开始支持正则表达式,关键字 match/nmatch 不区分大小写。 **语法** - WHERE (column|tbname) **match/MATCH/nmatch/NMATCH** *regex* + WHERE (column|tag|tbname) **match/MATCH/nmatch/NMATCH** *regex* + + match/MATCH 匹配正则表达式 + + nmatch/NMATCH 不匹配正则表达式 **正则表达式规范** - 确保使用的正则表达式符合POSIX的规范,具体规范内容可参见[Regular Expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html) + 确保使用的正则表达式符合POSIX的规范,具体规范内容可参见 [Regular Expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html),目前 TDengine 使用的是 glibc 里面的 regex 实现,使用正则表达式进行 match 时是区分大小写的 + + **正则表达使用示例** + + ```sql + taos> select distinct location from meters; + location | + =================== + beijing | + shanghai | + Query OK, 2 row(s) in set (0.003513s) + + taos> select count(*) from meters; + count(*) | + ======================== + 100000 | + Query OK, 1 row(s) in set (0.015054s) + + taos> select count(*) from meters where location match '^b'; + count(*) | + ======================== + 48000 | + Query OK, 1 row(s) in set (0.006977s) + + taos> select count(*) from meters where location nmatch '^b'; + count(*) | + ======================== + 52000 | + Query OK, 1 row(s) in set (0.008188s) + ``` **使用限制** - 只能针对表名(即 tbname 筛选)、binary/nchar类型标签值进行正则表达式过滤,不支持普通列的过滤。 + 只能针对表名 (tbname) 以及binary类型的普通列或标签进行正则表达式过滤。 - 正则匹配字符串长度不能超过 128 字节。可以通过参数 *maxRegexStringLen* 设置和调整最大允许的正则匹配字符串,该参数是客户端配置参数,需要重启才能生效。 + 正则匹配字符串长度不能超过 128 字节。可以通过参数 *maxRegexStringLen* 设置和调整最大允许的正则匹配字符串,该参数是客户端配置参数,需要重启客户端才能生效。 @@ -1083,7 +1118,73 @@ TDengine支持针对数据的聚合查询。提供支持的聚合和选择函数 {slop:1.000000, intercept:9.733334} | Query OK, 1 row(s) in set (0.000921s) ``` + +- **MODE** + ```mysql + SELECT MODE(field_name) FROM tb_name [WHERE clause]; + ``` + 功能说明:返回出现频率最高的值,若存在多个频率相同的最高值,输出空。不能匹配标签、时间戳输出。 + + 返回结果数据类型:同应用的字段。 + + 应用字段:适合于除时间主列外的任何类型字段。 + + 说明:由于返回数据量未知,考虑到内存因素,为了函数可以正常返回结果,建议不重复的数据量在10万级别,否则会报错。 + 示例: + ```mysql + taos> select voltage from d002; + voltage | + ======================== + 1 | + 1 | + 2 | + 19 | + Query OK, 4 row(s) in set (0.003545s) + + taos> select mode(voltage) from d002; + mode(voltage) | + ======================== + 1 | + Query OK, 1 row(s) in set (0.019393s) + ``` + +- **HYPERLOGLOG** + ```mysql + SELECT HYPERLOGLOG(field_name) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明: + - 采用hyperloglog算法,返回某列的基数。该算法在数据量很大的情况下,可以明显降低内存的占用,但是求出来的基数是个估算值,标准误差(标准误差是多次实验,每次的平均数的标准差,不是与真实结果的误差)为0.81%。 + - 在数据量较少的时候该算法不是很准确,可以使用select count(data) from (select unique(col) as data from table) 的方法。 + + 返回结果类型:整形。 + + 适用数据类型:适合于任何类型字段。 + + 支持的版本:2.6.0.x 之后的版本。 + + 示例: + ```mysql + taos> select dbig from shll; + dbig | + ======================== + 1 | + 1 | + 1 | + NULL | + 2 | + 19 | + NULL | + 9 | + Query OK, 8 row(s) in set (0.003755s) + + taos> select hyperloglog(dbig) from shll; + hyperloglog(dbig)| + ======================== + 4 | + Query OK, 1 row(s) in set (0.008388s) + ``` + ### 选择函数 在使用所有的选择函数的时候,可以同时指定输出 ts 列或标签列(包括 tbname),这样就可以方便地知道被选出的值是源于哪个数据行的。 @@ -1482,13 +1583,93 @@ TDengine支持针对数据的聚合查询。提供支持的聚合和选择函数 Query OK, 2 row(s) in set (0.003487s) ``` +- **TAIL** + ```mysql + SELECT TAIL(field_name, k, offset_val) FROM {tb_name | stb_name} [WHERE clause]; + ``` + 功能说明:返回跳过最后 offset_value个,然后取连续 k 个记录,不忽略 NULL 值。offset_val 可以不输入。此时返回最后的 k 个记录。当有 offset_val 输入的情况下,该函数功能等效于order by ts desc LIMIT k OFFSET offset_val。 + + 参数范围:k: [1,100] offset_val: [0,100]。 + + 返回结果数据类型:同应用的字段。 + + 应用字段:适合于除时间主列外的任何类型字段。 + + 适用于:**表、超级表**。 + + 支持版本:2.6.0.x 之后的版本。 + + 示例: + ```mysql + taos> select ts,dbig from tail2; + ts | dbig | + ================================================== + 2021-10-15 00:31:33.000 | 1 | + 2021-10-17 00:31:31.000 | NULL | + 2021-12-24 00:31:34.000 | 2 | + 2022-01-01 08:00:05.000 | 19 | + 2022-01-01 08:00:06.000 | NULL | + 2022-01-01 08:00:07.000 | 9 | + Query OK, 6 row(s) in set (0.001952s) + + taos> select tail(dbig,2,2) from tail2; + ts | tail(dbig,2,2) | + ================================================== + 2021-12-24 00:31:34.000 | 2 | + 2022-01-01 08:00:05.000 | 19 | + Query OK, 2 row(s) in set (0.002307s) + +- **UNIQUE** + ```mysql + SELECT UNIQUE(field_name) FROM {tb_name | stb_name} [WHERE clause]; + ``` + 功能说明:返回该列的数值首次出现的值。该函数功能与 distinct 相似,但是可以匹配标签和时间戳信息。可以针对除时间列以外的字段进行查询,可以匹配标签和时间戳,其中的标签和时间戳是第一次出现时刻的标签和时间戳。 + + 返回结果数据类型:同应用的字段。 + + 应用字段:适合于除时间类型以外的字段。 + + 适用于:**表、超级表**。 + + 支持版本:2.6.0.x 之后的版本。 + + 说明: + - 该函数可以应用在普通表和超级表上。不能和窗口操作一起使用,例如 interval/state_window/session_window 。 + - 由于返回数据量未知,考虑到内存因素,为了函数可以正常返回结果,建议不重复的数据量在10万级别,否则会报错。 + + 示例: + ```mysql + taos> select ts,voltage from unique1; + ts | voltage | + ================================================== + 2021-10-17 00:31:31.000 | 1 | + 2022-01-24 00:31:31.000 | 1 | + 2021-10-17 00:31:31.000 | 1 | + 2021-12-24 00:31:31.000 | 2 | + 2022-01-01 08:00:01.000 | 19 | + 2021-10-17 00:31:31.000 | NULL | + 2022-01-01 08:00:02.000 | NULL | + 2022-01-01 08:00:03.000 | 9 | + Query OK, 8 row(s) in set (0.003018s) + + taos> select unique(voltage) from unique1; + ts | unique(voltage) | + ================================================== + 2021-10-17 00:31:31.000 | 1 | + 2021-10-17 00:31:31.000 | NULL | + 2021-12-24 00:31:31.000 | 2 | + 2022-01-01 08:00:01.000 | 19 | + 2022-01-01 08:00:03.000 | 9 | + Query OK, 5 row(s) in set (0.108458s) + + ### 计算函数 - **DIFF** ```mysql - SELECT DIFF(field_name) FROM tb_name [WHERE clause]; + SELECT {DIFF(field_name, ignore_negative) | DIFF(field_name)} FROM tb_name [WHERE clause]; ``` - 功能说明:统计表中某列的值与前一行对应值的差。 + 功能说明:统计表中某列的值与前一行对应值的差。 ignore_negative 取值为 0|1 , 可以不填,默认值为 0. 不忽略负值。ignore_negative为1时表示忽略负数。 返回结果数据类型:同应用字段。 @@ -1496,7 +1677,7 @@ TDengine支持针对数据的聚合查询。提供支持的聚合和选择函数 适用于:**表、(超级表)**。 - 说明:输出结果行数是范围内总行数减一,第一行没有结果输出。从 2.1.3.0 版本开始,DIFF 函数可以在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname)。 + 说明:输出结果行数是范围内总行数减一,第一行没有结果输出。从 2.1.3.0 版本开始,DIFF 函数可以在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname)。从2.6.0开始,DIFF函数支持ignore_negative参数 示例: ```mysql @@ -1580,7 +1761,7 @@ TDengine支持针对数据的聚合查询。提供支持的聚合和选择函数 支持 +、-、*、/ 运算,如 ceil(col1) + ceil(col2)。 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 该函数可以应用在普通表和超级表上。 - + - **FLOOR** ```mysql SELECT FLOOR(field_name) FROM { tb_name | stb_name } [WHERE clause]; @@ -1595,6 +1776,438 @@ TDengine支持针对数据的聚合查询。提供支持的聚合和选择函数 功能说明:获得指定列的四舍五入的结果。 其他使用说明参见CEIL函数描述。 +- **CSUM** + ```sql + SELECT CSUM(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + + 功能说明:累加和(Cumulative sum),输出行与输入行数相同。 + + 返回结果类型: 输入列如果是整数类型返回值为长整型 (int64_t),浮点数返回值为双精度浮点数(Double)。无符号整数类型返回值为无符号长整型(uint64_t)。 返回结果中同时带有每行记录对应的时间戳。 + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在标签之上。 + + 嵌套子查询支持: 适用于内层查询和外层查询。 + + 补充说明: 不支持 +、-、*、/ 运算,如 csum(col1) + csum(col2)。只能与聚合(Aggregation)函数一起使用。 该函数可以应用在普通表和超级表上。 使用在超级表上的时候,需要搭配 Group by tbname使用,将结果强制规约到单个时间线。 + + 支持版本: 从2.3.0.x开始支持 + +- **MAVG** + ```sql + SELECT MAVG(field_name, K) FROM { tb_name | stb_name } [WHERE clause] + ``` + + 功能说明: 计算连续 k 个值的移动平均数(moving average)。如果输入行数小于 k,则无结果输出。参数 k 的合法输入范围是 1≤ k ≤ 1000。 + + 返回结果类型: 返回双精度浮点数类型。 + + 适用数据类型: 不能应用在 timestamp、binary、nchar、bool 类型上;在超级表查询中使用时,不能应用在标签之上。 + + 嵌套子查询支持: 适用于内层查询和外层查询。 + + 补充说明: 不支持 +、-、*、/ 运算,如 mavg(col1, k1) + mavg(col2, k1); 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用;该函数可以应用在普通表和超级表上;使用在超级表上的时候,需要搭配 Group by tbname使用,将结果强制规约到单个时间线。 + + 支持版本: 从2.3.0.x开始支持 + +- **SAMPLE** + ```sql + SELECT SAMPLE(field_name, K) FROM { tb_name | stb_name } [WHERE clause] + ``` + + 功能说明: 获取数据的 k 个采样值。参数 k 的合法输入范围是 1≤ k ≤ 1000。 + + 返回结果类型: 同原始数据类型, 返回结果中带有该行记录的时间戳。 + + 适用数据类型: 在超级表查询中使用时,不能应用在标签之上。 + + 嵌套子查询支持: 适用于内层查询和外层查询。 + + 补充说明: 不能参与表达式计算;该函数可以应用在普通表和超级表上;使用在超级表上的时候,需要搭配 Group by tbname 使用,将结果强制规约到单个时间线。 + + 支持版本: 从2.3.0.x开始支持 + + + +- **ASIN** + ```mysql + SELECT ASIN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的反正弦结果 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **ACOS** + ```mysql + SELECT ACOS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的反余弦结果 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **ATAN** + ```mysql + SELECT ATAN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的反正切结果 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **SIN** + ```mysql + SELECT SIN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的正弦结果 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **COS** + ```mysql + SELECT COS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的余弦结果 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **TAN** + ```mysql + SELECT TAN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的正切结果 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **POW** + ```mysql + SELECT POW(field_name, power) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的指数为power的幂 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **LOG** + ```mysql + SELECT LOG(field_name, base) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列对于底数base的对数 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **ABS** + ```mysql + SELECT ABS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的绝对值 + + 返回结果类型:如果输入值为整数,输出值是UBIGINT类型。如果输入值是FLOAT/DOUBLE数据类型,输出值是DOUBLE数据类型。 + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **SQRT** + ```mysql + SELECT SQRT(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:获得指定列的平方根 + + 返回结果类型:DOUBLE。如果输入值为NULL,输出值也为NULL + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上;在超级表查询中使用时,不能应用在 tag 列 + + 嵌套子查询支持:适用于内层查询和外层查询。 + + 使用说明: + + 只能与普通列,选择(Selection)、投影(Projection)函数一起使用,不能与聚合(Aggregation)函数一起使用。 + + 该函数可以应用在普通表和超级表上。 + + 版本2.6.0.x后支持 + +- **CAST** + ```mysql + SELECT CAST(expression AS type_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:数据类型转换函数,输入参数expression支持普通列、常量、标量函数及它们之间的四则运算,不支持tag列,只适用于select子句中。 + + 返回结果类型:CAST中指定的类型(type_name)。 + + 适用数据类型:输入参数expression的类型可以是除JSON外目前所有类型字段(BOOL/TINYINT/SMALLINT/INT/BIGINT/FLOAT/DOUBLE/BINARY(M)/TIMESTAMP/NCHAR(M)/TINYINT UNSIGNED/SMALLINT UNSIGNED/INT UNSIGNED/BIGINT UNSIGNED); 输出目标类型只支持BIGINT/BINARY(N)/TIMESTAMP/NCHAR(N)/BIGINT UNSIGNED。 + + 说明: + + 对于不能支持的类型转换会直接报错。 + + 如果输入值为NULL则输出值也为NULL。 + + 对于类型支持但某些值无法正确转换的情况对应的转换后的值以转换函数输出为准。目前可能遇到的几种情况: + 1)BINARY/NCHAR转BIGINT/BIGINT UNSIGNED时可能出现的无效字符情况,例如"a"可能转为0。 + 2)有符号数或TIMESTAMP转BIGINT UNSIGNED可能遇到的溢出问题。 + 3)BIGINT UNSIGNED转BIGINT可能遇到的溢出问题。 + 4)FLOAT/DOUBLE转BIGINT/BIGINT UNSIGNED可能遇到的溢出问题。 + 版本2.6.0.x后支持 + +- **CONCAT** + ```mysql + SELECT CONCAT(str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:字符串连接函数。 + + 返回结果类型:同输入参数类型,BINARY或者NCHAR。 + + 适用数据类型:输入参数或者全部是BINARY格式的字符串或者列,或者全部是NCHAR格式的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数最小参数个数为2个,最大参数个数为8个。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **CONCAT_WS** + ``` + SELECT CONCAT_WS(separator, str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:带分隔符的字符串连接函数。 + + 返回结果类型:同输入参数类型,BINARY或者NCHAR。 + + 适用数据类型:输入参数或者全部是BINARY格式的字符串或者列,或者全部是NCHAR格式的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果separator值为NULL,输出值为NULL。如果separator值不为NULL,其他输入为NULL,输出为空串 + 该函数最小参数个数为3个,最大参数个数为9个。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **LENGTH** + ``` + SELECT LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:以字节计数的字符串长度。 + + 返回结果类型:INT。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **CHAR_LENGTH** + ``` + SELECT CHAR_LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:以字符计数的字符串长度。 + + 返回结果类型:INT。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **LOWER** + ``` + SELECT LOWER(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:将字符串参数值转换为全小写字母。 + + 返回结果类型:同输入类型。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **UPPER** + ``` + SELECT UPPER(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:将字符串参数值转换为全大写字母。 + + 返回结果类型:同输入类型。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **LTRIM** + ``` + SELECT LTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:返回清除左边空格后的字符串。 + + 返回结果类型:同输入类型。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **RTRIM** + ``` + SELECT RTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:返回清除右边空格后的字符串。 + + 返回结果类型:同输入类型。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + +- **SUBSTR** + ``` + SELECT SUBSTR(str,pos[,len]) FROM { tb_name | stb_name } [WHERE clause] + ``` + 功能说明:从源字符串str中的指定位置pos开始取一个长度为len的子串并返回。 + + 返回结果类型:同输入类型。 + + 适用数据类型:输入参数是BINARY类型或者NCHAR类型的字符串或者列。不能应用在TAG列。 + + 说明: + + 如果输入值为NULL,输出值为NULL。 + 输入参数pos可以为正数,也可以为负数。如果pos是正数,表示开始位置从字符串开头正数计算。如果pos为负数,表示开始位置从字符串结尾倒数计算。如果输入参数len被忽略,返回的子串包含从pos开始的整个字串。 + 该函数可以应用在普通表和超级表上。 + 该函数适用于内层查询和外层查询。 + 版本2.6.0.x后支持 + - **四则运算** ```mysql @@ -1623,7 +2236,417 @@ TDengine支持针对数据的聚合查询。提供支持的聚合和选择函数 80.810000718 | Query OK, 3 row(s) in set (0.001046s) ``` + +- **STATECOUNT** + ```mysql + SELECT STATECOUNT(field_name, oper, val) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:返回满足某个条件的连续记录的个数,结果作为新的一列追加在每行后面。条件根据参数计算,如果条件为true则加1,条件为false则重置为-1,如果数据为NULL,跳过该条数据。 + + 参数范围: + - oper : LT (小于)、GT(大于)、LE(小于等于)、GE(大于等于)、NE(不等于)、EQ(等于),不区分大小写。 + - val : 数值型 + + 返回结果类型:整形。 + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上。 + + 嵌套子查询支持:不支持应用在子查询上。 + + 支持的版本:2.6.0.x 之后的版本。 + + 说明: + + - 该函数可以应用在普通表上,在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname) + + - 不能和窗口操作一起使用,例如interval/state_window/session_window。 + + 示例: + ```mysql + taos> select ts,dbig from statef2; + ts | dbig | + ======================================================== + 2021-10-15 00:31:33.000000000 | 1 | + 2021-10-17 00:31:31.000000000 | NULL | + 2021-12-24 00:31:34.000000000 | 2 | + 2022-01-01 08:00:05.000000000 | 19 | + 2022-01-01 08:00:06.000000000 | NULL | + 2022-01-01 08:00:07.000000000 | 9 | + Query OK, 6 row(s) in set (0.002977s) + + taos> select stateCount(dbig,GT,2) from statef2; + ts | dbig | statecount(dbig,gt,2) | + ================================================================================ + 2021-10-15 00:31:33.000000000 | 1 | -1 | + 2021-10-17 00:31:31.000000000 | NULL | NULL | + 2021-12-24 00:31:34.000000000 | 2 | -1 | + 2022-01-01 08:00:05.000000000 | 19 | 1 | + 2022-01-01 08:00:06.000000000 | NULL | NULL | + 2022-01-01 08:00:07.000000000 | 9 | 2 | + Query OK, 6 row(s) in set (0.002791s) + ``` + +- **STATEDURATION** + ```mysql + SELECT stateDuration(field_name, oper, val, unit) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:返回满足某个条件的连续记录的时间长度,结果作为新的一列追加在每行后面。条件根据参数计算,如果条件为true则加上两个记录之间的时间长度(第一个满足条件的记录时间长度记为0),条件为false则重置为-1,如果数据为NULL,跳过该条数据。 + + 参数范围: + - oper : LT (小于)、GT(大于)、LE(小于等于)、GE(大于等于)、NE(不等于)、EQ(等于),不区分大小写。 + - val : 数值型 + - unit : 时间长度的单位,范围[1s、1m、1h ],不足一个单位舍去。默认为1s。 + + 返回结果类型:整形。 + + 适用数据类型:不能应用在 timestamp、binary、nchar、bool 类型字段上。 + + 嵌套子查询支持:不支持应用在子查询上。 + + 支持的版本:2.6.0.x 之后的版本。 + + 说明: + + - 该函数可以应用在普通表上,在由 GROUP BY 划分出单独时间线的情况下用于超级表(也即 GROUP BY tbname) + + - 不能和窗口操作一起使用,例如interval/state_window/session_window。 + + 示例: + ```mysql + taos> select ts,dbig from statef2; + ts | dbig | + ======================================================== + 2021-10-15 00:31:33.000000000 | 1 | + 2021-10-17 00:31:31.000000000 | NULL | + 2021-12-24 00:31:34.000000000 | 2 | + 2022-01-01 08:00:05.000000000 | 19 | + 2022-01-01 08:00:06.000000000 | NULL | + 2022-01-01 08:00:07.000000000 | 9 | + Query OK, 6 row(s) in set (0.002407s) + + taos> select stateDuration(dbig,GT,2) from statef2; + ts | dbig | stateduration(dbig,gt,2) | + =================================================================================== + 2021-10-15 00:31:33.000000000 | 1 | -1 | + 2021-10-17 00:31:31.000000000 | NULL | NULL | + 2021-12-24 00:31:34.000000000 | 2 | -1 | + 2022-01-01 08:00:05.000000000 | 19 | 0 | + 2022-01-01 08:00:06.000000000 | NULL | NULL | + 2022-01-01 08:00:07.000000000 | 9 | 2 | + Query OK, 6 row(s) in set (0.002613s) + ``` +- **HISTOGRAM** + ```mysql + SELECT HISTOGRAM(field_name,bin_type, bin_description, normalized) FROM tb_name [WHERE clause]; + ``` + 功能说明:统计数据按照用户指定区间的分布。 + + 返回结果数据类型:如归一化参数 normalized 设置为 1,返回结果为双精度浮点类型 DOUBLE,否则为长整形 INT64。 + + 应用字段:数值型字段。 + + 适用于:**表、(超级表)**。 + + 说明: + 1)从 2.6.0.0 版本开始支持此函数。 + 2)bin_type 用户指定的分桶类型, 有效输入类型为"user_input“, ”linear_bin", "log_bin"。 + 3)bin_description 描述如何生成分桶区间,针对三种桶类型,分别为以下描述格式(均为 JSON 格式字符串): + - "user_input": "[1, 3, 5, 7]" + 用户指定 bin 的具体数值。 + + - "linear_bin": "{"start": 0.0, "width": 5.0, "count": 5, "infinity": true}" + "start" 表示数据起始点,"width" 表示每次 bin 偏移量, "count" 为 bin 的总数,"infinity" 表示是否添加(-inf, inf)作为区间起点跟终点, + 生成区间为[-inf, 0.0, 5.0, 10.0, 15.0, 20.0, +inf]。 + + - "log_bin": "{"start":1.0, "factor": 2.0, "count": 5, "infinity": true}" + "start" 表示数据起始点,"factor" 表示按指数递增的因子,"count" 为 bin 的总数,"infinity" 表示是否添加(-inf, inf)作为区间起点跟终点, + 生成区间为[-inf, 1.0, 2.0, 4.0, 8.0, 16.0, +inf]。 + 4)normalized 是否将返回结果归一化到 0~1 之间 。有效输入为 0 和 1。 + + 示例: + ```mysql + taos> SELECT HISTOGRAM(voltage, "user_input", "[1,3,5,7]", 1) FROM meters; + histogram(voltage, "user_input", "[1,3,5,7]", 1) | + ======================================================= + {"lower_bin":1, "upper_bin":3, "count":0.333333} | + {"lower_bin":3, "upper_bin":5, "count":0.333333} | + {"lower_bin":5, "upper_bin":7, "count":0.333333} | + Query OK, 3 row(s) in set (0.004273s) + + taos> SELECT HISTOGRAM(voltage, 'linear_bin', '{"start": 1, "width": 3, "count": 3, "infinity": false}', 0) FROM meters; + histogram(voltage, 'linear_bin', '{"start": 1, "width": 3, " | + =================================================================== + {"lower_bin":1, "upper_bin":4, "count":3} | + {"lower_bin":4, "upper_bin":7, "count":3} | + {"lower_bin":7, "upper_bin":10, "count":3} | + Query OK, 3 row(s) in set (0.004887s) + + taos> SELECT HISTOGRAM(voltage, 'log_bin', '{"start": 1, "factor": 3, "count": 3, "infinity": true}', 0) FROM meters; + histogram(voltage, 'log_bin', '{"start": 1, "factor": 3, "count" | + =================================================================== + {"lower_bin":-inf, "upper_bin":1, "count":3} | + {"lower_bin":1, "upper_bin":3, "count":2} | + {"lower_bin":3, "upper_bin":9, "count":6} | + {"lower_bin":9, "upper_bin":27, "count":3} | + {"lower_bin":27, "upper_bin":inf, "count":1} | + ``` + +### 时间函数 + +从 2.6.0.0 版本开始,TDengine查询引擎支持以下时间相关函数: + +- **NOW** + ```mysql + SELECT NOW() FROM { tb_name | stb_name } [WHERE clause]; + SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operatior NOW(); + INSERT INTO tb_name VALUES (NOW(), ...); + ``` + 功能说明:返回客户端当前系统时间。 + + 返回结果数据类型:TIMESTAMP 时间戳类型。 + + 应用字段:在 WHERE 或 INSERT 语句中使用时只能作用于TIMESTAMP类型的字段。 + + 适用于:**表、超级表**。 + + 说明: + 1)支持时间加减操作,如NOW() + 1s, 支持的时间单位如下: + b(纳秒)、u(微秒)、a(毫秒)、s(秒)、m(分)、h(小时)、d(天)、w(周)。 + 2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + + 示例: + ```mysql + taos> SELECT NOW() FROM meters; + now() | + ========================== + 2022-02-02 02:02:02.456 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT NOW() + 1h FROM meters; + now() + 1h | + ========================== + 2022-02-02 03:02:02.456 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT COUNT(voltage) FROM d1001 WHERE ts < NOW(); + count(voltage) | + ============================= + 5 | + Query OK, 5 row(s) in set (0.004475s) + + taos> INSERT INTO d1001 VALUES (NOW(), 10.2, 219, 0.32); + Query OK, 1 of 1 row(s) in database (0.002210s) + ``` + +- **TODAY** + ```mysql + SELECT TODAY() FROM { tb_name | stb_name } [WHERE clause]; + SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operatior TODAY()]; + INSERT INTO tb_name VALUES (TODAY(), ...); + ``` + 功能说明:返回客户端当日零时的系统时间。 + + 返回结果数据类型:TIMESTAMP 时间戳类型。 + + 应用字段:在 WHERE 或 INSERT 语句中使用时只能作用于 TIMESTAMP 类型的字段。 + + 适用于:**表、超级表**。 + + 说明: + 1)支持时间加减操作,如TODAY() + 1s, 支持的时间单位如下: + b(纳秒),u(微秒),a(毫秒),s(秒),m(分),h(小时),d(天),w(周)。 + 2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + + 示例: + ```mysql + taos> SELECT TODAY() FROM meters; + today() | + ========================== + 2022-02-02 00:00:00.000 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT TODAY() + 1h FROM meters; + today() + 1h | + ========================== + 2022-02-02 01:00:00.000 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT COUNT(voltage) FROM d1001 WHERE ts < TODAY(); + count(voltage) | + ============================= + 5 | + Query OK, 5 row(s) in set (0.004475s) + + taos> INSERT INTO d1001 VALUES (TODAY(), 10.2, 219, 0.32); + Query OK, 1 of 1 row(s) in database (0.002210s) + ``` + +- **TIMEZONE** + ```mysql + SELECT TIMEZONE() FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:返回客户端当前时区信息。 + + 返回结果数据类型:BINARY 类型。 + + 应用字段:无 + + 适用于:**表、超级表**。 + + 示例: + ```mysql + taos> SELECT TIMEZONE() FROM meters; + timezone() | + ================================= + UTC (UTC, +0000) | + Query OK, 1 row(s) in set (0.002093s) + ``` + +- **TO_ISO8601** + ```mysql + SELECT TO_ISO8601(ts_val | ts_col) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:将 UNIX 时间戳转换成为 ISO8601 标准的日期时间格式,并附加客户端时区信息。 + 返回结果数据类型:BINARY 类型。 + + 应用字段:UNIX 时间戳常量或是 TIMESTAMP 类型的列 + + 适用于:**表、超级表**。 + + 说明:如果输入是 UNIX 时间戳常量,返回格式精度由时间戳的位数决定,如果输入是 TIMSTAMP 类型的列,返回格式的时间戳精度与当前 DATABASE 设置的时间精度一致。 + + 示例: + ```mysql + taos> SELECT TO_ISO8601(1643738400) FROM meters; + to_iso8601(1643738400) | + ============================== + 2022-02-02T02:00:00+0800 | + + taos> SELECT TO_ISO8601(ts) FROM meters; + to_iso8601(ts) | + ============================== + 2022-02-02T02:00:00+0800 | + 2022-02-02T02:00:00+0800 | + 2022-02-02T02:00:00+0800 | + ``` + + - **TO_UNIXTIMESTAMP** + ```mysql + SELECT TO_UNIXTIMESTAMP(datetime_string | ts_col) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:将日期时间格式的字符串转换成为 UNIX 时间戳。 + + 返回结果数据类型:长整型INT64。 + + 应用字段:字符串常量或是 BINARY/NCHAR 类型的列。 + + 适用于:**表、超级表**。 + + 说明: + 1)输入的日期时间字符串须符合 ISO8601/RFC3339 标准,无法转换的字符串格式将返回0。 + 2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + + 示例: + ```mysql + taos> SELECT TO_UNIXTIMESTAMP("2022-02-02T02:00:00.000Z") FROM meters; + to_unixtimestamp("2022-02-02T02:00:00.000Z") | + ============================================== + 1643767200000 | + + + taos> SELECT TO_UNIXTIMESTAMP(col_binary) FROM meters; + to_unixtimestamp(col_binary) | + ======================================== + 1643767200000 | + 1643767200000 | + 1643767200000 | + ``` + + - **TIMETRUNCATE** + ```mysql + SELECT TIMETRUNCATE(ts_val | datetime_string | ts_col, time_unit) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:将时间戳按照指定时间单位 time_unit 进行截断。 + + 返回结果数据类型:TIMESTAMP 时间戳类型。 + + 应用字段:UNIX 时间戳,日期时间格式的字符串,或者 TIMESTAMP 类型的列。 + + 适用于:**表、超级表**。 + + 说明: + 1)支持的时间单位 time_unit 如下: + 1u(微秒),1a(毫秒),1s(秒),1m(分),1h(小时),1d(天)。 + 2)返回的时间戳精度与当前 DATABASE 设置的时间精度一致。 + + 示例: + ```mysql + taos> SELECT TIMETRUNCATE(1643738522000, 1h) FROM meters; + timetruncate(1643738522000, 1h) | + =================================== + 2022-02-02 02:00:00.000 | + Query OK, 1 row(s) in set (0.001499s) + + taos> SELECT TIMETRUNCATE("2022-02-02 02:02:02", 1h) FROM meters; + timetruncate("2022-02-02 02:02:02", 1h) | + =========================================== + 2022-02-02 02:00:00.000 | + Query OK, 1 row(s) in set (0.003903s) + + taos> SELECT TIMETRUNCATE(ts, 1h) FROM meters; + timetruncate(ts, 1h) | + ========================== + 2022-02-02 02:00:00.000 | + 2022-02-02 02:00:00.000 | + 2022-02-02 02:00:00.000 | + Query OK, 3 row(s) in set (0.003903s) + ``` + + - **TIMEDIFF** + ```mysql + SELECT TIMEDIFF(ts_val1 | datetime_string1 | ts_col1, ts_val2 | datetime_string2 | ts_col2 [, time_unit]) FROM { tb_name | stb_name } [WHERE clause]; + ``` + 功能说明:计算两个时间戳之间的差值,并近似到时间单位 time_unit 指定的精度。 + + 返回结果数据类型:长整型INT64。 + + 应用字段:UNIX 时间戳,日期时间格式的字符串,或者 TIMESTAMP 类型的列。 + + 适用于:**表、超级表**。 + + 说明: + 1)支持的时间单位 time_unit 如下: + 1u(微秒),1a(毫秒),1s(秒),1m(分),1h(小时),1d(天)。 + 2)如果时间单位 time_unit 未指定, 返回的时间差值精度与当前 DATABASE 设置的时间精度一致。 + + 示例: + ```mysql + taos> SELECT TIMEDIFF(1643738400000, 1643742000000) FROM meters; + timediff(1643738400000, 1643742000000) | + ========================================= + 3600000 | + Query OK, 1 row(s) in set (0.002553s) + + taos> SELECT TIMEDIFF(1643738400000, 1643742000000, 1h) FROM meters; + timediff(1643738400000, 1643742000000, 1h) | + ============================================= + 1 | + Query OK, 1 row(s) in set (0.003726s) + + taos> SELECT TIMEDIFF("2022-02-02 03:00:00", "2022-02-02 02:00:00", 1h) FROM meters; + timediff("2022-02-02 03:00:00", "2022-02-02 02:00:00", 1h) | + ============================================================= + 1 | + Query OK, 1 row(s) in set (0.001937s) + + taos> SELECT TIMEDIFF(ts_col1, ts_col2, 1h) FROM meters; + timediff(ts_col1, ts_col2, 1h) | + =================================== + 1 | + Query OK, 1 row(s) in set (0.001937s) + ``` + ## 按窗口切分聚合 TDengine 支持按时间段窗口切分方式进行聚合结果查询,比如温度传感器每秒采集一次数据,但需查询每隔 10 分钟的温度平均值。这种场景下可以使用窗口子句来获得需要的查询结果。 @@ -1762,7 +2785,7 @@ IS NOT NULL 支持所有类型的列。不为空的表达式为 <>"",仅对非 TDengine 中的表(列)名命名规则如下: 只能由字母、数字、下划线构成,数字不能在首位,长度不能超过192字节,不区分大小写。这里表名称不包括数据库名的前缀和分隔符。 -转移后表(列)名规则: +转义后表(列)名规则: 为了兼容支持更多形式的表(列)名,TDengine 引入新的转义符 "`"。可用让表名与关键词不冲突,同时不受限于上述表名称合法性约束检查,转义符不计入表名称的长度。 转义后的表(列)名同样受到长度限制要求,且长度计算的时候不计算转义符。使用转义字符以后,不再对转义字符中的内容进行大小写统一。 diff --git a/documentation20/cn/13.faq/docs.md b/documentation20/cn/13.faq/docs.md index 209f07b666d4b93e0c05be460e6a37117bbb8b16..5447565241c9c9921cffa3979808ddf6349c8faa 100644 --- a/documentation20/cn/13.faq/docs.md +++ b/documentation20/cn/13.faq/docs.md @@ -1,23 +1,27 @@ # 常见问题及反馈 ## 问题反馈 + 如果 FAQ 中的信息不能够帮到您,需要 TDengine 技术团队的技术支持与协助,请将以下两个目录中内容打包: + 1. /var/log/taos (如果没有修改过默认路径) 2. /etc/taos -附上必要的问题描述,包括使用的 TDengine 版本信息、平台环境信息、发生该问题的执行操作、出现问题的表征及大概的时间,在 [GitHub](https://github.com/taosdata/TDengine) 提交Issue。 +附上必要的问题描述,包括使用的 TDengine 版本信息、平台环境信息、发生该问题的执行操作、出现问题的表征及大概的时间,在 [GitHub](https://github.com/taosdata/TDengine) 提交 Issue。 + +为了保证有足够的 debug 信息,如果问题能够重复,请修改/etc/taos/taos.cfg文件,最后面添加一行“debugFlag 135"(不带引号本身),然后重启 `taosd`, 重复问题,然后再递交。也可以通过如下 SQL 语句,临时设置 taosd 的日志级别。 -为了保证有足够的debug信息,如果问题能够重复,请修改/etc/taos/taos.cfg文件,最后面添加一行“debugFlag 135"(不带引号本身),然后重启taosd, 重复问题,然后再递交。也可以通过如下SQL语句,临时设置taosd的日志级别。 ``` - alter dnode debugFlag 135; + ALTER DNODE debugFlag 135; ``` -但系统正常运行时,请一定将debugFlag设置为131,否则会产生大量的日志信息,降低系统效率。 + +但系统正常运行时,请一定将 debugFlag 设置为 131,否则会产生大量的日志信息,降低系统效率。 ## 常见问题列表 -**1. TDengine2.0之前的版本升级到2.0及以上的版本应该注意什么?☆☆☆** +**1. TDengine 2.0 之前的版本升级到 2.0 及以上的版本应该注意什么?☆☆☆** -2.0版在之前版本的基础上,进行了完全的重构,配置文件和数据文件是不兼容的。在升级之前务必进行如下操作: +2.0 版在之前版本的基础上,进行了完全的重构,配置文件和数据文件是不兼容的。在升级之前务必进行如下操作: 1. 删除配置文件,执行 `sudo rm -rf /etc/taos/taos.cfg` 2. 删除日志文件,执行 `sudo rm -rf /var/log/taos/` @@ -29,11 +33,11 @@ 请看为此问题撰写的[技术博客](https://www.taosdata.com/blog/2019/12/03/950.html)。 -**3. 创建数据表时提示more dnodes are needed** +**3. 创建数据表时提示 more dnodes are needed** 请看为此问题撰写的[技术博客](https://www.taosdata.com/blog/2019/12/03/965.html)。 -**4. 如何让TDengine crash时生成core文件?** +**4. 如何让 TDengine crash 时生成 core 文件?** 请看为此问题撰写的[技术博客](https://www.taosdata.com/blog/2019/12/06/974.html)。 @@ -42,53 +46,53 @@ 客户端遇到连接故障,请按照下面的步骤进行检查: 1. 检查网络环境 - * 云服务器:检查云服务器的安全组是否打开TCP/UDP 端口6030-6042的访问权限 - * 本地虚拟机:检查网络能否ping通,尽量避免使用`localhost` 作为hostname - * 公司服务器:如果为NAT网络环境,请务必检查服务器能否将消息返回值客户端 + * 云服务器:检查云服务器的安全组是否打开 TCP/UDP 端口 6030-6042 的访问权限 + * 本地虚拟机:检查网络能否 ping 通,尽量避免使用`localhost` 作为 hostname + * 公司服务器:如果为 NAT 网络环境,请务必检查服务器能否将消息返回值客户端 2. 确保客户端与服务端版本号是完全一致的,开源社区版和企业版也不能混用 3. 在服务器,执行 `systemctl status taosd` 检查*taosd*运行状态。如果没有运行,启动*taosd* -4. 确认客户端连接时指定了正确的服务器FQDN (Fully Qualified Domain Name —— 可在服务器上执行Linux命令hostname -f获得),FQDN配置参考:[一篇文章说清楚TDengine的FQDN](https://www.taosdata.com/blog/2020/09/11/1824.html)。 +4. 确认客户端连接时指定了正确的服务器 FQDN (Fully Qualified Domain Name —— 可在服务器上执行 Linux 命令 `hostname -f` 获得),FQDN 配置参考:[一篇文章说清楚 TDengine 的 FQDN](https://www.taosdata.com/blog/2020/09/11/1824.html)。 -5. ping服务器FQDN,如果没有反应,请检查你的网络,DNS设置,或客户端所在计算机的系统hosts文件。如果部署的是TDengine集群,客户端需要能ping通所有集群节点的FQDN。 +5. ping 服务器 FQDN,如果没有反应,请检查你的网络,DNS 设置,或客户端所在计算机的系统 `hosts` 文件。如果部署的是 TDengine 集群,客户端需要能 ping 通所有集群节点的 FQDN。 -6. 检查防火墙设置(Ubuntu 使用 ufw status,CentOS 使用 firewall-cmd --list-port),确认TCP/UDP 端口6030-6042 是打开的 +6. 检查防火墙设置(Ubuntu 使用 `ufw status`,CentOS 使用 `firewall-cmd --list-port`),确认 TCP/UDP 端口 6030-6042 是打开的 -7. 对于Linux上的JDBC(ODBC, Python, Go等接口类似)连接, 确保*libtaos.so*在目录*/usr/local/taos/driver*里, 并且*/usr/local/taos/driver*在系统库函数搜索路径*LD_LIBRARY_PATH*里 +7. 对于 Linux 上的 JDBC(ODBC, Python, Go 等接口类似)连接, 确保*libtaos.so*在目录*/usr/local/taos/driver*里, 并且*/usr/local/taos/driver*在系统库函数搜索路径*LD_LIBRARY_PATH*里 -8. 对于Windows上的JDBC, ODBC, Python, Go等连接,确保*C:\TDengine\driver\taos.dll*在你的系统库函数搜索目录里 (建议*taos.dll*放在目录 *C:\Windows\System32*) +8. 对于 Windows 上的 JDBC, ODBC, Python, Go等连接,确保*C:\TDengine\driver\taos.dll*在你的系统库函数搜索目录里 (建议*taos.dll*放在目录 *C:\Windows\System32*) 9. 如果仍不能排除连接故障 - * Linux 系统请使用命令行工具nc来分别判断指定端口的TCP和UDP连接是否通畅 - 检查UDP端口连接是否工作:`nc -vuz {hostIP} {port} ` - 检查服务器侧TCP端口连接是否工作:`nc -l {port}` - 检查客户端侧TCP端口连接是否工作:`nc {hostIP} {port}` + * Linux 系统请使用命令行工具 `nc` 来分别判断指定端口的 TCP 和 UDP 连接是否通畅 + 检查 UDP 端口连接是否工作:`nc -vuz {hostIP} {port} ` + 检查服务器侧 TCP 端口连接是否工作:`nc -l {port}` + 检查客户端侧 TCP 端口连接是否工作:`nc {hostIP} {port}` * Windows 系统请使用 PowerShell 命令 Net-TestConnection -ComputerName {fqdn} -Port {port} 检测服务段端口是否访问 -10. 也可以使用taos程序内嵌的网络连通检测功能,来验证服务器和客户端之间指定的端口连接是否通畅(包括TCP和UDP):[TDengine 内嵌网络检测工具使用指南](https://www.taosdata.com/blog/2020/09/08/1816.html)。 +10. 也可以使用 `taos` 程序内嵌的网络连通检测功能,来验证服务器和客户端之间指定的端口连接是否通畅(包括 TCP 和 UDP):[TDengine 内嵌网络检测工具使用指南](https://www.taosdata.com/blog/2020/09/08/1816.html)。 **6. 遇到错误“Unexpected generic error in RPC”或者“Unable to resolve FQDN”,我怎么办?** -产生这个错误,是由于客户端或数据节点无法解析FQDN(Fully Qualified Domain Name)导致。对于TAOS Shell或客户端应用,请做如下检查: +产生这个错误,是由于客户端或数据节点无法解析 FQDN(Fully Qualified Domain Name)导致。对于 TAOS Shell 或客户端应用,请做如下检查: -1. 请检查连接的服务器的FQDN是否正确,FQDN配置参考:[一篇文章说清楚TDengine的FQDN](https://www.taosdata.com/blog/2020/09/11/1824.html) -2. 如果网络配置有DNS server,请检查是否正常工作 -3. 如果网络没有配置DNS server,请检查客户端所在机器的hosts文件,查看该FQDN是否配置,并是否有正确的IP地址 -4. 如果网络配置OK,从客户端所在机器,你需要能Ping该连接的FQDN,否则客户端是无法连接服务器的 -5. 如果服务器曾经使用过TDengine,且更改过hostname,建议检查data目录的dnodeEps.json是否符合当前配置的EP,路径默认为/var/lib/taos/dnode。正常情况下,建议更换新的数据目录或者备份后删除以前的数据目录,这样可以避免该问题。 -6. 检查/etc/hosts 和/etc/hostname是否是预配置的FQDN +1. 请检查连接的服务器的 FQDN 是否正确,FQDN 配置参考:[一篇文章说清楚 TDengine 的 FQDN](https://www.taosdata.com/blog/2020/09/11/1824.html) +2. 如果网络配置有 DNS server,请检查是否正常工作 +3. 如果网络没有配置 DNS server,请检查客户端所在机器的 `hosts` 文件,查看该 FQDN 是否配置,并是否有正确的 IP 地址 +4. 如果网络配置 OK,从客户端所在机器,你需要能 ping 该连接的 FQDN,否则客户端是无法连接服务器的 +5. 如果服务器曾经使用过 TDengine,且更改过 hostname,建议检查 `data` 目录的 `dnodeEps.json` 是否符合当前配置的 EP,路径默认为 `/var/lib/taos/dnode`。正常情况下,建议更换新的数据目录或者备份后删除以前的数据目录,这样可以避免该问题。 +6. 检查 `/etc/hosts` 和 ``/etc/hostname` 是否是预配置的 FQDN **7. 虽然语法正确,为什么我还是得到 "Invalid SQL" 错误** -如果你确认语法正确,2.0之前版本,请检查SQL语句长度是否超过64K。如果超过,也会返回这个错误。 +如果你确认语法正确,2.0之前版本,请检查 SQL 语句长度是否超过 64K。如果超过,也会返回这个错误。 **8. 是否支持validation queries?** -TDengine还没有一组专用的validation queries。然而建议你使用系统监测的数据库”log"来做。 +TDengine 还没有一组专用的 validation queries。然而建议你使用系统监测的数据库”log"来做。 @@ -98,7 +102,7 @@ TDengine 目前尚不支持删除功能,未来根据用户需求可能会支 从 2.0.8.0 开始,TDengine 支持更新已经写入数据的功能。使用更新功能需要在创建数据库时使用 UPDATE 1 参数,之后可以使用 INSERT INTO 命令更新已经写入的相同时间戳数据。UPDATE 参数不支持 ALTER DATABASE 命令修改。没有使用 UPDATE 1 参数创建的数据库,写入相同时间戳的数据不会修改之前的数据,也不会报错。 -另需注意,在 UPDATE 设置为 0 时,后发送的相同时间戳的数据会被直接丢弃,但并不会报错,而且仍然会被计入 affected rows (所以不能利用 INSERT 指令的返回信息进行时间戳查重)。这样设计的主要原因是,TDengine 把写入的数据看做一个数据流,无论时间戳是否出现冲突,TDengine 都认为产生数据的原始设备真实地产生了这样的数据。UPDATE 参数只是控制这样的流数据在进行持久化时要怎样处理——UPDATE 为 0 时,表示先写入的数据覆盖后写入的数据;而 UPDATE 为 1 时,表示后写入的数据覆盖先写入的数据。这种覆盖关系如何选择,取决于对数据的后续使用和统计中,希望以先还是后生成的数据为准。 +另需注意,在 UPDATE 设置为 0 时,后发送的相同时间戳的数据会被直接丢弃,但并不会报错,而且仍然会被计入 affected rows (所以不能利用 INSERT 指令的返回信息进行时间戳查重)。这样设计的主要原因是,TDengine 把写入的数据看做一个数据流,无论时间戳是否出现冲突,TDengine 都认为产生数据的原始设备真实地产生了这样的数据。UPDATE 参数只是控制这样的流数据在进行持久化时要怎样处理—— UPDATE 为 0 时,表示先写入的数据覆盖后写入的数据;而 UPDATE 为 1 时,表示后写入的数据覆盖先写入的数据。这种覆盖关系如何选择,取决于对数据的后续使用和统计中,希望以先还是后生成的数据为准。 此外,从 2.1.7.0 版本开始,支持将 UPDATE 参数设为 2,表示“支持部分列更新”。也即,当 UPDATE 设为 1 时,如果更新一个数据行,其中某些列没有提供取值,那么这些列会被设为 NULL;而当 UPDATE 设为 2 时,如果更新一个数据行,其中某些列没有提供取值,那么这些列会保持原有数据行中的对应值。 @@ -110,9 +114,10 @@ TDengine 目前尚不支持删除功能,未来根据用户需求可能会支 批量插入。每条写入语句可以一张表同时插入多条记录,也可以同时插入多张表的多条记录。 -**12. Windows系统下插入的nchar类数据中的汉字被解析成了乱码如何解决?** +**12. Windows 系统下插入的 nchar 类数据中的汉字被解析成了乱码如何解决?** + +Windows下插入 nchar 类的数据中如果有中文,请先确认系统的地区设置成了中国(在Control Panel里可以设置),这时cmd中的 `taos` 客户端应该已经可以正常工作了;如果是在 IDE 里开发 Java 应用,比如 Eclipse, IntelliJ,请确认 IDE 里的文件编码为 GBK(这是 Java 默认的编码类型),然后在生成 Connection 时,初始化客户端的配置,具体语句如下: -Windows下插入nchar类的数据中如果有中文,请先确认系统的地区设置成了中国(在Control Panel里可以设置),这时cmd中的`taos`客户端应该已经可以正常工作了;如果是在IDE里开发Java应用,比如Eclipse, Intellij,请确认IDE里的文件编码为GBK(这是Java默认的编码类型),然后在生成Connection时,初始化客户端的配置,具体语句如下: ```JAVA Class.forName("com.taosdata.jdbc.TSDBDriver"); Properties properties = new Properties(); @@ -120,9 +125,10 @@ properties.setProperty(TSDBDriver.LOCALE_KEY, "UTF-8"); Connection = DriverManager.getConnection(url, properties); ``` -**13.JDBC报错: the excuted SQL is not a DML or a DDL?** +**13.JDBC 报错: the excuted SQL is not a DML or a DDL?** + +请更新至最新的 JDBC 驱动 -请更新至最新的JDBC驱动 ```xml com.taosdata.jdbc @@ -133,18 +139,18 @@ Connection = DriverManager.getConnection(url, properties); **14. taos connect failed, reason: invalid timestamp** -常见原因是服务器和客户端时间没有校准,可以通过和时间服务器同步的方式(Linux 下使用 ntpdate 命令,Windows 在系统时间设置中选择自动同步)校准。 +常见原因是服务器和客户端时间没有校准,可以通过和时间服务器同步的方式(Linux 下使用 `ntpdate` 命令,Windows 在系统时间设置中选择自动同步)校准。 **15. 表名显示不全** -由于 taos shell 在终端中显示宽度有限,有可能比较长的表名显示不全,如果按照显示的不全的表名进行相关操作会发生 Table does not exist 错误。解决方法可以是通过修改 taos.cfg 文件中的设置项 maxBinaryDisplayWidth, 或者直接输入命令 set max_binary_display_width 100。或者在命令结尾使用 \G 参数来调整结果的显示方式。 +由于 taos shell 在终端中显示宽度有限,有可能比较长的表名显示不全,如果按照显示的不全的表名进行相关操作会发生 Table does not exist 错误。解决方法可以是通过修改 `taos.cfg` 文件中的设置项 `maxBinaryDisplayWidth`, 或者直接输入命令 `set max_binary_display_width 100`。或者在命令结尾使用 \G 参数来调整结果的显示方式。 **16. 如何进行数据迁移?** -TDengine是根据hostname唯一标志一台机器的,在数据文件从机器A移动机器B时,注意如下两件事: +TDengine 是根据 hostname 唯一标志一台机器的,在数据文件从机器A移动机器B时,注意如下两件事: -- 2.0.0.0 至 2.0.6.x 的版本,重新配置机器B的hostname为机器A的hostname。 -- 2.0.7.0 及以后的版本,到/var/lib/taos/dnode下,修复dnodeEps.json的dnodeId对应的FQDN,重启。确保机器内所有机器的此文件是完全相同的。 +- 2.0.0.0 至 2.0.6.x 的版本,重新配置机器B的 hostname 为机器A的 hostname。 +- 2.0.7.0 及以后的版本,到 /var/lib/taos/dnode 下,修复 dnodeEps.json 的 dnodeId 对应的 FQDN,重启。确保机器内所有机器的此文件是完全相同的。 - 1.x 和 2.x 版本的存储结构不兼容,需要使用迁移工具或者自己开发应用导出导入数据。 **17. 如何在命令行程序 taos 中临时调整日志级别** @@ -156,6 +162,7 @@ ALTER LOCAL flag_name flag_value; ``` 其含义是,在当前的命令行程序下,修改一个特定模块的日志记录级别(只对当前命令行程序有效,如果 taos 命令行程序重启,则需要重新设置): + - flag_name 的取值可以是:debugFlag,cDebugFlag,tmrDebugFlag,uDebugFlag,rpcDebugFlag - flag_value 的取值可以是:131(输出错误和警告日志),135( 输出错误、警告和调试日志),143( 输出错误、警告、调试和跟踪日志) @@ -172,6 +179,7 @@ ALTER LOCAL RESETLOG; TDengine 中时间戳的时区总是由客户端进行处理,而与服务端无关。具体来说,客户端会对 SQL 语句中的时间戳进行时区转换,转为 UTC 时区(即 Unix 时间戳——Unix Timestamp)再交由服务端进行写入和查询;在读取数据时,服务端也是采用 UTC 时区提供原始数据,客户端收到后再根据本地设置,把时间戳转换为本地系统所要求的时区进行显示。 客户端在处理时间戳字符串时,会采取如下逻辑: + 1. 在未做特殊设置的情况下,客户端默认使用所在操作系统的时区设置。 2. 如果在 taos.cfg 中设置了 timezone 参数,则客户端会以这个配置文件中的设置为准。 3. 如果在 C/C++/Java/Python 等各种编程语言的 Connector Driver 中,在建立数据库连接时显式指定了 timezone,那么会以这个指定的时区设置为准。例如 Java Connector 的 JDBC URL 中就有 timezone 参数。 @@ -192,24 +200,23 @@ TDengine 中时间戳的时区总是由客户端进行处理,而与服务端 | TCP | 6042 | Arbitrator 的服务端口。 | 随 Arbitrator 启动参数设置变化。 | | TCP | 6043 | TaosKeeper 监控服务端口。 | 随 TaosKeeper 启动参数设置变化。 | | TCP | 6044 | 支持 StatsD 的数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | -| TCP | 6045 | 支持 collectd 数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | +| UDP | 6045 | 支持 collectd 数据接入端口。 | 随 taosAdapter 启动参数设置变化(2.3.0.1+以上版本)。 | | TCP | 6060 | 企业版内 Monitor 服务的网络端口。 | | | UDP | 6030-6034 | 客户端与服务端之间通讯。 | 随 serverPort 端口变化。 | | UDP | 6035-6039 | 多节点集群的节点间通讯。 | 随 serverPort 端口变化。 | -**20. go 语言编写组件编译失败怎样解决?** +**20. Go 语言编写组件编译失败怎样解决?** -新版本 TDengine 2.3.0.0 包含一个使用 go 语言开发的 taosAdapter 独立组件,需要单独运行,取代之前 taosd 内置的 httpd ,提供包含原 httpd 功能以及支持多种其他软件(Prometheus、Telegraf、collectd、StatsD等)的数据接入功能。 +新版本 TDengine 2.3.0.0 包含一个使用 Go 语言开发的 taosAdapter 独立组件,需要单独运行,取代之前 taosd 内置的 httpd ,提供包含原 httpd 功能以及支持多种其他软件(Prometheus、Telegraf、collectd、StatsD 等)的数据接入功能。 使用最新 develop 分支代码编译需要先 `git submodule update --init --recursive` 下载 taosAdapter 仓库代码后再编译。 -目前编译方式默认自动编译 taosAdapter。go 语言版本要求 1.14 以上,如果发生 go 编译错误,往往是国内访问 go mod 问题,可以通过设置 go 环境变量来解决: +目前编译方式默认自动编译 taosAdapter。Go 语言版本要求 1.14 以上,如果发生 Go 编译错误,往往是国内访问 go mod 问题,可以通过设置 Go 环境变量来解决: ```sh go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,direct ``` -如果希望继续使用之前的内置 httpd,可以关闭 taosAdapter 编译,使用 +如果希望继续使用之前的内置 httpd,可以关闭 taosAdapter 编译,使用 `cmake .. -DBUILD_HTTP=true` 使用原来内置的 httpd。 - diff --git a/documentation20/cn/14.devops/03.immigrate/docs.md b/documentation20/cn/14.devops/03.immigrate/docs.md index 1b003f5d0c9adab5a2da3ce22133eacaf5132df4..21f9aa9053e598774710069f5a1d2354da742858 100644 --- a/documentation20/cn/14.devops/03.immigrate/docs.md +++ b/documentation20/cn/14.devops/03.immigrate/docs.md @@ -118,8 +118,8 @@ TDengine 当前只支持 Grafana 的可视化看板呈现,所以如果你的 | 序号 | 测量(metric) | 值名称 | 类型 | tag1 | tag2 | tag3 | tag4 | tag5 | | ---- | -------------- | ------ | ------ | ---- | ----------- | -------------------- | --------- | ------ | -| 1 | memory | value | double | host | memory_type | memory_type_instance | source | n/a | -| 2 | swap | value | double | host | swap_type | swap_type_instance | source | n/a | +| 1 | memory | value | double | host | memory_type | memory_type_instance | source | n/a | +| 2 | swap | value | double | host | swap_type | swap_type_instance | source | n/a | | 3 | disk | value | double | host | disk_point | disk_instance | disk_type | source | TDengine 要求存储的数据具有数据模式,即写入数据之前需创建超级表并指定超级表的模式。对于数据模式的建立,你有两种方式来完成此项工作:1)充分利用 TDengine 对 OpenTSDB 的数据原生写入的支持,调用 TDengine 提供的 API 将(文本行或 JSON 格式)数据写入,并自动化地建立单值模型。采用这种方式不需要对数据写入应用进行较大的调整,也不需要对写入的数据格式进行转换。 @@ -174,7 +174,7 @@ TDengine 支持标准的 JDBC 3.0 接口操纵数据库,你也可以使用其 为了方便历史数据的迁移工作,我们为数据同步工具 DataX 提供了插件,能够将数据自动写入到 TDengine 中,需要注意的是 DataX 的自动化数据迁移只能够支持单值模型的数据迁移过程。 -DataX 具体的使用方式及如何使用 DataX 将数据写入 TDengine 请参见[基于DataX的TDeninge数据迁移工具](https://www.taosdata.com/blog/2021/10/26/3156.html)。 +DataX 具体的使用方式及如何使用 DataX 将数据写入 TDengine 请参见[基于 DataX 的 TDengine 数据迁移工具](https://www.taosdata.com/blog/2021/10/26/3156.html)。 在对 DataX 进行迁移实践后,我们发现通过启动多个进程,同时迁移多个 metric 的方式,可以大幅度的提高迁移历史数据的效率,下面是迁移过程中的部分记录,希望这些能为应用迁移工作带来参考。 @@ -198,7 +198,7 @@ DataX 具体的使用方式及如何使用 DataX 将数据写入 TDengine 请参 2)在系统全负载运行下,如果有足够的剩余计算和 IO 资源,可以建立多线程的导入机制,最大限度地提升数据迁移的效率。考虑到数据解析对于 CPU 带来的巨大负载,需要控制最大的并行任务数量,以避免因导入历史数据而触发的系统整体过载。 -由于 TDegnine 本身操作简易性,所以不需要在整个过程中进行索引维护、数据格式的变化处理等工作,整个过程只需要顺序执行即可。 +由于 TDengine 本身操作简易性,所以不需要在整个过程中进行索引维护、数据格式的变化处理等工作,整个过程只需要顺序执行即可。 当历史数据完全导入到 TDengine 以后,此时两个系统处于同时运行的状态,之后便可以将查询请求切换到 TDengine 上,从而实现无缝的应用切换。 diff --git a/documentation20/en/00.index/docs.md b/documentation20/en/00.index/docs.md index 2929ee5e33eab7531e3777869a4d9dafea40e7b4..ae7818bc7aa13b3cbb6e62a51889c80704d49233 100644 --- a/documentation20/en/00.index/docs.md +++ b/documentation20/en/00.index/docs.md @@ -38,6 +38,8 @@ TDengine is a highly efficient platform to store, query, and analyze time-series - [Data Writing via Schemaless](/insert#schemaless): write one or multiple records with automatic table creation and adaptive table structure maintenance - [Data Writing via Prometheus](/insert#prometheus): Configure Prometheus to write data directly without any code - [Data Writing via Telegraf](/insert#telegraf): Configure Telegraf to write collected data directly without any code +- [Data Writing via collectd](/insert#collectd): Configure collectd to write collected data directly without any code +- [Data Writing via StatsD](/insert#statsd): Configure StatsD to write collected data directly without any code - [Data Writing via EMQX](/insert#emq): Configure EMQX to write MQTT data directly without any code - [Data Writing via HiveMQ Broker](/insert#hivemq): Configure HiveMQ to write MQTT data directly without any code @@ -95,7 +97,8 @@ TDengine is a highly efficient platform to store, query, and analyze time-series - [R](/connections#r): access data stored in TDengine server via JDBC configured within R - [IDEA Database](https://www.taosdata.com/blog/2020/08/27/1767.html): use TDengine visually through IDEA Database Management Tool - [TDengineGUI](https://github.com/skye0207/TDengineGUI): a TDengine management tool with Graphical User Interface -- [DataX](https://github.com/taosdata/datax): a data immigaration tool with TDeninge supported +- [DataX](https://github.com/taosdata/datax): a data immigration tool with TDengine supported +- [Awesome TDengine](https://github.com/taosdata/awesome-tdengine):A curated list of awesome things related to TDengine ## [Installation and Management of TDengine Cluster](/cluster) diff --git a/documentation20/en/02.getting-started/01.docker/docs.md b/documentation20/en/02.getting-started/01.docker/docs.md index bd5fd3167b8d3fb5f11a9e6c0ea6e709be99a2d3..65a7abcedbecc69087c1a0a4f2d050b03aaed8f5 100644 --- a/documentation20/en/02.getting-started/01.docker/docs.md +++ b/documentation20/en/02.getting-started/01.docker/docs.md @@ -197,7 +197,7 @@ column[0]:FLOAT column[1]:INT column[2]:FLOAT Press enter key to continue or Ctrl-C to stop ``` -After enter, this command will automatically create a super table `meters` under the database test, there are 10,000 tables under this super table, the table name is "d0" to "d9999", each table has 10,000 records, each record has four fields (ts, current, voltage, phase), the time stamp is from "2017-07-14 10:40:00 000" to "2017-07-14 10:40:09 999", each table has a tag location and groupId, groupId is set from 1 to 10 and location is set to "beijing" or "shanghai". +After enter, this command will automatically create a super table `meters` under the database test, there are 10,000 tables under this super table, the table name is "d0" to "d9999", each table has 10,000 records, each record has four fields (ts, current, voltage, phase), the time stamp is from "2017-07-14 10:40:00 000" to "2017-07-14 10:40:09 999", each table has a tag location and groupid, groupid is set from 1 to 10 and location is set to "beijing" or "shanghai". It takes about a few minutes to execute this command and ends up inserting a total of 100 million records. @@ -217,7 +217,7 @@ taos> - **View the database.** ```bash -$ taos> show databases; +$ taos> SHOW DATABASES; name | created_time | ntables | vgroups | ··· test | 2021-08-18 06:01:11.021 | 10000 | 6 | ··· log | 2021-08-18 05:51:51.065 | 4 | 1 | ··· @@ -227,10 +227,10 @@ $ taos> show databases; - **View Super Tables.** ```bash -$ taos> use test; +$ taos> USE test; Database changed. -$ taos> show stables; +$ taos> SHOW STABLES; name | created_time | columns | tags | tables | ============================================================================================ meters | 2021-08-18 06:01:11.116 | 4 | 2 | 10000 | @@ -241,10 +241,7 @@ Query OK, 1 row(s) in set (0.003259s) - **View the table and limit the output to 10 entries.** ```bash -$ taos> select * from test.t0 limit 10; - -DB error: Table does not exist (0.002857s) -taos> select * from test.d0 limit 10; +taos> SELECT * FROM test.d0 LIMIT 10; ts | current | voltage | phase | ====================================================================================== 2017-07-14 10:40:00.000 | 10.12072 | 223 | 0.34167 | @@ -264,7 +261,7 @@ Query OK, 10 row(s) in set (0.016791s) - **View the tag values for the d0 table.** ```bash -$ taos> select groupid, location from test.d0; +$ taos> SELECT groupid, location FROM test.d0; groupid | location | ================================= 0 | shanghai | @@ -283,23 +280,23 @@ echo "foo:1|c" | nc -u -w0 127.0.0.1 6044 Then you can use the taos shell to query the taosAdapter automatically created database statsd and the contents of the super table foo. ``` -taos> show databases; +taos> SHOW DATABASES; name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | ==================================================================================================================================================================================================================================================================================== log | 2021-12-28 09:18:55.765 | 12 | 1 | 1 | 1 | 10 | 30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | 0 | us | 0 | ready | statsd | 2021-12-28 09:21:48.841 | 1 | 1 | 1 | 1 | 10 | 3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | 0 | ns | 2 | ready | Query OK, 2 row(s) in set (0.002112s) -taos> use statsd; +taos> USE statsd; Database changed. -taos> show stables; +taos> SHOW STABLES; name | created_time | columns | tags | tables | ============================================================================================ foo | 2021-12-28 09:21:48.894 | 2 | 1 | 1 | Query OK, 1 row(s) in set (0.001160s) -taos> select * from foo; +taos> SELECT * FROM foo; ts | value | metric_type | ======================================================================================= 2021-12-28 09:21:48.840820836 | 1 | counter | diff --git a/documentation20/en/02.getting-started/02.taosdemo/docs.md b/documentation20/en/02.getting-started/02.taosdemo/docs.md index ff017c01559d9137792a25dec8ffd052ad643cda..0d4ceb24290fe549270b5e0a5f8ce26eb3f30cce 100644 --- a/documentation20/en/02.getting-started/02.taosdemo/docs.md +++ b/documentation20/en/02.getting-started/02.taosdemo/docs.md @@ -1,4 +1,4 @@ -Since TDengine was open sourced in July 2019, it has gained a lot of popularity among time-series database developers with its innovative data modeling design, simple installation method, easy programming interface, and powerful data insertion and query performance. The insertion and querying performance is often astonishing to users who are new to TDengine. In order to help users to experience the high performance and functions of TDengine in the shortest time, we developed an application called `taosBenchmark` (was named `taosdemo`) for insertion and querying performance testing of TDengine. Then user can easily simulate the scenario of a large number of devices generating a very large amount of data. User can easily manipulate the number of columns, data types, disorder ratio, and number of concurrent threads with taosBenchmark customized parameters. +Since TDengine was open sourced in July 2019, it has gained a lot of popularity among time-series database developers with its innovative data modeling design, simple installation method, easy programming interface, and powerful data insertion and query performance. The insertion and querying performance is often astonishing to users who are new to TDengine. In order to help users to experience the high performance and functions of TDengine in the shortest time, we developed an application called `taosBenchmark` (was named `taosdemo`) for insertion and querying performance testing of TDengine. Then user can easily simulate the scenario of a large number of devices generating a very large amount of data. User can easily manipulate the number of tables, columns, data types, disorder ratio, and number of concurrent threads with taosBenchmark customized parameters. Running taosBenchmark is very simple. Just download the [TDengine installation package](https://www.taosdata.com/cn/all-downloads/) or compiling the [TDengine code](https://github.com/taosdata/TDengine). It can be found and run in the installation directory or in the compiled results directory. @@ -160,41 +160,70 @@ The complete list of taosBenchmark command-line arguments can be displayed via t ``` $ taosBenchmark --help --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. --p, --password The password to use when connecting to the server. --c, --config-dir=CONFIG_DIR Configuration directory. --h, --host=HOST TDengine server FQDN to connect. The default host is localhost. --P, --port=PORT The TCP/IP port number to use for the connection. --I, --interface=INTERFACE The interface (taosc, rest, and stmt) taosBenchmark uses. By default use 'taosc'. --d, --database=DATABASE Destination database. By default is 'test'. --a, --replica=REPLICA Set the replica parameters of the database, By default use 1, min: 1, max: 3. --m, --table-prefix=TABLEPREFIX Table prefix name. By default use 'd'. --s, --sql-file=FILE The select sql file. --N, --normal-table Use normal table flag. --o, --output=FILE Direct output to the named file. By default use './output.txt'. --q, --query-mode=MODE Query mode -- 0: SYNC, 1: ASYNC. By default use SYNC. --b, --data-type=DATATYPE The data_type of columns, By default use: FLOAT, INT, FLOAT. --w, --binwidth=WIDTH The width of data_type 'BINARY' or 'NCHAR'. By default use 64 --l, --columns=COLUMNS The number of columns per record. Demo mode by default is 1 (float, int, float). Max values is 4095 -All of the new column(s) type is INT. If use -b to specify column type, -l will be ignored. --T, --threads=NUMBER The number of threads. By default use 8. --i, --insert-interval=NUMBER The sleep time (ms) between insertion. By default is 0. --S, --time-step=TIME_STEP The timestamp step between insertion. By default is 1. --B, --interlace-rows=NUMBER The interlace rows of insertion. By default is 0. --r, --rec-per-req=NUMBER The number of records per request. By default is 30000. --t, --tables=NUMBER The number of tables. By default is 10000. --n, --records=NUMBER The number of records per table. By default is 10000. --M, --random The value of records generated are totally random. -By default to simulate power equipment scenario. --x, --aggr-func Test aggregation functions after insertion. --y, --answer-yes Input yes for prompt. --O, --disorder=NUMBER Insert order mode--0: In order, 1 ~ 50: disorder ratio. By default is in order. --R, --disorder-range=NUMBER Out of order data's range. Unit is ms. By default is 1000. --g, --debug Print debug info. --?, --help Give this help list ---usage Give a short usage message --V, --version Print program version. +Usage: taosBenchmark [OPTION...] + + -f, --file=FILE (**IMPORTANT**) Set JSON configuration file(all + options are going to read from this JSON file), + which is mutually exclusive with other commandline + options + -a, --replia=NUMBER The number of replica when create database, + default is 1. + -A, --tag-type=TAG_TYPE Data type of tables' tags, default is + INT,BINARY(16). + -b, --data-type=COL_TYPE Data type of tables' cols, default is + FLOAT,INT,FLOAT. + -B, --interlace-rows=NUMBER The number of interlace rows insert into + tables, default is 0 + -c, --config-dir=CONFIG_DIR Configuration directory. + -C, --chinese Nchar and binary are basic unicode chinese + characters, optional. + -d, --database=DATABASE Name of database, default is test. + -E, --escape-character Use escape character in stable and child table + name, optional. + -F, --prepared_rand=NUMBER Random data source size, default is 10000. + -g, --debug Debug mode, optional. + -G, --performance Performance mode, optional. + -h, --host=HOST TDengine server FQDN to connect, default is + localhost. + -i, --insert-interval=NUMBER Insert interval for interlace mode in + milliseconds, default is 0. + -I, --interface=IFACE insert mode, default is taosc, options: + taosc|rest|stmt|sml + -l, --columns=NUMBER Number of INT data type columns in table, default + is 0. + -m, --table-prefix=TABLE_PREFIX + Prefix of child table name, default is d. + -M, --random Data source is randomly generated, optional. + -n, --records=NUMBER Number of records for each table, default is + 10000. + -N, --normal-table Only create normal table without super table, + optional. + -o, --output=FILE The path of result output file, default is + ./output.txt. + -O, --disorder=NUMBER Ratio of inserting data with disorder timestamp, + default is 0. + -p, --password=PASSWORD The password to use when connecting to the server, + default is taosdata. + -P, --port=PORT The TCP/IP port number to use for the connection, + default is 6030. + -r, --rec-per-req=NUMBER Number of records in each insert request, default + is 30000. + -R, --disorder-range=NUMBER Range of disordered timestamp, default is 1000. + + -S, --time-step=NUMBER Timestamp step in milliseconds, default is 1. + -t, --tables=NUMBER Number of child tables, default is 10000. + -T, --threads=NUMBER The number of thread when insert data, default is + 8. + -u, --user=USER The user name to use when connecting to the + server, default is root. + -w, --binwidth=NUMBER The default length of nchar and binary if not + specified, default is 64. + -x, --aggr-func Query aggregation function after insertion, + optional. + -y, --answer-yes Pass confirmation prompt to continue, optional. + -?, --help Give this help list + --usage Give a short usage message + -V, --version Print program version Mandatory or optional arguments to long options are also mandatory or optional for any corresponding short options. @@ -205,7 +234,7 @@ Report bugs to . taosBenchmark's parameters are designed to meet the needs of data simulation. A few commonly used parameters are described below. ``` --I, --interface=INTERFACE The interface (taosc, rest, and stmt) taosBenchmark uses. Default is 'taosc'. +-I, --interface=IFACE The interface (taosc, rest, and stmt) taosBenchmark uses. Default is 'taosc'. ``` The performance difference between different interfaces of taosBenchmark has been mentioned earlier, the -I parameter is used to select different interfaces, currently taosc, stmt and rest are supported. The -I parameter is used to select different interfaces, currently taosc, stmt and rest are supported. taosc uses SQL statements to write data, stmt uses parameter binding interface to write data, and rest uses RESTful protocol to write data. @@ -346,6 +375,7 @@ In addition to the command line approach, taosBenchmark also supports take a JSO "start_timestamp": "2020-10-01 00:00:00.000", "sample_format": "csv", "sample_file": "./sample.csv", + "use_sample_ts": "no", "tags_file": "", "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] @@ -354,7 +384,9 @@ In addition to the command line approach, taosBenchmark also supports take a JSO } ``` -For example, we can specify different number of threads for table creation and data insertion with "thread_count" and "thread_count_create_tbl". You can use a combination of "child_table_exists", "childtable_limit" and "childtable_offset" to use multiple taosBenchmark processes (even on different computers) to write to different ranges of child tables of the same super table at the same time. You can also import existing data by specifying the data source as a csv file with "data_source" and "sample_file". +For example, we can specify different number of threads for table creation and data insertion with `thread_count` and `thread_count_create_tbl`. You can use a combination of `child_table_exists`, `childtable_limit` and `childtable_offset` to use multiple taosBenchmark processes (even on different computers) to write to different ranges of child tables of the same super table at the same time. You can also import existing data by specifying the data source as a CSV file with `data_source` and `sample_file`. The argument `use_sample_ts` indicate whether the first column, timestamp in TDengine would use the data of the specified CSV file too. + +CSV file is a plain text format and use comma signs as separators between two columns. The number of columns must is same as the number of columns or tags of the table you intend to insert. # Use taosBenchmark for query and subscription testing @@ -410,7 +442,7 @@ The following parameters are specific to the query in the JSON file. "specified_table_query": { query for the specified table "query_interval": interval to execute sqls, in seconds. Optional, default is 0. "concurrent": the number of threads to execute sqls concurrently, optional, default is 1. Each thread executes all sqls. -"sqls": multiple sql statements can be added, support up to 100 statements. +"sqls": multiple SQL statements can be added, support up to 100 statements. "sql": query statement. Mandatory. "result": the name of the file where the query result will be written. Optional, default is null, means the query result will not be written to the file. "super_table_query": { query for all sub-tables in the super table @@ -470,7 +502,7 @@ The following are the meanings of the parameters specific to the subscription fu "restart": subscription restart." yes": restart the subscription if it already exists, "no": continue the previous subscription. (Please note that the executing user needs to have read/write access to the dataDir directory) "keepProgress": keep the progress of the subscription information. yes means keep the subscription information, no means don't keep it. The value is yes and restart is no to continue the previous subscriptions. "resubAfterConsume": Used in conjunction with keepProgress to call unsubscribe after the subscription has been consumed the appropriate number of times and to subscribe again. -"result": the name of the file to which the query result is written. Optional, default is null, means the query result will not be written to the file. Note: The file to save the result after each sql statement cannot be renamed, and the file name will be appended with the thread number when generating the result file. +"result": the name of the file to which the query result is written. Optional, default is null, means the query result will not be written to the file. Note: The file to save the result after each SQL statement cannot be renamed, and the file name will be appended with the thread number when generating the result file. ``` # Conclusion diff --git a/documentation20/en/02.getting-started/docs.md b/documentation20/en/02.getting-started/docs.md index db538f45f709442d4fbf1691d8be80e15595ee41..5608a46489a9af9814bb016071f3eb3cf9ea6e98 100644 --- a/documentation20/en/02.getting-started/docs.md +++ b/documentation20/en/02.getting-started/docs.md @@ -35,7 +35,7 @@ wget -qO - http://repos.taosdata.com/tdengine.key | sudo apt-key add - echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-stable stable main" | sudo tee /etc/apt/sources.list.d/tdengine-stable.list [Optional] echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list sudo apt-get update -apt-get policy tdengine +apt-cache policy tdengine sudo apt-get install tdengine ``` diff --git a/documentation20/en/05.insert/docs.md b/documentation20/en/05.insert/docs.md index 76be97d4f2cfefa4eaecdbc8c1f7a125e5d3cd54..f03cd3fec5da1087ff0b35854cb6dd2ab8255af3 100644 --- a/documentation20/en/05.insert/docs.md +++ b/documentation20/en/05.insert/docs.md @@ -4,7 +4,7 @@ TDengine supports multiple ways to write data, including SQL, Prometheus, Telegr ## Data Writing via SQL -Applications insert data by executing SQL insert statements through C/C++, Java, Go, C#, Python, Node.js Connectors, and users can manually enter SQL insert statements to insert data through TAOS Shell. For example, the following insert writes a record to table d1001: +Applications insert data by executing SQL insert statements through C/C++, Java, Go, C#, Python, Node.js connectors, and users can manually enter SQL insert statements to insert data through TAOS Shell. For example, the following insert writes a record to table d1001: ```mysql INSERT INTO d1001 VALUES (1538548685000, 10.3, 219, 0.31); @@ -36,7 +36,7 @@ For the SQL INSERT Grammar, please refer to [Taos SQL insert](https://www.taosd **Introduction**
In many IoT applications, data collection is often used in intelligent control, business analysis and device monitoring etc. As fast application upgrade and iteration, or hardware adjustment, data collection metrics can change rapidly over time. To provide solutions to such use cases, from version 2.2.0.0, TDengine supports writing data via Schemaless. When using Schemaless, action of pre-creating table before inserting data is no longer needed anymore. Tables, data columns and tags can be created automatically. Schemaless can also add additional data columns to tables if necessary, to make sure data can be properly stored into TDengine. -
TDengine C/C++ Connector provides Schemaless API. Please see [Schemaless data writing API](https://www.taosdata.com/en/documentation/connector#schemaless) for detailed data writing format. +
TDengine's all official connectors provide Schemaless API now. Please see [Schemaless data writing API](https://www.taosdata.com/en/documentation/connector#schemaless) for detailed data writing format.
Super table and corresponding child tables created via Schemaless are identical to the ones created via SQL, so inserting data into these tables via SQL is also supported. Note that child table names are generated via Schemaless are following special rules through tags mapping. Therefore, child table names are usually not meaningful in terms of readability. **Schemaless writing protocols** @@ -167,8 +167,7 @@ In above example second line has one more column c6 with value "passit" compared **Error code**
If users do not write data following corresponding protocol syntax, application will get TSDB_CODE_TSC_LINE_SYNTAX_ERROR error code, which indicates error is happened in input text. Other generic error codes returned by TDengine can also be obtained through taos_errstr API to get detailed error messages. -**Future enhancement** -
Currently TDengine only provides clang API support for Schemaless. In future versions, APIs/connectors of more languages will be supported, e.g., Java/Go/Python/C# etc. From TDengine v2.3 and later versions, users can also use taosAdaptor to writing data via Schemaless through RESTful interface. +
Beside TDengine C/C++ Schemaless API, you can use the API of other official connectors as well, including Java/Go/Python/C#/Node.js/Rust. From TDengine v2.4 and later versions, users can also use taosAdaptor to writing data via Schemaless through RESTful interface. ## Data Writing via Prometheus via taosAdapter diff --git a/documentation20/en/08.connector/docs.md b/documentation20/en/08.connector/docs.md index c74dc7fb0bd2252a9d517b5bde8fdd794a5c158e..c82ea08bda58c887aab6551c498a4ed5eb341dae 100644 --- a/documentation20/en/08.connector/docs.md +++ b/documentation20/en/08.connector/docs.md @@ -22,7 +22,7 @@ Note: ● stands for that has been verified by official tests; ○ stands for th Note: - To access the TDengine database through connectors (except RESTful) in the system without TDengine server software, it is necessary to install the corresponding version of the client installation package to make the application driver (the file name is libtaos.so in Linux system and taos.dll in Windows system) installed in the system, otherwise, the error that the corresponding library file cannot be found will occur. -- All APIs that execute SQL statements, such as `tao_query()`, `taos_query_a()`, `taos_subscribe()` in C/C++ Connector, and APIs corresponding to them in other languages, can only execute one SQL statement at a time. If the actual parameters contain multiple statements, their behavior is undefined. +- All APIs that execute SQL statements, such as `taos_query()`, `taos_query_a()`, `taos_subscribe()` in C/C++ connector, and APIs corresponding to them in other languages, can only execute one SQL statement at a time. If the actual parameters contain multiple statements, their behavior is undefined. - Users upgrading to TDengine 2.0. 8.0 must update the JDBC connection. TDengine must upgrade taos-jdbcdriver to 2.0.12 and above. - No matter which programming language connector is selected, TDengine version 2.0 and above recommends that each thread of database application establish an independent connection or establish a connection pool based on threads to avoid mutual interference between threads of "USE statement" state variables in the connection (but query and write operations of the connection are thread-safe). @@ -347,26 +347,107 @@ Gets the result set of the statement. The result set is used in the same way as Execution completed, release all resources. -### Continuous query interface +- `char * taos_stmt_errstr(TAOS_STMT *stmt)` -TDengine provides time-driven real-time stream computing APIs. You can perform various real-time aggregation calculation operations on tables (data streams) of one or more databases at regular intervals. The operation is simple, only APIs for opening and closing streams. The details are as follows: +Gets the error message if any stmt API returns error. -- `TAOS_STREAM *taos_open_stream(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, TAOS_ROW row), int64_t stime, void *param, void (*callback)(void *))` + +### Schemaless writing API -This API is used to create data streams where: +In addition to writing data using SQL or using the parameter binding API, writing can also be done using Schemaless, which eliminates the need to create a super table/data sub-table data structure in advance and writes data directly, while the TDengine system automatically creates and maintains the required table structure based on the written data content. The use of Schemaless is described in the Schemaless Writing section, and the C/C++ API used with it is described here. - * taos: Database connection established - * sql: SQL query statement (query statement only) - * fp: user-defined callback function pointer. After each stream computing is completed, TDengine passes the query result (TAOS_ROW), query status (TAOS_RES), and user-defined parameters (PARAM) to the callback function. In the callback function, the user can use `taos_num_fields()` to obtain the number of columns in the result set, and `taos_fetch_fields()` to obtain the type of data in each column of the result set. - * stime: The time when stream computing starts. If it is 0, it means starting from now. If it is not zero, it means starting from the specified time (the number of milliseconds from 1970/1/1 UTC time). - * param: It is a parameter provided by the application for callback. During callback, the parameter is provided to the application - * callback: The second callback function is called when the continuous query stop automatically. +- `TAOS_RES* taos_schemaless_insert(TAOS* taos, const char* lines[], int numLines, int protocol, int precision)` + + **Function Description** + + This interface writes the text data of the line protocol to TDengine. + + **Parameter Description** + + taos: database connection, the database connection established by taos_connect function. + + lines: text data. A pattern-free text string that meets the parsing format requirements. + + numLines: the number of lines of the text data, cannot be 0. + + protocol: the protocol type of the lines, used to identify the format of the text data. + + precision: precision string of the timestamp in the text data. + + **Return Value** + + TAOS_RES structure, the application can get the error message by using taos_errstr and also get the error code by using taos_errno. + + In some cases, the returned TAOS_RES is NULL, in which case taos_errno can still be called to safely get the error code information. + + The returned TAOS_RES needs to be freed by the caller, otherwise a memory leak will occur. + + **Description** + + The protocol type is enumerated and contains the following three formats. + + TSDB_SML_LINE_PROTOCOL: InfluxDB line protocol (Line Protocol) + + TSDB_SML_TELNET_PROTOCOL: OpenTSDB Text Line Protocol + + TSDB_SML_JSON_PROTOCOL: OpenTSDB JSON protocol format + + The timestamp resolution is defined in the taos.h file, as follows + + TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0, + + TSDB_SML_TIMESTAMP_HOURS, -The return value is NULL, indicating creation failed; the return value is not NULL, indicating creation successful. + TSDB_SML_TIMESTAMP_MINUTES, -- `void taos_close_stream (TAOS_STREAM *tstr)` + TSDB_SML_TIMESTAMP_SECONDS, -Close the data flow, where the parameter provided is the return value of `taos_open_stream()`. When the user stops stream computing, be sure to close the data flow. + TSDB_SML_TIMESTAMP_MILLI_SECONDS, + + TSDB_SML_TIMESTAMP_MICRO_SECONDS, + + TSDB_SML_TIMESTAMP_NANO_SECONDS + + Note that the timestamp resolution parameter only takes effect when the protocol type is SML_LINE_PROTOCOL. + + For OpenTSDB text protocols, the timestamp resolution follows the official resolution rules - the time precision is determined by the number of characters contained in the timestamp. + + **Supported versions** + + This functional interface is supported since version 2.3.0.0. + +```c +#include +#include +#include + +int main() { + const char* host = "127.0.0.1"; + const char* user = "root"; + const char* passwd = "taosdata"; + + // connect to server + TAOS* taos = taos_connect(host, user, passwd, "test", 0); + + // prepare the line string + char* lines1[] = { + "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", + "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000" + }; + + // schema-less insert + TAOS_RES* res = taos_schemaless_insert(taos, lines1, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); + if (taos_errno(res) != 0) { + printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res)); + } + + taos_free_result(res); + + // close the connection + taos_close(taos); + return (code); +} +``` ### Data subscription interface @@ -468,13 +549,15 @@ for row in results: - Write data ```python + import taos import datetime - + conn = taos.connect() + c1 = conn.cursor() # Create a database - c1.execute('create database db') - c1.execute('use db') + c1.execute('create database if not exists db1') + c1.execute('use db1') # Create a table - c1.execute('create table tb (ts timestamp, temperature int, humidity float)') + c1.execute('create table if not exists tb (ts timestamp, temperature int, humidity float)') # Insert data start_time = datetime.datetime(2019, 11, 1) affected_rows = c1.execute('insert into tb values (\'%s\', 0, 0.0)' %start_time) @@ -482,9 +565,11 @@ for row in results: time_interval = datetime.timedelta(seconds=60) sqlcmd = ['insert into tb values'] for irow in range(1,11): - start_time += time_interval - sqlcmd.append('(\'%s\', %d, %f)' %(start_time, irow, irow*1.2)) - affected_rows = c1.execute(' '.join(sqlcmd)) + start_time += time_interval + sqlcmd.append('(\'%s\', %d, %f)' %(start_time, irow, irow*1.2)) + affected_rows += c1.execute(' '.join(sqlcmd)) + + print("inserted %s records" % affected_rows) ``` - Query data @@ -497,12 +582,12 @@ for row in results: numOfRows = c1.rowcount numOfCols = len(c1.description) for irow in range(numOfRows): - print("Row%d: ts=%s, temperature=%d, humidity=%f" %(irow, data[irow][0], data[irow][1],data[irow][2])) + print("Row%d: ts=%s, temperature=%d, humidity=%f" %(irow, data[irow][0], data[irow][1],data[irow][2])) # Use cursor loop directly to pull query result c1.execute('select * from tb') for data in c1: - print("ts=%s, temperature=%d, humidity=%f" %(data[0], data[1],data[2])) + print("ts=%s, temperature=%d, humidity=%f" %(data[0], data[1],data[2])) ``` #### Query API diff --git a/documentation20/en/10.cluster/docs.md b/documentation20/en/10.cluster/docs.md index 7f39f23502ae7826042cd77aa3ad238de8b6e274..eb12df4526878e99b22c2e6159a360fff9184dd0 100644 --- a/documentation20/en/10.cluster/docs.md +++ b/documentation20/en/10.cluster/docs.md @@ -25,7 +25,7 @@ Please refer to the [video tutorial](https://www.taosdata.com/blog/2020/11/11/19 **Step 4:** Check the network settings of all data nodes and the physical nodes where the application is located: 1. Execute command `hostname -f` on each physical node, and check and confirm that the hostnames of all nodes are different (the node where the application driver is located does not need to do this check). -2. Execute `ping host` on each physical node, wherein host is that hostname of other physical node, and see if other physical nodes can be communicated to; if not, you need to check the network settings, or the /etc/hosts file (the default path for Windows systems is C:\ Windows\ system32\ drivers\ etc\ hosts), or the configuration of DNS. If it fails to ping, then we cann't build the cluster. +2. Execute `ping host` on each physical node, wherein host is that hostname of other physical node, and see if other physical nodes can be communicated to; if not, you need to check the network settings, or the /etc/hosts file (the default path for Windows systems is C:\ Windows\ system32\ drivers\ etc\ hosts), or the configuration of DNS. If it fails to ping, then we cannot build the cluster. 3. From the physical node where the application runs, ping the data node where taosd runs. If the ping fails, the application cannot connect to taosd. Please check the DNS settings or hosts file of the physical node where the application is located; 4. The End Point of each data node is the output hostname plus the port number, for example, `h1.taosdata.com:6030` @@ -35,7 +35,7 @@ Please refer to the [video tutorial](https://www.taosdata.com/blog/2020/11/11/19 // firstEp is the first data node connected after each data node’s first launch firstEp h1.taosdata.com:6030 // Must configure it as the FQDN of this data node. If this machine has only one hostname, you can comment out this configuration -fqdn h1.taosdata.com +fqdn h1.taosdata.com // Configure the port number of this data node, the default is 6030 serverPort 6030 // For application scenarios, please refer to the section “Use of Arbitrator” @@ -90,7 +90,7 @@ To add subsequent data nodes to the existing cluster, there are the following st 2. On the first data node, use CLI program taos to log in to TDengine system and execute the command: ``` - CREATE DNODE "h2.taos.com:6030"; + CREATE DNODE "h2.taos.com:6030"; ``` Add the End Point of the new data node (learned in Step 4 of the preparation) to the cluster's EP list. **"fqdn: port" needs to be enclosed in double quotation marks**, otherwise an error will occur. Notice that the example "[h2.taos.com](http://h2.taos.com/): 6030" is replaced with the End Point for this new data node. @@ -123,7 +123,7 @@ The above has already introduced how to build clusters from scratch. After the c Execute CLI program taos, log in to the system using root account, and execute: ``` -CREATE DNODE "fqdn:port"; +CREATE DNODE "fqdn:port"; ``` Add the End Point for the new data node to the cluster's EP list. **"fqdn: port" needs to be enclosed in double quotation marks**, otherwise an error will occur. The fqdn and port of a data node's external service can be configured through the configuration file taos.cfg, which is automatically obtained by default. [It is strongly not recommended to configure FQDN with automatic acquisition, which may cause the End Point of the generated data node to be not expected] @@ -175,7 +175,7 @@ The number of replicas of vnode is associated with DB. There can be multiple DBs CREATE DATABASE demo replica 3; ``` -The data in a DB will be partitioned and splitted into multiple vnode groups. The number of vnodes in a vnode group is the number of replicas of the DB, and the data of each vnode in the same vnode group is completely consistent. In order to ensure high-availability, the vnodes in a vnode group must be distributed in different dnode data nodes (in actual deployment, they need to be on different physical machines). As long as more than half of the vnodes in a vgroup are working, the vgroup can be normally serving. +The data in a DB will be partitioned and split into multiple vnode groups. The number of vnodes in a vnode group is the number of replicas of the DB, and the data of each vnode in the same vnode group is completely consistent. In order to ensure high-availability, the vnodes in a vnode group must be distributed in different dnode data nodes (in actual deployment, they need to be on different physical machines). As long as more than half of the vnodes in a vgroup are working, the vgroup can be normally serving. There may be data from multiple DBs of data in a data node dnode, so when a dnode is offline, it may affect multiple DBs. If half or more of the vnodes in a vnode group do not work, then the vnode group cannot serve externally and cannot insert or read data, which will affect the reading and writing operations of some tables in the DB to which it belongs. diff --git a/documentation20/en/11.administrator/docs.md b/documentation20/en/11.administrator/docs.md index 59955c76a175b44cac3f3164ed6514effd35dc65..9a6decb6337b0e751dd5bf2123b79ae85e799d71 100644 --- a/documentation20/en/11.administrator/docs.md +++ b/documentation20/en/11.administrator/docs.md @@ -59,14 +59,14 @@ When TDengine receives the application's request packet, it first writes the req There are two system configuration parameters involved: -- walLevel: WAL level, 0: do not write wal; 1: write wal, but do not execute fsync; 2: write wal and execute fsync. +- walLevel: WAL level, 0: do not write WAL; 1: write WAL, but do not execute fsync; 2: write WAL and execute fsync. - fsync: the cycle in which fsync is executed when walLevel is set to 2. Setting to 0 means that fsync is executed immediately whenever there is a write. To guarantee 100% data safe, you need to set walLevel to 2 and fsync to 0. In that way, the write speed will decrease. However, if the number of threads starting to write data on the application side reaches a certain number (more than 50), the performance of writing data will also be good, only about 30% lower than that of fsync set to 3000 milliseconds. ### Disaster recovery -The cluster of TDengine provides high-availability of the system and implements disaster recovery through the multipl-replica mechanism. +The cluster of TDengine provides high-availability of the system and implements disaster recovery through the multiple-replica mechanism. TDengine cluster is managed by mnode. In order to ensure the high reliability of the mnode, multiple mnode replicas can be configured. The number of replicas is determined by system configuration parameter numOfMnodes. In order to support high reliability, it needs to be set to be greater than 1. In order to ensure the strong consistency of metadata, mnode replicas duplicate data synchronously to ensure the strong consistency of metadata. @@ -114,8 +114,8 @@ Data in different application scenarios often have different data characteristic - minRows: the minimum number of records in a file block, in pieces, default: 100. - maxRows: the maximum number of records in a file block, in pieces, default: 4096. - comp: file compression flag bit, 0: off; 1: one-stage compression; 2: two-stage compression. Default: 2. -- walLevel: WAL level. 1: write wal, but do not execute fsync; 2: write wal and execute fsync. Default: 1. -- fsync: the period during which fsync is executed when wal is set to 2. Setting to 0 means that fsync is executed immediately whenever a write happens, in milliseconds, and the default value is 3000. +- walLevel: WAL level. 1: write WAL, but do not execute fsync; 2: write WAL and execute fsync. Default: 1. +- fsync: the period during which fsync is executed when WAL is set to 2. Setting to 0 means that fsync is executed immediately whenever a write happens, in milliseconds, and the default value is 3000. - cache: the size of the memory block in megabytes (MB), default: 16. - blocks: how many cache-sized memory blocks are in each VNODE (TSDB). Therefore, the memory size used by a VNODE is roughly (cache * blocks), in blocks, and the default value is 4. - replica: number of replicas; value range: 1-3, in items, default value: 1 @@ -377,7 +377,7 @@ The system administrator can query the connection, ongoing query and stream comp SHOW CONNECTIONS; ``` -Show the connection of the database, and one column shows ip: port, which is the IP address and port number of the connection. +Show the connection of the database, and one column shows IP: port, which is the IP address and port number of the connection. ```mysql KILL CONNECTION ; @@ -442,7 +442,7 @@ Some CLI options are needed to use the script: sudo ./TDinsight.sh -a http://localhost:6041 -u root -p taosdata -E ``` - 2. Use TDengine data source plugin's builtin [Aliyun SMS](https://www.aliyun.com/product/sms) alerting support with `-s` flag, and input these options: + 2. Use TDengine data source plugin's built-in [Aliyun SMS](https://www.aliyun.com/product/sms) alerting support with `-s` flag, and input these options: 1. Access key id with option `-I` 2. Access key secret with option `K` 3. Access key sign name with option `-S` @@ -468,7 +468,7 @@ After installing TDengine, the following directories or files are generated in t | **Directory/File** | **Description** | | ------------------------- | ------------------------------------------------------------ | -| /usr/local/taos/bin | TEngine’s executable directory. The executables are connected to the/usr/bin directory via softly links. | +| /usr/local/taos/bin | TDengine’s executable directory. The executables are connected to the/usr/bin directory via softly links. | | /usr/local/taos/connector | TDengine’s various connector directories. | | /usr/local/taos/driver | TDengine’s dynamic link library directory. Connect to /usr/lib directory via soft links. | | /usr/local/taos/examples | TDengine’s application example directory for various languages. | diff --git a/documentation20/en/12.taos-sql/docs.md b/documentation20/en/12.taos-sql/docs.md index cbd2d77a507e0d55f1d870423d517cd1b79aac10..137dfe9123fe817307bd2414e4d81dd305aba2d8 100755 --- a/documentation20/en/12.taos-sql/docs.md +++ b/documentation20/en/12.taos-sql/docs.md @@ -602,6 +602,8 @@ Query OK, 1 row(s) in set (0.000081s) > `TBNAME`: It can be regarded as a special tag in a STable query, representing the name of sub-table involved in the query > > _c0: Represents the first column of a table (STable) +> _qstart,_qstop,_qduration: Represents starting time/stopping time/duration of query time window filter in where condition (supported since 2.6.0.0) +> _wstart,_wstop,_wduration: Used in time-dimension aggregation query(e.g. interval/session window/state window)to represent starting time/stopping time/duration of each generated time window (supported since 2.6.0.0) #### Tips @@ -852,6 +854,73 @@ TDengine supports aggregations over data, they are listed below: Query OK, 1 row(s) in set (0.000921s) ``` +- **MODE** + ```mysql + SELECT MODE(field_name) FROM tb_name [WHERE clause]; + ``` + Function: Returns the value with the highest frequency. If there are multiple highest values with the same frequency, the output is NULL. + + Return Data Type: Same as applicable fields. + + Applicable Fields: All types except timestamp. + + Supported version: Version after 2.6.0 . + + Note: Since the amount of returned data is unknown, considering the memory factor, in order to return the result normally, it is recommended that the amount of non repeated data is 100000, otherwise an error will be reported. + + Example: + ```mysql + taos> select voltage from d002; + voltage | + ======================== + 1 | + 1 | + 2 | + 19 | + Query OK, 4 row(s) in set (0.003545s) + + taos> select mode(voltage) from d002; + mode(voltage) | + ======================== + 1 | + Query OK, 1 row(s) in set (0.019393s) + ``` + +- **HYPERLOGLOG** + ```mysql + SELECT HYPERLOGLOG(field_name) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: + - The hyperloglog algorithm is used to return the cardinality of a column. In the case of large amount of data, the algorithm can significantly reduce the occupation of memory, but the cardinality is an estimated value, and the standard error(the standard error is the standard deviation of the average of multiple experiments, not the error with the real result) is 0.81%. + - When the amount of data is small, the algorithm is not very accurate. You can use the method like this: select count(data) from (select unique(col) as data from table). + + Return Data Type:Integer. + + Applicable Fields: All types. + + Supported version: Version after 2.6.0 . + + Example: + ```mysql + taos> select dbig from shll; + dbig | + ======================== + 1 | + 1 | + 1 | + NULL | + 2 | + 19 | + NULL | + 9 | + Query OK, 8 row(s) in set (0.003755s) + + taos> select hyperloglog(dbig) from shll; + hyperloglog(dbig)| + ======================== + 4 | + Query OK, 1 row(s) in set (0.008388s) + ### Selector Functions - **MIN** @@ -1102,6 +1171,85 @@ TDengine supports aggregations over data, they are listed below: Query OK, 1 row(s) in set (0.001042s) ``` +- **TAIL** + ```mysql + SELECT TAIL(field_name, k, offset_val) FROM {tb_name | stb_name} [WHERE clause]; + ``` + Function: Skip the last num of offset_value, return the k consecutive records without ignoring NULL value. offset_val can be empty, then the last K records are returned.The function is equivalent to:order by ts desc LIMIT k OFFSET offset_val. + + Range:k: [1,100] offset_val: [0,100]。 + + Return Data Type: Same as applicable fields. + + Applicable Fields: All types except timestamp. + + Applied to: **table stable**. + + Supported version: Version after 2.6.0 . + + Example: + ```mysql + taos> select ts,dbig from tail2; + ts | dbig | + ================================================== + 2021-10-15 00:31:33.000 | 1 | + 2021-10-17 00:31:31.000 | NULL | + 2021-12-24 00:31:34.000 | 2 | + 2022-01-01 08:00:05.000 | 19 | + 2022-01-01 08:00:06.000 | NULL | + 2022-01-01 08:00:07.000 | 9 | + Query OK, 6 row(s) in set (0.001952s) + + taos> select tail(dbig,2,2) from tail2; + ts | tail(dbig,2,2) | + ================================================== + 2021-12-24 00:31:34.000 | 2 | + 2022-01-01 08:00:05.000 | 19 | + Query OK, 2 row(s) in set (0.002307s) + +- **UNIQUE** + ```mysql + SELECT UNIQUE(field_name) FROM {tb_name | stb_name} [WHERE clause]; + ``` + Function: Returns the first occurrence of a value in this column. + + Return Data Type: Same as applicable fields. + + Applicable Fields: All types except timestamp. + + Applied to: **table stable**. + + Supported version: Version after 2.6.0 . + + Note: + - This function can be applied to ordinary tables and super tables. Cannot be used with window operations,such as interval/state_window/session_window. + - Since the amount of returned data is unknown, considering the memory factor, in order to return the result normally, it is recommended that the amount of non repeated data is 100000, otherwise an error will be reported. + + Example: + ```mysql + taos> select ts,voltage from unique1; + ts | voltage | + ================================================== + 2021-10-17 00:31:31.000 | 1 | + 2022-01-24 00:31:31.000 | 1 | + 2021-10-17 00:31:31.000 | 1 | + 2021-12-24 00:31:31.000 | 2 | + 2022-01-01 08:00:01.000 | 19 | + 2021-10-17 00:31:31.000 | NULL | + 2022-01-01 08:00:02.000 | NULL | + 2022-01-01 08:00:03.000 | 9 | + Query OK, 8 row(s) in set (0.003018s) + + taos> select unique(voltage) from unique1; + ts | unique(voltage) | + ================================================== + 2021-10-17 00:31:31.000 | 1 | + 2021-10-17 00:31:31.000 | NULL | + 2021-12-24 00:31:31.000 | 2 | + 2022-01-01 08:00:01.000 | 19 | + 2022-01-01 08:00:03.000 | 9 | + Query OK, 5 row(s) in set (0.108458s) + ### Computing Functions - **DIFF** @@ -1156,6 +1304,468 @@ TDengine supports aggregations over data, they are listed below: Query OK, 1 row(s) in set (0.000836s) ``` +- **CSUM** + ```sql + SELECT CSUM(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + + Function: Cumulative sum computes the running total of one time series. It occurs in select clause of SQL statement. + + Input: Input column data type should be a numeric type. + + Output: If the input data type is unsigned int type, the result data type is uint64_t. If the input data type is signed int type, the result data type is int64_t. If the input data type is float or double, the result data type is double. The function also outputs the timestamp of the current row. + + Table: The csum function only applies to the normal table, child table, and super table with group by tbname. + + Nested Query: The csum function applies to both outer query and nested query. + + Note: Can't be used with +-*/ arithmatic operations,like csum(col1) + csum(col2), can only be used with aggragation functions. + +- **MAVG** + ```sql + SELECT MAVG(field_name, K) FROM { tb_name | stb_name } [WHERE clause] + ``` + + Function: Moving Average Function Computes the rolling simple average over k values of one time series. It occurs in select clause of SQL statement. If the input time series has less than k values, no result is calculated. + + Input: Input column data should be a numeric type. + + Output: The Result data type is double. The function also outputs the timestamp of the current row. + + Parameter: K is an integer between 1 and 1000. + + Table: The mavg function only applies to the normal table, child table, and super table with group by tbname. + + Nested Query: The mavg function applies to both outer query and nested query. + + Note: Can't be used with +-*/ arithmatic operations, like mavg(col1, k1) + mavg(col2, k1); can only be used with normal columns, selection and projection functions,can't be used with aggragation functions. + +- **SAMPLE** + ``` + SELECT SAMPLE(field_name, K) FROM { tb_name | stb_name } [WHERE clause] + ``` + + Function: Sample function samples k values from a specific time series with equal probability. It occurs in select clause of SQL statement + + Input: There are no restrictions on the input data type. + + Output: The output data type is the same as the input data type. The function also outputs the timestamp of the current row. + + Parameter: K is an integer between 1 and 1000. + + Table: he sample function only applies to the normal table, child table, and super table with group by tbname. + + Nested Query: The sample function applies to both outer query and nested query. + + Note: Can't be used as operand in an expression + + +- **ASIN** + ```mysql + SELECT ASIN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the arc-sine of the input value. + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + + +- **ACOS** + ```mysql + SELECT ACOS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the arc-cosine of the input value. + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + + +- **ATAN** + ```mysql + SELECT ATAN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the arc-tangent of the input value. + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + + +- **SIN** + ```mysql + SELECT SIN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the sine of the input value. + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + + +- **COS** + ```mysql + SELECT COS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the cosine of the input value. + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + +- **TAN** + ```mysql + SELECT TAN(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the tangent of the input value. + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + + + +- **POW** + ```mysql + SELECT POW(field_name, power) FROM { tb_name | stb_name } [WHERE clause] + ``` + + Function: Returns the input value raised to the specified power of the second argument + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + +- **LOG** + ```mysql + SELECT LOG(field_name, base) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the logarithm of the input value with base + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + +- **ABS** + ```mysql + SELECT ABS(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the absolute value of the input value + + Output Data Type: If the input data is an integer numeric value, the output data type is ubigint. If the input data is a float or double value, the output data type is double + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + + +- **SQRT** + ```mysql + SELECT SQRT(field_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the square root value of the input value + + Output Data Type: DOUBLE. + + Input: applies to value of all types except timestamp, binary, nchar, and bool. Can not apply to tag column of super table. + + Embedded Query Support: Both Outer Query and Inner Query + + Notes: + + If input value is NULL, the output value is NULL. + + It is a scalar function and can not be used together with aggregate function + + Applies to columns of normal table, child table and super table + + Supported after version 2.6.0.x + +- **CAST** + ```mysql + SELECT CAST(expression AS type_name) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Converts a value into as a specific data type of type_name. + + Output Data Type: type_name specified. Supported types include BIGINT, BINARY(N), TIMESTAMP and NCHAR(N) and BIGINT UNSIGNED + + Input: Normal column, constant, scalar function and the arithmetic computation(+,-,*,/,%) among them. Input data type includes BOOL, TINYINT, SMALLINT, INT, BIGINT, FLOAT, DOUBLE, BINARY(M), TIMESTAMP, NCHAR(M), TINYINT UNSIGNED, SMALLINT UNSIGNED, INT UNSIGNED, and BIGINT UNSIGNED + + Notes: + + Reports error for unsupported cast + + It is a scalar function and its output is NULL for input NULL + + Supported after version 2.6.0.x + + +- **CONCAT** + ```mysql + SELECT CONCAT(str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the string from concatenating the arguments + + Output Data Type: With binary inputs, the output data type is binary. With nchar inputs, the output data type is nchar. + + Input: all inputs shall be of data type binary or nchar. Can not apply to tag columns. + + Notes: + + If one of the string inputs is NULL, the resulting output is NULL. + The function takes 2 to 8 string values as input. all inputs must be of the same data type. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **CONCAT_WS** + ``` + SELECT CONCAT_WS(separator, str1|column1, str2|column2, ...) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the string from concatenating the arguments with separator. + + Output Data Type: With binary inputs, the output data type is binary. With nchar inputs, the output data type is nchar. + + Input: all inputs shall be of data type binary or nchar. Can not apply to tag columns. + + Notes: + + Returns NULL when the separator is NULL. If the separator is not NULL and all the other string values are NULL, the result is an empty string. + The function takes 3 to 9 string values as input. all inputs must be of the same data type. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + + +- **LENGTH** + ``` + SELECT LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the length of the string measure in bytes + + Output Data Type: INT。 + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **CHAR_LENGTH** + ``` + SELECT CHAR_LENGTH(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the length of the string measure in characters + + Output Data Type: INT。 + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **LOWER** + ``` + SELECT LOWER(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the lower case of input value + + Output Data Type: BINARY or NCHAR. Same data type as Input. + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **UPPER** + ``` + SELECT UPPER(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: Returns the upper case of input value + + Output Data Type: BINARY or NCHAR. Same data type as Input. + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **LTRIM** + ``` + SELECT LTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: removes leading spaces from a string + + Output Data Type: BINARY or NCHAR. Same data type as Input. + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **RTRIM** + ``` + SELECT RTRIM(str|column) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: removes trailing spaces from a string + + Output Data Type: BINARY or NCHAR. Same data type as Input. + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + +- **SUBSTR** + ``` + SELECT SUBSTR(str,pos[,len]) FROM { tb_name | stb_name } [WHERE clause] + ``` + Function: extracts substring from a string str, starting from pos and extracting len characters. + + Output Data Type: BINARY or NCHAR. Same data type as Input. + + Input: BINARY or NCHAR values. Can not apply to tag columns + + Notes: + + Returns NULL when input is NULL. + Input pos can be negative or positive. If it is a positive number, the beginning of the substring is pos characters from the beginning of the string. If it is a negative number, the beginning of the substring is pos characters from the end of the string + If input len is omitted, the output is whole substring starting from pos. + This function applies to normal table, child table and super table + This function applies to bother out query and inner query + Supported after version 2.6.0.x + + - **Four Operations** ```mysql @@ -1172,6 +1782,411 @@ TDengine supports aggregations over data, they are listed below: 1. Calculation between two or more columns is supported, and the calculation priorities can be controlled by parentheses(); 2. The NULL field does not participate in the calculation. If a row involved in calculation contains NULL, the calculation result of the row is NULL. +- **STATECOUNT** + ```mysql + SELECT STATECOUNT(field_name, oper, val) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Returns the number of consecutive records that meet a certain condition, and the result is appended to each row as a new column. The condition is calculated according to the parameters. If the condition is true, it will be increased by 1. If the condition is false, it will be reset to -1. If the data is NULL, the data will be skipped. + + Range: + - oper : LT(<),GT(>),LE(<=),GE(>=),NE(!=),EQ(=),case insensitive. + - val : Number. + + Returned Data Type: Integer。 + + Applicable Fields: All types except timestamp, binary, nchar, bool. + + Supported version: Version after 2.6.0 . + + Note: + - This function can be applied to ordinary tables. When a separate timeline is divided by group by, it is used for super tables (i.e. group by TBNAME). + - Cannot be used with window operations,such as interval/state_window/session_window. + + Example: + ```mysql + taos> select ts,dbig from statef2; + ts | dbig | + ======================================================== + 2021-10-15 00:31:33.000000000 | 1 | + 2021-10-17 00:31:31.000000000 | NULL | + 2021-12-24 00:31:34.000000000 | 2 | + 2022-01-01 08:00:05.000000000 | 19 | + 2022-01-01 08:00:06.000000000 | NULL | + 2022-01-01 08:00:07.000000000 | 9 | + Query OK, 6 row(s) in set (0.002977s) + + taos> select stateCount(dbig,GT,2) from statef2; + ts | dbig | statecount(dbig,gt,2) | + ================================================================================ + 2021-10-15 00:31:33.000000000 | 1 | -1 | + 2021-10-17 00:31:31.000000000 | NULL | NULL | + 2021-12-24 00:31:34.000000000 | 2 | -1 | + 2022-01-01 08:00:05.000000000 | 19 | 1 | + 2022-01-01 08:00:06.000000000 | NULL | NULL | + 2022-01-01 08:00:07.000000000 | 9 | 2 | + Query OK, 6 row(s) in set (0.002791s) + ``` + +- **STATEDURATION** + ```mysql + SELECT stateDuration(field_name, oper, val, unit) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Returns the length of time of continuous records that meet a certain condition, and the result is appended to each row as a new column. The condition is calculated according to the parameters. If the condition is true, the length of time between two records will be added (the length of time of the first record that meets the condition is recorded as 0). If the condition is false, it will be reset to -1. If the data is NULL, the data will be skipped. + + Range: + - oper : LT(<),GT(>),LE(<=),GE(>=),NE(!=),EQ(=),case insensitive. + - val : Number. + - unit : Unit of time length, range [1s, 1M, 1H], less than one unit is rounded off. The default is 1s. + + Returned Data Type: Integer。 + + Applicable Fields: All types except timestamp, binary, nchar, bool. + + Supported version: Version after 2.6.0 . + + Note: + - This function can be applied to ordinary tables. When a separate timeline is divided by group by, it is used for super tables (i.e. group by TBNAME). + - Cannot be used with window operations,such as interval/state_window/session_window. + + Example: + ```mysql + taos> select ts,dbig from statef2; + ts | dbig | + ======================================================== + 2021-10-15 00:31:33.000000000 | 1 | + 2021-10-17 00:31:31.000000000 | NULL | + 2021-12-24 00:31:34.000000000 | 2 | + 2022-01-01 08:00:05.000000000 | 19 | + 2022-01-01 08:00:06.000000000 | NULL | + 2022-01-01 08:00:07.000000000 | 9 | + Query OK, 6 row(s) in set (0.002407s) + + taos> select stateDuration(dbig,GT,2) from statef2; + ts | dbig | stateduration(dbig,gt,2) | + =================================================================================== + 2021-10-15 00:31:33.000000000 | 1 | -1 | + 2021-10-17 00:31:31.000000000 | NULL | NULL | + 2021-12-24 00:31:34.000000000 | 2 | -1 | + 2022-01-01 08:00:05.000000000 | 19 | 0 | + 2022-01-01 08:00:06.000000000 | NULL | NULL | + 2022-01-01 08:00:07.000000000 | 9 | 2 | + Query OK, 6 row(s) in set (0.002613s) + ``` +- **HISTOGRAM** + ```mysql + SELECT HISTOGRAM(field_name,bin_type, bin_description, normalized) FROM tb_name [WHERE clause]; + ``` + Function: Returns count of data points in user-specified ranges. + + Return Data Type: Double or INT64, depends on normalized parameter settings. + + Applicable Fields: Numerical types. + + Applied to: **table stable**. + + Note: + 1. This function is supported since 2.6.0.0. + 2. bin_type: parameter to indicate the bucket type, valid inputs are: "user_input", "linear_bin", "log_bin"。 + 3)bin_description: parameter to describe how to generate buckets,can be in the following JSON formats for each bin_type respectively: + - "user_input": "[1, 3, 5, 7]" + User defined specified bin values. + + - "linear_bin": "{"start": 0.0, "width": 5.0, "count": 5, "infinity": true}" + "start" - bin starting point. + "width" - bin offset. + "count" - number of bins generated. + "infinity" - whether to add(-inf, inf)as start/end point in generated set of bins. + The above "linear_bin" descriptor generates a set of bins: [-inf, 0.0, 5.0, 10.0, 15.0, 20.0, +inf]. + + - "log_bin": "{"start":1.0, "factor": 2.0, "count": 5, "infinity": true}" + "start" - bin starting point. + "factor" - exponential factor of bin offset. + "count" - number of bins generated. + "infinity" - whether to add(-inf, inf)as start/end point in generated range of bins. + The above "log_bin" descriptor generates a set of bins:[-inf, 1.0, 2.0, 4.0, 8.0, 16.0, +inf]. + 4)normalized: setting to 1/0 to turn on/off result normalization. + + Example: + ```mysql + taos> SELECT HISTOGRAM(voltage, "user_input", "[1,3,5,7]", 1) FROM meters; + histogram(voltage, "user_input", "[1,3,5,7]", 1) | + ======================================================= + {"lower_bin":1, "upper_bin":3, "count":0.333333} | + {"lower_bin":3, "upper_bin":5, "count":0.333333} | + {"lower_bin":5, "upper_bin":7, "count":0.333333} | + Query OK, 3 row(s) in set (0.004273s) + + taos> SELECT HISTOGRAM(voltage, 'linear_bin', '{"start": 1, "width": 3, "count": 3, "infinity": false}', 0) FROM meters; + histogram(voltage, 'linear_bin', '{"start": 1, "width": 3, " | + =================================================================== + {"lower_bin":1, "upper_bin":4, "count":3} | + {"lower_bin":4, "upper_bin":7, "count":3} | + {"lower_bin":7, "upper_bin":10, "count":3} | + Query OK, 3 row(s) in set (0.004887s) + + taos> SELECT HISTOGRAM(voltage, 'log_bin', '{"start": 1, "factor": 3, "count": 3, "infinity": true}', 0) FROM meters; + histogram(voltage, 'log_bin', '{"start": 1, "factor": 3, "count" | + =================================================================== + {"lower_bin":-inf, "upper_bin":1, "count":3} | + {"lower_bin":1, "upper_bin":3, "count":2} | + {"lower_bin":3, "upper_bin":9, "count":6} | + {"lower_bin":9, "upper_bin":27, "count":3} | + {"lower_bin":27, "upper_bin":inf, "count":1} | + ``` +### Time Functions + +Starting from version 2.6.0.0, TDengine supports following time related functions: + +- **NOW** + ```mysql + SELECT NOW() FROM { tb_name | stb_name } [WHERE clause]; + SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operator NOW(); + INSERT INTO tb_name VALUES (NOW(), ...); + ``` + Function: Returns current time of client. + + Returned Data Type: TIMESTAMP type. + + Applicable Fields: Can only be applied to TIMESTAMP field when used in WHERE or INSERT clause. + + Applied to: **table stable**. + + Note: + 1)Support arithmetic operations,e.g. NOW() + 1s. Valid time unit: + b(nanosecond)、u(microsecond)、a(millisecond)、s(second)、m(minute)、h(hour)、d(day)、w(week). + 2)Returned timestamp precision is consist with current DATABASE precision settings. + + Example: + ```mysql + taos> SELECT NOW() FROM meters; + now() | + ========================== + 2022-02-02 02:02:02.456 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT NOW() + 1h FROM meters; + now() + 1h | + ========================== + 2022-02-02 03:02:02.456 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT COUNT(voltage) FROM d1001 WHERE ts < NOW(); + count(voltage) | + ============================= + 5 | + Query OK, 5 row(s) in set (0.004475s) + + taos> INSERT INTO d1001 VALUES (NOW(), 10.2, 219, 0.32); + Query OK, 1 of 1 row(s) in database (0.002210s) + ``` + +- **TODAY** + ```mysql + SELECT TODAY() FROM { tb_name | stb_name } [WHERE clause]; + SELECT select_expr FROM { tb_name | stb_name } WHERE ts_col cond_operator TODAY()]; + INSERT INTO tb_name VALUES (TODAY(), ...); + ``` + Function: Returns current date of client. + + Returned Data Type: TIMESTAMP type。 + + Applicable Fields: Can only be applied to TIMESTAMP field when used in WHERE or INSERT clause. + + Applied to: **table stable**. + + Note: + 1)Support arithmetic operations, e.g. TODAY() + 1s. Valid time unit: + b(nanosecond)、u(microsecond)、a(millisecond)、s(second)、m(minute)、h(hour)、d(day)、w(week). + 2)Returned timestamp precision is consist with current DATABASE precision settings. + + Example: + ```mysql + taos> SELECT TODAY() FROM meters; + today() | + ========================== + 2022-02-02 00:00:00.000 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT TODAY() + 1h FROM meters; + today() + 1h | + ========================== + 2022-02-02 01:00:00.000 | + Query OK, 1 row(s) in set (0.002093s) + + taos> SELECT COUNT(voltage) FROM d1001 WHERE ts < TODAY(); + count(voltage) | + ============================= + 5 | + Query OK, 5 row(s) in set (0.004475s) + + taos> INSERT INTO d1001 VALUES (TODAY(), 10.2, 219, 0.32); + Query OK, 1 of 1 row(s) in database (0.002210s) + ``` + +- **TIMEZONE** + ```mysql + SELECT TIMEZONE() FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Returns current time zone information of client. + + Returned Data Type: BINARY type. + + Applicable Fields: N/A. + + Applied to: **table stable**. + + Example: + ```mysql + taos> SELECT TIMEZONE() FROM meters; + timezone() | + ================================= + UTC (UTC, +0000) | + Query OK, 1 row(s) in set (0.002093s) + ``` + +- **TO_ISO8601** + ```mysql + SELECT TO_ISO8601(ts_val | ts_col) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Convert UNIX timestamp to ISO8601 standard date-time format string, with client time zone information attached. + + Returned Data Type: BINARY type. + + Applicable Fields: UNIX timestamp constant and TIMESTAMP type columns. + + Applied to: **table stable**. + + Note: If input is UNIX timestamp constant,returned ISO8601 format precision is determined by input timestamp digits. If input is TIMESTAMP type column, returned ISO8601 format precision is consist with current DATABASE precision settings. + + Example: + ```mysql + taos> SELECT TO_ISO8601(1643738400) FROM meters; + to_iso8601(1643738400) | + ============================== + 2022-02-02T02:00:00+0800 | + + taos> SELECT TO_ISO8601(ts) FROM meters; + to_iso8601(ts) | + ============================== + 2022-02-02T02:00:00+0800 | + 2022-02-02T02:00:00+0800 | + 2022-02-02T02:00:00+0800 | + ``` + + - **TO_UNIXTIMESTAMP** + ```mysql + SELECT TO_UNIXTIMESTAMP(datetime_string | ts_col) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Convert date-time format string to UNIX timestamp. + + Returned Data Type: INT64. + + Applicable Fields: String literal or BINARY/NCHAR type columns. + + Applied to: **table stable**. + + Note: + 1)Input date-time string format should conform ISO8601/RFC3339 standard,otherwise conversion will fail and 0 is returned. + 2)Returned timestamp precision is consist with current DATABASE precision settings. + + Example: + ```mysql + taos> SELECT TO_UNIXTIMESTAMP("2022-02-02T02:00:00.000Z") FROM meters; + to_unixtimestamp("2022-02-02T02:00:00.000Z") | + ============================================== + 1643767200000 | + + taos> SELECT TO_UNIXTIMESTAMP(col_binary) FROM meters; + to_unixtimestamp(col_binary) | + ======================================== + 1643767200000 | + 1643767200000 | + 1643767200000 | + ``` + + - **TIMETRUNCATE** + ```mysql + SELECT TIMETRUNCATE(ts_val | datetime_string | ts_col, time_unit) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Truncate timestamp by time_unit. + + Returned Data Type: TIMESTAMP type. + + Applicable Fields: UNIX timestamp, date-time format string, and TIMESTAMP type columns. + + Applied to: **table stable**. + + Note: + 1)Supported time_unit: + 1u(microsecond),1a(millisecond),1s(second),1m(minute),1h(hour),1d(day)。 + 2)Returned timestamp precision is consist with current DATABASE precision settings. + + Example: + ```mysql + taos> SELECT TIMETRUNCATE(1643738522000, 1h) FROM meters; + timetruncate(1643738522000, 1h) | + =================================== + 2022-02-02 02:00:00.000 | + Query OK, 1 row(s) in set (0.001499s) + + taos> SELECT TIMETRUNCATE("2022-02-02 02:02:02", 1h) FROM meters; + timetruncate("2022-02-02 02:02:02", 1h) | + =========================================== + 2022-02-02 02:00:00.000 | + Query OK, 1 row(s) in set (0.003903s) + + taos> SELECT TIMETRUNCATE(ts, 1h) FROM meters; + timetruncate(ts, 1h) | + ========================== + 2022-02-02 02:00:00.000 | + 2022-02-02 02:00:00.000 | + 2022-02-02 02:00:00.000 | + Query OK, 3 row(s) in set (0.003903s) + ``` + + - **TIMEDIFF** + ```mysql + SELECT TIMEDIFF(ts_val1 | datetime_string1 | ts_col1, ts_val2 | datetime_string2 | ts_col2 [, time_unit]) FROM { tb_name | stb_name } [WHERE clause]; + ``` + Function: Calculate duration between two timestamps with time_unit precision。 + + Returned Data Type: INT64. + + Applicable Fields: UNIX timestamp, date-time format string, and TIMESTAMP type columns. + + Applied to: **table stable**. + + Note: + 1)Supported time_unit: + 1u(microsecond),1a(millisecond),1s(second),1m(minute),1h(hour),1d(day)。 + 2)If time_unit is unspecified, returned time duration unit is consist with current DATABASE precision settings. + + Example: + ```mysql + taos> SELECT TIMEDIFF(1643738400000, 1643742000000) FROM meters; + timediff(1643738400000, 1643742000000) | + ========================================= + 3600000 | + Query OK, 1 row(s) in set (0.002553s) + taos> SELECT TIMEDIFF(1643738400000, 1643742000000, 1h) FROM meters; + timediff(1643738400000, 1643742000000, 1h) | + ============================================= + 1 | + Query OK, 1 row(s) in set (0.003726s) + + taos> SELECT TIMEDIFF("2022-02-02 03:00:00", "2022-02-02 02:00:00", 1h) FROM meters; + timediff("2022-02-02 03:00:00", "2022-02-02 02:00:00", 1h) | + ============================================================= + 1 | + Query OK, 1 row(s) in set (0.001937s) + + taos> SELECT TIMEDIFF(ts_col1, ts_col2, 1h) FROM meters; + timediff(ts_col1, ts_col2, 1h) | + =================================== + 1 | + Query OK, 1 row(s) in set (0.001937s) + ``` + ## Time-dimension Aggregation TDengine supports aggregating by intervals (time range). Data in a table can partitioned by intervals and aggregated to generate results. For example, a temperature sensor collects data once per second, but the average temperature needs to be queried every 10 minutes. This aggregation is suitable for down sample operation, and the syntax is as follows: diff --git a/documentation20/en/13.faq/docs.md b/documentation20/en/13.faq/docs.md index 683a16e8895a3b9500bda7a3ab836c7b87dbaee2..62b82a3ee257a0f676d6e663a16fb21157bd50ba 100644 --- a/documentation20/en/13.faq/docs.md +++ b/documentation20/en/13.faq/docs.md @@ -30,7 +30,7 @@ Version 2.0 is a complete refactoring of the previous version, and the configura 4. Install the latest stable version of TDengine 5. If you need to migrate data or the data file is corrupted, please contact the official technical support team of TAOS Data to assist -## 2. When encoutered with the error " Unable to establish connection " in Windows, what can I do? +## 2. When encountered with the error " Unable to establish connection " in Windows, what can I do? See the [technical blog](https://www.taosdata.com/blog/2019/12/03/jdbcdriver%E6%89%BE%E4%B8%8D%E5%88%B0%E5%8A%A8%E6%80%81%E9%93%BE%E6%8E%A5%E5%BA%93/) for this issue. @@ -103,7 +103,7 @@ Insert in batches. Each write statement can insert multiple records into one or ## 12. What is the most effective way to write data? How to solve the problem that Chinese characters in nchar inserted under Windows systems are parsed into messy code? -If there are Chinese characters in nchar data under Windows, please first confirm that the region of the system is set to China (which can be set in the Control Panel), then the taos client in cmd should already support it normally; If you are developing Java applications in an IDE, such as Eclipse and Intellij, please confirm that the file code in the IDE is GBK (this is the default coding type of Java), and then initialize the configuration of the client when generating the Connection. The specific statement is as follows: +If there are Chinese characters in nchar data under Windows, please first confirm that the region of the system is set to China (which can be set in the Control Panel), then the taos client in cmd should already support it normally; If you are developing Java applications in an IDE, such as Eclipse and IntelliJ, please confirm that the file code in the IDE is GBK (this is the default coding type of Java), and then initialize the configuration of the client when generating the Connection. The specific statement is as follows: ```JAVA Class.forName("com.taosdata.jdbc.TSDBDriver"); @@ -126,7 +126,7 @@ Please update to the latest JDBC driver. ## 14. taos connect failed, reason: invalid timestamp. -The common reason is that the server time and client time are not calibrated, which can be calibrated by synchronizing with the time server (use ntpdate command under Linux, and select automatic synchronization in the Windows time setting). +The common reason is that the server time and client time are not calibrated, which can be calibrated by synchronizing with the time server (use `ntpdate` command under Linux, and select automatic synchronization in the Windows time setting). ## 15. Incomplete display of table name diff --git a/documentation20/en/14.devops/03.immigrate/docs.md b/documentation20/en/14.devops/03.immigrate/docs.md index 875ecd5932987f25f0921226825f5f60a70df50e..6669f5d7bc26f375233c369c4930b2518d097f89 100644 --- a/documentation20/en/14.devops/03.immigrate/docs.md +++ b/documentation20/en/14.devops/03.immigrate/docs.md @@ -9,7 +9,7 @@ Compared with OpenTSDB, TDengine has the following distinctive features. - Performance of data writing and querying far exceeds that of OpenTSDB. - Efficient compression mechanism for time-series data, which compresses less than 1/5 of the storage space on disk. - The installation and deployment is very simple, a single installation package to complete the installation and deployment, no other third-party software, the entire installation and deployment process in seconds; -- The built-in functions cover all the query functions supported by OpenTSDB, and also support more time-series data query functions, scalar functions and aggregation functions, and support advanced query functions such as multiple time-window aggregation, join query, expression operation, multiple group aggregation, user-defined sorting, and user-defined functions. Adopting SQL-like syntax rules, it is easier to learn and basically has no learning cost. +- The built-in functions cover all the query functions supported by OpenTSDB, and also support more time-series data query functions, scalar functions and aggregation functions, and support advanced query functions such as multiple time-window aggregation, join query, expression operation, multiple group aggregation, user-defined sorting, and user-defined functions. Adopting SQL-like syntax rules, it is easier to learn and basically has no learning cost. For OpenTSDB functions, please refer to Appendix 1 in this blog (scroll down to find it); for any other functions supported by TDengine, please refer to the SQL reference guide part in TDengine document on website. - Supports up to 128 tags with a total tag length of up to 16 KB. - In addition to HTTP, it also provides interfaces to Java, Python, C, Rust, Go, and other languages, and supports a variety of enterprise-class standard connector protocols such as JDBC. @@ -63,7 +63,7 @@ This allows collectd to push the data to taosAdapter using the push to OpenTSDB After the data has been written to TDengine properly, you can adapt Grafana to visualize the data written to TDengine. There is a connection plugin for Grafana in the TDengine installation directory connector/grafanaplugin. The way to use this plugin is simple. -First copy the entire dist directory under the grafanaplugin directory to Grafana's plugins directory (the default address is /var/lib/grafana/plugins/), and then restart Grafana to see the TDengine data source under the Add Data Source menu. +First copy the entire `dist` directory under the grafanaplugin directory to Grafana's plugins directory (the default address is /var/lib/grafana/plugins/), and then restart Grafana to see the TDengine data source under the Add Data Source menu. ```shell sudo cp -r . /var/lib/grafana/plugins/tdengine @@ -144,15 +144,15 @@ The steps are as follows: the name of the metrics is used as the name of the TDe Create 3 super tables in TDengine. ```sql -create stable memory(ts timestamp, val float) tags(host binary(12),memory_type binary(20), memory_type_instance binary(20), source binary(20)); -create stable swap(ts timestamp, val double) tags(host binary(12), swap_type binary(20), swap_type_binary binary(20), source binary(20)); -create stable disk(ts timestamp, val double) tags(host binary(12), disk_point binary(20), disk_instance binary(20), disk_type binary(20), source binary(20)); +CREATE STABLE memory(ts timestamp, val float) tags(host binary(12),memory_type binary(20), memory_type_instance binary(20), source binary(20)); +CREATE STABLE swap(ts timestamp, val double) tags(host binary(12), swap_type binary(20), swap_type_binary binary(20), source binary(20)); +CREATE STABLE disk(ts timestamp, val double) tags(host binary(12), disk_point binary(20), disk_instance binary(20), disk_type binary(20), source binary(20)); ``` For sub-tables use dynamic table creation as shown below: ```sql -insert into memory_vm130_memory_bufferred_collectd using memory tags(‘vm130’, ‘memory’, 'buffer', 'collectd') values(1632979445, 3.0656); +INSERT INTO memory_vm130_memory_buffered_collectd USING memory TAGS(‘vm130’, ‘memory’, 'buffer', 'collectd') VALUES(1632979445, 3.0656); ``` Eventually about 340 sub-tables and 3 super-tables will be created in the system. Note that if the use of concatenated tagged values causes the sub-table names to exceed the system limit (191 bytes), then some encoding (e.g. MD5) needs to be used to convert them to an acceptable length. @@ -168,7 +168,7 @@ Data is subscribed from the message queue and an adapted writer is started to wr After the data starts to be written for a sustained period, SQL statements can be used to check whether the amount of data written meets the expected write requirements. The following SQL statement is used to count the amount of data. ```sql -select count(*) from memory +SELECT COUNT(*) FROM memory ``` After completing the query, if the written data does not differ from the expected one, and there are no abnormal error messages from the writing program itself, then you can confirm that the data writing is complete and valid. @@ -207,13 +207,15 @@ Equivalent function: avg Example. +```sql SELECT avg(val) FROM (SELECT first(val) FROM super_table WHERE ts >= startTime and ts <= endTime INTERVAL(20s) Fill(linear)) INTERVAL(20s) +``` Notes. 1. the value within the Interval needs to be the same as the interval value of the outer query. -As the interpolation of values in OpenTSDB uses linear interpolation, use fill(linear) to declare the interpolation type in the interpolation clause. The following functions with the same interpolation requirements are handled by this method. 3. +As the interpolation of values in OpenTSDB uses linear interpolation, use FILL(linear) to declare the interpolation type in the interpolation clause. The following functions with the same interpolation requirements are handled by this method. 3. 2. The 20s parameter in Interval means that the inner query will generate results in a 20-second window. In a real query, it needs to be adjusted to the time interval between different records. This ensures that the interpolation results are generated equivalently to the original data. @@ -226,7 +228,9 @@ Equivalent function: count Example. -select count(*) from super_table_name; +```sql +SELECT COUNT(*) FROM super_table_name; +``` **Dev** @@ -234,7 +238,9 @@ Equivalent function: stddev Example. -Select stddev(val) from table_name +```sql +SELECT STDDEV(val) FROM table_name +``` **Estimated percentiles** @@ -242,7 +248,9 @@ Equivalent function: apercentile Example. -Select apercentile(col1, 50, “t-digest”) from table_name +```sql +SELECT APERCENTILE(col1, 50, “t-digest”) FROM table_name +``` Remark. @@ -254,7 +262,9 @@ Equivalent function: first Example. -Select first(col1) from table_name +```sql +SELECT FIRST(col1) FROM table_name +``` **Last** @@ -262,7 +272,9 @@ Equivalent function: last Example. -Select last(col1) from table_name +```sql +SELECT LAST(col1) FROM table_name +``` **Max** @@ -270,7 +282,9 @@ Equivalent function: max Example. -Select max(value) from (select first(val) value from table_name interval(10s) fill(linear)) interval(10s) +```sql +SELECT MAX(value) FROM (SELECT FIRST(val) value FROM table_name INTERVAL(10s) FILL(linear)) INTERVAL(10s) +``` Note: The Max function requires interpolation, for the reasons given above. @@ -280,13 +294,17 @@ Equivalent function: min Example. -Select min(value) from (select first(val) value from table_name interval(10s) fill(linear)) interval(10s); +```sql +SELECT MIN(value) FROM (select first(val) value FROM table_name INTERVAL(10s) FILL(linear)) INTERVAL(10s); +``` **MinMax** Equivalent function: max -Select max(val) from table_name +```sql +SELECT max(val) FROM table_name +``` Note: This function does not require interpolation, so it can be calculated directly. @@ -294,7 +312,9 @@ Note: This function does not require interpolation, so it can be calculated dire Equivalent function: min -Select min(val) from table_name +```sql +SELECT min(val) FROM table_name +``` Note: This function does not require interpolation, so it can be calculated directly. @@ -308,7 +328,9 @@ Note: Equivalent function: sum -Select max(value) from (select first(val) value from table_name interval(10s) fill(linear)) interval(10s) +```sql +SELECT MAX(value) FROM (SELECT FIRST(val) value FROM table_name INTERVAL(10s) FILL(linear)) INTERVAL(10s) +``` Note: This function does not require interpolation, so it can be calculated directly. @@ -316,7 +338,9 @@ Note: This function does not require interpolation, so it can be calculated dire Equivalent function: sum -Select sum(val) from table_name +```sql +SELECT SUM(val) FROM table_name +``` Note: This function does not require interpolation, so it can be calculated directly. @@ -331,8 +355,10 @@ query = { "metric":"cpu.usage_user", }] } +``` // Equivalent SQL: +```sql SELECT count(*) FROM `cpu.usage_user` WHERE ts>=1510560000 AND ts<=1515000009 @@ -356,7 +382,7 @@ Combining the above formula and bringing the parameters into the calculation for ### Storage device selection considerations -The hard disk should be used with a better random read performance hard disk device, if you can have SSD, consider using SSD as much as possible. better random read performance of the disk is extremely helpful to improve the system query performance and can improve the overall query response performance of the system. To obtain better query performance, the performance index of single-threaded random read IOPS of the hard disk device should not be lower than 1000, it is better to reach 5000 IOPS or more. To obtain an evaluation of the current device random read IO performance, it is recommended that fio software be used to evaluate its operational performance (see Appendix 1 for details on how to use it) to confirm whether it can meet the large file random read performance requirements. +The hard disk should be used with a better random read performance hard disk device, if you can have SSD, consider using SSD as much as possible. better random read performance of the disk is extremely helpful to improve the system query performance and can improve the overall query response performance of the system. To obtain better query performance, the performance index of single-threaded random read IOPS of the hard disk device should not be lower than 1000, it is better to reach 5000 IOPS or more. To obtain an evaluation of the current device random read IO performance, it is recommended that `fio` software be used to evaluate its operational performance (see Appendix 1 for details on how to use it) to confirm whether it can meet the large file random read performance requirements. Hard disk write performance has little impact on TDengine; TDengine writes in append write mode, so as long as it has good sequential write performance, both SAS hard disks and SSDs, in general, can meet TDengine's requirements for disk write performance well. @@ -390,7 +416,7 @@ FQDN, firstEp, secondEP, dataDir, logDir, tmpDir, serverPort. The specific meani Follow the same steps to set the parameters on the node that needs to run and start the taosd service, then add the Dnode to the cluster. -Finally, start taos and execute the command show dnodes, if you can see all the nodes that have joined the cluster, then the cluster is successfully built. For the specific operation procedure and notes, please refer to the document [TDengine Cluster Installation, Management](https://www.taosdata.com/cn/documentation/cluster). +Finally, start taos and execute the command `SHOW DNODES`, if you can see all the nodes that have joined the cluster, then the cluster is successfully built. For the specific operation procedure and notes, please refer to the document [TDengine Cluster Installation, Management](https://www.taosdata.com/cn/documentation/cluster). ## Appendix 4: Super table names diff --git a/examples/C#/.gitignore b/examples/C#/.gitignore index 2a959a77c900524f996f3214446d37f34026c6e4..b488758990212a16505807bc1debc907d4660a5a 100644 --- a/examples/C#/.gitignore +++ b/examples/C#/.gitignore @@ -14,4 +14,5 @@ taosdemo/obj/ jsonTag/bin/ jsonTag/obj/ insertCn/bin/ -insertCn/obj/ \ No newline at end of file +insertCn/obj/ +.vs diff --git a/examples/JDBC/taosdemo/pom.xml b/examples/JDBC/taosdemo/pom.xml index e249d83e16def830b61e9f8ab82197d30e7e0d33..54edd40ebc01f1aca6b744356b40cefb12a223c3 100644 --- a/examples/JDBC/taosdemo/pom.xml +++ b/examples/JDBC/taosdemo/pom.xml @@ -10,7 +10,7 @@ Demo project for TDengine - 5.3.14 + 5.3.18 diff --git a/examples/R/command.txt b/examples/R/command.txt index 9a549ff200968d96336666c23999e13aa07dbb3f..84ac1d50a413013b2a07172a9d31314a7e12b436 100644 --- a/examples/R/command.txt +++ b/examples/R/command.txt @@ -1,5 +1,5 @@ # Linux Platform -install.packages('rJDBC', repos='http://cran.us.r-project.org') +install.packages('RJDBC', repos='http://cran.us.r-project.org') # Loading RJDBC packages library('RJDBC') diff --git a/examples/R/rjdbc.sample.R b/examples/R/rjdbc.sample.R new file mode 100644 index 0000000000000000000000000000000000000000..806cc3b78ec8453e53109ccf78ba5d4d673fc11d --- /dev/null +++ b/examples/R/rjdbc.sample.R @@ -0,0 +1,86 @@ + +#install.packages('RJDBC', repos='http://cran.us.r-project.org') + +library('DBI') +library('rJava') +library('RJDBC') +# get jdbc from input parameters +args<- commandArgs(trailingOnly = TRUE) +# arg[1] for jdbc path,arg[2] fro jdbc name +# like "/src/connector/jdbc/target/taos-jdbcdriver-2.0.37-dist.jar" +jdbc<- paste(args[1],args[2],sep="/") + + +print("***************************taos-jdbcDriver support RJDBC sample *************************************") +#JNI +# Get JBDC-JNI connection +drv<-JDBC("com.taosdata.jdbc.TSDBDriver",jdbc, identifier.quote="\"") +conn<-dbConnect(drv,"jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata","root","taosdata") + +#Restful +#drv<-JDBC("com.taosdata.jdbc.TSDBDriver",jdbc, identifier.quote="\"") +#conn<-dbConnect(drv,"jdbc:TAOS-RS://127.0.0.1:6041/test?user=root&password=taosdata","root","taosdata") + +# Get connection information +dbGetInfo(conn) + +# create database +dbSendUpdate(conn,"create database if not exists r_example_db keep 3650") + +# use db +dbSendUpdate(conn,"use r_example_db") +dbSendUpdate(conn,"create table if not exists test(ts timestamp,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnry binary(50),nchr nchar(50)) tags(k int,v binary(20))") + +# insert data +dbSendUpdate(conn,"insert into test_s01 using test tags(1,'sub_01') values(now,1,2,3,4,'binary1','nchar1')(now+1s,5,6,7,8,'binary2','nchar2')(now+2s,9,0,1,2,'binary3','nchar3')") + +# View all tables +print("==============dbGetQuery==================") +table1<-dbGetQuery(conn,"select * from test") +print(table1) + +# Functional support for RJDBC + +# List all tables +print("=============dbListTables===================") +dbListTables(conn,"test%") + +print("=============dbExistsTable===================") +# Is there table "test" +dbExistsTable(conn,"test") + +# Connect summary information +print("=============summary===================") +summary(conn) +print("=============dbGetInfo===================") +dbGetInfo(conn) + + +# Read all the data from the test table +print("=============dbReadTable===================") +dbReadTable(conn,"test") + + +# Execute any non-query SQL statements +dbSendUpdate(conn, "create table if not exists t1(ts timestamp,id int,u nchar(40))") +dbGetTables(conn, "t") +sampleData=data.frame(ts=c('2022-03-22 00:00:00.000','2022-03-22 10:00:00.000'),id=c(1,2),u=c('涛思数据','TDengine')) +print("=============dbWriteTable===================") +dbWriteTable(conn, "t1", sampleData, overwrite=FALSE, append=TRUE) +dbReadTable(conn,"t1") + +# Delete table t1 +dbRemoveTable(conn,"t1") + +# Extracting data on demand using SQL statements +print("=============dbGetQuery===================") +dbGetQuery(conn, "select * from test_s01") + +# Drop database +dbSendUpdate(conn,"drop database if exists r_example_db") + +# Close the connection +print("=============dbDisconnect===================") +dbDisconnect(conn) + +print("***************************taos-jdbcDriver support RJDBC sample done*************************************") diff --git a/examples/c/apitest.c b/examples/c/apitest.c index 2c197887e7d7f1e6397213641a02ee8b37a84190..597a108a2686b4dd501513ea895c25a2de1b8dad 100644 --- a/examples/c/apitest.c +++ b/examples/c/apitest.c @@ -262,32 +262,6 @@ void verify_async(TAOS* taos) { usleep(1000000); } -void stream_callback(void* param, TAOS_RES* res, TAOS_ROW row) { - if (res == NULL || row == NULL) { - return; - } - - int num_fields = taos_num_fields(res); - TAOS_FIELD* fields = taos_fetch_fields(res); - - printf("got one row from stream_callback\n"); - char temp[256] = {0}; - taos_print_row(temp, row, fields, num_fields); - puts(temp); -} - -void verify_stream(TAOS* taos) { - prepare_data(taos); - TAOS_STREAM* strm = - taos_open_stream(taos, "select count(*) from meters interval(1m)", stream_callback, 0, NULL, NULL); - printf("waiting for stream data\n"); - usleep(100000); - TAOS_RES* result = taos_query(taos, "insert into t0 values(now, 0)(now+5s,1)(now+10s, 2);"); - taos_free_result(result); - usleep(200000000); - taos_close_stream(strm); -} - void verify_schema_less(TAOS* taos) { TAOS_RES* result; result = taos_query(taos, "drop database if exists test;"); @@ -447,8 +421,6 @@ int main(int argc, char* argv[]) { printf("*********** verify subscribe ************\n"); verify_subscribe(taos); - printf("************ verify stream *************\n"); - // verify_stream(taos); printf("done\n"); taos_close(taos); taos_cleanup(); diff --git a/examples/c/makefile b/examples/c/makefile index 355d1a2d54c1293e909309dafe986daa716ac293..4d6cfc1f5f3e8d4d8b0a7ce88ce285c1b3259a5a 100644 --- a/examples/c/makefile +++ b/examples/c/makefile @@ -17,7 +17,6 @@ exe: gcc $(CFLAGS) ./asyncdemo.c -o $(ROOT)asyncdemo $(LFLAGS) gcc $(CFLAGS) ./demo.c -o $(ROOT)demo $(LFLAGS) gcc $(CFLAGS) ./prepare.c -o $(ROOT)prepare $(LFLAGS) - gcc $(CFLAGS) ./stream.c -o $(ROOT)stream $(LFLAGS) gcc $(CFLAGS) ./subscribe.c -o $(ROOT)subscribe $(LFLAGS) gcc $(CFLAGS) ./apitest.c -o $(ROOT)apitest $(LFLAGS) @@ -25,6 +24,5 @@ clean: rm $(ROOT)asyncdemo rm $(ROOT)demo rm $(ROOT)prepare - rm $(ROOT)stream rm $(ROOT)subscribe rm $(ROOT)apitest diff --git a/examples/c/stream.c b/examples/c/stream.c deleted file mode 100644 index f759da4283bfca69d921f4bbfbb2e78e2123a70c..0000000000000000000000000000000000000000 --- a/examples/c/stream.c +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -#include -#include -#include -#include -#include // include TDengine header file -#include - -typedef struct { - char server_ip[64]; - char db_name[64]; - char tbl_name[64]; -} param; - -int g_thread_exit_flag = 0; -void *insert_rows(void *sarg); - -void streamCallBack(void *param, TAOS_RES *res, TAOS_ROW row) { - // in this simple demo, it just print out the result - char temp[128]; - - TAOS_FIELD *fields = taos_fetch_fields(res); - int numFields = taos_num_fields(res); - - taos_print_row(temp, row, fields, numFields); - - printf("\n%s\n", temp); -} - -int main(int argc, char *argv[]) { - TAOS *taos; - char db_name[64]; - char tbl_name[64]; - char sql[1024] = {0}; - - if (argc != 4) { - printf("usage: %s server-ip dbname tblname\n", argv[0]); - exit(0); - } - - strcpy(db_name, argv[2]); - strcpy(tbl_name, argv[3]); - - // create pthread to insert into row per second for stream calc - param *t_param = (param *)malloc(sizeof(param)); - if (NULL == t_param) { - printf("failed to malloc\n"); - exit(1); - } - memset(t_param, 0, sizeof(param)); - strcpy(t_param->server_ip, argv[1]); - strcpy(t_param->db_name, db_name); - strcpy(t_param->tbl_name, tbl_name); - - pthread_t pid; - pthread_create(&pid, NULL, (void *(*)(void *))insert_rows, t_param); - - sleep(3); // waiting for database is created. - // open connection to database - taos = taos_connect(argv[1], "root", "taosdata", db_name, 0); - if (taos == NULL) { - printf("failed to connet to server:%s\n", argv[1]); - free(t_param); - exit(1); - } - - // starting stream calc, - printf("please input stream SQL:[e.g., select count(*) from tblname interval(5s) sliding(2s);]\n"); - fgets(sql, sizeof(sql), stdin); - if (sql[0] == 0) { - printf("input NULL stream SQL, so exit!\n"); - free(t_param); - exit(1); - } - - // param is set to NULL in this demo, it shall be set to the pointer to app context - TAOS_STREAM *pStream = taos_open_stream(taos, sql, streamCallBack, 0, NULL, NULL); - if (NULL == pStream) { - printf("failed to create stream\n"); - free(t_param); - exit(1); - } - - printf("press any key to exit\n"); - getchar(); - - taos_close_stream(pStream); - - g_thread_exit_flag = 1; - pthread_join(pid, NULL); - - taos_close(taos); - free(t_param); - - return 0; -} - -void *insert_rows(void *sarg) { - TAOS * taos; - char command[1024] = {0}; - param *winfo = (param *)sarg; - - if (NULL == winfo) { - printf("para is null!\n"); - exit(1); - } - - taos = taos_connect(winfo->server_ip, "root", "taosdata", NULL, 0); - if (taos == NULL) { - printf("failed to connet to server:%s\n", winfo->server_ip); - exit(1); - } - - // drop database - sprintf(command, "drop database %s;", winfo->db_name); - if (taos_query(taos, command) != 0) { - printf("failed to drop database, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // create database - sprintf(command, "create database %s;", winfo->db_name); - if (taos_query(taos, command) != 0) { - printf("failed to create database, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // use database - sprintf(command, "use %s;", winfo->db_name); - if (taos_query(taos, command) != 0) { - printf("failed to use database, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // create table - sprintf(command, "create table %s (ts timestamp, speed int);", winfo->tbl_name); - if (taos_query(taos, command) != 0) { - printf("failed to create table, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // insert data - int64_t begin = (int64_t)time(NULL); - int index = 0; - while (1) { - if (g_thread_exit_flag) break; - - index++; - sprintf(command, "insert into %s values (%ld, %d)", winfo->tbl_name, (begin + index) * 1000, index); - if (taos_query(taos, command)) { - printf("failed to insert row [%s], reason:%s\n", command, taos_errstr(taos)); - } - sleep(1); - } - - taos_close(taos); - return 0; -} diff --git a/packaging/cfg/taos.cfg b/packaging/cfg/taos.cfg index 46e27b98e9339cb0cb0cb0d8fe0d038bde926148..9a88a0679d50e0eedb861cdc1628b7678bf719a5 100644 --- a/packaging/cfg/taos.cfg +++ b/packaging/cfg/taos.cfg @@ -307,3 +307,6 @@ keepColumnName 1 # unit MB. Flush vnode wal file if walSize > walFlushSize and walSize > cache*0.5*blocks # walFlushSize 1024 + +# unit Hour. Latency of data migration +# keepTimeOffset 0 diff --git a/packaging/docker/Dockerfile b/packaging/docker/Dockerfile index 1f3bd503f6a641679924075e8ca9d164cb1a5ee3..26349e257676d99d0ea81e03509c8b09c20a2248 100644 --- a/packaging/docker/Dockerfile +++ b/packaging/docker/Dockerfile @@ -9,8 +9,10 @@ RUN echo ${pkgFile} && echo ${dirName} COPY ${pkgFile} /root/ RUN tar -zxf ${pkgFile} -WORKDIR /root/${dirName}/ -RUN /bin/bash install.sh -e no +WORKDIR /root/ +RUN cd /root/${dirName}/ && /bin/bash install.sh -e no && cd /root +RUN rm /root/${pkgFile} +RUN rm -rf /root/${dirName} ENV DEBIAN_FRONTEND=noninteractive RUN apt-get clean && apt-get update && apt-get install -y locales tzdata netcat && locale-gen en_US.UTF-8 diff --git a/packaging/tools/makeclient.sh b/packaging/tools/makeclient.sh index 1e15a916cfa569508aeea2c4ab3aa9b57a93d61d..b24759e640f172befb16d624abd62c6c9484255e 100755 --- a/packaging/tools/makeclient.sh +++ b/packaging/tools/makeclient.sh @@ -145,6 +145,7 @@ if [[ "$pagMode" != "lite" ]] && [[ "$cpuType" != "aarch32" ]]; then cp -r ${examples_dir}/go ${install_dir}/examples cp -r ${examples_dir}/nodejs ${install_dir}/examples cp -r ${examples_dir}/C# ${install_dir}/examples + mkdir -p ${install_dir}/examples/taosbenchmark-json && cp ${examples_dir}/../src/kit/taos-tools/example/* ${install_dir}/examples/taosbenchmark-json fi # Copy driver mkdir -p ${install_dir}/driver diff --git a/packaging/tools/makepkg.sh b/packaging/tools/makepkg.sh index 9f3d67f386cb967c0cb203b70e7c6d4afe85b5a2..34198eae15fa44a13eb2dc97a2be3aebc98f3d64 100755 --- a/packaging/tools/makepkg.sh +++ b/packaging/tools/makepkg.sh @@ -279,6 +279,7 @@ if [[ $dbName == "taos" ]]; then cp -r ${examples_dir}/go ${install_dir}/examples cp -r ${examples_dir}/nodejs ${install_dir}/examples cp -r ${examples_dir}/C# ${install_dir}/examples + mkdir -p ${install_dir}/examples/taosbenchmark-json && cp ${examples_dir}/../src/kit/taos-tools/example/* ${install_dir}/examples/taosbenchmark-json fi fi diff --git a/src/client/inc/tscUtil.h b/src/client/inc/tscUtil.h index e380dc77768a97a267ce80f8fb20273acb389fa7..f7d3aa630f24e0054a1ce963e6a1939a511fe4d7 100644 --- a/src/client/inc/tscUtil.h +++ b/src/client/inc/tscUtil.h @@ -400,7 +400,7 @@ void tscRemoveCachedTableMeta(STableMetaInfo* pTableMetaInfo, uint64_t id); char* cloneCurrentDBName(SSqlObj* pSql); -int parseJsontoTagData(char* json, SKVRowBuilder* kvRowBuilder, char* errMsg, int16_t startColId); +int parseJsontoTagData(char* json, uint32_t jsonLength, SKVRowBuilder* kvRowBuilder, char* errMsg, int16_t startColId); int8_t jsonType2DbType(double data, int jsonType); void getJsonKey(SStrToken *t0); diff --git a/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h b/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h index 4c999b710a62d1e620064af4d5647ee46d9a570e..6b987141996d3c9a0bf78e162f1c11b758008536 100644 --- a/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h +++ b/src/client/jni/com_taosdata_jdbc_TSDBJNIConnector.h @@ -11,257 +11,254 @@ extern "C" { #define com_taosdata_jdbc_TSDBJNIConnector_INVALID_CONNECTION_POINTER_VALUE 0LL /* * Class: com_taosdata_jdbc_TSDBJNIConnector - * Method: + * Method: * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setAllocModeImp - (JNIEnv *, jclass, jint, jstring, jboolean); +JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setAllocModeImp(JNIEnv *, jclass, jint, jstring, + jboolean); /* * Class: com_taosdata_jdbc_TSDBJNIConnector - * Method: + * Method: * Signature: ()Ljava/lang/String; */ -JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_dumpMemoryLeakImp - (JNIEnv *, jclass); +JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_dumpMemoryLeakImp(JNIEnv *, jclass); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: initImp * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp - (JNIEnv *, jclass, jstring); +JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_initImp(JNIEnv *, jclass, jstring); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: setOptions * Signature: (ILjava/lang/String;)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions - (JNIEnv *, jclass, jint, jstring); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setOptions(JNIEnv *, jclass, jint, jstring); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: setConfigImp * Signature: (Ljava/lang/String;)Lcom/taosdata/jdbc/TSDBException; */ -JNIEXPORT jobject JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setConfigImp - (JNIEnv *, jclass, jstring); +JNIEXPORT jobject JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setConfigImp(JNIEnv *, jclass, jstring); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getTsCharset * Signature: ()Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getTsCharset - (JNIEnv *, jclass); +JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getTsCharset(JNIEnv *, jclass); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getResultTimePrecisionImp * Signature: (JJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TDDBJNIConnector_getResultTimePrecisionImp - (JNIEnv *, jobject, jlong, jlong); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TDDBJNIConnector_getResultTimePrecisionImp(JNIEnv *, jobject, jlong, + jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: connectImp * Signature: (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)J */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp - (JNIEnv *, jobject, jstring, jint, jstring, jstring, jstring); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_connectImp(JNIEnv *, jobject, jstring, jint, jstring, + jstring, jstring); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: executeQueryImp * Signature: ([BJ)I */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp - (JNIEnv *, jobject, jbyteArray, jlong); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeQueryImp(JNIEnv *, jobject, jbyteArray, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getErrCodeImp * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrCodeImp - (JNIEnv *, jobject, jlong, jlong); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrCodeImp(JNIEnv *, jobject, jlong, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getErrMsgImp * Signature: (J)Ljava/lang/String; */ -JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrMsgImp - (JNIEnv *, jobject, jlong); +JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getErrMsgImp(JNIEnv *, jobject, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getResultSetImp * Signature: (J)J */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getResultSetImp - (JNIEnv *env, jobject jobj, jlong con, jlong tres); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getResultSetImp(JNIEnv *env, jobject jobj, jlong con, + jlong tres); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: isUpdateQueryImp * Signature: (JJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_isUpdateQueryImp - (JNIEnv *env, jobject jobj, jlong con, jlong tres); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_isUpdateQueryImp(JNIEnv *env, jobject jobj, jlong con, + jlong tres); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: freeResultSetImp * Signature: (JJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp - (JNIEnv *, jobject, jlong, jlong); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_freeResultSetImp(JNIEnv *, jobject, jlong, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getAffectedRowsImp * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getAffectedRowsImp - (JNIEnv *env, jobject jobj, jlong con, jlong res); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getAffectedRowsImp(JNIEnv *env, jobject jobj, jlong con, + jlong res); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: getSchemaMetaDataImp * Signature: (JJLjava/util/List;)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getSchemaMetaDataImp - (JNIEnv *, jobject, jlong, jlong, jobject); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_getSchemaMetaDataImp(JNIEnv *, jobject, jlong, jlong, + jobject); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: fetchRowImp * Signature: (JJLcom/taosdata/jdbc/TSDBResultSetRowData;)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchRowImp - (JNIEnv *, jobject, jlong, jlong, jobject); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchRowImp(JNIEnv *, jobject, jlong, jlong, jobject); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: fetchBlockImp * Signature: (JJLcom/taosdata/jdbc/TSDBResultSetBlockData;)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchBlockImp - (JNIEnv *, jobject, jlong, jlong, jobject); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchBlockImp(JNIEnv *, jobject, jlong, jlong, jobject); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: closeConnectionImp * Signature: (J)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeConnectionImp - (JNIEnv *, jobject, jlong); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeConnectionImp(JNIEnv *, jobject, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: subscribeImp * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JI)J */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_subscribeImp - (JNIEnv *, jobject, jlong, jboolean, jstring, jstring, jint); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_subscribeImp(JNIEnv *, jobject, jlong, jboolean, + jstring, jstring, jint); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: consumeImp * Signature: (J)Lcom/taosdata/jdbc/TSDBResultSetRowData; */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_consumeImp - (JNIEnv *, jobject, jlong); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_consumeImp(JNIEnv *, jobject, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: unsubscribeImp * Signature: (J)V */ -JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_unsubscribeImp - (JNIEnv *, jobject, jlong, jboolean); +JNIEXPORT void JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_unsubscribeImp(JNIEnv *, jobject, jlong, jboolean); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: validateCreateTableSqlImp * Signature: (J[B)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_validateCreateTableSqlImp - (JNIEnv *, jobject, jlong, jbyteArray); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_validateCreateTableSqlImp(JNIEnv *, jobject, jlong, + jbyteArray); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: prepareStmtImp * Signature: ([BJ)I */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_prepareStmtImp - (JNIEnv *, jobject, jbyteArray, jlong); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_prepareStmtImp(JNIEnv *, jobject, jbyteArray, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: setBindTableNameImp * Signature: (JLjava/lang/String;J)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setBindTableNameImp - (JNIEnv *, jobject, jlong, jstring, jlong); - +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setBindTableNameImp(JNIEnv *, jobject, jlong, jstring, + jlong); /** * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: setTableNameTagsImp * Signature: (JLjava/lang/String;I[B[B[B[BJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsImp - (JNIEnv *, jobject, jlong, jstring, jint, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jlong); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_setTableNameTagsImp(JNIEnv *, jobject, jlong, jstring, + jint, jbyteArray, jbyteArray, + jbyteArray, jbyteArray, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: bindColDataImp * Signature: (J[B[B[BIIIIJ)J */ -JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_bindColDataImp -(JNIEnv *, jobject, jlong, jbyteArray, jbyteArray, jbyteArray, jint, jint, jint, jint, jlong); +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_bindColDataImp(JNIEnv *, jobject, jlong, jbyteArray, + jbyteArray, jbyteArray, jint, jint, jint, + jint, jlong); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: stmt_add_batch * Signature: (JJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_addBatchImp(JNIEnv *env, jobject jobj, jlong stmt, jlong con); - +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_addBatchImp(JNIEnv *env, jobject jobj, jlong stmt, + jlong con); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: executeBatchImp * Signature: (JJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeBatchImp(JNIEnv *env, jobject jobj, jlong stmt, jlong con); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_executeBatchImp(JNIEnv *env, jobject jobj, jlong stmt, + jlong con); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: closeStmt * Signature: (JJ)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeStmt(JNIEnv *env, jobject jobj, jlong stmt, jlong con); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeStmt(JNIEnv *env, jobject jobj, jlong stmt, + jlong con); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: stmt_errstr * Signature: (JJ)I */ -JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_stmtErrorMsgImp(JNIEnv *env, jobject jobj, jlong stmt, jlong con); +JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_stmtErrorMsgImp(JNIEnv *env, jobject jobj, jlong stmt, + jlong con); /* * Class: com_taosdata_jdbc_TSDBJNIConnector * Method: insertLinesImp * Signature: ([Ljava/lang/String;JII)I */ -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp - (JNIEnv *, jobject, jobjectArray, jlong, jint, jint); +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JNIEnv *, jobject, jobjectArray, jlong, + jint, jint); + +/* + * Class: com_taosdata_jdbc_TSDBJNIConnector + * Method: schemalessInsertImp + * Signature: (J[B[B[BIIIIJ)J + */ +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_schemalessInsertImp(JNIEnv *, jobject, jobjectArray, + jlong, jint, jint); #ifdef __cplusplus } diff --git a/src/client/src/TSDBJNIConnector.c b/src/client/src/TSDBJNIConnector.c index 67a08fa4fac39e2497a3cc0447b73f2a93d0c4ee..c7d328bf1db4d9cd66b9157191f0f05ca439ab6f 100644 --- a/src/client/src/TSDBJNIConnector.c +++ b/src/client/src/TSDBJNIConnector.c @@ -573,8 +573,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchBlockImp(JNI return code; } - TAOS_RES *tres = (TAOS_RES *)res; - TAOS_FIELD *fields = taos_fetch_fields(tres); + TAOS_RES *tres = (TAOS_RES *)res; int32_t numOfFields = taos_num_fields(tres); assert(numOfFields > 0); @@ -596,14 +595,10 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_fetchBlockImp(JNI (*env)->CallVoidMethod(env, rowobj, g_blockdataSetNumOfRowsFp, (jint)numOfRows); (*env)->CallVoidMethod(env, rowobj, g_blockdataSetNumOfColsFp, (jint)numOfFields); + int32_t *field = taos_fetch_lengths(tres); for (int i = 0; i < numOfFields; i++) { - int bytes = fields[i].bytes; - - if (fields[i].type == TSDB_DATA_TYPE_BINARY || fields[i].type == TSDB_DATA_TYPE_NCHAR) { - bytes += 2; - } - (*env)->CallVoidMethod(env, rowobj, g_blockdataSetByteArrayFp, i, bytes * numOfRows, - jniFromNCharToByteArray(env, (char *)row[i], bytes * numOfRows)); + (*env)->CallVoidMethod(env, rowobj, g_blockdataSetByteArrayFp, i, field[i] * numOfRows, + jniFromNCharToByteArray(env, (char *)row[i], field[i] * numOfRows)); } return JNI_SUCCESS; @@ -945,7 +940,7 @@ JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_bindColDataImp( } JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_addBatchImp(JNIEnv *env, jobject jobj, jlong stmt, - jlong con) { + jlong con) { TAOS *tscon = (TAOS *)con; if (tscon == NULL) { jniError("jobj:%p, connection already closed", jobj); @@ -1017,7 +1012,7 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_closeStmt(JNIEnv } JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_stmtErrorMsgImp(JNIEnv *env, jobject jobj, jlong stmt, - jlong con) { + jlong con) { char errMsg[128]; TAOS *tscon = (TAOS *)con; if (tscon == NULL) { @@ -1036,20 +1031,12 @@ JNIEXPORT jstring JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_stmtErrorMsgIm return (*env)->NewStringUTF(env, taos_stmt_errstr((TAOS_STMT *)stmt)); } -JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JNIEnv *env, jobject jobj, - jobjectArray lines, jlong conn, - jint protocol, jint precision) { - TAOS *taos = (TAOS *)conn; - if (taos == NULL) { - jniError("jobj:%p, connection already closed", jobj); - return JNI_CONNECTION_NULL; - } - +SSqlObj *schemalessInsert(JNIEnv *env, jobject jobj, jobjectArray lines, TAOS *taos, jint protocol, jint precision) { int numLines = (*env)->GetArrayLength(env, lines); char **c_lines = calloc(numLines, sizeof(char *)); if (c_lines == NULL) { jniError("c_lines:%p, alloc memory failed", c_lines); - return JNI_OUT_OF_MEMORY; + return NULL; } for (int i = 0; i < numLines; ++i) { jstring line = (jstring)((*env)->GetObjectArrayElement(env, lines, i)); @@ -1057,7 +1044,6 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JN } SSqlObj *result = (SSqlObj *)taos_schemaless_insert(taos, c_lines, numLines, protocol, precision); - int code = taos_errno(result); for (int i = 0; i < numLines; ++i) { jstring line = (jstring)((*env)->GetObjectArrayElement(env, lines, i)); @@ -1065,6 +1051,24 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JN } tfree(c_lines); + return result; +} + +JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JNIEnv *env, jobject jobj, + jobjectArray lines, jlong conn, + jint protocol, jint precision) { + TAOS *taos = (TAOS *)conn; + if (taos == NULL) { + jniError("jobj:%p, connection already closed", jobj); + return JNI_CONNECTION_NULL; + } + + SSqlObj *result = (SSqlObj *)schemalessInsert(env, jobj, lines, taos, protocol, precision); + + if (result == NULL) { + return JNI_OUT_OF_MEMORY; + } + int code = taos_errno(result); if (code != TSDB_CODE_SUCCESS) { jniError("jobj:%p, conn:%p, code:%s, msg:%s", jobj, taos, tstrerror(code), taos_errstr(result)); taos_free_result((void *)result); @@ -1074,3 +1078,19 @@ JNIEXPORT jint JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_insertLinesImp(JN return JNI_SUCCESS; } + +JNIEXPORT jlong JNICALL Java_com_taosdata_jdbc_TSDBJNIConnector_schemalessInsertImp(JNIEnv *env, jobject jobj, + jobjectArray lines, jlong conn, + jint protocol, jint precision) { + TAOS *taos = (TAOS *)conn; + if (taos == NULL) { + jniError("jobj:%p, connection already closed", jobj); + return JNI_CONNECTION_NULL; + } + + SSqlObj *result = schemalessInsert(env, jobj, lines, taos, protocol, precision); + if (result == NULL) { + return JNI_OUT_OF_MEMORY; + } + return (jlong)result; +} \ No newline at end of file diff --git a/src/client/src/taos.def b/src/client/src/taos.def index 77eb9144657facc82dda70129dd77480a0f0b9e8..b3f232bb7b33b93c50dfb35536b4ebe6e633e95c 100644 --- a/src/client/src/taos.def +++ b/src/client/src/taos.def @@ -53,4 +53,8 @@ taos_is_null taos_insert_lines taos_schemaless_insert taos_result_block -taos_print_row_ex \ No newline at end of file +taos_print_row_ex +taos_stmt_affected_rows +taos_is_update_query +taos_reset_current_db +taos_parse_time \ No newline at end of file diff --git a/src/client/src/tscGlobalmerge.c b/src/client/src/tscGlobalmerge.c index a22269f98e270ea681f5e6bc25a3865b21b8988e..b8d47022b4d00cf4025904fee91ee3dba232a59c 100644 --- a/src/client/src/tscGlobalmerge.c +++ b/src/client/src/tscGlobalmerge.c @@ -819,7 +819,7 @@ SSDataBlock* doMultiwayMergeSort(void* param, bool* newgroup) { pOneDataSrc->rowIdx, pIndex->colIndex); char *data = pInfo->prevRow[i]; - int32_t ret = columnValueAscendingComparator(data, newRow, pColInfo->info.type, pColInfo->info.bytes); + int32_t ret = columnValueAscendingComparator(data, newRow, pColInfo->info.type, pColInfo->info.bytes, true); if (ret == 0) { continue; } else { @@ -881,7 +881,7 @@ static bool isSameGroup(SArray* orderColumnList, SSDataBlock* pBlock, char** dat assert(pIndex->colId == pColInfo->info.colId); char *data = dataCols[i]; - int32_t ret = columnValueAscendingComparator(data, pColInfo->pData, pColInfo->info.type, pColInfo->info.bytes); + int32_t ret = columnValueAscendingComparator(data, pColInfo->pData, pColInfo->info.type, pColInfo->info.bytes, true); if (ret == 0) { continue; } else { @@ -1067,7 +1067,7 @@ static int32_t doSlimitImpl(SOperatorInfo* pOperator, SSLimitOperatorInfo* pInfo SColumnInfo *pColInfo = &pColInfoData->info; char *d = rowIndex * pColInfo->bytes + (char *)pColInfoData->pData; - int32_t ret = columnValueAscendingComparator(pInfo->prevRow[i], d, pColInfo->type, pColInfo->bytes); + int32_t ret = columnValueAscendingComparator(pInfo->prevRow[i], d, pColInfo->type, pColInfo->bytes, true); if (ret != 0) { // it is a new group samegroup = false; break; diff --git a/src/client/src/tscLocal.c b/src/client/src/tscLocal.c index f648baa9744cf00545e3f96b736661dce6e958e0..81d658d964dc2a404e04f363751e0a17ebe6e46f 100644 --- a/src/client/src/tscLocal.c +++ b/src/client/src/tscLocal.c @@ -240,6 +240,18 @@ static int32_t tscGetNthFieldResult(TAOS_ROW row, TAOS_FIELD* fields, int *lengt case TSDB_DATA_TYPE_BIGINT: sprintf(result, "%"PRId64, *((int64_t *)val)); break; + case TSDB_DATA_TYPE_UTINYINT: + sprintf(result, "%u", *((uint8_t *)val)); + break; + case TSDB_DATA_TYPE_USMALLINT: + sprintf(result, "%u", *((uint16_t *)val)); + break; + case TSDB_DATA_TYPE_UINT: + sprintf(result, "%u", *((uint32_t *)val)); + break; + case TSDB_DATA_TYPE_UBIGINT: + sprintf(result, "%"PRIu64, *((uint64_t *)val)); + break; case TSDB_DATA_TYPE_FLOAT: sprintf(result, "%f", GET_FLOAT_VAL(val)); break; diff --git a/src/client/src/tscParseInsert.c b/src/client/src/tscParseInsert.c index c5719dde276abecd667efc95a960ab1a45af6962..af8c6837219cc32e22491427f04a19f70a8e50b0 100644 --- a/src/client/src/tscParseInsert.c +++ b/src/client/src/tscParseInsert.c @@ -1068,7 +1068,7 @@ static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql, char** boundC tfree(tmp); return tscSQLSyntaxErrMsg(pInsertParam->msg, "json tag too long", NULL); } - code = parseJsontoTagData(sToken.z, &kvRowBuilder, pInsertParam->msg, pTagSchema[spd.boundedColumns[0]].colId); + code = parseJsontoTagData(sToken.z, sToken.n, &kvRowBuilder, pInsertParam->msg, pTagSchema[spd.boundedColumns[0]].colId); if (code != TSDB_CODE_SUCCESS) { tdDestroyKVRowBuilder(&kvRowBuilder); tscDestroyBoundColumnInfo(&spd); diff --git a/src/client/src/tscParseLineProtocol.c b/src/client/src/tscParseLineProtocol.c index 5d1173e8cf3859403c765a514c07120cb0f18ba7..93cdd1ab99e48ce5a6ff75f8284031d30c58640a 100644 --- a/src/client/src/tscParseLineProtocol.c +++ b/src/client/src/tscParseLineProtocol.c @@ -177,10 +177,10 @@ static int32_t getSmlMd5ChildTableName(TAOS_SML_DATA_POINT* point, char* tableNa } size_t len = 0; char* keyJoined = taosStringBuilderGetResult(&sb, &len); - MD5_CTX context; - MD5Init(&context); - MD5Update(&context, (uint8_t *)keyJoined, (uint32_t)len); - MD5Final(&context); + T_MD5_CTX context; + tMD5Init(&context); + tMD5Update(&context, (uint8_t *)keyJoined, (uint32_t)len); + tMD5Final(&context); uint64_t digest1 = *(uint64_t*)(context.digest); uint64_t digest2 = *(uint64_t*)(context.digest + 8); *tableNameLen = snprintf(tableName, *tableNameLen, @@ -2140,64 +2140,331 @@ static int32_t parseSmlKey(TAOS_SML_KV *pKV, const char **index, SHashObj *pHash static int32_t parseSmlValue(TAOS_SML_KV *pKV, const char **index, bool *is_last_kv, SSmlLinesInfo* info, bool isTag) { - const char *start, *cur, *tmp; - int32_t ret = TSDB_CODE_SUCCESS; - char *value = NULL; - int16_t len = 0; - bool searchQuote = false; - start = cur = *index; + const char *start, *cur; + int32_t ret = TSDB_CODE_SUCCESS; + char *value = NULL; + int16_t len = 0; + + bool kv_done = false; + bool back_slash = false; + bool double_quote = false; + size_t line_len = 0; + + enum { + tag_common, + tag_lqoute, + tag_rqoute + } tag_state; + + enum { + val_common, + val_lqoute, + val_rqoute + } val_state; - //if field value is string - if (!isTag) { - if (*cur == '"') { - searchQuote = true; - cur += 1; - len += 1; - } else if (*cur == 'L' && *(cur + 1) == '"') { - searchQuote = true; - cur += 2; - len += 2; - } - } + start = cur = *index; + tag_state = tag_common; + val_state = val_common; while (1) { - // unescaped ',' or ' ' or '\0' identifies a value - if (((*cur == ',' || *cur == ' ' ) && *(cur - 1) != '\\') || *cur == '\0') { - if (searchQuote == true) { - //first quote ignored while searching - if (*(cur - 1) == '"' && len != 1 && len != 2) { - *is_last_kv = (*cur == ' ' || *cur == '\0') ? true : false; + if (isTag) { + /* ',', '=' and spaces MUST be escaped */ + switch (tag_state) { + case tag_common: + if (back_slash == true) { + if (*cur != ',' && *cur != '=' && *cur != ' ') { + tscError("SML:0x%"PRIx64" tag value: state(%d), incorrect character(%c) escaped", info->id, tag_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + + back_slash = false; + cur++; + len++; + break; + } + + if (*cur == '"') { + if (cur == *index) { + tag_state = tag_lqoute; + } + cur += 1; + len += 1; + break; + } else if (*cur == 'L') { + line_len = strlen(*index); + + /* common character at the end */ + if (cur + 1 >= *index + line_len) { + *is_last_kv = true; + kv_done = true; + break; + } + + if (*(cur + 1) == '"') { + /* string starts here */ + if (cur + 1 == *index + 1) { + tag_state = tag_lqoute; + } + cur += 2; + len += 2; + break; + } + } + + switch (*cur) { + case '\\': + back_slash = true; + cur++; + len++; + break; + case ',': + kv_done = true; + break; + + case ' ': + /* fall through */ + case '\0': + *is_last_kv = true; + kv_done = true; break; - } else if (*cur == '\0') { + + default: + cur++; + len++; + } + + break; + case tag_lqoute: + if (back_slash == true) { + if (*cur != ',' && *cur != '=' && *cur != ' ') { + tscError("SML:0x%"PRIx64" tag value: state(%d), incorrect character(%c) escaped", info->id, tag_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + + back_slash = false; + cur++; + len++; + break; + } else if (double_quote == true) { + if (*cur != ' ' && *cur != ',' && *cur != '\0') { + tscError("SML:0x%"PRIx64" tag value: state(%d), incorrect character(%c) behind closing \"", info->id, tag_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + + if (*cur == ' ' || *cur == '\0') { + *is_last_kv = true; + } + + double_quote = false; + tag_state = tag_rqoute; + break; + } + + switch (*cur) { + case '\\': + back_slash = true; + cur++; + len++; + break; + + case '"': + double_quote = true; + cur++; + len++; + break; + + case ',': + /* fall through */ + case '=': + /* fall through */ + case ' ': + if (*(cur - 1) != '\\') { + tscError("SML:0x%"PRIx64" tag value: state(%d), character(%c) not escaped", info->id, tag_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + kv_done = true; + } + break; + + case '\0': + tscError("SML:0x%"PRIx64" tag value: state(%d), closing \" not found", info->id, tag_state); ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; - goto error; - } else { + kv_done = true; + break; + + default: cur++; len++; - continue; } + + break; + + default: + kv_done = true; } - //unescaped ' ' or '\0' indicates end of value - *is_last_kv = (*cur == ' ' || *cur == '\0') ? true : false; - if (*cur == ' ' && *(cur + 1) == ' ') { - cur++; - continue; - } else { + } else { + switch (val_state) { + case val_common: + if (back_slash == true) { + if (*cur != '\\' && *cur != '"') { + tscError("SML:0x%"PRIx64" field value: state(%d), incorrect character(%c) escaped", info->id, val_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + + back_slash = false; + cur++; + len++; + break; + } + + if (*cur == '"') { + if (cur == *index) { + val_state = val_lqoute; + } else { + if (*(cur - 1) != '\\') { + tscError("SML:0x%"PRIx64" field value: state(%d), \" not escaped", info->id, val_state); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + } + + cur += 1; + len += 1; + break; + } else if (*cur == 'L') { + line_len = strlen(*index); + + /* common character at the end */ + if (cur + 1 >= *index + line_len) { + *is_last_kv = true; + kv_done = true; + break; + } + + if (*(cur + 1) == '"') { + /* string starts here */ + if (cur + 1 == *index + 1) { + val_state = val_lqoute; + cur += 2; + len += 2; + } else { + /* MUST at the end of string */ + if (cur + 2 >= *index + line_len) { + cur += 2; + len += 2; + *is_last_kv = true; + kv_done = true; + } else { + if (*(cur + 2) != ' ' && *(cur + 2) != ',') { + tscError("SML:0x%"PRIx64" field value: state(%d), not closing character(L\")", info->id, val_state); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } else { + if (*(cur + 2) == ' ') { + *is_last_kv = true; + } + + cur += 2; + len += 2; + kv_done = true; + } + } + } + break; + } + } + + switch (*cur) { + case '\\': + back_slash = true; + cur++; + len++; + break; + + case ',': + kv_done = true; + break; + + case ' ': + /* fall through */ + case '\0': + *is_last_kv = true; + kv_done = true; + break; + + default: + cur++; + len++; + } + break; + case val_lqoute: + if (back_slash == true) { + if (*cur != '\\' && *cur != '"') { + tscError("SML:0x%"PRIx64" field value: state(%d), incorrect character(%c) escaped", info->id, val_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + + back_slash = false; + cur++; + len++; + break; + } else if (double_quote == true) { + if (*cur != ' ' && *cur != ',' && *cur != '\0') { + tscError("SML:0x%"PRIx64" field value: state(%d), incorrect character(%c) behind closing \"", info->id, val_state, *cur); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + goto error; + } + + if (*cur == ' ' || *cur == '\0') { + *is_last_kv = true; + } + + double_quote = false; + val_state = val_rqoute; + break; + } + + switch (*cur) { + case '\\': + back_slash = true; + cur++; + len++; + break; + + case '"': + double_quote = true; + cur++; + len++; + break; + + case '\0': + tscError("SML:0x%"PRIx64" field value: state(%d), closing \" not found", info->id, val_state); + ret = TSDB_CODE_TSC_LINE_SYNTAX_ERROR; + kv_done = true; + break; + + default: + cur++; + len++; + } + + break; + default: + kv_done = true; } } - //Escape special character - if (*cur == '\\') { - tmp = cur; - escapeSpecialCharacter(isTag ? 2 : 3, &cur); - if (tmp != cur) { - continue; - } + + if (kv_done == true) { + break; } - cur++; - len++; } - if (len == 0) { + + if (len == 0 || ret != TSDB_CODE_SUCCESS) { free(pKV->key); pKV->key = NULL; return TSDB_CODE_TSC_LINE_SYNTAX_ERROR; diff --git a/src/client/src/tscSQLParser.c b/src/client/src/tscSQLParser.c index 4fd814ee72cd3735485af1b55410ae9e0bc97c55..3f39ffb83ce19cb029c69ecbdacbb8b1bff611c3 100644 --- a/src/client/src/tscSQLParser.c +++ b/src/client/src/tscSQLParser.c @@ -51,7 +51,7 @@ #define COLUMN_INDEX_INITIAL_VAL (-2) #define COLUMN_INDEX_INITIALIZER \ { COLUMN_INDEX_INITIAL_VAL, COLUMN_INDEX_INITIAL_VAL } -#define COLUMN_INDEX_VALIDE(index) (((index).tableIndex >= 0) && ((index).columnIndex >= TSDB_TBNAME_COLUMN_INDEX)) +#define COLUMN_INDEX_VALID(index) (((index).tableIndex >= 0) && ((index).columnIndex >= TSDB_MIN_VALID_COLUMN_INDEX)) #define TBNAME_LIST_SEP "," typedef struct SColumnList { // todo refactor @@ -98,7 +98,7 @@ static int32_t parseIntervalOffset(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SStrTo static int32_t parseSlidingClause(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SStrToken* pSliding); static int32_t validateStateWindowNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSqlNode, bool isStable); -static int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, tSqlExprItem* pItem, bool outerQuery); +static int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, tSqlExprItem* pItem, bool outerQuery, bool timeWindowQuery); static int32_t validateWhereNode(SQueryInfo* pQueryInfo, tSqlExpr** pExpr, SSqlObj* pSql, bool joinQuery); static int32_t validateFillNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSqlNode); @@ -1113,7 +1113,7 @@ static int32_t addPrimaryTsColumnForTimeWindowQuery(SQueryInfo* pQueryInfo, SSql static int32_t checkInvalidExprForTimeWindow(SSqlCmd* pCmd, SQueryInfo* pQueryInfo) { const char* msg1 = "invalid query expression"; const char* msg2 = "top/bottom query does not support order by value in time window query"; - const char* msg3 = "unique function does not supportted in time window query"; + const char* msg3 = "unique/state function does not supportted in time window query"; /* * invalid sql: @@ -1125,7 +1125,8 @@ static int32_t checkInvalidExprForTimeWindow(SSqlCmd* pCmd, SQueryInfo* pQueryIn if (pExpr->base.functionId == TSDB_FUNC_COUNT && TSDB_COL_IS_TAG(pExpr->base.colInfo.flag)) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1); } - if (pExpr->base.functionId == TSDB_FUNC_UNIQUE) { + if (pExpr->base.functionId == TSDB_FUNC_UNIQUE || pExpr->base.functionId == TSDB_FUNC_STATE_COUNT || + pExpr->base.functionId == TSDB_FUNC_STATE_DURATION) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg3); } } @@ -1848,8 +1849,6 @@ static int32_t handleScalarTypeExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32 } } - // expr string is set as the parameter of function - SColumnIndex index = {.tableIndex = tableIndex}; tExprNode* pNode = NULL; SArray* colList = taosArrayInit(10, sizeof(SColIndex)); @@ -1888,9 +1887,11 @@ static int32_t handleScalarTypeExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32 return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); } - + SColumnIndex index = {.tableIndex = tableIndex}; SExprInfo* pExpr = tscExprAppend(pQueryInfo, TSDB_FUNC_SCALAR_EXPR, &index, pNode->resultType, pNode->resultBytes, getNewResColId(pCmd), 0, false); + // set the colId to the result column id + pExpr->base.colInfo.colId = pExpr->base.resColId; char* name = (pItem->aliasName != NULL)? pItem->aliasName:pItem->pNode->exprToken.z; size_t len = MIN(sizeof(pExpr->base.aliasName), pItem->pNode->exprToken.n + 1); @@ -2261,7 +2262,7 @@ int32_t validateSelectNodeList(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pS (type == SQL_NODE_EXPR && pItem->pNode->tokenId == TK_ARROW)) { // use the dynamic array list to decide if the function is valid or not // select table_name1.field_name1, table_name2.field_name2 from table_name1, table_name2 - if (addProjectionExprAndResultField(pCmd, pQueryInfo, pItem, outerQuery) != TSDB_CODE_SUCCESS) { + if (addProjectionExprAndResultField(pCmd, pQueryInfo, pItem, outerQuery, timeWindowQuery) != TSDB_CODE_SUCCESS) { return TSDB_CODE_TSC_INVALID_OPERATION; } } else { @@ -2404,13 +2405,14 @@ static int32_t doAddProjectionExprAndResultFields(SQueryInfo* pQueryInfo, SColum return numOfTotalColumns; } -int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, tSqlExprItem* pItem, bool outerQuery) { +int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, tSqlExprItem* pItem, bool outerQuery, bool timeWindowQuery) { const char* msg1 = "tag for normal table query is not allowed"; const char* msg2 = "invalid column name"; - const char* msg3 = "tbname not allowed in outer query"; + const char* msg3 = "tbname/_wstart/_wstop/_wduration/_qstart/_qstop/_qduration in outer query does not match inner query result"; const char* msg4 = "-> operate can only used in json type"; const char* msg5 = "the right value of -> operation must be string"; const char* msg6 = "select name is too long than 64, please use alias name"; + const char* msg7 = "_wstart/_wstop/_wduraion can only be applied to time window query"; int32_t startPos = (int32_t)tscNumOfExprs(pQueryInfo); int32_t tokenId = pItem->pNode->tokenId; @@ -2476,7 +2478,8 @@ int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, t return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); } - if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) { + //for tbname and other pseudo columns + if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX || TSDB_COL_IS_TSWIN_COL(index.columnIndex)) { if (outerQuery) { STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, index.tableIndex); int32_t numOfCols = tscGetNumOfColumns(pTableMetaInfo->pTableMeta); @@ -2484,7 +2487,20 @@ int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, t bool existed = false; SSchema* pSchema = pTableMetaInfo->pTableMeta->schema; for (int32_t i = 0; i < numOfCols; ++i) { - if (strncasecmp(pSchema[i].name, TSQL_TBNAME_L, tListLen(pSchema[i].name)) == 0) { + if ((strncasecmp(pSchema[i].name, TSQL_TBNAME_L, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) || + (strncasecmp(pSchema[i].name, TSQL_TSWIN_START, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_TSWIN_START_COLUMN_INDEX) || + (strncasecmp(pSchema[i].name, TSQL_TSWIN_STOP, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_TSWIN_STOP_COLUMN_INDEX) || + (strncasecmp(pSchema[i].name, TSQL_TSWIN_DURATION, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_TSWIN_DURATION_COLUMN_INDEX) || + (strncasecmp(pSchema[i].name, TSQL_QUERY_START, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_QUERY_START_COLUMN_INDEX) || + (strncasecmp(pSchema[i].name, TSQL_QUERY_STOP, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_QUERY_STOP_COLUMN_INDEX) || + (strncasecmp(pSchema[i].name, TSQL_QUERY_DURATION, tListLen(pSchema[i].name)) == 0 && + index.columnIndex == TSDB_QUERY_DURATION_COLUMN_INDEX)) { existed = true; index.columnIndex = i; break; @@ -2503,13 +2519,28 @@ int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, t /*SExprInfo* pExpr = */ tscAddFuncInSelectClause(pQueryInfo, startPos, TSDB_FUNC_PRJ, &index, &colSchema, TSDB_COL_NORMAL, getNewResColId(pCmd)); } else { - SSchema colSchema = *tGetTbnameColumnSchema(); - char name[TSDB_COL_NAME_LEN] = {0}; + SSchema colSchema; + int16_t functionId, colType; + if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) { + colSchema = *tGetTbnameColumnSchema(); + functionId = TSDB_FUNC_TAGPRJ; + colType = TSDB_COL_TAG; + } else { + if (!timeWindowQuery && (index.columnIndex == TSDB_TSWIN_START_COLUMN_INDEX || + index.columnIndex == TSDB_TSWIN_STOP_COLUMN_INDEX || + index.columnIndex == TSDB_TSWIN_DURATION_COLUMN_INDEX)) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg7); + } + colSchema = *tGetTimeWindowColumnSchema(index.columnIndex); + functionId = getTimeWindowFunctionID(index.columnIndex); + colType = TSDB_COL_NORMAL; + } + char name[TSDB_COL_NAME_LEN] = {0}; getColumnName(pItem, name, colSchema.name, sizeof(colSchema.name) - 1); tstrncpy(colSchema.name, name, TSDB_COL_NAME_LEN); - /*SExprInfo* pExpr = */ tscAddFuncInSelectClause(pQueryInfo, startPos, TSDB_FUNC_TAGPRJ, &index, &colSchema, - TSDB_COL_TAG, getNewResColId(pCmd)); + /*SExprInfo* pExpr = */ tscAddFuncInSelectClause(pQueryInfo, startPos, functionId, &index, &colSchema, + colType, getNewResColId(pCmd)); } pQueryInfo->type |= TSDB_QUERY_TYPE_PROJECTION_QUERY; } else { @@ -2695,6 +2726,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col const char* msg28 = "the second paramter of diff should be 0 or 1"; const char* msg29 = "key timestamp column cannot be used to unique/mode/tail function"; const char* msg30 = "offset is out of range [0, 100]"; + const char* msg31 = "state function can not be used in subquery"; switch (functionId) { case TSDB_FUNC_COUNT: { @@ -2793,7 +2825,10 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col case TSDB_FUNC_STDDEV: case TSDB_FUNC_LEASTSQR: case TSDB_FUNC_ELAPSED: - case TSDB_FUNC_MODE: { + case TSDB_FUNC_MODE: + case TSDB_FUNC_STATE_COUNT: + case TSDB_FUNC_STATE_DURATION: + case TSDB_FUNC_HYPERLOGLOG:{ // 1. valid the number of parameters int32_t numOfParams = (pItem->pNode->Expr.paramList == NULL) ? 0 : (int32_t)taosArrayGetSize(pItem->pNode->Expr.paramList); @@ -2801,10 +2836,12 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col // no parameters or more than one parameter for function if (pItem->pNode->Expr.paramList == NULL || (functionId != TSDB_FUNC_LEASTSQR && functionId != TSDB_FUNC_DERIVATIVE && functionId != TSDB_FUNC_ELAPSED && - functionId != TSDB_FUNC_DIFF && numOfParams != 1) || + functionId != TSDB_FUNC_DIFF && functionId != TSDB_FUNC_STATE_COUNT && functionId != TSDB_FUNC_STATE_DURATION && numOfParams != 1) || ((functionId == TSDB_FUNC_LEASTSQR || functionId == TSDB_FUNC_DERIVATIVE) && numOfParams != 3) || (functionId == TSDB_FUNC_ELAPSED && numOfParams != 1 && numOfParams != 2) || - (functionId == TSDB_FUNC_DIFF && numOfParams != 1 && numOfParams != 2)) { + (functionId == TSDB_FUNC_DIFF && numOfParams != 1 && numOfParams != 2) || + (functionId == TSDB_FUNC_STATE_COUNT && numOfParams != 3) || + (functionId == TSDB_FUNC_STATE_DURATION && numOfParams != 3 && numOfParams != 4)) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); } @@ -2843,6 +2880,11 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col } } + if ((functionId == TSDB_FUNC_STATE_COUNT || functionId == TSDB_FUNC_STATE_DURATION) && + pQueryInfo->pUpstream != NULL && taosArrayGetSize(pQueryInfo->pUpstream) > 0) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg31); + } + STableComInfo info = tscGetTableInfo(pTableMetaInfo->pTableMeta); // functions can not be applied to tags @@ -2857,7 +2899,8 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col if (functionId == TSDB_FUNC_MODE && pColumnSchema->colId == PRIMARYKEY_TIMESTAMP_COL_INDEX && pColumnSchema->type == TSDB_DATA_TYPE_TIMESTAMP){ return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg29); - } else if (!IS_NUMERIC_TYPE(pSchema->type) && (functionId != TSDB_FUNC_ELAPSED) && (functionId != TSDB_FUNC_MODE)) { + } else if (!IS_NUMERIC_TYPE(pSchema->type) && (functionId != TSDB_FUNC_ELAPSED) && + (functionId != TSDB_FUNC_MODE) && (functionId != TSDB_FUNC_HYPERLOGLOG)) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1); } else if (IS_UNSIGNED_NUMERIC_TYPE(pSchema->type) && (functionId == TSDB_FUNC_DIFF || functionId == TSDB_FUNC_DERIVATIVE)) { @@ -2885,6 +2928,24 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col aAggs[TSDB_FUNC_TS_DUMMY].name, pExpr); } + if (functionId == TSDB_FUNC_STATE_COUNT || functionId == TSDB_FUNC_STATE_DURATION) { + SColumnIndex indexTS = {.tableIndex = index.tableIndex, .columnIndex = 0}; + SExprInfo* pExpr = tscExprAppend(pQueryInfo, TSDB_FUNC_PRJ, &indexTS, TSDB_DATA_TYPE_TIMESTAMP, + TSDB_KEYSIZE, 0, TSDB_KEYSIZE, false); + tstrncpy(pExpr->base.aliasName, aAggs[TSDB_FUNC_TS_DUMMY].name, sizeof(pExpr->base.aliasName)); + + SColumnList ids = createColumnList(1, 0, 0); + insertResultField(pQueryInfo, colIndex, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, + aAggs[TSDB_FUNC_TS].name, pExpr); + + pExpr = tscExprAppend(pQueryInfo, TSDB_FUNC_PRJ, &index, pSchema->type, + pSchema->bytes, getNewResColId(pCmd), 0, false); + tstrncpy(pExpr->base.aliasName, pParamElem->pNode->columnName.z, pParamElem->pNode->columnName.n+1); + ids = createColumnList(1, index.tableIndex, index.columnIndex); + insertResultField(pQueryInfo, colIndex + 1, &ids, pExpr->base.resBytes, (int32_t)pExpr->base.resType, + pExpr->base.aliasName, pExpr); + } + SExprInfo* pExpr = tscExprAppend(pQueryInfo, functionId, &index, resultType, resultSize, getNewResColId(pCmd), intermediateResSize, false); @@ -2963,6 +3024,41 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col } } tscExprAddParams(&pExpr->base, val, TSDB_DATA_TYPE_BIGINT, sizeof(int64_t)); + } else if (functionId == TSDB_FUNC_STATE_COUNT || functionId == TSDB_FUNC_STATE_DURATION) { + if (pParamElem[1].pNode->tokenId != TK_ID || !isValidStateOper(pParamElem[1].pNode->columnName.z, pParamElem[1].pNode->columnName.n)) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); + } + tscExprAddParams(&pExpr->base, pParamElem[1].pNode->columnName.z, TSDB_DATA_TYPE_BINARY, pParamElem[1].pNode->columnName.n); + + if (pParamElem[2].pNode->tokenId != TK_INTEGER && pParamElem[2].pNode->tokenId != TK_FLOAT) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); + } + tVariantAssign(&pExpr->base.param[pExpr->base.numOfParams++], &pParamElem[2].pNode->value); + + if (functionId == TSDB_FUNC_STATE_DURATION){ + if (numOfParams == 4) { + // unit must be 1s 1m 1h + if (pParamElem[3].pNode->tokenId != TK_TIMESTAMP || (pParamElem[3].pNode->value.i64 != MILLISECOND_PER_SECOND * 1000000L && + pParamElem[3].pNode->value.i64 != MILLISECOND_PER_MINUTE * 1000000L && pParamElem[3].pNode->value.i64 != MILLISECOND_PER_HOUR * 1000000L)) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); + } + if (info.precision == TSDB_TIME_PRECISION_MILLI) { + pParamElem[3].pNode->value.i64 /= TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_MICRO); + } else if (info.precision == TSDB_TIME_PRECISION_MICRO) { + pParamElem[3].pNode->value.i64 /= TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_MILLI); + } + + tVariantAssign(&pExpr->base.param[pExpr->base.numOfParams++], &pParamElem[3].pNode->value); + }else{ + int64_t tmp = TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_NANO); + if (info.precision == TSDB_TIME_PRECISION_MILLI) { + tmp /= TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_MICRO); + } else if (info.precision == TSDB_TIME_PRECISION_MICRO) { + tmp /= TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_MILLI); + } + tscExprAddParams(&pExpr->base, (char *)&tmp, TSDB_DATA_TYPE_BIGINT, sizeof(tmp)); + } + } } SColumnList ids = createColumnList(1, index.tableIndex, index.columnIndex); @@ -2987,7 +3083,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col case TSDB_FUNC_LAST: case TSDB_FUNC_SPREAD: case TSDB_FUNC_LAST_ROW: - case TSDB_FUNC_INTERP: { + case TSDB_FUNC_INTERP: { // link to TD-14196, if add FUNC in this place, please search TD-14196, because there are connection in exprTreeFromSqlExpr bool requireAllFields = (pItem->pNode->Expr.paramList == NULL); // NOTE: has time range condition or normal column filter condition, the last_row query will be transferred to last query @@ -3263,14 +3359,20 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col } else { tVariantDump(pVariant, val, TSDB_DATA_TYPE_BIGINT, true); + if(functionId == TSDB_FUNC_UNIQUE){ // consider of memory size + if(pSchema->bytes < 10){ + GET_INT64_VAL(val) = MAX_UNIQUE_RESULT_ROWS * 100; + }else if(pSchema->bytes < 100){ + GET_INT64_VAL(val) = MAX_UNIQUE_RESULT_ROWS * 10; + }else{ + GET_INT64_VAL(val) = MAX_UNIQUE_RESULT_ROWS; + } + } + int64_t numRowsSelected = GET_INT64_VAL(val); if (functionId != TSDB_FUNC_UNIQUE && (numRowsSelected <= 0 || numRowsSelected > 100)) { // todo use macro return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg12); } - - if(functionId == TSDB_FUNC_UNIQUE){ - GET_INT64_VAL(val) = MAX_UNIQUE_RESULT_ROWS; - } // todo REFACTOR // set the first column ts for top/bottom query SColumnIndex index1 = {index.tableIndex, PRIMARYKEY_TIMESTAMP_COL_INDEX}; @@ -3283,9 +3385,10 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col aAggs[TSDB_FUNC_TS].name, pExpr); colIndex += 1; // the first column is ts - + getResultDataInfo(pSchema->type, pSchema->bytes, functionId, (int32_t)numRowsSelected, &resultType, + &resultSize, &interResult, 0, false, pUdfInfo); pExpr = tscExprAppend(pQueryInfo, functionId, &index, resultType, resultSize, getNewResColId(pCmd), - resultSize, false); + interResult, false); if (functionId == TSDB_FUNC_TAIL){ int64_t offset = 0; if (taosArrayGetSize(pItem->pNode->Expr.paramList) == 3){ @@ -3486,7 +3589,7 @@ int32_t addExprAndResultField(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, int32_t col } pVariant = &pParamElem[2].pNode->value; - if (pVariant == NULL && pVariant->nType != TSDB_DATA_TYPE_BINARY) { + if (pVariant == NULL || pVariant->nType != TSDB_DATA_TYPE_BINARY) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg2); } @@ -3753,6 +3856,34 @@ static bool isTablenameToken(SStrToken* token) { return (tmpToken.n == strlen(TSQL_TBNAME_L) && strncasecmp(TSQL_TBNAME_L, tmpToken.z, tmpToken.n) == 0); } +static bool isTimeWindowToken(SStrToken* token, int16_t *columnIndex) { + SStrToken tmpToken = *token; + SStrToken tableToken = {0}; + + extractTableNameFromToken(&tmpToken, &tableToken); + if (tmpToken.n == strlen(TSQL_TSWIN_START) && strncasecmp(TSQL_TSWIN_START, tmpToken.z, tmpToken.n) == 0) { + *columnIndex = TSDB_TSWIN_START_COLUMN_INDEX; + return true; + } else if (tmpToken.n == strlen(TSQL_TSWIN_STOP) && strncasecmp(TSQL_TSWIN_STOP, tmpToken.z, tmpToken.n) == 0) { + *columnIndex = TSDB_TSWIN_STOP_COLUMN_INDEX; + return true; + } else if (tmpToken.n == strlen(TSQL_TSWIN_DURATION) && strncasecmp(TSQL_TSWIN_DURATION, tmpToken.z, tmpToken.n) == 0) { + *columnIndex = TSDB_TSWIN_DURATION_COLUMN_INDEX; + return true; + } else if (tmpToken.n == strlen(TSQL_QUERY_START) && strncasecmp(TSQL_QUERY_START, tmpToken.z, tmpToken.n) == 0) { + *columnIndex = TSDB_QUERY_START_COLUMN_INDEX; + return true; + } else if (tmpToken.n == strlen(TSQL_QUERY_STOP) && strncasecmp(TSQL_QUERY_STOP, tmpToken.z, tmpToken.n) == 0) { + *columnIndex = TSDB_QUERY_STOP_COLUMN_INDEX; + return true; + } else if (tmpToken.n == strlen(TSQL_QUERY_DURATION) && strncasecmp(TSQL_QUERY_DURATION, tmpToken.z, tmpToken.n) == 0) { + *columnIndex = TSDB_QUERY_DURATION_COLUMN_INDEX; + return true; + } else { + return false; + } +} + static int16_t doGetColumnIndex(SQueryInfo* pQueryInfo, int32_t index, SStrToken* pToken) { STableMeta* pTableMeta = tscGetMetaInfo(pQueryInfo, index)->pTableMeta; @@ -3789,11 +3920,14 @@ int32_t doGetColumnIndexByName(SStrToken* pToken, SQueryInfo* pQueryInfo, SColum return TSDB_CODE_TSC_INVALID_OPERATION; } + int16_t tsWinColumnIndex; if (isTablenameToken(pToken)) { pIndex->columnIndex = TSDB_TBNAME_COLUMN_INDEX; } else if (strlen(DEFAULT_PRIMARY_TIMESTAMP_COL_NAME) == pToken->n && strncasecmp(pToken->z, DEFAULT_PRIMARY_TIMESTAMP_COL_NAME, pToken->n) == 0) { pIndex->columnIndex = PRIMARYKEY_TIMESTAMP_COL_INDEX; // just make runtime happy, need fix java test case InsertSpecialCharacterJniTest + } else if (isTimeWindowToken(pToken, &tsWinColumnIndex)) { + pIndex->columnIndex = tsWinColumnIndex; } else { // not specify the table name, try to locate the table index by column name if (pIndex->tableIndex == COLUMN_INDEX_INITIAL_VAL) { @@ -3821,7 +3955,7 @@ int32_t doGetColumnIndexByName(SStrToken* pToken, SQueryInfo* pQueryInfo, SColum } } - if (COLUMN_INDEX_VALIDE(*pIndex)) { + if (COLUMN_INDEX_VALID(*pIndex)) { return TSDB_CODE_SUCCESS; } else { return TSDB_CODE_TSC_INVALID_OPERATION; @@ -4038,7 +4172,8 @@ int32_t tscTansformFuncForSTableQuery(SQueryInfo* pQueryInfo) { (functionId == TSDB_FUNC_HISTOGRAM) || (functionId == TSDB_FUNC_UNIQUE) || (functionId == TSDB_FUNC_MODE) || - (functionId == TSDB_FUNC_TAIL)) { + (functionId == TSDB_FUNC_TAIL) || + (functionId == TSDB_FUNC_HYPERLOGLOG)) { if (getResultDataInfo(pSrcSchema->type, pSrcSchema->bytes, functionId, (int32_t)pExpr->base.param[0].i64, &type, &bytes, &interBytes, 0, true, NULL) != TSDB_CODE_SUCCESS) { return TSDB_CODE_TSC_INVALID_OPERATION; @@ -4187,6 +4322,7 @@ static bool functionCompatibleCheck(SQueryInfo* pQueryInfo, bool joinQuery, bool int32_t scalarFuncNum = 0; int32_t funcCompatFactor = INT_MAX; int32_t countTbname = 0; + int32_t queryWinNum = 0; size_t numOfExpr = tscNumOfExprs(pQueryInfo); assert(numOfExpr > 0); @@ -4196,7 +4332,7 @@ static bool functionCompatibleCheck(SQueryInfo* pQueryInfo, bool joinQuery, bool // diff function cannot be executed with other function // arithmetic function can be executed with other arithmetic functions size_t size = tscNumOfExprs(pQueryInfo); - + for (int32_t i = startIdx; i < size; ++i) { SExprInfo* pExpr1 = tscExprGet(pQueryInfo, i); @@ -4226,6 +4362,10 @@ static bool functionCompatibleCheck(SQueryInfo* pQueryInfo, bool joinQuery, bool ++scalarFuncNum; } + if (functionId == TSDB_FUNC_QSTART || functionId == TSDB_FUNC_QSTOP || functionId == TSDB_FUNC_QDURATION) { + ++queryWinNum; + } + if (functionId == TSDB_FUNC_PRJ && (pExpr1->base.colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX || TSDB_COL_IS_UD_COL(pExpr1->base.colInfo.flag))) { continue; } @@ -4257,7 +4397,7 @@ static bool functionCompatibleCheck(SQueryInfo* pQueryInfo, bool joinQuery, bool } } - aggNum = (int32_t)size - prjNum - scalarFuncNum - aggUdf - scalarUdf - countTbname; + aggNum = (int32_t)size - prjNum - scalarFuncNum - aggUdf - scalarUdf - countTbname - queryWinNum; assert(aggNum >= 0); @@ -6716,7 +6856,7 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq const char* msg8 = "only column in groupby clause allowed as order column"; const char* msg10 = "not support distinct mixed with order by"; const char* msg11 = "not support order with udf"; - const char* msg12 = "order by tags not supported with diff/derivative/csum/mavg"; + const char* msg12 = "order by tags not supported with diff/derivative/csum/mavg/stateCount/stateDuration"; const char* msg13 = "order by json tag, key is too long"; const char* msg14 = "order by json tag, must be json->'key'"; @@ -6915,7 +7055,7 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq return invalidOperationMsg(pMsgBuf, msg1); } - if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX && !isTopBottomUniqueQuery(pQueryInfo)) { + if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX && !isTopBottomUniqueQuery(pQueryInfo)){ bool validOrder = false; SArray *columnInfo = pQueryInfo->groupbyExpr.columnInfo; if (columnInfo != NULL && taosArrayGetSize(columnInfo) > 0) { @@ -6926,15 +7066,8 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq if (!validOrder) { return invalidOperationMsg(pMsgBuf, msg7); } - - if (udf) { - return invalidOperationMsg(pMsgBuf, msg11); - } - pQueryInfo->groupbyExpr.orderType = pItem->sortOrder; - } - - if (isTopBottomUniqueQuery(pQueryInfo)) { + }else if (isTopBottomUniqueQuery(pQueryInfo)) { SArray *columnInfo = pQueryInfo->groupbyExpr.columnInfo; if (columnInfo != NULL && taosArrayGetSize(columnInfo) > 0) { SColIndex* pColIndex = taosArrayGet(columnInfo, 0); @@ -6954,14 +7087,16 @@ int32_t validateOrderbyNode(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SSqlNode* pSq return invalidOperationMsg(pMsgBuf, msg5); } } + pQueryInfo->order.order = pItem->sortOrder; + pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId; + }else{ + pQueryInfo->order.order = pItem->sortOrder; + pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX; } if (udf) { return invalidOperationMsg(pMsgBuf, msg11); } - - pQueryInfo->order.order = pItem->sortOrder; - pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId; } else { // handle the temp table order by clause. You can order by any single column in case of the temp table, created by // inner subquery. @@ -7229,7 +7364,7 @@ int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) { int8_t tagVal = TSDB_DATA_JSON_PLACEHOLDER; tdAddColToKVRow(&kvRowBuilder, pTagsSchema->colId, pTagsSchema->type, &tagVal, false); - code = parseJsontoTagData(pItem->pVar.pz, &kvRowBuilder, pMsg, pTagsSchema->colId); + code = parseJsontoTagData(pItem->pVar.pz, pItem->pVar.nLen, &kvRowBuilder, pMsg, pTagsSchema->colId); if (code != TSDB_CODE_SUCCESS) { tdDestroyKVRowBuilder(&kvRowBuilder); return code; @@ -7526,7 +7661,8 @@ int32_t validateFunctionsInIntervalOrGroupbyQuery(SSqlCmd* pCmd, SQueryInfo* pQu int32_t f = pExpr->base.functionId; if ((f == TSDB_FUNC_PRJ && pExpr->base.numOfParams == 0) || f == TSDB_FUNC_DIFF || f == TSDB_FUNC_SCALAR_EXPR || f == TSDB_FUNC_DERIVATIVE || - f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG) + f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG || f == TSDB_FUNC_STATE_COUNT || + f == TSDB_FUNC_STATE_DURATION) { isProjectionFunction = true; break; @@ -7579,6 +7715,7 @@ int32_t validateDNodeConfig(SMiscInfo* pOptions) { const int tokenDebugFlag = 4; const int tokenDebugFlagEnd = 20; const int tokenOfflineInterval = 21; + const int tokenKeepTimeOffset = 22; const SDNodeDynConfOption cfgOptions[] = { {"resetLog", 8}, {"resetQueryCache", 15}, {"balance", 7}, {"monitor", 7}, {"debugFlag", 9}, {"monDebugFlag", 12}, {"vDebugFlag", 10}, {"mDebugFlag", 10}, @@ -7587,6 +7724,7 @@ int32_t validateDNodeConfig(SMiscInfo* pOptions) { {"dDebugFlag", 10}, {"mqttDebugFlag", 13}, {"wDebugFlag", 10}, {"tmrDebugFlag", 12}, {"cqDebugFlag", 11}, {"offlineInterval", 15}, + {"keepTimeOffset", 14}, }; SStrToken* pOptionToken = taosArrayGet(pOptions->a, 1); @@ -7626,6 +7764,14 @@ int32_t validateDNodeConfig(SMiscInfo* pOptions) { return TSDB_CODE_TSC_INVALID_OPERATION; // options value is invalid } return TSDB_CODE_SUCCESS; + } else if ((strncasecmp(cfgOptions[tokenKeepTimeOffset].name, pOptionToken->z, pOptionToken->n) == 0) && + (cfgOptions[tokenKeepTimeOffset].len == pOptionToken->n)) { + SStrToken* pValToken = taosArrayGet(pOptions->a, 2); + int32_t val = strtol(pValToken->z, NULL, 10); + if (val < -23 || val > 23) { + return TSDB_CODE_TSC_INVALID_OPERATION; // options value is invalid + } + return TSDB_CODE_SUCCESS; } else { SStrToken* pValToken = taosArrayGet(pOptions->a, 2); @@ -8146,6 +8292,7 @@ static int32_t checkUpdateTagPrjFunctions(SQueryInfo* pQueryInfo, char* msg) { int16_t numOfScalar = 0; int16_t numOfSelectivity = 0; int16_t numOfAggregation = 0; + int16_t numOfTimeWindow = 0; size_t numOfExprs = taosArrayGetSize(pQueryInfo->exprList); for (int32_t i = 0; i < numOfExprs; ++i) { @@ -8159,13 +8306,21 @@ static int32_t checkUpdateTagPrjFunctions(SQueryInfo* pQueryInfo, char* msg) { for (int32_t i = 0; i < numOfExprs; ++i) { SExprInfo* pExpr = taosArrayGetP(pQueryInfo->exprList, i); - + int16_t functionId = pExpr->base.functionId; if (functionId == TSDB_FUNC_TAGPRJ || functionId == TSDB_FUNC_PRJ || functionId == TSDB_FUNC_TS || - functionId == TSDB_FUNC_SCALAR_EXPR || functionId == TSDB_FUNC_TS_DUMMY) { + functionId == TSDB_FUNC_SCALAR_EXPR || functionId == TSDB_FUNC_TS_DUMMY || functionId == TSDB_FUNC_STATE_COUNT || + functionId == TSDB_FUNC_STATE_DURATION) { continue; } + if (isTimeWindowFunction(functionId)) { + numOfTimeWindow++; + if (functionId >= TSDB_FUNC_QSTART && functionId <= TSDB_FUNC_QDURATION) { + continue; + } + } + if (functionId < 0) { SUdfInfo* pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, -1 * functionId - 1); if (pUdfInfo->funcType == TSDB_UDF_TYPE_AGGREGATE) { @@ -8236,7 +8391,7 @@ static int32_t checkUpdateTagPrjFunctions(SQueryInfo* pQueryInfo, char* msg) { } } else { if ((pQueryInfo->type & TSDB_QUERY_TYPE_PROJECTION_QUERY) != 0) { - if (numOfAggregation > 0 && pQueryInfo->groupbyExpr.numOfGroupCols == 0) { + if (numOfAggregation > 0 && pQueryInfo->groupbyExpr.numOfGroupCols == 0 && numOfTimeWindow == 0) { return invalidOperationMsg(msg, msg2); } @@ -8365,12 +8520,11 @@ static int32_t doTagFunctionCheck(SQueryInfo* pQueryInfo) { int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* msg) { const char* msg1 = "functions/columns not allowed in group by query"; - const char* msg2 = "projection query on columns not allowed"; const char* msg3 = "group by/session/state_window not allowed on projection query"; const char* msg4 = "retrieve tags not compatible with group by or interval query"; const char* msg5 = "functions can not be mixed up"; - const char* msg6 = "TWA/Diff/Derivative/Irate/CSum/MAvg/Elapsed only support group by tbname"; - const char* msg7 = "unique function does not supportted in state window query"; + const char* msg6 = "TWA/Diff/Derivative/Irate/CSum/MAvg/Elapsed/stateCount/stateDuration only support group by tbname"; + const char* msg7 = "unique/state function does not supportted in state window query"; // only retrieve tags, group by is not supportted if (tscQueryTags(pQueryInfo)) { @@ -8403,31 +8557,11 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* SExprInfo* pExpr = tscExprGet(pQueryInfo, i); int32_t f = pExpr->base.functionId; - /* - * group by normal columns. - * Check if the column projection is identical to the group by column or not - */ - if (f == TSDB_FUNC_PRJ && pExpr->base.colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX) { - bool qualified = false; - for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) { - SColIndex* pColIndex = taosArrayGet(pQueryInfo->groupbyExpr.columnInfo, j); - if (pColIndex->colId == pExpr->base.colInfo.colId) { - qualified = true; - break; - } - } - - if (!qualified) { - return invalidOperationMsg(msg, msg2); - } - } - if (f < 0) { SUdfInfo* pUdfInfo = taosArrayGet(pQueryInfo->pUdfInfo, -1 * f - 1); if (pUdfInfo->funcType == TSDB_UDF_TYPE_SCALAR) { return invalidOperationMsg(msg, msg1); } - continue; } @@ -8437,7 +8571,8 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* } if ((!pQueryInfo->stateWindow) && (f == TSDB_FUNC_DIFF || f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || - f == TSDB_FUNC_IRATE || f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG || f == TSDB_FUNC_ELAPSED)) { + f == TSDB_FUNC_IRATE || f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG || f == TSDB_FUNC_ELAPSED || + f == TSDB_FUNC_STATE_COUNT || f == TSDB_FUNC_STATE_DURATION)) { for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) { SColIndex* pColIndex = taosArrayGet(pQueryInfo->groupbyExpr.columnInfo, j); if (j == 0) { @@ -8450,7 +8585,7 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* } } - if (pQueryInfo->stateWindow && f == TSDB_FUNC_UNIQUE){ + if (pQueryInfo->stateWindow && (f == TSDB_FUNC_UNIQUE || f == TSDB_FUNC_STATE_COUNT || f == TSDB_FUNC_STATE_DURATION)){ return invalidOperationMsg(msg, msg7); } @@ -8460,11 +8595,6 @@ int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, char* f != TSDB_FUNC_UNIQUE && f != TSDB_FUNC_TAIL) { return invalidOperationMsg(msg, msg1); } - - - if (f == TSDB_FUNC_COUNT && pExpr->base.colInfo.colIndex == TSDB_TBNAME_COLUMN_INDEX) { - return invalidOperationMsg(msg, msg1); - } } if (checkUpdateTagPrjFunctions(pQueryInfo, msg) != TSDB_CODE_SUCCESS) { @@ -8501,7 +8631,8 @@ int32_t validateFunctionFromUpstream(SQueryInfo* pQueryInfo, char* msg) { SExprInfo* pExpr = tscExprGet(pQueryInfo, i); int32_t f = pExpr->base.functionId; - if (f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || f == TSDB_FUNC_IRATE || f == TSDB_FUNC_DIFF || f == TSDB_FUNC_ELAPSED) { + if (f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || f == TSDB_FUNC_IRATE || f == TSDB_FUNC_DIFF || f == TSDB_FUNC_ELAPSED || + f == TSDB_FUNC_STATE_COUNT || f == TSDB_FUNC_STATE_DURATION) { for (int32_t j = 0; j < upNum; ++j) { SQueryInfo* pUp = taosArrayGetP(pQueryInfo->pUpstream, j); STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pUp, 0); @@ -9049,7 +9180,7 @@ int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg3); } - ret = parseJsontoTagData(pItem->pVar.pz, &kvRowBuilder, tscGetErrorMsgPayload(pCmd), pTagSchema[0].colId); + ret = parseJsontoTagData(pItem->pVar.pz, pItem->pVar.nLen, &kvRowBuilder, tscGetErrorMsgPayload(pCmd), pTagSchema[0].colId); if (ret != TSDB_CODE_SUCCESS) { tdDestroyKVRowBuilder(&kvRowBuilder); return ret; @@ -9498,12 +9629,23 @@ int32_t getHavingExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pSelectNode return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1); } + pLeft->functionId = isValidFunction(pLeft->Expr.operand.z, pLeft->Expr.operand.n); + if (pLeft->functionId < 0) { + return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1); + } + if (pLeft->Expr.paramList) { size_t size = taosArrayGetSize(pLeft->Expr.paramList); for (int32_t i = 0; i < size; i++) { tSqlExprItem* pParamItem = taosArrayGet(pLeft->Expr.paramList, i); - tSqlExpr* pExpr1 = pParamItem->pNode; + + if (pLeft->functionId == TSDB_FUNC_STATE_COUNT || pLeft->functionId == TSDB_FUNC_STATE_DURATION){ + if (i == 1 && pExpr1->tokenId == TK_ID) continue; + if (pLeft->functionId == TSDB_FUNC_STATE_DURATION && i == 3 && pExpr1->tokenId == TK_TIMESTAMP) + continue; + } + if (pExpr1->tokenId != TK_ALL && pExpr1->tokenId != TK_ID && pExpr1->tokenId != TK_STRING && @@ -9533,11 +9675,6 @@ int32_t getHavingExpr(SSqlCmd* pCmd, SQueryInfo* pQueryInfo, SArray* pSelectNode } } - pLeft->functionId = isValidFunction(pLeft->Expr.operand.z, pLeft->Expr.operand.n); - if (pLeft->functionId < 0) { - return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg1); - } - return handleExprInHavingClause(pCmd, pQueryInfo, pSelectNodeList, pExpr, parentOptr); } @@ -9986,7 +10123,7 @@ static STableMeta* extractTempTableMetaFromSubquery(SQueryInfo* pUpstream) { static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SSqlObj* pSql, SQueryInfo* pQueryInfo, char* msgBuf) { SRelElementPair* subInfo = taosArrayGet(pSqlNode->from->list, index); - // union all is not support currently + // union all is not supported currently SSqlNode* p = taosArrayGetP(subInfo->pSubquery, 0); if (taosArrayGetSize(subInfo->pSubquery) >= 2) { return invalidOperationMsg(msgBuf, "not support union in subquery"); @@ -10061,7 +10198,7 @@ int32_t validateSqlNode(SSqlObj* pSql, SSqlNode* pSqlNode, SQueryInfo* pQueryInf const char* msg4 = "interval query not supported, since the result of sub query not include valid timestamp column"; const char* msg5 = "only tag query not compatible with normal column filter"; const char* msg6 = "not support stddev/percentile in the outer query yet"; - const char* msg7 = "derivative/twa/rate/irate/diff/tail requires timestamp column exists in subquery"; + const char* msg7 = "derivative/twa/rate/irate/diff/tail/stateCount/stateDuration requires timestamp column exists in subquery"; const char* msg8 = "condition missing for join query"; const char* msg9 = "not support 3 level select"; @@ -10107,11 +10244,14 @@ int32_t validateSqlNode(SSqlObj* pSql, SSqlNode* pSqlNode, SQueryInfo* pQueryInf } int32_t timeWindowQuery = - (TPARSER_HAS_TOKEN(pSqlNode->interval.interval) || TPARSER_HAS_TOKEN(pSqlNode->sessionVal.gap)); - TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TABLE_QUERY); + (TPARSER_HAS_TOKEN(pSqlNode->interval.interval) || + TPARSER_HAS_TOKEN(pSqlNode->sessionVal.gap) || + TPARSER_HAS_TOKEN(pSqlNode->windowstateVal.col)); int32_t joinQuery = (pSqlNode->from != NULL && taosArrayGetSize(pSqlNode->from->list) > 1); + TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TABLE_QUERY); + // parse the group by clause in the first place if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pCmd) != TSDB_CODE_SUCCESS) { return TSDB_CODE_TSC_INVALID_OPERATION; @@ -10143,7 +10283,8 @@ int32_t validateSqlNode(SSqlObj* pSql, SSqlNode* pSqlNode, SQueryInfo* pQueryInf int32_t f = pExpr->base.functionId; if (f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_TWA || f == TSDB_FUNC_IRATE || - f == TSDB_FUNC_RATE || f == TSDB_FUNC_DIFF || f == TSDB_FUNC_TAIL) { + f == TSDB_FUNC_RATE || f == TSDB_FUNC_DIFF || f == TSDB_FUNC_TAIL || + f == TSDB_FUNC_STATE_COUNT || f == TSDB_FUNC_STATE_DURATION) { return invalidOperationMsg(tscGetErrorMsgPayload(pCmd), msg7); } } @@ -10268,7 +10409,9 @@ int32_t validateSqlNode(SSqlObj* pSql, SSqlNode* pSqlNode, SQueryInfo* pQueryInf } int32_t timeWindowQuery = - (TPARSER_HAS_TOKEN(pSqlNode->interval.interval) || TPARSER_HAS_TOKEN(pSqlNode->sessionVal.gap)); + (TPARSER_HAS_TOKEN(pSqlNode->interval.interval) || + TPARSER_HAS_TOKEN(pSqlNode->sessionVal.gap) || + TPARSER_HAS_TOKEN(pSqlNode->windowstateVal.col)); if (validateSelectNodeList(pCmd, pQueryInfo, pSqlNode->pSelNodeList, joinQuery, timeWindowQuery, false) != TSDB_CODE_SUCCESS) { @@ -10567,7 +10710,8 @@ int32_t exprTreeFromSqlExpr(SSqlCmd* pCmd, tExprNode **pExpr, const tSqlExpr* pS if (pLeft->_node.optr == TSDB_RELATION_ARROW){ pLeft = pLeft->_node.pLeft; } - if (pRight->pVal->nType == TSDB_DATA_TYPE_BOOL && (pLeft->pSchema->type == TSDB_DATA_TYPE_BOOL || pLeft->pSchema->type == TSDB_DATA_TYPE_JSON)) { + if (pRight->pVal->nType == TSDB_DATA_TYPE_BOOL && pLeft->nodeType == TSQL_NODE_COL && + (pLeft->pSchema->type == TSDB_DATA_TYPE_BOOL || pLeft->pSchema->type == TSDB_DATA_TYPE_JSON)) { return TSDB_CODE_TSC_INVALID_OPERATION; } } @@ -10602,14 +10746,23 @@ int32_t exprTreeFromSqlExpr(SSqlCmd* pCmd, tExprNode **pExpr, const tSqlExpr* pS *pExpr = calloc(1, sizeof(tExprNode)); (*pExpr)->nodeType = TSQL_NODE_COL; (*pExpr)->pSchema = calloc(1, sizeof(SSchema)); - strncpy((*pExpr)->pSchema->name, pSqlExpr->exprToken.z, pSqlExpr->exprToken.n); + if (tsKeepOriginalColumnName && // TD-14196, tsKeepOriginalColumnName params makes logic special + (pSqlExpr->functionId == TSDB_FUNC_FIRST || + pSqlExpr->functionId == TSDB_FUNC_LAST || + pSqlExpr->functionId == TSDB_FUNC_SPREAD || + pSqlExpr->functionId == TSDB_FUNC_LAST_ROW || + pSqlExpr->functionId == TSDB_FUNC_INTERP)) { + tSqlExprItem* pParamElem = taosArrayGet(pSqlExpr->Expr.paramList, 0); + strncpy((*pExpr)->pSchema->name, pParamElem->pNode->columnName.z, pParamElem->pNode->columnName.n); + }else{ + strncpy((*pExpr)->pSchema->name, pSqlExpr->exprToken.z, pSqlExpr->exprToken.n); + } // set the input column data byte and type. size_t size = taosArrayGetSize(pQueryInfo->exprList); for (int32_t i = 0; i < size; ++i) { SExprInfo* p1 = taosArrayGetP(pQueryInfo->exprList, i); - if (strcmp((*pExpr)->pSchema->name, p1->base.aliasName) == 0) { (*pExpr)->pSchema->type = (uint8_t)p1->base.resType; (*pExpr)->pSchema->bytes = p1->base.resBytes; diff --git a/src/client/src/tscServer.c b/src/client/src/tscServer.c index 4ce44fad76568063c8d8ef4184fa2002b36de0f2..c821c25987042d0c26c4aa302a142544a08b943c 100644 --- a/src/client/src/tscServer.c +++ b/src/client/src/tscServer.c @@ -951,7 +951,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) { pQueryMsg->window.ekey = htobe64(query.window.ekey); pQueryMsg->range.skey = htobe64(query.range.skey); pQueryMsg->range.ekey = htobe64(query.range.ekey); - + pQueryMsg->order = htons(query.order.order); pQueryMsg->orderColId = htons(query.order.orderColId); pQueryMsg->fillType = htons(query.fillType); @@ -990,7 +990,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) { pQueryMsg->numOfGroupCols = htons(pQueryInfo->groupbyExpr.numOfGroupCols); pQueryMsg->queryType = htonl(pQueryInfo->type); pQueryMsg->prevResultLen = htonl(pQueryInfo->bufLen); - + // set column list ids size_t numOfCols = taosArrayGetSize(pQueryInfo->colList); char *pMsg = (char *)(pQueryMsg->tableCols) + numOfCols * sizeof(SColumnInfo); @@ -1184,7 +1184,7 @@ int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) { tlv->len = htonl(sizeof(int16_t) * 2); *(int16_t*)tlv->value = htons(pTableMeta->sversion); *(int16_t*)(tlv->value+sizeof(int16_t)) = htons(pTableMeta->tversion); - pMsg += sizeof(*tlv) + ntohl(tlv->len); + pMsg += sizeof(*tlv) + sizeof(int16_t) * 2; tlv = (STLV *)pMsg; tlv->type = htons(TLV_TYPE_END_MARK); diff --git a/src/client/src/tscSubquery.c b/src/client/src/tscSubquery.c index be9b3a2cf32e969594986066fdaba7af847607ac..9360ed05898aab1ed7da54f03b1c15617b8b9c76 100644 --- a/src/client/src/tscSubquery.c +++ b/src/client/src/tscSubquery.c @@ -662,6 +662,7 @@ static int32_t tscLaunchRealSubqueries(SSqlObj* pSql) { } else { filterVgroupTables(pQueryInfo, pTableMetaInfo->pVgroupTables); } + pQueryInfo->stableQuery = true; } subquerySetState(pNew, &pSql->subState, i, 0); @@ -935,6 +936,96 @@ static void setTidTagType(SJoinSupporter* p, uint8_t type) { } } +static int32_t tidTagsMerge(SArray *arr, int32_t start, int32_t mid, int32_t end, const int32_t tagSize) +{ + char *pTmp, *pRes = NULL; + char *result = NULL; + STidTags *pi, *pj, *p; + + int32_t k = 0; + int32_t i = start; + int32_t j = mid + 1; + + if (end - start > 0) { + result = calloc(1, (end - start + 1) * tagSize); + if (result == NULL) { + tscError("failed to allocate memory for tidTagsMerge"); + return TSDB_CODE_TSC_OUT_OF_MEMORY; + } + } + + pRes = result; + + while (i <= mid && j <= end) { + pi = taosArrayGet(arr, i); + pj = taosArrayGet(arr, j); + + if (pi->vgId <= pj->vgId) { + p = taosArrayGet(arr, i++); + memcpy(pRes, p, tagSize); + } else { + p = taosArrayGet(arr, j++); + memcpy(pRes, p, tagSize); + } + + k++; + pRes += tagSize; + } + + if (i == mid + 1) { + while(j <= end) { + p = taosArrayGet(arr, j++); + memcpy(pRes, p, tagSize); + k++; + pRes += tagSize; + } + } + + if (j == end + 1) { + while (i <= mid) { + p = taosArrayGet(arr, i++); + memcpy(pRes, p, tagSize); + k++; + pRes += tagSize; + } + } + + for (i = start, j = 0, pTmp = result; j < k; i++, j++, pTmp += tagSize) { + p = (STidTags *) taosArrayGet(arr, i); + memcpy(p, pTmp, tagSize); + } + + if (result) { + tfree(result); + } + + return TSDB_CODE_SUCCESS; +} + +static int32_t tidTagsMergeSort(SArray *arr, int32_t start, int32_t end, const int32_t tagSize) +{ + int32_t ret; + int32_t mid; + + if (start >= end) { + return TSDB_CODE_SUCCESS; + } + + mid = (start + end) / 2; + + ret = tidTagsMergeSort(arr, start, mid, tagSize); + if (ret != TSDB_CODE_SUCCESS) { + return ret; + } + + ret = tidTagsMergeSort(arr, mid + 1, end, tagSize); + if (ret != TSDB_CODE_SUCCESS) { + return ret; + } + + return tidTagsMerge(arr, start, mid, end, tagSize); +} + static int32_t getIntersectionOfTableTuple(SQueryInfo* pQueryInfo, SSqlObj* pParentSql, SArray* resList) { int16_t joinNum = pParentSql->subState.numOfSub; STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0); @@ -1122,13 +1213,16 @@ static int32_t getIntersectionOfTableTuple(SQueryInfo* pQueryInfo, SSqlObj* pPar for (int32_t i = 0; i < joinNum; ++i) { // reorganize the tid-tag value according to both the vgroup id and tag values // sort according to the tag value - size_t num = taosArrayGetSize(ctxlist[i].res); + int32_t num = (int32_t) taosArrayGetSize(ctxlist[i].res); - qsort((ctxlist[i].res)->pData, num, size, tidTagsCompar); + int32_t ret = tidTagsMergeSort(ctxlist[i].res, 0, num - 1, size); + if (ret != TSDB_CODE_SUCCESS) { + return TSDB_CODE_TSC_OUT_OF_MEMORY; + } taosArrayPush(resList, &ctxlist[i].res); - tscDebug("0x%"PRIx64" tags match complete, result num: %"PRIzu, pParentSql->self, num); + tscDebug("0x%"PRIx64" tags match complete, result num: %d", pParentSql->self, num); } return TSDB_CODE_SUCCESS; diff --git a/src/client/src/tscUtil.c b/src/client/src/tscUtil.c index 84ae4bdb6b455718530bd3e74c4929c629cca81f..099f01e9a708377b076895d3d472d653b977fc56 100644 --- a/src/client/src/tscUtil.c +++ b/src/client/src/tscUtil.c @@ -116,9 +116,26 @@ int32_t converToStr(char *str, int type, void *buf, int32_t bufSize, int32_t *le return TSDB_CODE_TSC_INVALID_VALUE; } - *str = '\''; + bool squote = false; + for (int32_t i = 0; i < bufSize; ++i) { + if (((char *)buf)[i] == '\'') { + squote = true; + break; + } + } + + if (squote) { + *str = '\"'; + } else { + *str = '\''; + } + memcpy(str + 1, buf, bufSize); - *(str + bufSize + 1) = '\''; + if (squote) { + *(str + bufSize + 1) = '\"'; + } else { + *(str + bufSize + 1) = '\''; + } n = bufSize + 2; break; @@ -328,7 +345,8 @@ bool tscIsProjectionQuery(SQueryInfo* pQueryInfo) { if (f != TSDB_FUNC_PRJ && f != TSDB_FUNC_TAGPRJ && f != TSDB_FUNC_TAG && f != TSDB_FUNC_TS && f != TSDB_FUNC_SCALAR_EXPR && f != TSDB_FUNC_DIFF && - f != TSDB_FUNC_DERIVATIVE && !TSDB_FUNC_IS_SCALAR(f)) { + f != TSDB_FUNC_DERIVATIVE && !TSDB_FUNC_IS_SCALAR(f) && + f != TSDB_FUNC_STATE_COUNT && f != TSDB_FUNC_STATE_DURATION) { return false; } } @@ -347,8 +365,8 @@ bool tscIsDiffDerivLikeQuery(SQueryInfo* pQueryInfo) { continue; } - if (f == TSDB_FUNC_DIFF || f == TSDB_FUNC_DERIVATIVE || - f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG) { + if (f == TSDB_FUNC_DIFF || f == TSDB_FUNC_DERIVATIVE || f == TSDB_FUNC_CSUM || f == TSDB_FUNC_MAVG || + f == TSDB_FUNC_STATE_COUNT || f == TSDB_FUNC_STATE_DURATION) { return true; } } @@ -356,7 +374,6 @@ bool tscIsDiffDerivLikeQuery(SQueryInfo* pQueryInfo) { return false; } - bool tscHasColumnFilter(SQueryInfo* pQueryInfo) { // filter on primary timestamp column if (pQueryInfo->window.skey != INT64_MIN || pQueryInfo->window.ekey != INT64_MAX) { @@ -394,7 +411,7 @@ bool tscIsPointInterpQuery(SQueryInfo* pQueryInfo) { } bool tscNeedTableSeqScan(SQueryInfo* pQueryInfo) { - return pQueryInfo->stableQuery && (tscQueryContainsFunction(pQueryInfo, TSDB_FUNC_TWA) || tscQueryContainsFunction(pQueryInfo, TSDB_FUNC_ELAPSED)); + return pQueryInfo->stableQuery && (tscQueryContainsFunction(pQueryInfo, TSDB_FUNC_TWA) || tscQueryContainsFunction(pQueryInfo, TSDB_FUNC_ELAPSED) || (pQueryInfo->tsBuf != NULL)); } bool tscGetPointInterpQuery(SQueryInfo* pQueryInfo) { @@ -978,6 +995,26 @@ static void doSetupSDataBlock(SSqlRes* pRes, SSDataBlock* pBlock, void* pFilterI pColData->pData = pRes->urow[i]; } + if (pColData->info.type == TSDB_DATA_TYPE_NCHAR) { + int32_t rows = pBlock->info.rows; + int32_t bytes = pColData->info.bytes; + char *dstData = malloc(bytes * rows); + char *srcData = pColData->pData; + for (int32_t j = 0; j < rows; ++j) { + char *srcRow = srcData + bytes * j; + char *dstRow = dstData + bytes * j; + if(isNull(srcRow, TSDB_DATA_TYPE_NCHAR)){ + varDataCopy(dstRow, srcRow); + continue; + } + int32_t len = 0; + taosMbsToUcs4(varDataVal(srcRow), varDataLen(srcRow), varDataVal(dstRow), + bytes-VARSTR_HEADER_SIZE, &len); + varDataSetLen(dstRow, len); + } + memcpy(srcData, dstData, bytes*rows); + free(dstData); + } offset += pColData->info.bytes; } @@ -986,14 +1023,9 @@ static void doSetupSDataBlock(SSqlRes* pRes, SSDataBlock* pBlock, void* pFilterI SColumnDataParam param = {.numOfCols = pBlock->info.numOfCols, .pDataBlock = pBlock->pDataBlock}; filterSetColFieldData(pFilterInfo, ¶m, getColumnDataFromId); - bool gotNchar = false; - filterConverNcharColumns(pFilterInfo, pBlock->info.rows, &gotNchar); int8_t* p = NULL; //bool all = doFilterDataBlock(pFilterInfo, numOfFilterCols, pBlock->info.rows, p); bool all = filterExecute(pFilterInfo, pBlock->info.rows, &p, NULL, 0); - if (gotNchar) { - filterFreeNcharColumns(pFilterInfo); - } if (!all) { if (p) { doCompactSDataBlock(pBlock, pBlock->info.rows, p); @@ -1491,7 +1523,7 @@ void handleDownstreamOperator(SSqlObj** pSqlObjList, int32_t numOfUpstream, SQue pex->base.param[2].nType = TSDB_DATA_TYPE_INT; pex->base.param[2].i64 = pInputQI->order.order; } - } + } } tscDebug("0x%"PRIx64" create QInfo 0x%"PRIx64" to execute the main query while all nest queries are ready", pSql->self, pSql->self); @@ -1508,7 +1540,7 @@ void handleDownstreamOperator(SSqlObj** pSqlObjList, int32_t numOfUpstream, SQue uint64_t qId = pSql->self; qTableQuery(px->pQInfo, &qId); - convertQueryResult(pOutput, px, pSql->self, false, false); + convertQueryResult(pOutput, px, pSql->self, true, false); } static void tscDestroyResPointerInfo(SSqlRes* pRes) { @@ -2551,6 +2583,11 @@ SExprInfo* tscExprCreate(STableMetaInfo* pTableMetaInfo, int16_t functionId, SCo p->colInfo.colId = TSDB_TBNAME_COLUMN_INDEX; p->colBytes = s->bytes; p->colType = s->type; + } else if (TSDB_COL_IS_TSWIN_COL(pColIndex->columnIndex)) { + SSchema* s = tGetTimeWindowColumnSchema(pColIndex->columnIndex); + p->colInfo.colId = s->colId; + p->colBytes = s->bytes; + p->colType = s->type; } else if (pColIndex->columnIndex <= TSDB_UD_COLUMN_INDEX) { p->colInfo.colId = pColIndex->columnIndex; p->colBytes = size; @@ -2974,7 +3011,8 @@ int32_t tscValidateName(SStrToken* pToken, bool escapeEnabled, bool *dbIncluded) if (sep == NULL) { return TSDB_CODE_TSC_INVALID_OPERATION; } - *dbIncluded = true; + + if (dbIncluded) *dbIncluded = true; return tscValidateName(pToken, escapeEnabled, NULL); } @@ -3073,7 +3111,8 @@ bool tscValidateColumnId(STableMetaInfo* pTableMetaInfo, int32_t colId) { return false; } - if (colId == TSDB_TBNAME_COLUMN_INDEX || colId <= TSDB_UD_COLUMN_INDEX) { + if (colId == TSDB_TBNAME_COLUMN_INDEX || TSDB_COL_IS_TSWIN_COL(colId) || + colId <= TSDB_UD_COLUMN_INDEX) { return true; } @@ -4238,6 +4277,10 @@ void executeQuery(SSqlObj* pSql, SQueryInfo* pQueryInfo) { } return; + } else if (hasMoreClauseToTry(pSql)) { + if (pthread_mutex_init(&pSql->subState.mutex, NULL) != 0) { + goto _error; + } } pSql->cmd.active = pQueryInfo; @@ -4940,7 +4983,7 @@ static int32_t createGlobalAggregateExpr(SQueryAttr* pQueryAttr, SQueryInfo* pQu pse->colType = pExpr->base.resType; if(pExpr->base.resBytes > INT16_MAX && (pExpr->base.functionId == TSDB_FUNC_UNIQUE || pExpr->base.functionId == TSDB_FUNC_MODE - || pExpr->base.functionId == TSDB_FUNC_TAIL)){ + || pExpr->base.functionId == TSDB_FUNC_TAIL || pExpr->base.functionId == TSDB_FUNC_SAMPLE)){ pQueryAttr->interBytesForGlobal = pExpr->base.resBytes; }else{ pse->colBytes = pExpr->base.resBytes; @@ -5088,7 +5131,6 @@ int32_t tscCreateQueryFromQueryInfo(SQueryInfo* pQueryInfo, SQueryAttr* pQueryAt pQueryAttr->pUdfInfo = pQueryInfo->pUdfInfo; pQueryAttr->range = pQueryInfo->range; - if (pQueryInfo->order.order == TSDB_ORDER_ASC) { // TODO refactor pQueryAttr->window = pQueryInfo->window; } else { @@ -5388,7 +5430,7 @@ char* cloneCurrentDBName(SSqlObj* pSql) { return p; } -int parseJsontoTagData(char* json, SKVRowBuilder* kvRowBuilder, char* errMsg, int16_t startColId){ +int parseJsontoTagData(char* json, uint32_t jsonLength, SKVRowBuilder* kvRowBuilder, char* errMsg, int16_t startColId){ // set json NULL data uint8_t nullTypeVal[CHAR_BYTES + VARSTR_HEADER_SIZE + INT_BYTES] = {0}; uint32_t jsonNULL = TSDB_DATA_JSON_NULL; @@ -5399,7 +5441,7 @@ int parseJsontoTagData(char* json, SKVRowBuilder* kvRowBuilder, char* errMsg, in varDataSetLen(nullTypeVal + CHAR_BYTES, INT_BYTES); *(uint32_t*)(varDataVal(nullTypeKey)) = jsonNULL; tdAddColToKVRow(kvRowBuilder, jsonIndex++, TSDB_DATA_TYPE_NCHAR, nullTypeKey, false); // add json null type - if (!json || strtrim(json) == 0 || strncasecmp(json, "null", 4) == 0){ + if (!json || strtrim(json) == 0 || (jsonLength == strlen("null") && strncasecmp(json, "null", 4) == 0)){ *(uint32_t*)(varDataVal(nullTypeVal + CHAR_BYTES)) = jsonNULL; tdAddColToKVRow(kvRowBuilder, jsonIndex++, TSDB_DATA_TYPE_NCHAR, nullTypeVal, true); // add json null value return TSDB_CODE_SUCCESS; diff --git a/src/common/inc/tglobal.h b/src/common/inc/tglobal.h index 06ed93b110281756ade98d5e99dd4b57b4924fc3..fc4b1f0102b93ea263273ae3cc2c631771e1c286 100644 --- a/src/common/inc/tglobal.h +++ b/src/common/inc/tglobal.h @@ -43,6 +43,8 @@ extern int64_t tsArbOnlineTimestamp; extern int32_t tsDnodeId; extern int64_t tsDnodeStartTime; extern int8_t tsDnodeNopLoop; +extern int32_t tsTcpConnTimeout; +extern int32_t tsSyncCheckInterval; // common extern int tsRpcTimer; @@ -193,6 +195,7 @@ extern float tsReservedTmpDirectorySpace; extern float tsMinimalDataDirGB; extern int32_t tsTotalMemoryMB; extern uint32_t tsVersion; +extern int32_t tsKeepTimeOffset; // build info extern char version[]; diff --git a/src/common/inc/tname.h b/src/common/inc/tname.h index e6b7dd1463a754bfaa78bb1081e3b6b0b753d752..6c4b54ec3cfb2f46acf5341ecda7015035866e59 100644 --- a/src/common/inc/tname.h +++ b/src/common/inc/tname.h @@ -54,8 +54,8 @@ typedef struct SSqlExpr { int32_t resBytes; // length of return value int32_t interBytes; // inter result buffer size - int16_t colType; // table column type, this should be int32_t, because it is too small for globale merge stage, pQueryAttr->interBytesForGlobal - int16_t colBytes; // table column bytes + int16_t colType; // table column type + int16_t colBytes; // table column bytes,it should be int32_t, because it is too small for globale merge stage, pQueryAttr->interBytesForGlobal int16_t numOfParams; // argument value of each function tVariant param[3]; // parameters are not more than 3 @@ -103,6 +103,7 @@ bool tscValidateTableNameLength(size_t len); SColumnFilterInfo* tFilterInfoDup(const SColumnFilterInfo* src, int32_t numOfFilters); SSchema* tGetTbnameColumnSchema(); +SSchema* tGetTimeWindowColumnSchema(int16_t columnIndex); /** * check if the schema is valid or not, including following aspects: diff --git a/src/common/src/tdataformat.c b/src/common/src/tdataformat.c index d8999a0b6fece9cda4d5c8e2af82e65afa4ed580..55afd4c62096974e379e78d448086f10e9860764 100644 --- a/src/common/src/tdataformat.c +++ b/src/common/src/tdataformat.c @@ -624,8 +624,9 @@ static void tdMergeTwoDataCols(SDataCols *target, SDataCols *src1, int *iter1, i if ((key1 > key2) || (key1 == key2 && !TKEY_IS_DELETED(tkey2))) { for (int i = 0; i < src2->numOfCols; i++) { ASSERT(target->cols[i].type == src2->cols[i].type); - if (src2->cols[i].len > 0 && !isNull(src2->cols[i].pData, src2->cols[i].type)) { - dataColAppendVal(&(target->cols[i]), tdGetColDataOfRow(src2->cols + i, *iter2), target->numOfRows, + const void *src2Val = tdGetColDataOfRow(src2->cols + i, *iter2); + if (src2->cols[i].len > 0 && !isNull(src2Val, src2->cols[i].type)) { + dataColAppendVal(&(target->cols[i]), src2Val, target->numOfRows, target->maxPoints, 0); } else if(!forceSetNull && key1 == key2 && src1->cols[i].len > 0) { dataColAppendVal(&(target->cols[i]), tdGetColDataOfRow(src1->cols + i, *iter1), target->numOfRows, diff --git a/src/common/src/texpr.c b/src/common/src/texpr.c index 2774d9e2fabd11a3fcb45d650dc696518d504501..801fbe50fd23f50aae1ba04e8a82002d850f7a25 100644 --- a/src/common/src/texpr.c +++ b/src/common/src/texpr.c @@ -241,7 +241,8 @@ static void reverseCopy(char* dest, const char* src, int16_t type, int32_t numOf return; } case TSDB_DATA_TYPE_BIGINT: - case TSDB_DATA_TYPE_UBIGINT: { + case TSDB_DATA_TYPE_UBIGINT: + case TSDB_DATA_TYPE_TIMESTAMP: { int64_t* p = (int64_t*) dest; int64_t* pSrc = (int64_t*) src; @@ -438,7 +439,7 @@ void exprTreeFunctionNodeTraverse(tExprNode *pExpr, int32_t numOfRows, tExprOper } pInputs[i].numOfRows = (int16_t)numOfRows; } else if (pChild->nodeType == TSQL_NODE_VALUE) { - pChildrenOutput[i] = malloc(pChild->resultBytes); + pChildrenOutput[i] = malloc((pChild->resultBytes+1)*TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); tVariantDump(pChild->pVal, pChildrenOutput[i], pChild->resultType, true); pInputs[i].data = pChildrenOutput[i]; pInputs[i].numOfRows = 1; @@ -955,7 +956,7 @@ int32_t exprValidateStringConcatNode(tExprNode *pExpr) { if (!IS_VAR_DATA_TYPE(child->pVal->nType)) { return TSDB_CODE_TSC_INVALID_OPERATION; } - char* payload = malloc(child->pVal->nLen * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); + char* payload = malloc((child->pVal->nLen+1) * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); tVariantDump(child->pVal, payload, resultType, true); int16_t resultBytes = varDataTLen(payload); free(payload); @@ -1027,7 +1028,7 @@ int32_t exprValidateStringConcatWsNode(tExprNode *pExpr) { if (!IS_VAR_DATA_TYPE(child->pVal->nType)) { return TSDB_CODE_TSC_INVALID_OPERATION; } - char* payload = malloc(child->pVal->nLen * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); + char* payload = malloc((child->pVal->nLen+1) * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE); tVariantDump(child->pVal, payload, resultType, true); int16_t resultBytes = varDataTLen(payload); free(payload); @@ -2230,14 +2231,12 @@ void vectorMathFunc(int16_t functionId, tExprOperandInfo *pInputs, int32_t numIn void convertStringToTimestamp(int16_t type, char *inputData, int64_t timePrec, int64_t *timeVal) { int32_t charLen = varDataLen(inputData); - char *newColData; + char *newColData = calloc(1, charLen + 1); if (type == TSDB_DATA_TYPE_BINARY) { - newColData = calloc(1, charLen + 1); memcpy(newColData, varDataVal(inputData), charLen); taosParseTime(newColData, timeVal, charLen, (int32_t)timePrec, 0); tfree(newColData); } else if (type == TSDB_DATA_TYPE_NCHAR) { - newColData = calloc(1, charLen / TSDB_NCHAR_SIZE + 1); int len = taosUcs4ToMbs(varDataVal(inputData), charLen, newColData); if (len < 0){ uError("convertStringToTimestamp taosUcs4ToMbs error"); diff --git a/src/common/src/tglobal.c b/src/common/src/tglobal.c index 922ae1dedc806c8939a142d737e4661f3fe4561d..b27c62ed53c5c878ddf2b675ebc4f41cc394f8a6 100644 --- a/src/common/src/tglobal.c +++ b/src/common/src/tglobal.c @@ -48,6 +48,8 @@ char tsEmail[TSDB_FQDN_LEN] = {0}; int32_t tsDnodeId = 0; int64_t tsDnodeStartTime = 0; int8_t tsDnodeNopLoop = 0; +int32_t tsTcpConnTimeout = 1000; +int32_t tsSyncCheckInterval = 1500; // common int32_t tsRpcTimer = 300; @@ -217,6 +219,7 @@ char tsMnodeBakDir[PATH_MAX] = {0}; char tsDataDir[PATH_MAX] = {0}; char tsScriptDir[PATH_MAX] = {0}; char tsTempDir[PATH_MAX] = "/tmp/"; +int32_t tsKeepTimeOffset = 0; int32_t tsDiskCfgNum = 0; int32_t tsTopicBianryLen = 16000; @@ -635,6 +638,26 @@ static void doInitGlobalConfig(void) { cfg.unitType = TAOS_CFG_UTYPE_NONE; taosInitConfigOption(cfg); + cfg.option = "tcpConnTimout"; + cfg.ptr = &tsTcpConnTimeout; + cfg.valType = TAOS_CFG_VTYPE_INT32; + cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW; + cfg.minValue = 1; + cfg.maxValue = 10000; + cfg.ptrLength = 0; + cfg.unitType = TAOS_CFG_UTYPE_MS; + taosInitConfigOption(cfg); + + cfg.option = "syncCheckInterval"; + cfg.ptr = &tsSyncCheckInterval; + cfg.valType = TAOS_CFG_VTYPE_INT32; + cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW; + cfg.minValue = 1; + cfg.maxValue = 10000; + cfg.ptrLength = 0; + cfg.unitType = TAOS_CFG_UTYPE_MS; + taosInitConfigOption(cfg); + cfg.option = "balance"; cfg.ptr = &tsEnableBalance; cfg.valType = TAOS_CFG_VTYPE_INT8; @@ -665,6 +688,16 @@ static void doInitGlobalConfig(void) { cfg.unitType = TAOS_CFG_UTYPE_NONE; taosInitConfigOption(cfg); + cfg.option = "keepTimeOffset"; + cfg.ptr = &tsKeepTimeOffset; + cfg.valType = TAOS_CFG_VTYPE_INT32; + cfg.cfgType = TSDB_CFG_CTYPE_B_CONFIG | TSDB_CFG_CTYPE_B_SHOW; + cfg.minValue = -23; + cfg.maxValue = 23; + cfg.ptrLength = 0; + cfg.unitType = TAOS_CFG_UTYPE_NONE; + taosInitConfigOption(cfg); + // 0-any; 1-mnode; 2-vnode cfg.option = "role"; cfg.ptr = &tsAlternativeRole; diff --git a/src/common/src/tname.c b/src/common/src/tname.c index 68aa1be6b2ed0d9d1a248e6fc6ee2e701071fb21..97062cf3dd1279158315c55a4ee96f332e59f7ac 100644 --- a/src/common/src/tname.c +++ b/src/common/src/tname.c @@ -244,6 +244,41 @@ static struct SSchema _s = { .name = TSQL_TBNAME_L, }; +static struct SSchema _tswin[6] = { + {TSDB_DATA_TYPE_TIMESTAMP, TSQL_TSWIN_START, TSDB_TSWIN_START_COLUMN_INDEX, LONG_BYTES}, + {TSDB_DATA_TYPE_TIMESTAMP, TSQL_TSWIN_STOP, TSDB_TSWIN_STOP_COLUMN_INDEX, LONG_BYTES}, + {TSDB_DATA_TYPE_BIGINT, TSQL_TSWIN_DURATION, TSDB_TSWIN_DURATION_COLUMN_INDEX, LONG_BYTES}, + {TSDB_DATA_TYPE_TIMESTAMP, TSQL_QUERY_START, TSDB_QUERY_START_COLUMN_INDEX, LONG_BYTES}, + {TSDB_DATA_TYPE_TIMESTAMP, TSQL_QUERY_STOP, TSDB_QUERY_STOP_COLUMN_INDEX, LONG_BYTES}, + {TSDB_DATA_TYPE_BIGINT, TSQL_QUERY_DURATION, TSDB_QUERY_DURATION_COLUMN_INDEX, LONG_BYTES}, +}; + +SSchema* tGetTimeWindowColumnSchema(int16_t columnIndex) { + switch (columnIndex) { + case TSDB_TSWIN_START_COLUMN_INDEX: { + return &_tswin[0]; + } + case TSDB_TSWIN_STOP_COLUMN_INDEX: { + return &_tswin[1]; + } + case TSDB_TSWIN_DURATION_COLUMN_INDEX: { + return &_tswin[2]; + } + case TSDB_QUERY_START_COLUMN_INDEX: { + return &_tswin[3]; + } + case TSDB_QUERY_STOP_COLUMN_INDEX: { + return &_tswin[4]; + } + case TSDB_QUERY_DURATION_COLUMN_INDEX: { + return &_tswin[5]; + } + default: { + return NULL; + } + } +} + SSchema* tGetTbnameColumnSchema() { return &_s; } diff --git a/src/connector/C#/.gitignore b/src/connector/C#/.gitignore index 80558c70a1571c863749550f66d642baf089d627..18f1b837b4b3e038cb17d23066852f71c37281d6 100644 --- a/src/connector/C#/.gitignore +++ b/src/connector/C#/.gitignore @@ -8,3 +8,4 @@ src/test/doc/ NugetPackTest/ examples/bin/ examples/obj/ +.vs diff --git a/src/connector/C#/examples/Main.cs b/src/connector/C#/examples/Main.cs index 9d2ab85a87a541fbd891cf318f454d5d8ba001fd..103d5f2b068efece0c54841d3a1622f49007e314 100644 --- a/src/connector/C#/examples/Main.cs +++ b/src/connector/C#/examples/Main.cs @@ -14,13 +14,15 @@ namespace AsyncQueryExample IntPtr conn = UtilsTools.TDConnection(); AsyncQuerySample asyncQuery = new AsyncQuerySample(); - asyncQuery.RunQueryAsync(conn,"query_async"); - - SubscribeSample subscribeSample = new SubscribeSample(); + asyncQuery.RunQueryAsync(conn, "query_async"); + + SubscribeSample subscribeSample = new SubscribeSample(); subscribeSample.RunSubscribeWithCallback(conn, "subscribe_with_callback"); subscribeSample.RunSubscribeWithoutCallback(conn, "subscribe_without_callback"); - UtilsTools.CloseConnection(conn); + + SchemalessSample schemalessSample = new SchemalessSample(); + schemalessSample.RunSchemaless(); } } } diff --git a/src/connector/C#/examples/SchemalessSample.cs b/src/connector/C#/examples/SchemalessSample.cs new file mode 100644 index 0000000000000000000000000000000000000000..beeb6850a6473361d74b763b5a74816544b25ec9 --- /dev/null +++ b/src/connector/C#/examples/SchemalessSample.cs @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * 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 . + */ + +using System; +using System.Text; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Collections; +using Sample.UtilsTools; +using TDengineDriver; + +namespace Example +{ + class SchemalessSample + { + + private IntPtr conn = IntPtr.Zero; + private string dbName = "csharp_schemaless_example"; + public void RunSchemaless() + { + string[] lines = { + "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", + "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000" + }; + string[] jsonStr = { + "{" + +"\"metric\": \"stb0_0\"," + +"\"timestamp\": 1626006833," + +"\"value\": 10," + +"\"tags\": {" + +" \"t1\": true," + +"\"t2\": false," + +"\"t3\": 10," + +"\"t4\": \"123_abc_.!@#$%^&*:;,./?|+-=()[]{}<>\"" + +"}" + +"}" + }; + StringBuilder querySql = new StringBuilder(); + Console.WriteLine(querySql.ToString()); + this.conn = UtilsTools.TDConnection(this.dbName); + + schemalessInsert(lines, 2, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NANO_SECONDS); + querySql.Append("select * from ").Append(this.dbName).Append(".").Append("stg"); + UtilsTools.DisplayRes(UtilsTools.ExecuteQuery(this.conn, querySql.ToString())); + + schemalessInsert(jsonStr, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_SECONDS); + querySql.Clear(); + querySql.Append("select * from ").Append(this.dbName).Append(".").Append("stb0_0"); + UtilsTools.DisplayRes(UtilsTools.ExecuteQuery(this.conn, querySql.ToString())); + + querySql.Clear(); + querySql.Append("drop database if exists ").Append(this.dbName); + UtilsTools.ExecuteUpdate(this.conn, querySql.ToString()); + UtilsTools.CloseConnection(this.conn); + + } + public void schemalessInsert(string[] sqlstr, int lineCnt, int protocol, int precision) + { + + IntPtr res = TDengine.SchemalessInsert(this.conn, sqlstr, lineCnt, protocol, precision); + + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("schemaless_insert failed:{0}", TDengine.Error(res)); + Console.WriteLine("line string:{0}", sqlstr); + Console.WriteLine(""); + System.Environment.Exit(0); + } + else + { + Console.WriteLine("else"); + Console.WriteLine("schemaless insert success:{0}", TDengine.ErrorNo(res)); + } + + } + + } +} diff --git a/src/connector/C#/examples/lib/Utils.cs b/src/connector/C#/examples/lib/Utils.cs index d5c1fcd2f31efec5b8473a9dafcceb3971e240f3..add61a2da40f8a9481529568977f27db68cc1e44 100644 --- a/src/connector/C#/examples/lib/Utils.cs +++ b/src/connector/C#/examples/lib/Utils.cs @@ -14,17 +14,19 @@ namespace Sample.UtilsTools static string db = ""; static short port = 0; static string globalDbName = "csharp_example_db"; - //get a tdengine connection - public static IntPtr TDConnection() + //get a TDengine connection + public static IntPtr TDConnection(string dbName = "csharp_example_db") { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, GetConfigPath()); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); + TDengine.Options((int)TDengineInitOption.TSDB_OPTION_CONFIGDIR, GetConfigPath()); + TDengine.Options((int)TDengineInitOption.TSDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); TDengine.Init(); IntPtr conn = TDengine.Connect(ip, user, password, db, port); - UtilsTools.ExecuteUpdate(conn, $"drop database if exists {globalDbName}"); - UtilsTools.ExecuteUpdate(conn, $"create database if not exists {globalDbName} keep 3650"); - UtilsTools.ExecuteUpdate(conn, $"use {globalDbName}"); + + UtilsTools.ExecuteUpdate(conn, $"drop database if exists {dbName}"); + UtilsTools.ExecuteUpdate(conn, $"create database if not exists {dbName} keep 3650"); + UtilsTools.ExecuteUpdate(conn, $"use {dbName}"); + return conn; } //get taos.cfg file based on different os @@ -100,18 +102,18 @@ namespace Sample.UtilsTools ExitProgram(); } - List metas = GetResField(res); - int fieldCount = metas.Count; - // metas.ForEach((item) => { Console.Write("{0} ({1}) \t|\t", item.name, item.size); }); + List metaList = GetResField(res); + int fieldCount = metaList.Count; + // metaList.ForEach((item) => { Console.Write("{0} ({1}) \t|\t", item.name, item.size); }); - List datas = QueryRes(res, metas); - for (int index = 0; index < datas.Count; index++) + List dataList = QueryRes(res, metaList); + for (int index = 0; index < dataList.Count; index++) { if (index % fieldCount == 0 && index != 0) { Console.WriteLine(""); } - Console.Write("{0} \t|\t", datas[index].ToString()); + Console.Write("{0} \t|\t", dataList[index].ToString()); } Console.WriteLine(""); @@ -127,10 +129,10 @@ namespace Sample.UtilsTools ExitProgram(); } - List metas = GetResField(res); + List meta = GetResField(res); result.Add(colName); - dataRaw = QueryRes(res, metas); + dataRaw = QueryRes(res, meta); result.Add(dataRaw); if (TDengine.ErrorNo(res) != 0) @@ -161,7 +163,7 @@ namespace Sample.UtilsTools { if (TDengine.Close(conn) == 0) { - Console.WriteLine("close connection sucess"); + Console.WriteLine("close connection success"); } else { @@ -171,8 +173,8 @@ namespace Sample.UtilsTools } public static List GetResField(IntPtr res) { - List metas = TDengine.FetchFields(res); - return metas; + List meta = TDengine.FetchFields(res); + return meta; } public static void ExitProgram() { @@ -187,19 +189,19 @@ namespace Sample.UtilsTools { ExitProgram(); } - List metas = GetResField(res); - dataRaw = QueryRes(res, metas); + List meta = GetResField(res); + dataRaw = QueryRes(res, meta); return dataRaw; } - private static List QueryRes(IntPtr res, List metas) + private static List QueryRes(IntPtr res, List meta) { IntPtr taosRow; List dataRaw = new List(); - int fieldCount = metas.Count; + int fieldCount = meta.Count; while ((taosRow = TDengine.FetchRows(res)) != IntPtr.Zero) { - dataRaw.AddRange(FetchRow(taosRow,res)); + dataRaw.AddRange(FetchRow(taosRow, res)); } if (TDengine.ErrorNo(res) != 0) { @@ -293,9 +295,9 @@ namespace Sample.UtilsTools case TDengineDataType.TSDB_DATA_TYPE_JSONTAG: string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); dataRaw.Add(v16); - break; + break; default: - dataRaw.Add("nonsupport data type value"); + dataRaw.Add("nonsupport data type"); break; } diff --git a/src/connector/C#/src/TDengineDriver/TDengineDriver.cs b/src/connector/C#/src/TDengineDriver/TDengineDriver.cs index d3bae496746b61d40e4b1fd86f2bdbd0e1f9ff33..8656321e5a9f2c042ea3fdec28276a3ade688997 100644 --- a/src/connector/C#/src/TDengineDriver/TDengineDriver.cs +++ b/src/connector/C#/src/TDengineDriver/TDengineDriver.cs @@ -44,8 +44,26 @@ namespace TDengineDriver TSDB_OPTION_LOCALE = 0, TSDB_OPTION_CHARSET = 1, TSDB_OPTION_TIMEZONE = 2, - TDDB_OPTION_CONFIGDIR = 3, - TDDB_OPTION_SHELL_ACTIVITY_TIMER = 4 + TSDB_OPTION_CONFIGDIR = 3, + TSDB_OPTION_SHELL_ACTIVITY_TIMER = 4 + } + public enum TDengineSchemalessProtocol + { + TSDB_SML_UNKNOWN_PROTOCOL = 0, + TSDB_SML_LINE_PROTOCOL = 1, + TSDB_SML_TELNET_PROTOCOL = 2, + TSDB_SML_JSON_PROTOCOL = 3 + + } + public enum TDengineSchemalessPrecision + { + TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0, + TSDB_SML_TIMESTAMP_HOURS = 1, + TSDB_SML_TIMESTAMP_MINUTES = 2, + TSDB_SML_TIMESTAMP_SECONDS = 3, + TSDB_SML_TIMESTAMP_MILLI_SECONDS = 4, + TSDB_SML_TIMESTAMP_MICRO_SECONDS = 5, + TSDB_SML_TIMESTAMP_NANO_SECONDS = 6 } enum TaosField { @@ -147,7 +165,7 @@ namespace TDengineDriver /// /// User defined callback function for interface "QueryAsync()" /// ,actually is a delegate in .Net. - /// This function aim to handel the taoRes which points to + /// This function aim to handle the taoRes which points to /// the caller method's sql resultset. /// /// This parameter will sent by caller method (QueryAsync()). @@ -179,8 +197,6 @@ namespace TDengineDriver /// Additional parameters supplied by the client when taos_subscribe is called. /// Error code. public delegate void SubscribeCallback(IntPtr subscribe, IntPtr tasRes, IntPtr param, int code); - public delegate void StreamOpenCallback(IntPtr param, IntPtr taosRes, IntPtr taosRow); - public delegate void StreamOpenCallback2(IntPtr ptr); public class TDengine { @@ -234,10 +250,10 @@ namespace TDengineDriver { // const int fieldSize = 68; - List metas = new List(); + List metaList = new List(); if (res == IntPtr.Zero) { - return metas; + return metaList; } int fieldCount = FieldCount(res); @@ -250,11 +266,11 @@ namespace TDengineDriver meta.name = Marshal.PtrToStringAnsi(fieldsPtr + offset); meta.type = Marshal.ReadByte(fieldsPtr + offset + (int)TaosField.TYPE_OFFSET); meta.size = Marshal.ReadInt16(fieldsPtr + offset + (int)TaosField.BYTES_OFFSET); - metas.Add(meta); + metaList.Add(meta); } - return metas; + return metaList; } [DllImport("taos", EntryPoint = "taos_fetch_row", CallingConvention = CallingConvention.Cdecl)] @@ -270,7 +286,9 @@ namespace TDengineDriver [DllImport("taos", EntryPoint = "taos_result_precision", CallingConvention = CallingConvention.Cdecl)] 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); //stmt APIs: /// @@ -430,7 +448,7 @@ namespace TDengineDriver /// returned in this API is unknown. /// /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// piont the error message + /// point the error message [DllImport("taos", EntryPoint = "taos_stmt_errstr", CallingConvention = CallingConvention.Cdecl)] static extern private IntPtr StmtErrPtr(IntPtr stmt); @@ -452,9 +470,9 @@ namespace TDengineDriver // Async Query /// /// This API uses non-blocking call mode. - /// Application can open mutilple tables and manipulate(query or insert) opened table concurrently. - /// So applications must ensure that opetations on the same table is compeletly serialized. - /// Becuase that will cause some query and insert operations cannot be performed. + /// Application can open multiple tables and manipulate(query or insert) opened table concurrently. + /// So applications must ensure that opetations on the same table is completely serialized. + /// Because that will cause some query and insert operations cannot be performed. /// /// A taos connection return by Connect() /// sql command need to execute @@ -561,33 +579,5 @@ namespace TDengineDriver } } - // Stream - - /// - /// Used to open an stream, which can do continuous query. - /// - /// taos connection return by - /// Query statement( query only) - /// User defined callback. - /// The time when stream computing starts. If it is 0, it means starting from now. - /// If it is not zero, it means starting from the specified time (the number of - /// milliseconds from 1970/1/1 UTC time). - /// - /// First parameter provide by application for callback usage. - /// While callback,this parameter is provided to the application. - /// The second callback function which will be caled when the continuous query - /// stop automatically. - /// Return null indicate creation failed, not null for success. - [DllImport("taos", EntryPoint = "taos_open_stream", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr OpenStream(IntPtr taos, string sql, StreamOpenCallback fp, Int64 stime, IntPtr param, StreamOpenCallback2 callback2); - - /// - /// Used too stop data flow. - /// Remember to stop data flow when you stopped steam computing. - /// - /// Value returned by - [DllImport("taos", EntryPoint = "taos_close_stream", CallingConvention = CallingConvention.Cdecl)] - static extern public void CloseStream(IntPtr stream); - } } diff --git a/src/connector/C#/src/TDengineDriver/TDengineDriver.csproj b/src/connector/C#/src/TDengineDriver/TDengineDriver.csproj index 4a030046a1096490e014de9eed6b5f6ac669d7c8..dc577edcd51295330bf263cd676bc8cad84de499 100644 --- a/src/connector/C#/src/TDengineDriver/TDengineDriver.csproj +++ b/src/connector/C#/src/TDengineDriver/TDengineDriver.csproj @@ -4,7 +4,7 @@ net5;netstandard2.1; TDengine.Connector logo.jpg - 1.0.4 + 1.0.6 taosdata www.taosdata.com MIT diff --git a/src/connector/C#/src/TDengineDriver/TaosBind.cs b/src/connector/C#/src/TDengineDriver/TaosBind.cs index 4087d4ff51fc0723ad06e82f58c9cfd4d601ca19..0528cda3eaf35014b4c7fe66f926edac86748236 100644 --- a/src/connector/C#/src/TDengineDriver/TaosBind.cs +++ b/src/connector/C#/src/TDengineDriver/TaosBind.cs @@ -17,17 +17,17 @@ namespace TDengineDriver TAOS_BIND bind = new TAOS_BIND(); byte[] boolByteArr = BitConverter.GetBytes(val); int boolByteArrSize = Marshal.SizeOf(boolByteArr[0]) * boolByteArr.Length; - IntPtr bo = Marshal.AllocHGlobal(1); - Marshal.Copy(boolByteArr, 0, bo, boolByteArr.Length); + IntPtr c_bool = Marshal.AllocHGlobal(1); + Marshal.Copy(boolByteArr, 0, c_bool, boolByteArr.Length); int length = sizeof(Boolean); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BOOL; - bind.buffer = bo; + bind.buffer = c_bool; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -38,17 +38,17 @@ namespace TDengineDriver byte[] tinyIntByteArr = BitConverter.GetBytes(val); int tinyIntByteArrSize = Marshal.SizeOf(tinyIntByteArr[0]) * tinyIntByteArr.Length; - IntPtr uManageTinyInt = Marshal.AllocHGlobal(tinyIntByteArrSize); - Marshal.Copy(tinyIntByteArr, 0, uManageTinyInt, tinyIntByteArr.Length); + IntPtr c_tinyint = Marshal.AllocHGlobal(tinyIntByteArrSize); + Marshal.Copy(tinyIntByteArr, 0, c_tinyint, tinyIntByteArr.Length); int length = sizeof(sbyte); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TINYINT; - bind.buffer = uManageTinyInt; + bind.buffer = c_tinyint; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -58,17 +58,17 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - IntPtr uManageSmallInt = Marshal.AllocHGlobal(sizeof(short)); - Marshal.WriteInt16(uManageSmallInt, val); + IntPtr c_smallint = Marshal.AllocHGlobal(sizeof(short)); + Marshal.WriteInt16(c_smallint, val); int length = sizeof(short); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_SMALLINT; - bind.buffer = uManageSmallInt; + bind.buffer = c_smallint; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -77,17 +77,17 @@ namespace TDengineDriver public static TAOS_BIND BindInt(int val) { TAOS_BIND bind = new TAOS_BIND(); - IntPtr uManageInt = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(uManageInt, val); + IntPtr c_int = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(c_int, val); int length = sizeof(int); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_INT; - bind.buffer = uManageInt; + bind.buffer = c_int; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -97,17 +97,17 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - IntPtr uManageBigInt = Marshal.AllocHGlobal(sizeof(long)); - Marshal.WriteInt64(uManageBigInt, val); + IntPtr c_bigint = Marshal.AllocHGlobal(sizeof(long)); + Marshal.WriteInt64(c_bigint, val); int length = sizeof(long); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BIGINT; - bind.buffer = uManageBigInt; + bind.buffer = c_bigint; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -117,17 +117,17 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - IntPtr uManageTinyInt = Marshal.AllocHGlobal(sizeof(byte)); - Marshal.WriteByte(uManageTinyInt, val); + IntPtr c_unsigned_tinyint = Marshal.AllocHGlobal(sizeof(byte)); + Marshal.WriteByte(c_unsigned_tinyint, val); int length = sizeof(byte); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UTINYINT; - bind.buffer = uManageTinyInt; + bind.buffer = c_unsigned_tinyint; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -139,17 +139,17 @@ namespace TDengineDriver byte[] uSmallIntByteArr = BitConverter.GetBytes(val); int usmallSize = Marshal.SizeOf(uSmallIntByteArr[0]) * uSmallIntByteArr.Length; - IntPtr uManageUnsignSmallInt = Marshal.AllocHGlobal(usmallSize); - Marshal.Copy(uSmallIntByteArr, 0, uManageUnsignSmallInt, uSmallIntByteArr.Length); + IntPtr c_unsigned_smallint = Marshal.AllocHGlobal(usmallSize); + Marshal.Copy(uSmallIntByteArr, 0, c_unsigned_smallint, uSmallIntByteArr.Length); int length = sizeof(UInt16); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_USMALLINT; - bind.buffer = uManageUnsignSmallInt; + bind.buffer = c_unsigned_smallint; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -159,19 +159,19 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - byte[] uManageIntByteArr = BitConverter.GetBytes(val); - int usmallSize = Marshal.SizeOf(uManageIntByteArr[0]) * uManageIntByteArr.Length; - IntPtr uManageInt = Marshal.AllocHGlobal(usmallSize); - Marshal.Copy(uManageIntByteArr, 0, uManageInt, uManageIntByteArr.Length); + byte[] byteArr = BitConverter.GetBytes(val); + int usmallSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length; + IntPtr c_unsigned_int = Marshal.AllocHGlobal(usmallSize); + Marshal.Copy(byteArr, 0, c_unsigned_int, byteArr.Length); int length = sizeof(uint); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UINT; - bind.buffer = uManageInt; + bind.buffer = c_unsigned_int; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -181,19 +181,19 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - byte[] uManageBigIntByteArr = BitConverter.GetBytes(val); - int usmallSize = Marshal.SizeOf(uManageBigIntByteArr[0]) * uManageBigIntByteArr.Length; - IntPtr uManageBigInt = Marshal.AllocHGlobal(usmallSize); - Marshal.Copy(uManageBigIntByteArr, 0, uManageBigInt, uManageBigIntByteArr.Length); + byte[] byteArr = BitConverter.GetBytes(val); + int usmallSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length; + IntPtr c_unsigned_bigint = Marshal.AllocHGlobal(usmallSize); + Marshal.Copy(byteArr, 0, c_unsigned_bigint, byteArr.Length); int length = sizeof(ulong); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UBIGINT; - bind.buffer = uManageBigInt; + bind.buffer = c_unsigned_bigint; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -203,19 +203,19 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - byte[] floatByteArr = BitConverter.GetBytes(val); - int floatByteArrSize = Marshal.SizeOf(floatByteArr[0]) * floatByteArr.Length; - IntPtr uManageFloat = Marshal.AllocHGlobal(floatByteArrSize); - Marshal.Copy(floatByteArr, 0, uManageFloat, floatByteArr.Length); + byte[] byteArr = BitConverter.GetBytes(val); + int floatByteArrSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length; + IntPtr c_float = Marshal.AllocHGlobal(floatByteArrSize); + Marshal.Copy(byteArr, 0, c_float, byteArr.Length); int length = sizeof(float); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_FLOAT; - bind.buffer = uManageFloat; + bind.buffer = c_float; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -225,19 +225,19 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - byte[] doubleByteArr = BitConverter.GetBytes(val); - int doubleByteArrSize = Marshal.SizeOf(doubleByteArr[0]) * doubleByteArr.Length; - IntPtr uManageDouble = Marshal.AllocHGlobal(doubleByteArrSize); - Marshal.Copy(doubleByteArr, 0, uManageDouble, doubleByteArr.Length); + byte[] byteArr = BitConverter.GetBytes(val); + int doubleByteArrSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length; + IntPtr c_double = Marshal.AllocHGlobal(doubleByteArrSize); + Marshal.Copy(byteArr, 0, c_double, byteArr.Length); int length = sizeof(Double); - IntPtr lengPtr = Marshal.AllocHGlobal(sizeof(int)); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int)); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_DOUBLE; - bind.buffer = uManageDouble; + bind.buffer = c_double; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; @@ -247,17 +247,17 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - // IntPtr umanageBinary = Marshal.StringToHGlobalAnsi(val); - IntPtr umanageBinary = Marshal.StringToCoTaskMemUTF8(val); + // IntPtr unmanagedBinary = Marshal.StringToHGlobalAnsi(val); + IntPtr c_str = Marshal.StringToCoTaskMemUTF8(val); var strToBytes = System.Text.Encoding.UTF8.GetBytes(val); - int leng = strToBytes.Length; + int length = strToBytes.Length; IntPtr lenPtr = Marshal.AllocHGlobal(sizeof(ulong)); - Marshal.WriteInt64(lenPtr, leng); + Marshal.WriteInt64(lenPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BINARY; - bind.buffer = umanageBinary; - bind.buffer_length = leng; + bind.buffer = c_str; + bind.buffer_length = length; bind.length = lenPtr; bind.is_null = IntPtr.Zero; @@ -267,17 +267,17 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); var strToBytes = System.Text.Encoding.UTF8.GetBytes(val); - // IntPtr umanageNchar = (IntPtr)Marshal.StringToHGlobalAnsi(val); - IntPtr umanageNchar = (IntPtr)Marshal.StringToCoTaskMemUTF8(val); + // IntPtr unmanagedNchar = (IntPtr)Marshal.StringToHGlobalAnsi(val); + IntPtr c_str = (IntPtr)Marshal.StringToCoTaskMemUTF8(val); - int leng = strToBytes.Length; + int length = strToBytes.Length; IntPtr lenPtr = Marshal.AllocHGlobal(sizeof(ulong)); - Marshal.WriteInt64(lenPtr, leng); + Marshal.WriteInt64(lenPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_NCHAR; - bind.buffer = umanageNchar; - bind.buffer_length = leng; + bind.buffer = c_str; + bind.buffer_length = length; bind.length = lenPtr; bind.is_null = IntPtr.Zero; @@ -301,17 +301,17 @@ namespace TDengineDriver { TAOS_BIND bind = new TAOS_BIND(); - IntPtr uManageTs = Marshal.AllocHGlobal(sizeof(long)); - Marshal.WriteInt64(uManageTs, ts); + IntPtr c_long = Marshal.AllocHGlobal(sizeof(long)); + Marshal.WriteInt64(c_long, ts); int length = sizeof(long); - IntPtr lengPtr = Marshal.AllocHGlobal(4); - Marshal.WriteInt32(lengPtr, length); + IntPtr lengthPtr = Marshal.AllocHGlobal(4); + Marshal.WriteInt32(lengthPtr, length); bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP; - bind.buffer = uManageTs; + bind.buffer = c_long; bind.buffer_length = length; - bind.length = lengPtr; + bind.length = lengthPtr; bind.is_null = IntPtr.Zero; return bind; diff --git a/src/connector/C#/src/TDengineDriver/TaosMultiBind.cs b/src/connector/C#/src/TDengineDriver/TaosMultiBind.cs index a738c3cbfe213be5fdf0a2d8d4ee681f8aeb22ad..69ce27eec3bcb47673927ba50d8c94cbf12658f8 100644 --- a/src/connector/C#/src/TDengineDriver/TaosMultiBind.cs +++ b/src/connector/C#/src/TDengineDriver/TaosMultiBind.cs @@ -17,7 +17,7 @@ namespace TDengineDriver int byteSize = sizeof(byte); //TAOS_MULTI_BIND.buffer - IntPtr unmanagedBoolArr = Marshal.AllocHGlobal(elementCount * typeSize); + IntPtr c_bool_ptr = Marshal.AllocHGlobal(elementCount * typeSize); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -26,7 +26,7 @@ namespace TDengineDriver for (int i = 0; i < elementCount; i++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteByte(unmanagedBoolArr, typeSize * i, Convert.ToByte(arr[i] ?? false)); + Marshal.WriteByte(c_bool_ptr, typeSize * i, Convert.ToByte(arr[i] ?? false)); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -34,7 +34,7 @@ namespace TDengineDriver } //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BOOL; - multiBind.buffer = unmanagedBoolArr; + multiBind.buffer = c_bool_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -53,7 +53,7 @@ namespace TDengineDriver int intSize = sizeof(int); //TAOS_MULTI_BIND.buffer - IntPtr unmanagedTintIntArr = Marshal.AllocHGlobal(elementCount); + IntPtr c_tinyint_ptr = Marshal.AllocHGlobal(elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -64,7 +64,7 @@ namespace TDengineDriver Byte[] toByteArr = BitConverter.GetBytes(arr[i] ?? sbyte.MinValue); //set TAOS_MULTI_BIND.buffer - Marshal.WriteByte(unmanagedTintIntArr, typeSize * i, toByteArr[0]); + Marshal.WriteByte(c_tinyint_ptr, typeSize * i, toByteArr[0]); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -73,7 +73,7 @@ namespace TDengineDriver //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TINYINT; - multiBind.buffer = unmanagedTintIntArr; + multiBind.buffer = c_tinyint_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -92,7 +92,7 @@ namespace TDengineDriver int byteSize = sizeof(byte); //TAOS_MULTI_BIND.buffer - IntPtr unmanagedSmallIntArr = Marshal.AllocHGlobal(elementCount * typeSize); + IntPtr c_smallint_ptr = Marshal.AllocHGlobal(elementCount * typeSize); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -101,7 +101,7 @@ namespace TDengineDriver for (int i = 0; i < elementCount; i++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteInt16(unmanagedSmallIntArr, typeSize * i, arr[i] ?? short.MinValue); + Marshal.WriteInt16(c_smallint_ptr, typeSize * i, arr[i] ?? short.MinValue); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -110,7 +110,7 @@ namespace TDengineDriver } //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_SMALLINT; - multiBind.buffer = unmanagedSmallIntArr; + multiBind.buffer = c_smallint_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -127,7 +127,7 @@ namespace TDengineDriver int byteSize = sizeof(byte); //TAOS_MULTI_BIND.buffer - IntPtr intBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_int_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -136,7 +136,7 @@ namespace TDengineDriver for (int i = 0; i < elementCount; i++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteInt32(intBuff, typeSize * i, arr[i] ?? int.MinValue); + Marshal.WriteInt32(c_int_ptr, typeSize * i, arr[i] ?? int.MinValue); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -145,7 +145,7 @@ namespace TDengineDriver } //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_INT; - multiBind.buffer = intBuff; + multiBind.buffer = c_int_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -162,7 +162,7 @@ namespace TDengineDriver int byteSize = sizeof(byte); //TAOS_MULTI_BIND.buffer - IntPtr intBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_long_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -171,7 +171,7 @@ namespace TDengineDriver for (int i = 0; i < elementCount; i++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteInt64(intBuff, typeSize * i, arr[i] ?? long.MinValue); + Marshal.WriteInt64(c_long_ptr, typeSize * i, arr[i] ?? long.MinValue); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -181,7 +181,7 @@ namespace TDengineDriver } //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BIGINT; - multiBind.buffer = intBuff; + multiBind.buffer = c_long_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -200,7 +200,7 @@ namespace TDengineDriver float[] arrTmp = new float[elementCount]; //TAOS_MULTI_BIND.buffer - IntPtr floatBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_float_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -216,11 +216,11 @@ namespace TDengineDriver Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0)); } //set TAOS_MULTI_BIND.buffer - Marshal.Copy(arrTmp, 0, floatBuff, elementCount); + Marshal.Copy(arrTmp, 0, c_float_ptr, elementCount); //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_FLOAT; - multiBind.buffer = floatBuff; + multiBind.buffer = c_float_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -239,7 +239,7 @@ namespace TDengineDriver double[] arrTmp = new double[elementCount]; //TAOS_MULTI_BIND.buffer - IntPtr doubleBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_double_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -255,11 +255,11 @@ namespace TDengineDriver Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0)); } //set TAOS_MULTI_BIND.buffer - Marshal.Copy(arrTmp, 0, doubleBuff, elementCount); + Marshal.Copy(arrTmp, 0, c_double_ptr, elementCount); //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_DOUBLE; - multiBind.buffer = doubleBuff; + multiBind.buffer = c_double_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -277,7 +277,7 @@ namespace TDengineDriver //used to replace null //TAOS_MULTI_BIND.buffer - IntPtr uTinyIntBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_unsigned_tinyint_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -287,7 +287,7 @@ namespace TDengineDriver for (int i = 0; i < elementCount; i++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteByte(uTinyIntBuff, typeSize * i, arr[i] ?? byte.MaxValue); + Marshal.WriteByte(c_unsigned_tinyint_ptr, typeSize * i, arr[i] ?? byte.MaxValue); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -297,7 +297,7 @@ namespace TDengineDriver //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UTINYINT; - multiBind.buffer = uTinyIntBuff; + multiBind.buffer = c_unsigned_tinyint_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -315,7 +315,7 @@ namespace TDengineDriver //used to replace null //TAOS_MULTI_BIND.buffer - IntPtr uSmallIntBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_unsigned_smallint_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -328,7 +328,7 @@ namespace TDengineDriver for (int j = 0; j < byteArr.Length; j++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteByte(uSmallIntBuff, typeSize * i + j * byteSize, byteArr[j]); + Marshal.WriteByte(c_unsigned_smallint_ptr, typeSize * i + j * byteSize, byteArr[j]); } //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); @@ -339,7 +339,7 @@ namespace TDengineDriver //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_USMALLINT; - multiBind.buffer = uSmallIntBuff; + multiBind.buffer = c_unsigned_smallint_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -357,7 +357,7 @@ namespace TDengineDriver //used to replace null //TAOS_MULTI_BIND.buffer - IntPtr uIntBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_unsigned_int_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -370,7 +370,7 @@ namespace TDengineDriver for (int j = 0; j < byteArr.Length; j++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteByte(uIntBuff, typeSize * i + j * byteSize, byteArr[j]); + Marshal.WriteByte(c_unsigned_int_ptr, typeSize * i + j * byteSize, byteArr[j]); } //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); @@ -381,7 +381,7 @@ namespace TDengineDriver //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UINT; - multiBind.buffer = uIntBuff; + multiBind.buffer = c_unsigned_int_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -399,7 +399,7 @@ namespace TDengineDriver //used to replace null //TAOS_MULTI_BIND.buffer - IntPtr uBigIntBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_unsigned_bigint_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -412,7 +412,7 @@ namespace TDengineDriver for (int j = 0; j < byteArr.Length; j++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteByte(uBigIntBuff, typeSize * i + j * byteSize, byteArr[j]); + Marshal.WriteByte(c_unsigned_bigint_ptr, typeSize * i + j * byteSize, byteArr[j]); } //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); @@ -423,7 +423,7 @@ namespace TDengineDriver //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UBIGINT; - multiBind.buffer = uBigIntBuff; + multiBind.buffer = c_unsigned_bigint_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -439,7 +439,7 @@ namespace TDengineDriver //The size of the buffer is typeSize * elementCount //This buffer is used to store TAOS_MULTI_BIND.buffer int typeSize = MaxElementLength(arr); - //This intSize is used to calcuate buffer size of the struct TAOS_MULTI_BIND's + //This intSize is used to calculate buffer size of the struct TAOS_MULTI_BIND's //length. The buffer is intSize * elementCount,which is used to store TAOS_MULTI_BIND.length int intSize = sizeof(int); //This byteSize is used to calculate the buffer size of the struct TAOS_MULTI_BIND.is_null @@ -452,7 +452,7 @@ namespace TDengineDriver //TAOS_MULTI_BIND.is_null IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount); //TAOS_MULTI_BIND.buffer - IntPtr uNcharBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_char_prt = Marshal.AllocHGlobal(typeSize * elementCount); for (int i = 0; i < elementCount; i++) { @@ -464,7 +464,7 @@ namespace TDengineDriver for (int j = 0; j < itemLength; j++) { //Read byte after byte - Marshal.WriteByte(uNcharBuff, i * typeSize + j, decodeByte[j]); + Marshal.WriteByte(c_char_prt, i * typeSize + j, decodeByte[j]); } } //Set TAOS_MULTI_BIND.length @@ -474,7 +474,7 @@ namespace TDengineDriver } //Config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BINARY; - multiBind.buffer = uNcharBuff; + multiBind.buffer = c_char_prt; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -491,7 +491,7 @@ namespace TDengineDriver //The size of the buffer is typeSize * elementCount //This buffer is used to store TAOS_MULTI_BIND.buffer int typeSize = MaxElementLength(arr); - //This intSize is used to calcuate buffer size of the struct TAOS_MULTI_BIND's + //This intSize is used to calculate buffer size of the struct TAOS_MULTI_BIND's //length. The buffer is intSize * elementCount,which is used to store TAOS_MULTI_BIND.length int intSize = sizeof(int); //This byteSize is used to calculate the buffer size of the struct TAOS_MULTI_BIND.is_null @@ -503,7 +503,7 @@ namespace TDengineDriver //TAOS_MULTI_BIND.is_null IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount); //TAOS_MULTI_BIND.buffer - IntPtr uNcharBuff = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_char_prt = Marshal.AllocHGlobal(typeSize * elementCount); for (int i = 0; i < elementCount; i++) { @@ -515,7 +515,7 @@ namespace TDengineDriver for (int j = 0; j < itemLength; j++) { //Read byte after byte - Marshal.WriteByte(uNcharBuff, i * typeSize + j, decodeByte[j]); + Marshal.WriteByte(c_char_prt, i * typeSize + j, decodeByte[j]); } } //Set TAOS_MULTI_BIND.length @@ -525,7 +525,7 @@ namespace TDengineDriver } //Config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_NCHAR; - multiBind.buffer = uNcharBuff; + multiBind.buffer = c_char_prt; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; @@ -542,7 +542,7 @@ namespace TDengineDriver int intSize = sizeof(int); int byteSize = sizeof(byte); //TAOS_MULTI_BIND.buffer - IntPtr unmanagedTsArr = Marshal.AllocHGlobal(typeSize * elementCount); + IntPtr c_long_ptr = Marshal.AllocHGlobal(typeSize * elementCount); //TAOS_MULTI_BIND.length IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount); //TAOS_MULTI_BIND.is_null @@ -551,7 +551,7 @@ namespace TDengineDriver for (int i = 0; i < elementCount; i++) { //set TAOS_MULTI_BIND.buffer - Marshal.WriteInt64(unmanagedTsArr, typeSize * i, arr[i]); + Marshal.WriteInt64(c_long_ptr, typeSize * i, arr[i]); //set TAOS_MULTI_BIND.length Marshal.WriteInt32(lengthArr, intSize * i, typeSize); //set TAOS_MULTI_BIND.is_null @@ -560,7 +560,7 @@ namespace TDengineDriver //config TAOS_MULTI_BIND multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP; - multiBind.buffer = unmanagedTsArr; + multiBind.buffer = c_long_ptr; multiBind.buffer_length = (ulong)typeSize; multiBind.length = lengthArr; multiBind.is_null = nullArr; diff --git a/src/connector/C#/src/test/FunctionTest/DataSource.cs b/src/connector/C#/src/test/FunctionTest/DataSource.cs index cdeb817efdc5a9f91a015e687f1fb7376c91044d..58e99c6387c41360e137fa6bc5fbad3396afc337 100644 --- a/src/connector/C#/src/test/FunctionTest/DataSource.cs +++ b/src/connector/C#/src/test/FunctionTest/DataSource.cs @@ -116,7 +116,7 @@ namespace Test.UtilsTools.DataSource } // Get the tag data within and string list // Which will be retrieved as a string List - private static List GetTagCnData() + private static List GetTagCNData() { List tagData = new List(); tagData.Add(true.ToString()); @@ -136,7 +136,7 @@ namespace Test.UtilsTools.DataSource } // A line of data that's without CN character. // Which is construct as an TAOS_BIND array - public static TAOS_BIND[] GetNtableCNRow() + public static TAOS_BIND[] GetNTableCNRow() { TAOS_BIND[] binds = new TAOS_BIND[15]; binds[0] = TaosBind.BindTimestamp(1637064040000); @@ -157,7 +157,7 @@ namespace Test.UtilsTools.DataSource return binds; } //Get and list data that will be insert into table - public static List GetNtableCNRowData() + public static List GetNTableCNRowData() { var data = new List{ "1637064040000", @@ -180,16 +180,16 @@ namespace Test.UtilsTools.DataSource } // Get the data value and tag values which have chinese characters // And retrieved as a string list.This is single Line. - public static List GetStableCNRowData() + public static List GetSTableCNRowData() { - List columnData = GetNtableCNRowData(); - List tagData = GetTagCnData(); + List columnData = GetNTableCNRowData(); + List tagData = GetTagCNData(); columnData.AddRange(tagData); return columnData; } // A line of data that's without CN character - public static TAOS_BIND[] GetNtableRow() + public static TAOS_BIND[] GetNTableRow() { TAOS_BIND[] binds = new TAOS_BIND[15]; binds[0] = TaosBind.BindTimestamp(1637064040000); @@ -209,8 +209,8 @@ namespace Test.UtilsTools.DataSource binds[14] = TaosBind.BindNil(); return binds; } - // A List of data ,use as expectResData. The value is equal to getNtableRow() - public static List GetNtableRowData() + // A List of data ,use as expectResData. The value is equal to getNTableRow() + public static List GetNTableRowData() { var data = new List{ "1637064040000", @@ -232,7 +232,7 @@ namespace Test.UtilsTools.DataSource return data; } - // Five lines of data, that is construct as taos_mutli_bind array. + // Five lines of data, that is construct as taos_multi_bind array. // There aren't any CN character public static TAOS_MULTI_BIND[] GetMultiBindArr() { @@ -280,8 +280,8 @@ namespace Test.UtilsTools.DataSource } return rowData; } - // Five lines of data, that is construct as taos_mutli_bind array. - // There aren some CN characters and letters. + // Five lines of data, that is construct as taos_multi_bind array. + // There are some CN characters and letters. public static TAOS_MULTI_BIND[] GetMultiBindCNArr() { TAOS_MULTI_BIND[] mBinds = new TAOS_MULTI_BIND[14]; @@ -332,7 +332,7 @@ namespace Test.UtilsTools.DataSource public static List GetMultiBindStableCNRowData() { List columnData = new List(); - List tagData = GetTagCnData(); + List tagData = GetTagCNData(); for (int i = 0; i < tsArr.Length; i++) { columnData.Add(tsArr[i].ToString()); @@ -371,18 +371,18 @@ namespace Test.UtilsTools.DataSource TaosBind.FreeTaosBind(binds); } - public static void FreeTaosMBind(TAOS_MULTI_BIND[] mbinds) + public static void FreeTaosMBind(TAOS_MULTI_BIND[] mBinds) { - TaosMultiBind.FreeTaosBind(mbinds); + TaosMultiBind.FreeTaosBind(mBinds); } //Get the TDengineMeta list from the ddl either normal table or stable - public static List GetMetaFromDLL(string dllStr) + public static List GetMetaFromDDL(string dllStr) { var expectResMeta = new List(); //"CREATE TABLE meters(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS(location BINARY(30), groupId INT);"; - int bracetInd = dllStr.IndexOf("("); + int bracketInd = dllStr.IndexOf("("); //(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS(location BINARY(30), groupId INT); - string subDllStr = dllStr.Substring(bracetInd); + string subDllStr = dllStr.Substring(bracketInd); String[] stableSeparators = new String[] { "tags", "TAGS" }; //(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) diff --git a/src/connector/C#/src/test/FunctionTest/TaosFeild.cs b/src/connector/C#/src/test/FunctionTest/FetchFields.cs similarity index 85% rename from src/connector/C#/src/test/FunctionTest/TaosFeild.cs rename to src/connector/C#/src/test/FunctionTest/FetchFields.cs index ba6f7fad018e80d16b0b422503a3a1ca05d3f761..b0a5859d4dddef0b24bd98cc8183917b6ec4e1cb 100644 --- a/src/connector/C#/src/test/FunctionTest/TaosFeild.cs +++ b/src/connector/C#/src/test/FunctionTest/FetchFields.cs @@ -4,21 +4,34 @@ using TDengineDriver; using System.Collections.Generic; using Xunit; using Test.UtilsTools.ResultSet; +using Test.Fixture; +using Test.Case.Attributes; + namespace Cases { + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] public class FetchFieldCases { + + DatabaseFixture database; + + + public FetchFieldCases(DatabaseFixture fixture) + { + this.database = fixture; + } /// xiaolei - /// FetchFieldCases.TestFetchFieldJsonTag + /// FetchFieldsCases.TestFetchFieldsJsonTag /// test taos_fetch_fields(), check the meta data - /// TaosFeild.cs + /// FetchFields.cs /// pass or failed - [Fact(DisplayName = "FetchFieldCases.TestFetchFieldJsonTag()")] + [Fact(DisplayName = "FetchFieldsCases.TestFetchFieldJsonTag()"),TestExeOrder(1),Trait("Category", "FetchFieldJsonTag")] public void TestFetchFieldJsonTag() { - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; IntPtr _res = IntPtr.Zero; - string tableName = "fetchfeilds"; + string tableName = "fetch_fields"; var expectResMeta = new List { UtilsTools.ConstructTDengineMeta("ts", "timestamp"), UtilsTools.ConstructTDengineMeta("b", "bool"), diff --git a/src/connector/C#/src/test/FunctionTest/FetchLength.cs b/src/connector/C#/src/test/FunctionTest/FetchLength.cs index 130b53bfc898231456c3f4d0c068108ffa7f50bd..928e1dfa92a723c52a2939bece2552ddeba7fd3f 100644 --- a/src/connector/C#/src/test/FunctionTest/FetchLength.cs +++ b/src/connector/C#/src/test/FunctionTest/FetchLength.cs @@ -4,8 +4,11 @@ using System.Collections.Generic; using Xunit; using TDengineDriver; using Test.UtilsTools.ResultSet; +using Test.Case.Attributes; namespace Cases { + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + public class FetchLengthCase { /// xiaolei @@ -13,7 +16,7 @@ namespace Cases /// TD-12103 C# connector fetch_row with binary data retrieving error /// FetchLength.cs /// pass or failed - [Fact(DisplayName = "Skip FetchLengthCase.TestRetrieveBinary()")] + [Fact(DisplayName = "FetchLengthCase.TestRetrieveBinary()"),TestExeOrder(1)] public void TestRetrieveBinary() { IntPtr conn = UtilsTools.TDConnection(); diff --git a/src/connector/C#/src/test/FunctionTest/InsertCn.cs b/src/connector/C#/src/test/FunctionTest/InsertCn.cs index eec931aacb9333a007638799f819e9828b152297..51931340f50a9b9b8876a1d8ba2cf11c13259e97 100644 --- a/src/connector/C#/src/test/FunctionTest/InsertCn.cs +++ b/src/connector/C#/src/test/FunctionTest/InsertCn.cs @@ -5,19 +5,28 @@ using Test.UtilsTools.DataSource; using Xunit; using System.Collections.Generic; using Test.UtilsTools.ResultSet; +using Test.Case.Attributes; +using Test.Fixture; namespace Cases { - public class InsertCnCharacterCases + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] + public class InsertCNCases { + DatabaseFixture database; + public InsertCNCases(DatabaseFixture fixture) + { + this.database = fixture; + } /// xiaolei - /// InsertCnCharacterCases.TestInsertCnToNtable - /// test insert Chinese character into normal table's nchar column + /// InsertCNCases.TestNTable + /// Test insert Chinese characters into normal table's nchar column /// InsertCn.cs /// pass or failed - [Fact(DisplayName = "InsertCnCharacterCases.TestInsertCnToNtable()")] - public void TestInsertCnToNtable() + [Fact(DisplayName = "InsertCNCases.TestNTable"), TestExeOrder(1)] + public void TestNTable() { - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; IntPtr _res = IntPtr.Zero; string tableName = "cn_insert_nchar_ntable"; // var expectResData = new List { "1637064040000", "true", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "XI", "XII", "{\"k1\": \"v1\"}" }; @@ -37,7 +46,7 @@ namespace Cases String insertSql = UtilsTools.ConstructInsertSql(tableName, "", colData, null, 9); String selectSql = "select * from " + tableName; String dropSql = "drop table " + tableName; - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); UtilsTools.ExecuteUpdate(conn, dropTb); UtilsTools.ExecuteUpdate(conn, createTb); @@ -64,14 +73,14 @@ namespace Cases } /// xiaolei - /// InsertCnCharacterCases.TestInsertCnToStable + /// InsertCNCases.TestSTable /// test insert Chinese character into stable's nchar column,both tag and column /// InsertCn.cs /// pass or failed - [Fact(DisplayName = "InsertCnCharacterCases.TestInsertCnToStable()")] - public void TestInsertCnToStable() + [Fact(DisplayName = "InsertCNCases.TestSTable()"), TestExeOrder(2)] + public void TestSTable() { - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; IntPtr _res = IntPtr.Zero; string tableName = "cn_insert_nchar_stable"; var colData = new List{1637064040000,1,"涛思数据", @@ -84,15 +93,15 @@ namespace Cases 1637064047000,8,"8&涛思数据taos", 1637064048000,9,"&涛思数据taos9" }; - var tagData = new List{1,"涛思数据",}; + var tagData = new List { 1, "涛思数据", }; String dropTb = "drop table if exists " + tableName; String createTb = $"create table {tableName} (ts timestamp,v4 int,blob nchar(200))tags(id int,name nchar(50));"; - String insertSql = UtilsTools.ConstructInsertSql(tableName+"_sub1", tableName, colData, tagData, 9); + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_sub1", tableName, colData, tagData, 9); String selectSql = "select * from " + tableName; String dropSql = "drop table " + tableName; - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - List expectResData = UtilsTools.CombineColAndTagData(colData,tagData,9); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 9); UtilsTools.ExecuteUpdate(conn, dropTb); UtilsTools.ExecuteUpdate(conn, createTb); @@ -118,14 +127,14 @@ namespace Cases } /// xiaolei - /// InsertCnCharacterCases.TestInsertMutilCnToNtable + /// InsertCNCases.TestInsertMultiNTable /// test insert Chinese character into normal table's multiple nchar columns /// InsertCn.cs /// pass or failed - [Fact(DisplayName = "InsertCnCharacterCases.TestInsertMutilCnToNtable()")] - public void TestInsertMutilCnToNtable() + [Fact(DisplayName = "InsertCNCases.TestInsertMultiNTable()"), TestExeOrder(3)] + public void TestInsertMultiNTable() { - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; IntPtr _res = IntPtr.Zero; string tableName = "cn_multi_insert_nchar_ntable"; var colData = new List{1637064040000,1,"涛思数据","保利广场","Beijing","China", @@ -144,7 +153,7 @@ namespace Cases String insertSql = UtilsTools.ConstructInsertSql(tableName, "", colData, null, 9); String selectSql = "select * from " + tableName; String dropSql = "drop table " + tableName; - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); UtilsTools.ExecuteUpdate(conn, dropTb); UtilsTools.ExecuteUpdate(conn, createTb); @@ -168,16 +177,16 @@ namespace Cases Assert.Equal(colData[i].ToString(), actualResData[i]); } } - + /// xiaolei - /// InsertCnCharacterCases.TestInsertMutilCnToStable + /// InsertCNCases.TestInsertMultiSTable /// test insert Chinese character into stable's multiple nchar columns /// InsertCn.cs /// pass or failed - [Fact(DisplayName = "InsertCnCharacterCases.TestInsertMutilCnToStable()")] - public void TestInsertMutilCnToStable() + [Fact(DisplayName = "InsertCNCases.TestInsertMultiSTable()"), TestExeOrder(4)] + public void TestInsertMultiSTable() { - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; IntPtr _res = IntPtr.Zero; string tableName = "cn_multi_insert_nchar_stable"; var colData = new List{1637064040000,1,"涛思数据","保利广场","Beijing","China", @@ -190,7 +199,7 @@ namespace Cases 1637064047000,8,"8&涛思数据taos","incluse阿斯顿发","NewYork","US", 1637064048000,9,"&涛思数据taos9","123黑化肥werq会挥……&¥%发!afsdfa","NewYork","US", }; - var tagData = new List{1,"涛思数据","中国北方&南方长江黄河!49wq","tdengine"}; + var tagData = new List { 1, "涛思数据", "中国北方&南方长江黄河!49wq", "tdengine" }; String dropTb = "drop table if exists " + tableName; String createTb = $"create table if not exists {tableName} (ts timestamp," + $"v4 int," + @@ -203,12 +212,12 @@ namespace Cases $"name nchar(50)," + $"addr nchar(200)," + $"en_name binary(200));"; - String insertSql = UtilsTools.ConstructInsertSql(tableName+"_sub1", tableName, colData, tagData, 9); + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_sub1", tableName, colData, tagData, 9); String selectSql = "select * from " + tableName; String dropSql = "drop table " + tableName; - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - List expectResData = UtilsTools.CombineColAndTagData(colData,tagData,9); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 9); UtilsTools.ExecuteUpdate(conn, dropTb); UtilsTools.ExecuteUpdate(conn, createTb); @@ -233,4 +242,4 @@ namespace Cases } } } -} \ No newline at end of file +} diff --git a/src/connector/C#/src/test/FunctionTest/QueryAsync.cs b/src/connector/C#/src/test/FunctionTest/QueryAsync.cs new file mode 100644 index 0000000000000000000000000000000000000000..31e6665d6bfbc286eb817e0c1e4967aa7fefafd6 --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/QueryAsync.cs @@ -0,0 +1,295 @@ +using TDengineDriver; +using Test.UtilsTools; +using System; +using Xunit; +using System.Collections.Generic; +using Test.UtilsTools.DataSource; +using Test.UtilsTools.ResultSet; +using Xunit.Abstractions; +using Test.Fixture; +using Test.Case.Attributes; + +namespace Cases +{ + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] + + public class QueryAsyncCases + { + DatabaseFixture database; + + private readonly ITestOutputHelper output; + + public QueryAsyncCases(DatabaseFixture fixture, ITestOutputHelper output) + { + this.database = fixture; + this.output = output; + } + /// xiaolei + /// QueryAsyncCases.QueryAsyncCases + /// Test query without condition + /// QueryAsync.cs + /// pass or failed + [Fact(DisplayName = "QueryAsyncCases.QueryWithoutCondition()"),TestExeOrder(1),Trait("Category", "QueryAWithoutCondition")] + public void QueryWithoutCondition() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "query_a_without_condition"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))"; + var dropSql = $"drop table if exists {tableName}"; + + var colData = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值三", + }; + var tagData = new List { 1, "tag_one", "标签壹" }; + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3); + + var querySql = $"select * from {tableName}"; + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql); + + QueryAsyncCallback fq = new QueryAsyncCallback(QueryCallback); + TDengine.QueryAsync(conn, querySql, fq, IntPtr.Zero); + + void QueryCallback(IntPtr param, IntPtr taosRes, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback); + TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param); + } + else + { + Console.WriteLine($"async query data failed, failed code {code}"); + } + + } + + void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows) + { + if (numOfRows > 0) + { + ResultSet actualResult = new ResultSet(taosRes); + List actualMeta = actualResult.GetResultMeta(); + List actualResData = actualResult.GetResultData(); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // Console.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData[i].ToString(), actualResData[i]); + } + + TDengine.FetchRowAsync(taosRes, FetchCallback, param); + } + else + { + if (numOfRows == 0) + { + Console.WriteLine("async retrieve complete."); + + } + else + { + Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}"); + } + TDengine.FreeResult(taosRes); + } + } + } + + /// xiaolei + /// QueryAsyncCases.QueryWithCondition + /// Test query with condition + /// QueryAsync.cs + /// pass or failed + [Fact(DisplayName = "QueryAsyncCases.QueryWithCondition()"),TestExeOrder(2),Trait("Category", "QueryAWithCondition")] + public void QueryWithCondition() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "query_a_with_condition"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))"; + var dropSql = $"drop table if exists {tableName}"; + + var colData = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值三", + }; + var colDataActual = colData.GetRange(8, 8); + var tagData = new List { 1, "tag_one", "标签壹" }; + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colDataActual, tagData, 1); + colDataActual.ForEach((item) => { Console.Write("{0}\t", item); }); + + var querySql = $"select * from {tableName} where bl=true and t_bnr='tag_one' and i8>1 and t_nchr = '标签壹'"; + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql); + QueryAsyncCallback fq = new QueryAsyncCallback(QueryCallback); + TDengine.QueryAsync(conn, querySql, fq, IntPtr.Zero); + + void QueryCallback(IntPtr param, IntPtr taosRes, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback); + TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param); + } + else + { + Console.WriteLine($"async query data failed, failed code {code}"); + } + + } + + void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows) + { + if (numOfRows > 0) + { + ResultSet actualResult = new ResultSet(taosRes); + List actualMeta = actualResult.GetResultMeta(); + List actualResData = actualResult.GetResultData(); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // Console.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData[i].ToString(), actualResData[i]); + } + + TDengine.FetchRowAsync(taosRes, FetchCallback, param); + } + else + { + if (numOfRows == 0) + { + Console.WriteLine("async retrieve complete."); + + } + else + { + Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}"); + } + TDengine.FreeResult(taosRes); + } + } + + } + + /// xiaolei + /// QueryAsyncCases.QueryWithJsonCondition + /// Test query with condition + /// QueryAsync.cs + /// pass or failed + [Fact(DisplayName = "QueryAsyncCases.QueryWithJsonCondition()"),TestExeOrder(3),Trait("Category", "QueryAWithJsonCondition")] + public void QueryWithJsonCondition() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "query_a_json_condition"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(jtag json)"; + var dropSql = $"drop table if exists {tableName}"; + + var colData1 = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值三", + }; + var colData2 = new List{1646150410400,false,4,44,4444,44444444,"value three","值肆", + 1646150410500,true,5,55,5555,55555555,"value one","值伍", + 1646150410600,true,6,66,6666,66666666,"value two","值陆", + }; + var tagData1 = new List { "{\"t_bnr\":\"tag1\",\"t_i32\":1,\"t_nchr\":\"标签壹\"}" }; + var tagData2 = new List { "{\"t_bnr\":\"tag2\",\"t_i32\":2,\"t_nchar\":\"标签贰\"}" }; + var querySql = $"select * from {tableName} where jtag->'t_bnr'='tag1';"; + + + String insertSql1 = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData1, tagData1, 3); + String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData1, tagData2, 3); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colData1, tagData1, 3); + + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql1); + UtilsTools.ExecuteUpdate(conn, insertSql2); + QueryAsyncCallback fq = new QueryAsyncCallback(QueryCallback); + TDengine.QueryAsync(conn, querySql, fq, IntPtr.Zero); + + void QueryCallback(IntPtr param, IntPtr taosRes, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback); + TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param); + } + else + { + Console.WriteLine($"async query data failed, failed code {code}"); + } + + } + + void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows) + { + if (numOfRows > 0) + { + ResultSet actualResult = new ResultSet(taosRes); + List actualMeta = actualResult.GetResultMeta(); + List actualResData = actualResult.GetResultData(); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // Console.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData[i].ToString(), actualResData[i]); + } + + TDengine.FetchRowAsync(taosRes, FetchCallback, param); + } + else + { + if (numOfRows == 0) + { + Console.WriteLine("async retrieve complete."); + + } + else + { + Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}"); + } + TDengine.FreeResult(taosRes); + } + } + + + } + } +} diff --git a/src/connector/C#/src/test/FunctionTest/StmtNormalTable.cs b/src/connector/C#/src/test/FunctionTest/StmtNormalTable.cs index 7e6cc92d65863b634261153c9eb38c5c0a590891..72983dd02d44d8a1cf1cb2b80cf5ed033860b2f4 100644 --- a/src/connector/C#/src/test/FunctionTest/StmtNormalTable.cs +++ b/src/connector/C#/src/test/FunctionTest/StmtNormalTable.cs @@ -5,19 +5,30 @@ using Test.UtilsTools.DataSource; using Xunit; using System.Collections.Generic; using Test.UtilsTools.ResultSet; +using Test.Fixture; +using Test.Case.Attributes; + namespace Cases { + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] public class NormalTableStmtCases { + DatabaseFixture database; + + public NormalTableStmtCases(DatabaseFixture fixture) + { + this.database = fixture; + } /// xiaolei - /// NormalTableStmtCases.TestBindSingleLineCn + /// NormalTableStmtCases.TestBindSingleLineCN /// Test stmt insert single line of chinese character into normal table by column after column /// StmtNormalTable.cs /// pass or failed - [Fact(DisplayName = "NormalTableStmtCases.TestBindSingleLineCn()")] - public void TestBindSingleLineCn() + [Fact(DisplayName = "NormalTableStmtCases.TestBindSingleLineCN()"),TestExeOrder(2),Trait("Category", "bindParamCN")] + public void TestBindSingleLineCN() { - string tableName = "normal_tablestmt_cases_test_bind_single_line_cn"; + string tableName = "ntb_stmt_cases_test_bind_single_line_cn"; String createTb = $"create table if not exists {tableName} (" + "ts timestamp," + "tt tinyint," + @@ -38,11 +49,11 @@ namespace Cases string insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; string dropSql = $"drop table if exists {tableName}"; string querySql = "select * from " + tableName; - TAOS_BIND[] _valuesRow = DataSource.GetNtableCNRow(); - List expectResData = DataSource.GetNtableCNRowData(); - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + TAOS_BIND[] _valuesRow = DataSource.GetNTableCNRow(); + List expectResData = DataSource.GetNTableCNRowData(); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createTb); @@ -76,14 +87,14 @@ namespace Cases } /// xiaolei - /// NormalTableStmtCases.TestBindColumnCn + /// NormalTableStmtCases.TestBindColumnCN /// Test stmt insert single line of chinese character into normal table by column after column /// StmtNormalTable.cs /// pass or failed - [Fact(DisplayName = "NormalTableStmtCases.TestBindColumnCn()")] - public void TestBindColumnCn() + [Fact(DisplayName = "NormalTableStmtCases.TestBindColumnCN()"),TestExeOrder(4),Trait("Category", "bindSingleColumnCN")] + public void TestBindColumnCN() { - string tableName = "normal_tablestmt_cases_test_bind_column_cn"; + string tableName = "ntb_stmt_cases_test_bind_column_cn"; String createTb = $"create table if not exists {tableName} " + " (" + "ts timestamp," + @@ -104,10 +115,10 @@ namespace Cases String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName} "; List expectResData = DataSource.GetMultiBindCNRowData(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindCNArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + TAOS_MULTI_BIND[] mBind = DataSource.GetMultiBindCNArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createTb); @@ -115,26 +126,26 @@ namespace Cases StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableName(stmt, tableName); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[0], 0); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[1], 1); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[2], 2); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[3], 3); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[4], 4); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[5], 5); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[6], 6); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[7], 7); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[8], 8); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[9], 9); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[10], 10); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[11], 11); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[12], 12); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[13], 13); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[0], 0); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[1], 1); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[2], 2); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[3], 3); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[4], 4); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[5], 5); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[6], 6); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[7], 7); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[8], 8); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[9], 9); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[10], 10); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[11], 11); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[12], 12); + StmtUtilTools.BindSingleParamBatch(stmt, mBind[13], 13); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBind); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); @@ -158,15 +169,15 @@ namespace Cases } /// xiaolei - /// NormalTableStmtCases.TestBindMultiLineCn + /// NormalTableStmtCases.TestBindMultiLineCN /// Test stmt insert single line of chinese character into normal table by column after column /// StmtNormalTable.cs /// pass or failed - [Fact(DisplayName = "NormalTableStmtCases.TestBindMultiLineCn()")] - public void TestBindMultiLineCn() + [Fact(DisplayName = "NormalTableStmtCases.TestBindMultiLineCN()"),TestExeOrder(6),Trait("Category", "bindParamBatchCN")] + public void TestBindMultiLineCN() { - string tableName = "normal_tablestmt_cases_test_bind_multi_lines_cn"; - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindCNArr(); + string tableName = "ntb_stmt_cases_test_bind_multi_lines_cn"; + TAOS_MULTI_BIND[] mBind = DataSource.GetMultiBindCNArr(); String createTb = $"create table if not exists {tableName} " + " (" + "ts timestamp," + @@ -187,21 +198,21 @@ namespace Cases String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName} "; List expectResData = DataSource.GetMultiBindCNRowData(); - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - IntPtr conn = UtilsTools.TDConnection(); ; + IntPtr conn = database.conn; ; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createTb); IntPtr stmt = StmtUtilTools.StmtInit(conn); StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableName(stmt, tableName); - StmtUtilTools.BindParamBatch(stmt, mbind); + StmtUtilTools.BindParamBatch(stmt, mBind); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBind); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); @@ -228,13 +239,13 @@ namespace Cases /// xiaolei /// NormalTableStmtCases.TestBindSingleLine - /// Test stmt insert sinle line data into normal table + /// Test stmt insert single line data into normal table /// StmtNormalTable.cs /// pass or failed - [Fact(DisplayName = "NormalTableStmtCases.TestBindSingleLine")] + [Fact(DisplayName = "NormalTableStmtCases.TestBindSingleLine"),TestExeOrder(3),Trait("Category", "BindSingleColumn")] public void TestBindSingleLine() { - string tableName = "normal_tablestmt_cases_test_bind_single_line"; + string tableName = "ntb_stmt_cases_test_bind_single_line"; String createTb = $"create table if not exists {tableName} (" + "ts timestamp," + "tt tinyint," + @@ -255,11 +266,11 @@ namespace Cases string insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; string dropSql = $"drop table if exists {tableName}"; string querySql = "select * from " + tableName; - TAOS_BIND[] valuesRow = DataSource.GetNtableRow(); - List expectResData = DataSource.GetNtableRowData(); - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + TAOS_BIND[] valuesRow = DataSource.GetNTableRow(); + List expectResData = DataSource.GetNTableRowData(); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteQuery(conn, dropSql); UtilsTools.ExecuteQuery(conn, createTb); @@ -296,14 +307,14 @@ namespace Cases } /// xiaolei - /// NtableMutipleLine.TestBindMultiLine + /// NormalTableStmtCases.TestBindMultiLine /// Test stmt insert multiple rows of data into normal table /// StmtNormalTable.cs /// pass or failed - [Fact(DisplayName = "NormalTableStmtCases.TestBindMultiLine()")] + [Fact(DisplayName = "NormalTableStmtCases.TestBindMultiLine()"),TestExeOrder(5),Trait("Category", "bindParamBatch")] public void TestBindMultiLine() { - string tableName = "normal_table_stmt_cases_test_bind_multi_lines"; + string tableName = "ntb_stmt_case_test_bind_multi_lines"; String createTb = $"create table if not exists {tableName} " + " (" + "ts timestamp," + @@ -324,10 +335,10 @@ namespace Cases String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName} "; List expectResData = DataSource.GetMultiBindResData(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + TAOS_MULTI_BIND[] mBind = DataSource.GetMultiBindArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createTb); @@ -335,11 +346,11 @@ namespace Cases IntPtr stmt = StmtUtilTools.StmtInit(conn); StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableName(stmt, tableName); - StmtUtilTools.BindParamBatch(stmt, mbind); + StmtUtilTools.BindParamBatch(stmt, mBind); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBind); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); @@ -365,14 +376,14 @@ namespace Cases } /// xiaolei - /// NtableColumnByColumn.TestBindColumnCn + /// NormalTableStmtCases.TestBindColumn /// Test stmt insert multiple rows of data into normal table by column after column /// StmtNormalTable.cs /// pass or failed - [Fact(DisplayName = "NormalTableStmtCases.TestBindColumn()")] + [Fact(DisplayName = "NormalTableStmtCases.TestBindColumn()"),TestExeOrder(1),Trait("Category", "bindParam")] public void TestBindColumn() { - string tableName = "normal_tablestmt_cases_test_bind_column_cn"; + string tableName = "ntb_stmt_cases_test_bind_column"; DataSource data = new DataSource(); String createTb = $"create table if not exists {tableName} " + " (" + @@ -394,11 +405,11 @@ namespace Cases String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName} "; List expectResData = DataSource.GetMultiBindResData(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createTb); + TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createTb); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createTb); @@ -406,26 +417,26 @@ namespace Cases StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableName(stmt, tableName); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[0], 0); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[1], 1); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[2], 2); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[3], 3); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[4], 4); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[5], 5); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[6], 6); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[7], 7); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[8], 8); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[9], 9); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[10], 10); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[11], 11); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[12], 12); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[13], 13); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[0], 0); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[1], 1); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[2], 2); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[3], 3); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[4], 4); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[5], 5); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[6], 6); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[7], 7); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[8], 8); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[9], 9); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[10], 10); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[11], 11); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[12], 12); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[13], 13); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBinds); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); diff --git a/src/connector/C#/src/test/FunctionTest/StmtQuery.cs b/src/connector/C#/src/test/FunctionTest/StmtQuery.cs index 7909376ad8d2166acc51e9f683bfbbac1dcd652e..2911b8889e9c7520bf942fd65bc1bd5cc021ef53 100644 --- a/src/connector/C#/src/test/FunctionTest/StmtQuery.cs +++ b/src/connector/C#/src/test/FunctionTest/StmtQuery.cs @@ -5,7 +5,7 @@ using Test.UtilsTools.DataSource; namespace Cases { - public class StmtStableQuery + public class StmtSTableQuery { public void Test(IntPtr conn, string tableName) { @@ -26,7 +26,7 @@ namespace Cases } } - public class StmtNtableQuery + public class StmtNTableQuery { public void Test(IntPtr conn, string tableName) { diff --git a/src/connector/C#/src/test/FunctionTest/StmtStable.cs b/src/connector/C#/src/test/FunctionTest/StmtStable.cs index c79c355f02f8a6351098f6fca773751f64182ff9..44ecb298ffcfb3786c1fe76e4ce65336ad2b52fd 100644 --- a/src/connector/C#/src/test/FunctionTest/StmtStable.cs +++ b/src/connector/C#/src/test/FunctionTest/StmtStable.cs @@ -5,20 +5,33 @@ using Test.UtilsTools.DataSource; using System.Collections.Generic; using Test.UtilsTools.ResultSet; using Xunit; +using Test.Fixture; +using Test.Case.Attributes; namespace Cases { + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] + public class StableStmtCases { + + DatabaseFixture database; + + + public StableStmtCases(DatabaseFixture fixture) + { + this.database = fixture; + } /// xiaolei - /// StableStmtCases.TestBindSingleLineCn + /// StableStmtCases.TestBindSingleLineCN /// Test stmt insert single line of chinese character into stable by column after column /// StmtSTable.cs /// pass or failed - [Fact(DisplayName = "StableStmtCases.TestBindSingleLineCn()")] - public void TestBindSingleLineCn() + [Fact(DisplayName = "StableStmtCases.TestBindSingleLineCN()"),TestExeOrder(2),Trait("Category", "BindParamCN")] + public void TestBindSingleLineCN() { - string tableName = "stable_stmt_cases_test_bind_single_line_cn"; + string tableName = "stb_stmt_cases_test_bind_single_line_cn"; String createSql = $"create stable if not exists {tableName} " + " (ts timestamp," + "v1 tinyint," + @@ -52,12 +65,12 @@ namespace Cases ");"; String insertSql = $"insert into ? using {tableName} tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName} ;"; - List expectResMeta = DataSource.GetMetaFromDLL(createSql); - List expectResData = DataSource.GetStableCNRowData(); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = DataSource.GetSTableCNRowData(); TAOS_BIND[] tags = DataSource.GetCNTags(); - TAOS_BIND[] binds = DataSource.GetNtableCNRow(); + TAOS_BIND[] binds = DataSource.GetNTableCNRow(); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createSql); @@ -95,14 +108,14 @@ namespace Cases } /// xiaolei - /// StableStmtCases.TestBindColumnCn + /// StableStmtCases.TestBindColumnCN /// Test stmt insert single line of chinese character into stable by column after column /// StmtSTable.cs /// pass or failed - [Fact(DisplayName = "StableStmtCases.TestBindColumnCn()")] - public void TestBindColumnCn() + [Fact(DisplayName = "StableStmtCases.TestBindColumnCN()"),TestExeOrder(4),Trait("Category", "BindParamColumnCN")] + public void TestBindColumnCN() { - string tableName = "stable_stmt_cases_test_bindcolumn_cn"; + string tableName = "stb_stmt_cases_test_bindcolumn_cn"; String createSql = $"create stable if not exists {tableName} " + "(ts timestamp," + "b bool," + @@ -137,11 +150,11 @@ namespace Cases String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName};"; TAOS_BIND[] tags = DataSource.GetCNTags(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindCNArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createSql); + TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindCNArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); List expectResData = DataSource.GetMultiBindStableCNRowData(); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createSql); @@ -149,27 +162,27 @@ namespace Cases StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[0], 0); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[1], 1); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[2], 2); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[3], 3); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[4], 4); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[5], 5); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[6], 6); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[7], 7); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[8], 8); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[9], 9); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[10], 10); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[11], 11); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[12], 12); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[13], 13); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[0], 0); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[1], 1); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[2], 2); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[3], 3); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[4], 4); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[5], 5); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[6], 6); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[7], 7); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[8], 8); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[9], 9); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[10], 10); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[11], 11); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[12], 12); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[13], 13); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); DataSource.FreeTaosBind(tags); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBinds); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); @@ -195,14 +208,14 @@ namespace Cases } /// xiaolei - /// StableStmtCases.TestBindMultiLineCn + /// StableStmtCases.TestBindMultiLineCN /// Test stmt insert single line of chinese character into stable by column after column /// StmtSTable.cs /// pass or failed - [Fact(DisplayName = "StableStmtCases.TestBindMultiLineCn()")] - public void TestBindMultiLineCn() + [Fact(DisplayName = "StableStmtCases.TestBindMultiLineCN()"),TestExeOrder(6),Trait("Category", "BindParamBatchCN")] + public void TestBindMultiLineCN() { - string tableName = "stable_stmt_cases_test_bind_multi_line_cn"; + string tableName = "stb_stmt_cases_test_bind_multi_line_cn"; String createSql = $"create stable if not exists {tableName} " + "(ts timestamp," + "b bool," + @@ -237,24 +250,24 @@ namespace Cases String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName};"; TAOS_BIND[] tags = DataSource.GetCNTags(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindCNArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createSql); + TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindCNArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); List expectResData = DataSource.GetMultiBindStableCNRowData(); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createSql); IntPtr stmt = StmtUtilTools.StmtInit(conn); StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags); - StmtUtilTools.BindParamBatch(stmt, mbind); + StmtUtilTools.BindParamBatch(stmt, mBinds); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); DataSource.FreeTaosBind(tags); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBinds); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); @@ -282,11 +295,11 @@ namespace Cases /// Test stmt insert single line into stable by column after column /// StmtSTable.cs /// pass or failed - [Fact(DisplayName = "StableStmtCases.TestBindMultiLine()")] + [Fact(DisplayName = "StableStmtCases.TestBindMultiLine()"),TestExeOrder(5),Trait("Category", "BindParamBatch")] public void TestBindMultiLine() { - string tableName = "stable_stmt_cases_test_bind_multi_line"; - string createSql = $"create stable if not exists {tableName} " + + string tableName = "stb_stmt_cases_test_bind_multi_line"; + string createSql = $"create stable if not exists {tableName} " + "(ts timestamp," + "b bool," + "v1 tinyint," + @@ -320,24 +333,24 @@ namespace Cases String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName};"; TAOS_BIND[] tags = DataSource.GetTags(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createSql); + TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); List expectResData = DataSource.GetMultiBindStableRowData(); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createSql); IntPtr stmt = StmtUtilTools.StmtInit(conn); StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags); - StmtUtilTools.BindParamBatch(stmt, mbind); + StmtUtilTools.BindParamBatch(stmt, mBinds); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); DataSource.FreeTaosBind(tags); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBinds); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); @@ -370,10 +383,10 @@ namespace Cases /// Test stmt insert single line of chinese character into stable by column after column /// StmtSTable.cs /// pass or failed - [Fact(DisplayName = "StableStmtCases.TestBindColumn()")] + [Fact(DisplayName = "StableStmtCases.TestBindColumn()"),TestExeOrder(3),Trait("Category", "BindParamColumn")] public void TestBindColumn() { - string tableName = "stable_stmt_cases_test_bindcolumn"; + string tableName = "stb_stmt_cases_test_bindcolumn"; string createSql = $"create stable if not exists {tableName} " + "(ts timestamp," + "b bool," + @@ -408,11 +421,11 @@ namespace Cases String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String dropSql = $"drop table if exists {tableName};"; TAOS_BIND[] tags = DataSource.GetTags(); - TAOS_MULTI_BIND[] mbind = DataSource.GetMultiBindArr(); - List expectResMeta = DataSource.GetMetaFromDLL(createSql); + TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindArr(); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); List expectResData = DataSource.GetMultiBindStableRowData(); - IntPtr conn = UtilsTools.TDConnection(); + IntPtr conn = database.conn; UtilsTools.ExecuteUpdate(conn, dropSql); UtilsTools.ExecuteUpdate(conn, createSql); @@ -420,27 +433,27 @@ namespace Cases StmtUtilTools.StmtPrepare(stmt, insertSql); StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[0], 0); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[1], 1); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[2], 2); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[3], 3); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[4], 4); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[5], 5); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[6], 6); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[7], 7); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[8], 8); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[9], 9); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[10], 10); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[11], 11); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[12], 12); - StmtUtilTools.BindSingleParamBatch(stmt, mbind[13], 13); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[0], 0); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[1], 1); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[2], 2); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[3], 3); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[4], 4); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[5], 5); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[6], 6); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[7], 7); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[8], 8); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[9], 9); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[10], 10); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[11], 11); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[12], 12); + StmtUtilTools.BindSingleParamBatch(stmt, mBinds[13], 13); StmtUtilTools.AddBatch(stmt); StmtUtilTools.StmtExecute(stmt); StmtUtilTools.StmtClose(stmt); DataSource.FreeTaosBind(tags); - DataSource.FreeTaosMBind(mbind); + DataSource.FreeTaosMBind(mBinds); string querySql = "select * from " + tableName; IntPtr res = UtilsTools.ExecuteQuery(conn, querySql); diff --git a/src/connector/C#/src/test/FunctionTest/Subscribe.cs b/src/connector/C#/src/test/FunctionTest/Subscribe.cs new file mode 100644 index 0000000000000000000000000000000000000000..57ded4a82f530b759b014f8109cd63246f2dfc3b --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/Subscribe.cs @@ -0,0 +1,184 @@ +using TDengineDriver; +using Test.UtilsTools; +using System; +using System.Collections.Generic; +using Xunit; +using Test.UtilsTools.DataSource; +using System.Threading; +using Xunit.Abstractions; +using Test.Fixture; +using Test.Case.Attributes; + +namespace Cases +{ + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] + + public class SubscribeCases + { + DatabaseFixture database; + + private readonly ITestOutputHelper output; + + public SubscribeCases(DatabaseFixture fixture, ITestOutputHelper output) + { + this.database = fixture; + this.output = output; + } + /// xiaolei + /// SubscribeCases.ConsumeFromBegin + /// Subscribe a table and consume from beginning. + /// Subscribe.cs + /// pass or failed + [Fact(DisplayName = "SubscribeCases.ConsumeFromBegin()"), TestExeOrder(1), Trait("Category", "Without callback")] + public void ConsumeFromBegin() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "subscribe_from_begin"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))"; + var dropSql = $"drop table if exists {tableName}"; + + var colData = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值三", + }; + + var colData2 = new List{1646150410400,false,4,44,4444,44444444,"value three","值肆", + 1646150410500,true,5,55,5555,55555555,"value one","值伍", + 1646150410600,true,6,66,6666,66666666,"value two","值陆", + }; + + var tagData = new List { 1, "tag_one", "标签壹" }; + var tagData2 = new List { 2, "tag_two", "标签贰" }; + + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3); + String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3); + // Then + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3); + List expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3); + expectResData.AddRange(expectResData2); + + var querySql = $"select * from {tableName}"; + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql); + + + IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, null, IntPtr.Zero, 0); + _res = TDengine.Consume(subscribe); + // need to call fetch TAOS_RES + UtilsTools.GetResDataWithoutFree(_res); + TDengine.Unsubscribe(subscribe, true); + + UtilsTools.ExecuteUpdate(conn, insertSql2); + Thread.Sleep(100); + + + subscribe = TDengine.Subscribe(conn, true, tableName, querySql, null, IntPtr.Zero, 0); + _res = TDengine.Consume(subscribe); + + List actualMeta = UtilsTools.GetResField(_res); + List actualResData = UtilsTools.GetResDataWithoutFree(_res); + TDengine.Unsubscribe(subscribe, false); + + Assert.Equal(expectResData.Count, actualResData.Count); + output.WriteLine("Assert Meta data"); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + output.WriteLine("Assert retrieve data"); + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // output.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData[i].ToString(), actualResData[i]); + } + + } + + /// xiaolei + /// SubscribeCases.ConsumeFromLastProgress + /// Subscribe table from the last progress. + /// Subscribe.cs + /// pass or failed + [Fact(DisplayName = "SubscribeCases.ConsumeFromLastProgress()"), TestExeOrder(2), Trait("Category", "Without callback")] + public void ConsumeFromLastProgress() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "subscribe_from_progress"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))"; + var dropSql = $"drop table if exists {tableName}"; + + var colData = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值叁", + }; + + var colData2 = new List{1646150410400,false,4,44,4444,44444444,"value three","值肆", + 1646150410500,true,5,55,5555,55555555,"value one","值伍", + 1646150410600,true,6,66,6666,66666666,"value two","值陆", + }; + + var tagData = new List { 1, "tag_one", "标签壹" }; + var tagData2 = new List { 2, "tag_two", "标签贰" }; + + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3); + String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3); + // Then + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3); + List expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3); + + + var querySql = $"select * from {tableName}"; + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql); + + // First time subscribe + IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, null, IntPtr.Zero, 20); + _res = TDengine.Consume(subscribe); + // need to call fetch TAOS_RES + UtilsTools.GetResDataWithoutFree(_res); + // Close subscribe and save progress. + TDengine.Unsubscribe(subscribe, true); + + // Insert new data. + UtilsTools.ExecuteUpdate(conn, insertSql2); + Thread.Sleep(1000); + + subscribe = TDengine.Subscribe(conn, false, tableName, querySql, null, IntPtr.Zero, 20); + _res = TDengine.Consume(subscribe); + + List actualMeta = UtilsTools.GetResField(_res); + List actualResData = UtilsTools.GetResDataWithoutFree(_res); + TDengine.Unsubscribe(subscribe, true); + output.WriteLine("Assert Meta data"); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + output.WriteLine("Assert retrieve data"); + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // output.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData2[i].ToString(), actualResData[i]); + } + + } + } + +} \ No newline at end of file diff --git a/src/connector/C#/src/test/FunctionTest/SubscribeAsync.cs b/src/connector/C#/src/test/FunctionTest/SubscribeAsync.cs new file mode 100644 index 0000000000000000000000000000000000000000..6a954ef0e048331fdf9809e0030240cd80fa1d6f --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/SubscribeAsync.cs @@ -0,0 +1,237 @@ +using TDengineDriver; +using Test.UtilsTools; +using System; +using System.Collections.Generic; +using Xunit; +using Test.UtilsTools.DataSource; +using System.Threading; +using Xunit.Abstractions; +using Test.Fixture; +using Test.Case.Attributes; + +namespace Cases +{ + [TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")] + [Collection("Database collection")] + public class SubscribeAsyncCases + { + DatabaseFixture database; + + private readonly ITestOutputHelper output; + + public SubscribeAsyncCases(DatabaseFixture fixture, ITestOutputHelper output) + { + this.database = fixture; + this.output = output; + } + + /// xiaolei + /// SubscribeAsyncCases.ConsumeFromBegin + /// Subscribe a table and consume through callback and the beginning record of the table + /// Subscribe.cs + /// pass or failed + [Fact(DisplayName = "SubscribeAsyncCases.ConsumeFromBegin()"), TestExeOrder(1), Trait("Category", "With callback")] + public void ConsumeFromBegin() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "subscribe_async_from_begin"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))"; + var dropSql = $"drop table if exists {tableName}"; + + var colData = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值三", + }; + + var colData2 = new List{1646150410400,false,4,44,4444,44444444,"value three","值肆", + 1646150410500,true,5,55,5555,55555555,"value one","值伍", + 1646150410600,true,6,66,6666,66666666,"value two","值陆", + }; + + var tagData = new List { 1, "tag_one", "标签壹" }; + var tagData2 = new List { 2, "tag_two", "标签贰" }; + + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3); + String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3); + List expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3); + expectResData.AddRange(expectResData2); + var querySql = $"select * from {tableName}"; + + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql); + + SubscribeCallback subscribeCallback1 = new SubscribeCallback(SubCallback1); + SubscribeCallback subscribeCallback2 = new SubscribeCallback(SubCallback2); + IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, subscribeCallback1, IntPtr.Zero, 200); + + UtilsTools.ExecuteUpdate(conn, insertSql2); + Thread.Sleep(1000); + TDengine.Unsubscribe(subscribe, true); + + subscribe = TDengine.Subscribe(conn, true, tableName, querySql, subscribeCallback2, IntPtr.Zero, 200); + Thread.Sleep(1000); + TDengine.Unsubscribe(subscribe, false); + void SubCallback1(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + // cannot free taosRes using taosRes, otherwise will cause crash. + UtilsTools.GetResDataWithoutFree(taosRes); + } + else + { + output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}"); + } + + } + + void SubCallback2(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + List actualMeta = UtilsTools.GetResField(taosRes); + List actualResData = UtilsTools.GetResDataWithoutFree(taosRes); + // UtilsTools.DisplayRes(taosRes); + if (actualResData.Count == 0) + { + output.WriteLine($"consume in subscribe callback without data"); + } + else + { + output.WriteLine($"consume in subscribe callback with data"); + + Assert.Equal(expectResData.Count, actualResData.Count); + output.WriteLine("Assert Meta data"); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + output.WriteLine("Assert retrieve data"); + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // output.WriteLine("index:{0},expectResData:{1},actualResData:{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData[i].ToString(), actualResData[i]); + } + } + } + else + { + output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}"); + } + } + + } + + /// xiaolei + /// SubscribeAsyncCases.ConsumeFromLastProgress + /// Subscribe a table and consume through callback and from last consume progress. + /// Subscribe.cs + /// pass or failed + [Fact(DisplayName = "SubscribeAsyncCases.ConsumeFromLastProgress()"), TestExeOrder(2), Trait("Category", "With callback")] + public void ConsumeFromLastProgress() + { + IntPtr conn = database.conn; + IntPtr _res = IntPtr.Zero; + + var tableName = "subscribe_async_from_begin"; + var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))"; + var dropSql = $"drop table if exists {tableName}"; + + var colData = new List{1646150410100,true,1,11,1111,11111111,"value one","值壹", + 1646150410200,true,2,22,2222,22222222,"value two","值贰", + 1646150410300,false,3,33,3333,33333333,"value three","值三", + }; + + var colData2 = new List{1646150410400,false,4,44,4444,44444444,"value three","值肆", + 1646150410500,true,5,55,5555,55555555,"value one","值伍", + 1646150410600,true,6,66,6666,66666666,"value two","值陆", + }; + + var tagData = new List { 1, "tag_one", "标签壹" }; + var tagData2 = new List { 2, "tag_two", "标签贰" }; + + String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3); + String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3); + List expectResMeta = DataSource.GetMetaFromDDL(createSql); + List expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3); + List expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3); + var querySql = $"select * from {tableName}"; + + UtilsTools.ExecuteUpdate(conn, dropSql); + UtilsTools.ExecuteUpdate(conn, createSql); + UtilsTools.ExecuteUpdate(conn, insertSql); + + SubscribeCallback subscribeCallback1 = new SubscribeCallback(SubCallback1); + SubscribeCallback subscribeCallback2 = new SubscribeCallback(SubCallback2); + IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, subscribeCallback1, IntPtr.Zero, 200); + Thread.Sleep(1000); + TDengine.Unsubscribe(subscribe, true); + UtilsTools.ExecuteUpdate(conn, insertSql2); + subscribe = TDengine.Subscribe(conn, false, tableName, querySql, subscribeCallback2, IntPtr.Zero, 200); + Thread.Sleep(1000); + TDengine.Unsubscribe(subscribe, false); + void SubCallback1(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + // cannot free taosRes using taosRes, otherwise will cause crash. + UtilsTools.GetResDataWithoutFree(taosRes); + } + else if (taosRes != IntPtr.Zero) + { + output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}"); + } + + } + + void SubCallback2(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + List actualMeta = UtilsTools.GetResField(taosRes); + List actualResData = UtilsTools.GetResDataWithoutFree(taosRes); + UtilsTools.DisplayRes(taosRes); + if (actualResData.Count == 0) + { + output.WriteLine($"consume in subscribe callback without data"); + } + else + { + output.WriteLine($"consume in subscribe callback with data"); + + Assert.Equal(expectResData2.Count, actualResData.Count); + output.WriteLine("Assert Meta data"); + //Assert Meta data + for (int i = 0; i < actualMeta.Count; i++) + { + Assert.Equal(expectResMeta[i].name, actualMeta[i].name); + Assert.Equal(expectResMeta[i].type, actualMeta[i].type); + Assert.Equal(expectResMeta[i].size, actualMeta[i].size); + } + output.WriteLine("Assert retrieve data"); + // Assert retrieve data + for (int i = 0; i < actualResData.Count; i++) + { + // output.WriteLine("index:{0},expectResData:{1},actualResData:{2}", i, expectResData[i], actualResData[i]); + Assert.Equal(expectResData2[i].ToString(), actualResData[i]); + } + } + } + else + { + output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}"); + } + } + + } + } +} \ No newline at end of file diff --git a/src/connector/C#/src/test/FunctionTest/lib/DBFixture.cs b/src/connector/C#/src/test/FunctionTest/lib/DBFixture.cs new file mode 100644 index 0000000000000000000000000000000000000000..295726a525fb7a6c7740d5216fa19ee797109eb1 --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/lib/DBFixture.cs @@ -0,0 +1,79 @@ +using System; +using System.Configuration; +using System.Data.SqlClient; +using System.Runtime.InteropServices; +using TDengineDriver; + +namespace Test.Fixture +{ + public class DatabaseFixture : IDisposable + { + public IntPtr conn { get; set; } + + private string user = "root"; + private string password = "taosdata"; + private string ip = "127.0.0.1"; + private short port = 0; + + private string db = "xunit_test_fixture"; + public DatabaseFixture() + { + conn = TDengine.Connect(ip, user, password, "", port); + IntPtr res; + if (conn != IntPtr.Zero) + { + if ((res = TDengine.Query(conn, $"create database if not exists {db} keep 3650")) != IntPtr.Zero) + { + if ((res = TDengine.Query(conn, $"use {db}")) != IntPtr.Zero) + { + Console.WriteLine("Get connection success"); + } + else + { + throw new Exception(TDengine.Error(res)); + } + } + else + { + throw new Exception(TDengine.Error(res)); + } + } + else + { + throw new Exception("Get TDConnection failed"); + } + } + + // public IntPtr TDConnection { get; } + + public void Dispose() + { + IntPtr res; + if (conn != IntPtr.Zero) + { + if ((res = TDengine.Query(conn, $"drop database if exists {db}")) != IntPtr.Zero) + { + if (TDengine.Close(conn) == 0) + { + Console.WriteLine("close connection success"); + } + else + { + throw new Exception("close connection failed"); + } + + } + else + { + throw new Exception(TDengine.Error(res)); + } + } + else + { + throw new Exception("connection if already null"); + } + + } + + } +} diff --git a/src/connector/C#/src/test/FunctionTest/lib/DatabaseCollection.cs b/src/connector/C#/src/test/FunctionTest/lib/DatabaseCollection.cs new file mode 100644 index 0000000000000000000000000000000000000000..11651f99b9fab5ea7c1f86bad4a14e7bea590378 --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/lib/DatabaseCollection.cs @@ -0,0 +1,9 @@ +using Xunit; +using Test.Fixture; +[CollectionDefinition("Database collection")] +public class DatabaseCollection : ICollectionFixture +{ + // This class has no code, and is never created. Its purpose is simply + // to be the place to apply [CollectionDefinition] and all the + // ICollectionFixture<> interfaces. +} \ No newline at end of file diff --git a/src/connector/C#/src/test/FunctionTest/lib/ResultSetUtils.cs b/src/connector/C#/src/test/FunctionTest/lib/ResultSetUtils.cs index 1a904c827f3bae320cbaed390ebc6765226f735a..4fd7f871316623486508532dfdc91f1d58005e3e 100644 --- a/src/connector/C#/src/test/FunctionTest/lib/ResultSetUtils.cs +++ b/src/connector/C#/src/test/FunctionTest/lib/ResultSetUtils.cs @@ -1,7 +1,5 @@ using System; using TDengineDriver; -using System.Runtime.InteropServices; -using System.Text; using System.Collections.Generic; namespace Test.UtilsTools.ResultSet { @@ -17,10 +15,10 @@ namespace Test.UtilsTools.ResultSet resultData = UtilsTools.GetResData(res); } - public ResultSet(List metas, List datas) + public ResultSet(List meta, List data) { - resultMeta = metas; - resultData = datas; + resultMeta = meta; + resultData = data; } public List GetResultData() @@ -35,5 +33,4 @@ namespace Test.UtilsTools.ResultSet } - } \ No newline at end of file diff --git a/src/connector/C#/src/test/FunctionTest/lib/TestExeOrder.cs b/src/connector/C#/src/test/FunctionTest/lib/TestExeOrder.cs new file mode 100644 index 0000000000000000000000000000000000000000..8fec01c0bae05c1be047040c883d75b0b5091229 --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/lib/TestExeOrder.cs @@ -0,0 +1,12 @@ +using System; + +namespace Test.Case.Attributes +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class TestExeOrderAttribute : Attribute + { + public int ExeOrder { get; private set; } + + public TestExeOrderAttribute(int exeOrder) => ExeOrder = exeOrder; + } +} \ No newline at end of file diff --git a/src/connector/C#/src/test/FunctionTest/lib/TestExeOrderer.cs b/src/connector/C#/src/test/FunctionTest/lib/TestExeOrderer.cs new file mode 100644 index 0000000000000000000000000000000000000000..4ae0a41e86ef4b10de862000ce7e5409164e2a2f --- /dev/null +++ b/src/connector/C#/src/test/FunctionTest/lib/TestExeOrderer.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using System.Linq; +using Xunit.Abstractions; +using Xunit.Sdk; +using Test.Case.Attributes; + +namespace XUnit.Case.Orderers +{ + public class TestExeOrderer : ITestCaseOrderer + { + public IEnumerable OrderTestCases( + IEnumerable testCases) where TTestCase : ITestCase + { + string assemblyName = typeof(TestExeOrderAttribute).AssemblyQualifiedName!; + var sortedMethods = new SortedDictionary>(); + foreach (TTestCase testCase in testCases) + { + int exeOrder = testCase.TestMethod.Method + .GetCustomAttributes(assemblyName) + .FirstOrDefault() + ?.GetNamedArgument(nameof(TestExeOrderAttribute.ExeOrder)) ?? 0; + + GetOrCreate(sortedMethods, exeOrder).Add(testCase); + } + + foreach (TTestCase testCase in + sortedMethods.Keys.SelectMany( + exeOrder => sortedMethods[exeOrder].OrderBy( + testCase => testCase.TestMethod.Method.Name))) + { + yield return testCase; + } + } + + private static TValue GetOrCreate( + IDictionary dictionary, TKey key) + where TKey : struct + where TValue : new() => + dictionary.TryGetValue(key, out TValue result) + ? result + : (dictionary[key] = new TValue()); + } +} \ No newline at end of file diff --git a/src/connector/C#/src/test/FunctionTest/lib/Utils.cs b/src/connector/C#/src/test/FunctionTest/lib/Utils.cs index c2bba9298d022783c5d3d40643caa7eb1f73751c..9604a0b043fc7b99ee4e58208ba1ff5212453fc5 100644 --- a/src/connector/C#/src/test/FunctionTest/lib/Utils.cs +++ b/src/connector/C#/src/test/FunctionTest/lib/Utils.cs @@ -3,6 +3,7 @@ using TDengineDriver; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; +using Xunit.Abstractions; namespace Test.UtilsTools { public class UtilsTools @@ -13,11 +14,11 @@ namespace Test.UtilsTools static string password = "taosdata"; static string db = ""; static short port = 0; - //get a tdengine connection + //get a TDengine connection public static IntPtr TDConnection() { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, GetConfigPath()); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); + TDengine.Options((int)TDengineInitOption.TSDB_OPTION_CONFIGDIR, GetConfigPath()); + TDengine.Options((int)TDengineInitOption.TSDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); TDengine.Init(); IntPtr conn = TDengine.Connect(ip, user, password, db, port); // UtilsTools.ExecuteUpdate(conn, "drop database if exists csharp"); @@ -28,20 +29,20 @@ namespace Test.UtilsTools //get taos.cfg file based on different os public static string GetConfigPath() { - string configDir = "" ; - if(OperatingSystem.IsOSPlatform("Windows")) - { - configDir = "C:/TDengine/cfg"; - } - else if(OperatingSystem.IsOSPlatform("Linux")) - { - configDir = "/etc/taos"; - } - else if(OperatingSystem.IsOSPlatform("macOS")) - { - configDir = "/etc/taos"; - } - return configDir; + string configDir = ""; + if (OperatingSystem.IsOSPlatform("Windows")) + { + configDir = "C:/TDengine/cfg"; + } + else if (OperatingSystem.IsOSPlatform("Linux")) + { + configDir = "/etc/taos"; + } + else if (OperatingSystem.IsOSPlatform("macOS")) + { + configDir = "/usr/local/etc/taos"; + } + return configDir; } public static IntPtr ExecuteQuery(IntPtr conn, String sql) @@ -98,27 +99,21 @@ namespace Test.UtilsTools ExitProgram(); } - List metas = GetResField(res); - int fieldCount = metas.Count; + List metaList = GetResField(res); + int fieldCount = metaList.Count; IntPtr rowdata; - // StringBuilder builder = new StringBuilder(); - List datas = QueryRes(res, metas); - Console.Write(" DisplayRes ---"); - for (int i = 0; i < metas.Count; i++) + List dataList = QueryRes(res, metaList); + for (int i = 0; i < dataList.Count; i += metaList.Count) { - for (int j = 0; j < datas.Count; j++) + for (int j = 0; j < metaList.Count; j++) { - Console.Write(" {0} ---", datas[i * j + i]); + Console.Write(" {0} \t|", dataList[i + j]); + } Console.WriteLine(""); } - // if (TDengine.ErrorNo(res) != 0) - // { - // Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - // } - // TDengine.FreeResult(res); Console.WriteLine(""); } public static List> GetResultSet(IntPtr res) @@ -131,10 +126,10 @@ namespace Test.UtilsTools ExitProgram(); } - List metas = GetResField(res); + List metaList = GetResField(res); result.Add(colName); - dataRaw = QueryRes(res, metas); + dataRaw = QueryRes(res, metaList); result.Add(dataRaw); if (TDengine.ErrorNo(res) != 0) @@ -165,7 +160,7 @@ namespace Test.UtilsTools { if (TDengine.Close(conn) == 0) { - Console.WriteLine("close connection sucess"); + Console.WriteLine("close connection success"); } else { @@ -175,8 +170,8 @@ namespace Test.UtilsTools } public static List GetResField(IntPtr res) { - List metas = TDengine.FetchFields(res); - return metas; + List metaList = TDengine.FetchFields(res); + return metaList; } public static void AssertEqual(string expectVal, string actualVal) { @@ -197,14 +192,8 @@ namespace Test.UtilsTools } public static List GetResData(IntPtr res) { - List colName = new List(); - List dataRaw = new List(); - if (!IsValidResult(res)) - { - ExitProgram(); - } - List metas = GetResField(res); - dataRaw = QueryRes(res, metas); + List dataRaw = GetResDataWithoutFree(res); + FreeResult(res); return dataRaw; } @@ -286,111 +275,27 @@ namespace Test.UtilsTools return _meta; } - private static List QueryRes(IntPtr res, List metas) + private static List QueryRes(IntPtr res, List meta) { - IntPtr rowdata; - long queryRows = 0; + IntPtr taosRow; List dataRaw = new List(); - int fieldCount = metas.Count; - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) + int fieldCount = meta.Count; + while ((taosRow = TDengine.FetchRows(res)) != IntPtr.Zero) { - queryRows++; - IntPtr colLengthPtr = TDengine.FetchLengths(res); - int[] colLengthArr = new int[fieldCount]; - Marshal.Copy(colLengthPtr, colLengthArr, 0, fieldCount); - - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - if (data == IntPtr.Zero) - { - dataRaw.Add("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - dataRaw.Add(v1.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - sbyte v2 = (sbyte)Marshal.ReadByte(data); - dataRaw.Add(v2.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - dataRaw.Add(v3.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - dataRaw.Add(v4.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - dataRaw.Add(v5.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - dataRaw.Add(v6.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - dataRaw.Add(v7.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - // string v8 = Marshal.PtrToStringAnsi(data, colLengthArr[fields]); - string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[fields]); - dataRaw.Add(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - dataRaw.Add(v9.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - // string v10 = Marshal.PtrToStringAnsi(data, colLengthArr[fields]); - string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[fields]); - dataRaw.Add(v10); - break; - case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: - byte v12 = Marshal.ReadByte(data); - dataRaw.Add(v12.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: - ushort v13 = (ushort)Marshal.ReadInt16(data); - dataRaw.Add(v13.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_UINT: - uint v14 = (uint)Marshal.ReadInt32(data); - dataRaw.Add(v14.ToString()); - break; - case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: - ulong v15 = (ulong)Marshal.ReadInt64(data); - dataRaw.Add(v15.ToString()); - break; - default: - dataRaw.Add("unknown value"); - break; - } - } - + dataRaw.AddRange(FetchRow(taosRow, res)); } if (TDengine.ErrorNo(res) != 0) { Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); } - TDengine.FreeResult(res); Console.WriteLine(""); return dataRaw; } // Generate insert sql for the with the coldata and tag data - public static string ConstructInsertSql(string table,string stable,List colData,List tagData,int numOfRows) + public static string ConstructInsertSql(string table, string stable, List colData, List tagData, int numOfRows) { - int numofFileds = colData.Count / numOfRows; + int numOfFields = colData.Count / numOfRows; StringBuilder insertSql; if (stable == "") @@ -435,7 +340,7 @@ namespace Test.UtilsTools insertSql.Append(colData[i]); } - if ((i + 1) % numofFileds == 0 && (i + 1) != colData.Count) + if ((i + 1) % numOfFields == 0 && (i + 1) != colData.Count) { insertSql.Append(")("); } @@ -453,8 +358,8 @@ namespace Test.UtilsTools return insertSql.ToString(); } - - public static List CombineColAndTagData(List colData,List tagData, int numOfRows) + + public static List CombineColAndTagData(List colData, List tagData, int numOfRows) { var list = new List(); for (int i = 0; i < colData.Count; i++) @@ -470,6 +375,137 @@ namespace Test.UtilsTools } return list; } + + /// + /// Using this method to free TAOS_RES,otherwise will lead memory + /// leak.Notice do not call this method while subscribe/consume until + /// end of the program. + /// + /// TAOS_RES, the resultset usually is return by taos_query() + public static void FreeResult(IntPtr res) + { + TDengine.FreeResult(res); + } + + + /// + /// Using to parse TAOS_ROW. + /// + /// This is TAOS_RES pointer + /// This is TAOS_ROW pointer + /// + public static List FetchRow(IntPtr taosRow, IntPtr taosRes) + { + List metaList = TDengine.FetchFields(taosRes); + int numOfFiled = TDengine.FieldCount(taosRes); + + List dataRaw = new List(); + + IntPtr colLengthPrt = TDengine.FetchLengths(taosRes); + int[] colLengthArr = new int[numOfFiled]; + Marshal.Copy(colLengthPrt, colLengthArr, 0, numOfFiled); + + for (int i = 0; i < numOfFiled; i++) + { + TDengineMeta meta = metaList[i]; + IntPtr data = Marshal.ReadIntPtr(taosRow, IntPtr.Size * i); + + if (data == IntPtr.Zero) + { + dataRaw.Add("NULL"); + continue; + } + switch ((TDengineDataType)meta.type) + { + case TDengineDataType.TSDB_DATA_TYPE_BOOL: + bool v1 = Marshal.ReadByte(data) == 0 ? false : true; + dataRaw.Add(v1.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_TINYINT: + sbyte v2 = (sbyte)Marshal.ReadByte(data); + dataRaw.Add(v2.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: + short v3 = Marshal.ReadInt16(data); + dataRaw.Add(v3.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_INT: + int v4 = Marshal.ReadInt32(data); + dataRaw.Add(v4.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_BIGINT: + long v5 = Marshal.ReadInt64(data); + dataRaw.Add(v5.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_FLOAT: + float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); + dataRaw.Add(v6.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: + double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); + dataRaw.Add(v7.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_BINARY: + string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); + dataRaw.Add(v8); + break; + case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: + long v9 = Marshal.ReadInt64(data); + dataRaw.Add(v9.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_NCHAR: + string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); + dataRaw.Add(v10); + break; + case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: + byte v12 = Marshal.ReadByte(data); + dataRaw.Add(v12.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: + ushort v13 = (ushort)Marshal.ReadInt16(data); + dataRaw.Add(v13.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_UINT: + uint v14 = (uint)Marshal.ReadInt32(data); + dataRaw.Add(v14.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: + ulong v15 = (ulong)Marshal.ReadInt64(data); + dataRaw.Add(v15.ToString()); + break; + case TDengineDataType.TSDB_DATA_TYPE_JSONTAG: + string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]); + dataRaw.Add(v16); + break; + default: + dataRaw.Add("nonsupport data type value"); + break; + } + + } + return dataRaw; + } + + /// + /// Get the result data from TAO_RES but this interface will + /// not free the TAO_RES at the end. Remember to free the TAOS_RES + /// when you need to do so. + /// + /// This is a TAOS_RES pointer. + /// + public static List GetResDataWithoutFree(IntPtr res) + { + List colName = new List(); + List dataRaw = new List(); + if (!IsValidResult(res)) + { + ExitProgram(); + } + List meta = GetResField(res); + dataRaw = QueryRes(res, meta); + return dataRaw; + } } + } diff --git a/src/connector/C#/src/test/XUnitTest/TestTDengineMeta.cs b/src/connector/C#/src/test/XUnitTest/TestTDengineMeta.cs index 2154af78db00241e5388bbb02dc7f4f2dfed7f71..2890501e93c10b49462027d1fd907c6480dd82f8 100644 --- a/src/connector/C#/src/test/XUnitTest/TestTDengineMeta.cs +++ b/src/connector/C#/src/test/XUnitTest/TestTDengineMeta.cs @@ -8,7 +8,7 @@ namespace TDengineDriver.Test { /// xiaolei /// TestTDengineMeta.TestTypeNameBool - /// Unit test for oject TDengineDriver.TDengineMeta's bool meta info + /// Unit test for object TDengineDriver.TDengineMeta's bool meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -24,7 +24,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameTINYINT - /// Unit test for oject TDengineDriver.TDengineMeta's TinnyInt's meta info + /// Unit test for object TDengineDriver.TDengineMeta's TinnyInt's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -40,7 +40,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameSMALLINT - /// Unit test for oject TDengineDriver.TDengineMeta's SMALLINT's meta info + /// Unit test for object TDengineDriver.TDengineMeta's SMALLINT's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -56,7 +56,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameINT - /// Unit test for oject TDengineDriver.TDengineMeta's INT's meta info + /// Unit test for object TDengineDriver.TDengineMeta's INT's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -72,7 +72,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameBIGINT - /// Unit test for oject TDengineDriver.TDengineMeta's BIGINT's meta info + /// Unit test for object TDengineDriver.TDengineMeta's BIGINT's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -88,7 +88,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameUTINYINT - /// Unit test for oject TDengineDriver.TDengineMeta's TINYINT UNSIGNED's meta info + /// Unit test for object TDengineDriver.TDengineMeta's TINYINT UNSIGNED's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -104,7 +104,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameUSMALLINT - /// Unit test for oject TDengineDriver.TDengineMeta's SMALLINT UNSIGNED's meta info + /// Unit test for object TDengineDriver.TDengineMeta's SMALLINT UNSIGNED's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -120,7 +120,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameUINT - /// Unit test for oject TDengineDriver.TDengineMeta's INT UNSIGNED's meta info + /// Unit test for object TDengineDriver.TDengineMeta's INT UNSIGNED's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -136,7 +136,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameUBIGINT - /// Unit test for oject TDengineDriver.TDengineMeta's BIGINT UNSIGNED's meta info + /// Unit test for object TDengineDriver.TDengineMeta's BIGINT UNSIGNED's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -152,7 +152,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameFLOAT - /// Unit test for oject TDengineDriver.TDengineMeta's FLOAT's meta info + /// Unit test for object TDengineDriver.TDengineMeta's FLOAT's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -168,7 +168,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameDOUBLE - /// Unit test for oject TDengineDriver.TDengineMeta's DOUBLE's meta info + /// Unit test for object TDengineDriver.TDengineMeta's DOUBLE's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -184,7 +184,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameSTRING - /// Unit test for oject TDengineDriver.TDengineMeta's BINARY's meta info + /// Unit test for object TDengineDriver.TDengineMeta's BINARY's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -200,7 +200,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameTIMESTAMP - /// Unit test for oject TDengineDriver.TDengineMeta's TIMESTAMP's meta info + /// Unit test for object TDengineDriver.TDengineMeta's TIMESTAMP's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -216,7 +216,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameNCHAR - /// Unit test for oject TDengineDriver.TDengineMeta's NCHAR's meta info + /// Unit test for object TDengineDriver.TDengineMeta's NCHAR's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] @@ -232,7 +232,7 @@ namespace TDengineDriver.Test } /// xiaolei /// TestTDengineMeta.TestTypeNameUndefined - /// Unit test for oject TDengineDriver.TDengineMeta's undefine's meta info + /// Unit test for object TDengineDriver.TDengineMeta's undefine's meta info /// TestTDengineMeta.cs /// pass or failed [Fact] diff --git a/src/connector/C#/src/test/XUnitTest/TestTaosBind.cs b/src/connector/C#/src/test/XUnitTest/TestTaosBind.cs index 87dbae67feda7a670ea2509b0ee57a77f8078d4d..07678e6f84435438843c349bb287da7204eb535c 100644 --- a/src/connector/C#/src/test/XUnitTest/TestTaosBind.cs +++ b/src/connector/C#/src/test/XUnitTest/TestTaosBind.cs @@ -21,14 +21,14 @@ namespace TDengineDriver.Test int length = sizeof(bool); TDengineDriver.TAOS_BIND bind = TaosBind.BindBool(true); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); bool bindBuffer = Convert.ToBoolean(Marshal.ReadByte(bind.buffer)); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -49,14 +49,14 @@ namespace TDengineDriver.Test int length = sizeof(bool); TDengineDriver.TAOS_BIND bind = TaosBind.BindBool(false); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); bool bindBuffer = Convert.ToBoolean(Marshal.ReadByte(bind.buffer)); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -77,14 +77,14 @@ namespace TDengineDriver.Test int length = sizeof(sbyte); TDengineDriver.TAOS_BIND bind = TaosBind.BindTinyInt(0); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); sbyte bindBuffer = Convert.ToSByte(Marshal.ReadByte(bind.buffer)); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -103,14 +103,14 @@ namespace TDengineDriver.Test int length = sizeof(sbyte); TDengineDriver.TAOS_BIND bind = TaosBind.BindTinyInt(sbyte.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); sbyte bindBuffer = Convert.ToSByte(Marshal.ReadByte(bind.buffer)); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -130,14 +130,14 @@ namespace TDengineDriver.Test int length = sizeof(sbyte); TDengineDriver.TAOS_BIND bind = TaosBind.BindTinyInt(sbyte.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); short bindBuffer = Marshal.ReadInt16(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -157,14 +157,14 @@ namespace TDengineDriver.Test int length = sizeof(short); TDengineDriver.TAOS_BIND bind = TaosBind.BindSmallInt(short.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); short bindBuffer = Marshal.ReadInt16(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -184,14 +184,14 @@ namespace TDengineDriver.Test int length = sizeof(short); TDengineDriver.TAOS_BIND bind = TaosBind.BindSmallInt(0); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); short bindBuffer = Marshal.ReadInt16(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -211,14 +211,14 @@ namespace TDengineDriver.Test int length = sizeof(short); TDengineDriver.TAOS_BIND bind = TaosBind.BindSmallInt(short.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); short bindBuffer = Marshal.ReadInt16(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -238,14 +238,14 @@ namespace TDengineDriver.Test int length = sizeof(int); TDengineDriver.TAOS_BIND bind = TaosBind.BindInt(int.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); int bindBuffer = Marshal.ReadInt32(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -265,14 +265,14 @@ namespace TDengineDriver.Test int length = sizeof(int); TDengineDriver.TAOS_BIND bind = TaosBind.BindInt(0); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); int bindBuffer = Marshal.ReadInt32(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -292,14 +292,14 @@ namespace TDengineDriver.Test int length = sizeof(int); TDengineDriver.TAOS_BIND bind = TaosBind.BindInt(int.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); int bindBuffer = Marshal.ReadInt32(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -319,13 +319,13 @@ namespace TDengineDriver.Test int length = sizeof(long); TDengineDriver.TAOS_BIND bind = TaosBind.BindBigInt(long.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); long bindBuffer = Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -345,13 +345,13 @@ namespace TDengineDriver.Test int length = sizeof(long); TDengineDriver.TAOS_BIND bind = TaosBind.BindBigInt(0); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); long bindBuffer = Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -371,13 +371,13 @@ namespace TDengineDriver.Test int length = sizeof(long); TDengineDriver.TAOS_BIND bind = TaosBind.BindBigInt(long.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); long bindBuffer = Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -397,13 +397,13 @@ namespace TDengineDriver.Test int length = sizeof(sbyte); TDengineDriver.TAOS_BIND bind = TaosBind.BindUTinyInt(0); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); byte bindBuffer = Marshal.ReadByte(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -423,13 +423,13 @@ namespace TDengineDriver.Test int length = sizeof(sbyte); TDengineDriver.TAOS_BIND bind = TaosBind.BindUTinyInt(byte.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); byte bindBuffer = Marshal.ReadByte(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -449,13 +449,13 @@ namespace TDengineDriver.Test int length = sizeof(ushort); TDengineDriver.TAOS_BIND bind = TaosBind.BindUSmallInt(ushort.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); ushort bindBuffer = (ushort)Marshal.ReadInt16(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -475,13 +475,13 @@ namespace TDengineDriver.Test int length = sizeof(ushort); TDengineDriver.TAOS_BIND bind = TaosBind.BindUSmallInt(ushort.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); ushort bindBuffer = (ushort)Marshal.ReadInt16(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -501,13 +501,13 @@ namespace TDengineDriver.Test int length = sizeof(uint); TDengineDriver.TAOS_BIND bind = TaosBind.BindUInt(uint.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); uint bindBuffer = (uint)Marshal.ReadInt32(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -527,13 +527,13 @@ namespace TDengineDriver.Test int length = sizeof(uint); TDengineDriver.TAOS_BIND bind = TaosBind.BindUInt(uint.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); uint bindBuffer = (uint)Marshal.ReadInt32(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -553,13 +553,13 @@ namespace TDengineDriver.Test int length = sizeof(ulong); TDengineDriver.TAOS_BIND bind = TaosBind.BindUBigInt(ulong.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); ulong bindBuffer = (ulong)Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -579,13 +579,13 @@ namespace TDengineDriver.Test int length = sizeof(ulong); TDengineDriver.TAOS_BIND bind = TaosBind.BindUBigInt(ulong.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); ulong bindBuffer = (ulong)Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -605,14 +605,14 @@ namespace TDengineDriver.Test int length = sizeof(float); TDengineDriver.TAOS_BIND bind = TaosBind.BindFloat(float.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); float[] bindBufferArr = new float[1]; Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBufferArr[0], buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -632,14 +632,14 @@ namespace TDengineDriver.Test int length = sizeof(float); TDengineDriver.TAOS_BIND bind = TaosBind.BindFloat(0F); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); float[] bindBufferArr = new float[1]; Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBufferArr[0], buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -659,14 +659,14 @@ namespace TDengineDriver.Test int length = sizeof(float); TDengineDriver.TAOS_BIND bind = TaosBind.BindFloat(float.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); float[] bindBufferArr = new float[1]; Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBufferArr[0], buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -686,14 +686,14 @@ namespace TDengineDriver.Test int length = sizeof(double); TDengineDriver.TAOS_BIND bind = TaosBind.BindDouble(0D); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); double[] bindBufferArr = new double[1]; Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBufferArr[0], buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -713,14 +713,14 @@ namespace TDengineDriver.Test int length = sizeof(double); TDengineDriver.TAOS_BIND bind = TaosBind.BindDouble(double.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); double[] bindBufferArr = new double[1]; Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBufferArr[0], buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -740,14 +740,14 @@ namespace TDengineDriver.Test int length = sizeof(double); TDengineDriver.TAOS_BIND bind = TaosBind.BindDouble(double.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); double[] bindBufferArr = new double[1]; Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBufferArr[0], buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -767,13 +767,13 @@ namespace TDengineDriver.Test int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length; TDengineDriver.TAOS_BIND bind = TaosBind.BindBinary("qwertyuiopasdghjklzxcvbnm<>?:\"{}+_)(*&^%$#@!~QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-="); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -793,13 +793,13 @@ namespace TDengineDriver.Test int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length; TDengineDriver.TAOS_BIND bind = TaosBind.BindBinary("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./"); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -819,13 +819,13 @@ namespace TDengineDriver.Test int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length; TDengineDriver.TAOS_BIND bind = TaosBind.BindBinary("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -845,13 +845,13 @@ namespace TDengineDriver.Test int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length; TDengineDriver.TAOS_BIND bind = TaosBind.BindNchar("qwertyuiopasdghjklzxcvbnm<>?:\"{}+_)(*&^%$#@!~QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-="); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -871,13 +871,13 @@ namespace TDengineDriver.Test int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length; TDengineDriver.TAOS_BIND bind = TaosBind.BindNchar("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./"); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -897,13 +897,13 @@ namespace TDengineDriver.Test int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length; TDengineDriver.TAOS_BIND bind = TaosBind.BindNchar("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -945,13 +945,13 @@ namespace TDengineDriver.Test int length = sizeof(long); TDengineDriver.TAOS_BIND bind = TaosBind.BindTimestamp(long.MinValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); long bindBuffer = Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -971,13 +971,13 @@ namespace TDengineDriver.Test int length = sizeof(long); TDengineDriver.TAOS_BIND bind = TaosBind.BindTimestamp(0); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); long bindBuffer = Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); @@ -998,13 +998,13 @@ namespace TDengineDriver.Test int length = sizeof(long); TDengineDriver.TAOS_BIND bind = TaosBind.BindTimestamp(long.MaxValue); - int BindLengPtr = Marshal.ReadInt32(bind.length); + int bindLengthPtr = Marshal.ReadInt32(bind.length); long bindBuffer = Marshal.ReadInt64(bind.buffer); Assert.Equal(bind.buffer_type, bufferType); Assert.Equal(bindBuffer, buffer); Assert.Equal(bind.buffer_length, bufferLength); - Assert.Equal(BindLengPtr, length); + Assert.Equal(bindLengthPtr, length); Marshal.FreeHGlobal(bind.buffer); Marshal.FreeHGlobal(bind.length); diff --git a/src/connector/TypeScript-REST/.gitignore b/src/connector/TypeScript-REST/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..55adb43efb1284573319afc4e0fcd06f835ed098 --- /dev/null +++ b/src/connector/TypeScript-REST/.gitignore @@ -0,0 +1,6 @@ +package-lock.json +dist/main +dist/module +dist/types.d.ts +node_modules/ +tsc/ \ No newline at end of file diff --git a/src/connector/TypeScript-REST/example/example.ts b/src/connector/TypeScript-REST/example/example.ts new file mode 100644 index 0000000000000000000000000000000000000000..00f3318be5c3333d0005e1496d813bdb674f8000 --- /dev/null +++ b/src/connector/TypeScript-REST/example/example.ts @@ -0,0 +1,60 @@ +import { options, connect } from '../tdengine_rest' +options.path = '/rest/sqlt' +const db = 'rest_ts_db'; +const table = 'rest' +const createDB = `create database if not exists ${db} keep 3650`; +const dropDB = `drop database if exists ${db}`; +const createTB = `create table if not exists ${db}.${table}(ts timestamp,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(40),nchr nchar(40))`; +const addColumn = `alter table ${db}.${table} add column new_column nchar(40) `; +const dropColumn = `alter table ${db}.${table} drop column new_column`; +const insertSql = `insert into ${db}.${table} values('2022-03-30 18:30:51.567',1,2,3,4,'binary1','nchar1')` + + `('2022-03-30 18:30:51.568',5,6,7,8,'binary2','nchar2')` + + `('2022-03-30 18:30:51.569',9,0,1,2,'binary3','nchar3')`; +const querySql = `select * from ${db}.${table}`; +const errorSql = 'show database'; + +let conn = connect(options); +let cursor = conn.cursor(); + +async function execute(sql: string, pure = false) { + let result = await cursor.query(sql, pure); + // print query result as taos shell + result.toString(); + // Get Result object, return Result object. + console.log("result.getResult()",result.getResult()); + // Get status, return 'succ'|'error'. + console.log("result.getStatus()",result.getStatus()); + // Get head,return response head (Array|undefined,when execute failed this is undefined). + console.log("result.getHead()",result.getHead()); + // Get Meta data, return Meta[]|undefined(when execute failed this is undefined). + console.log("result.getMeta()",result.getMeta()); + // Get data,return Array>|undefined(when execute failed this is undefined). + console.log("result.getData()",result.getData()); + // Get affect rows,return number|undefined(when execute failed this is undefined). + console.log("result.getAffectRows()",result.getAffectRows()); + // Get command,return SQL send to server(need to `query(sql,false)`,set 'pure=false',default true). + console.log("result.getCommand()",result.getCommand()); + // Get error code ,return number|undefined(when execute failed this is undefined). + console.log("result.getErrCode()",result.getErrCode()); + // Get error string,return string|undefined(when execute failed this is undefined). + console.log("result.getErrStr()",result.getErrStr()); +} + +(async () => { + let start = new Date().getTime(); // 开始时间 + await execute(createDB); + await execute(createTB); + await execute(addColumn); + await execute(dropColumn); + await execute(insertSql); + await execute(querySql); + await execute(errorSql); + await execute(dropDB); + let end = new Date().getTime(); // 结束时间 + console.log("total spend time:%d ms",end - start); +})() + + + + + diff --git a/src/connector/TypeScript-REST/index.ts b/src/connector/TypeScript-REST/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d61cca21442311ccabed637ae89e38c620892bb --- /dev/null +++ b/src/connector/TypeScript-REST/index.ts @@ -0,0 +1,14 @@ + +import {TDConnect,Options} from './src/connect'; +let options:Options = { + host : '127.0.0.1', + port : 6041, + path : '/rest/sql', + user : 'root', + passwd : 'taosdata' +} +let connect = function connect(option:Options){ + return new TDConnect(option); +} + +export {options,connect} \ No newline at end of file diff --git a/src/connector/TypeScript-REST/package.json b/src/connector/TypeScript-REST/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c531fc6ce0124a97656642b3446a0dd4207919f4 --- /dev/null +++ b/src/connector/TypeScript-REST/package.json @@ -0,0 +1,41 @@ +{ + "name": "td2.0-rest-connector", + "version": "1.0.0", + "description": "A REST connector for TDengine", + "source": "tdengine_rest.ts", + "main": "dist/main/rest.js", + "module": "dist/module/rest.mjs", + "types": "dist/types.d.ts", + "directories": { + "example": "example", + "test": "test" + }, + "scripts": { + "test": "parcel build --no-source-maps && node ./dist/test/test.main.js && node ./dist/test/test.module.mjs", + "example": "tsc && node ./tsc/example/example.js", + "build": "parcel build --no-source-maps", + "watch": "parcel watch" + }, + "keywords": [ + "REST", + "Node.js", + "Typescript", + "TDengine", + "taos", + "IOT", + "node-fetch" + ], + "author": "", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.7" + }, + "devDependencies": { + "@parcel/packager-ts": "^2.4.1", + "@parcel/transformer-typescript-types": "^2.4.1", + "@types/node": "^17.0.23", + "@types/node-fetch": "^2.6.1", + "parcel": "^2.4.0", + "typescript": "^4.6.3" + } +} diff --git a/src/connector/TypeScript-REST/readme.md b/src/connector/TypeScript-REST/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..15830b31745a4860373685cc07a1e948d14c6bf8 --- /dev/null +++ b/src/connector/TypeScript-REST/readme.md @@ -0,0 +1,35 @@ +# TDengine RESTful +This is a TDengine's RESTful connector in TypeScript. It's depend on [node-fetch v2](https://github.com/node-fetch/node-fetch/tree/2.x). Using `fetch(url,options)` to send sql statement and receive response. + +# Usage + +```TypeScript +import { options, connect } from '../tdengine_rest' +options.path='/rest/sqlt'; +let conn = connect(options); +let cursor = conn.cursor(); +(async()=>{ + let result = cursor.execute("show database"); + // print query result as taos shell + result.toString(); + // Get Result object, return Result object. + console.log(result.getResult()); + // Get status, return 'succ'|'error'. + console.log(result.getStatus()); + // Get head,return response head (Array|undefined,when execute failed this is undefined). + console.log(result.getHead()); + // Get Meta data, return Meta[]|undefined(when execute failed this is undefined). + console.log(result.getMeta()); + // Get data,return Array>|undefined(when execute failed this is undefined). + console.log(result.getData()); + // Get affect rows,return number|undefined(when execute failed this is undefined). + console.log(result.getAffectRows()); + // Get command,return SQL send to server(need to `query(sql,false)`,set 'pure=false',default true). + console.log(result.getCommand()); + // Get error code ,return number|undefined(when execute failed this is undefined). + console.log(result.getErrCode()); + // Get error string,return string|undefined(when execute failed this is undefined). + console.log(result.getErrStr()); +})() + +``` diff --git a/src/connector/TypeScript-REST/src/connect.ts b/src/connector/TypeScript-REST/src/connect.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8ae42dcc0f872fd2da5ce93129863b0af1ed325 --- /dev/null +++ b/src/connector/TypeScript-REST/src/connect.ts @@ -0,0 +1,29 @@ +import { TDengineCursor } from './cursor' +import { Uri, User } from './options' + +/** + * Options used to connect with REST(taosAdapter) + * Need to set options with 'host','path','port','user','passwd'. + * connWith is optional attribute for further use. + */ +export interface Options extends Uri, User { + connWith?: 'rest' | 'taosc' +} + +/** + * Create connect with TDengine,actually pass options + * to `Cursor` which send and receive HTTP request. + */ +export class TDConnect { + + _connOption: Options; + + constructor(connOption: Options) { + this._connOption = connOption + } + + cursor(): TDengineCursor { + return new TDengineCursor(this._connOption); + } + +} diff --git a/src/connector/TypeScript-REST/src/cursor.ts b/src/connector/TypeScript-REST/src/cursor.ts new file mode 100644 index 0000000000000000000000000000000000000000..07af3f256a3e1b68c78010cd57264ee02e3318eb --- /dev/null +++ b/src/connector/TypeScript-REST/src/cursor.ts @@ -0,0 +1,42 @@ +import { Uri, User } from './options' +import { TDResRequest } from './request' +import { Result } from './result' + + +export class TDengineCursor { + field: Array; + data: Array + _rowCount: number; + _uri: Uri; + _user: User; + + constructor(options: any) { + this._uri = { + host: options.host, + path: options.path, + port: options.port, + + } + this._user = { + user: options.user, + passwd: options.passwd, + } + this._rowCount = 0; + this.field = []; + this.data = []; + + } + + async query(sql: string, pure = true): Promise { + let req = new TDResRequest(this._uri, this._user); + let response = await req.request(sql); + let res_json = await response.json(); + + if (pure == false) { + return new Result(res_json, sql); + } else { + return new Result(res_json); + } + + } +} \ No newline at end of file diff --git a/src/connector/TypeScript-REST/src/options.ts b/src/connector/TypeScript-REST/src/options.ts new file mode 100644 index 0000000000000000000000000000000000000000..26a8934f6e373a19f423982448be55b105622d0a --- /dev/null +++ b/src/connector/TypeScript-REST/src/options.ts @@ -0,0 +1,16 @@ +export interface FetchOptions { + method: 'POST'; + body: string; + headers: Record +} + +export interface User { + user: string; + passwd: string; +} + +export interface Uri { + host: '127.0.0.1'; + path: "/rest/sqlt" | '/rest/sqlutc' | '/rest/sql'; + port: 6041; +} \ No newline at end of file diff --git a/src/connector/TypeScript-REST/src/request.ts b/src/connector/TypeScript-REST/src/request.ts new file mode 100644 index 0000000000000000000000000000000000000000..259c34c32366dc2c9efc0d8121985c01baea8b52 --- /dev/null +++ b/src/connector/TypeScript-REST/src/request.ts @@ -0,0 +1,35 @@ + +import { Uri,User,FetchOptions } from "./options"; +import fetch from 'node-fetch'; + +export class TDResRequest { + uri: Uri; + options: FetchOptions; + user:User; + + constructor(url: Uri, user:User) { + this.uri = url; + this.user = user; + this.options = { + method: 'POST', + body:'', + headers:{'Authorization':this._token()} + } + } + + _makeUrl(): string { + return `http://${this.uri.host}:${this.uri.port}${this.uri.path}`; + } + _token(): string { + return`Basic ${Buffer.from(`${this.user.user}:${this.user.passwd}`).toString('base64')}` + } + _body(command:string):void{ + this.options.body = command; + } + request(command:string): Promise { + this._body(command); + return fetch(this._makeUrl(), this.options); + } +} + + diff --git a/src/connector/TypeScript-REST/src/result.ts b/src/connector/TypeScript-REST/src/result.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea2722e04d1bdcac3faccb7dae05433f2d4c243e --- /dev/null +++ b/src/connector/TypeScript-REST/src/result.ts @@ -0,0 +1,219 @@ +interface IResult { + status: string; + head?: Array; + column_meta?: Array>; + data?: Array>; + rows?: number; + command?: string; + //for error + code?: number; + desc?: string; +} + +interface meta { + columnName: string; + code: number; + size: number; + typeName?: string; +} + +export class Result { + private _status: string; + private _head?: string[]; + private _column_meta?: Array; + private _data?: Array>; + private _rows?: number; + private _command?: string; + //for error + private _code?: number; + private _desc?: string; + + constructor(res: IResult, commands?: string) { + let meta_list_length = res.column_meta == undefined ? 0 : res.column_meta.length + if (res.status === 'succ') { + this._status = res.status; + this._head = res.head; + this._column_meta = new Array(meta_list_length); + this._data = res.data; + this._rows = res.rows; + this._command = commands; + this._initMeta(res); + this._code = undefined; + this._desc = undefined; + } else { + this._status = res.status; + this._head = undefined; + this._column_meta = undefined; + this._data = undefined; + this._rows = undefined; + this._command = commands; + this._code = res.code; + this._desc = res.desc; + } + + } + private _initMeta(res: IResult): void { + if (res.column_meta != undefined) { + res.column_meta.forEach((item, index) => { + if (this._column_meta != undefined) + this._column_meta[index] = { + columnName: item[0], + code: item[1], + size: item[2], + typeName: typeNameMap[item[1]] + } + }) + } + } + + getResult(): Result { + return this; + } + + getStatus(): string { + return this._status; + } + + getHead(): Array | undefined { + return this._head; + } + + getMeta(): Array | undefined { + return this._column_meta; + } + + getData(): Array> | undefined { + return this._data; + } + + getAffectRows(): number | undefined { + return this._rows; + } + + getCommand(): string | undefined { + return this._command; + } + + getErrCode(): number | undefined { + return this._code; + } + + getErrStr(): string | undefined { + return this._desc; + } + + toString(): void { + let str = ''; + if(this._command != undefined){ + console.log(this._command); + } + if (this._status === 'succ' && this._column_meta != undefined && this._data != undefined) { + str = this._prettyStr(this._column_meta, this._data) + } else { + str = `Execute ${this._status},reason:${this._desc}. error_no:${this._code} `; + console.log(str) + } + } + + private _prettyStr(fields: Array, data: Array>): string { + let colName = new Array(); + let colType = new Array(); + let colSize = new Array(); + let colStr = ''; + + for (let i = 0; i < fields.length; i++) { + colName.push(fields[i].columnName) + colType.push(fields[i].typeName); + + if ((fields[i].code) == 8 || (fields[i].code) == 10) { + colSize.push(Math.max(fields[i].columnName.length, fields[i].size)); //max(column_name.length,column_type_precision) + } else { + colSize.push(Math.max(fields[i].columnName.length, suggestedMinWidths[fields[i].size]));// max(column_name.length,suggest_column_with_suggestion) + } + // console.log(colSize) + } + colName.forEach((name, i) => { + colStr += this._fillEmpty(Math.floor(colSize[i] / 2 - name.length / 2)) + name.toString() + this._fillEmpty(Math.ceil(colSize[i] / 2 - name.length / 2)) + " | " + }) + + let strSperator = "" + let sizeSum = colSize.reduce((a, b) => a += b, (0)) + colSize.length * 3 + strSperator = this._printN("=", sizeSum) + + console.log("\n" + colStr) + console.log(strSperator) + + data.forEach((row) => { + let rowStr = "" + row.forEach((cell, index) => { + rowStr += cell == null ? 'null' : cell.toString(); + rowStr += this._fillEmpty(colSize[index] - cell.toString().length) + " | " + }) + console.log(rowStr) + }) + + return colStr + } + + private _fillEmpty(n:number) { + let str = ""; + for (let i = 0; i < n; i++) { + str += " "; + } + return str; + } + + private _printN(s:string, n:number) { + let f = ""; + for (let i = 0; i < n; i++) { + f += s; + } + return f; + } +} + + + +interface indexableString { + [index: number]: string +} +/** + * this file record TDengine's data type and code. + */ +const typeNameMap: indexableString = { + 0: 'null', + 1: 'bool', + 2: 'tinyint', + 3: 'smallint', + 4: 'int', + 5: 'bigint', + 6: 'float', + 7: 'double', + 8: 'binary', + 9: 'timestamp', + 10: 'nchar', + 11: 'unsigned tinyint', + 12: 'unsigned smallint', + 13: 'unsigned int', + 14: 'unsigned bigint', + 15: 'json' +} + +interface indexableNumber { + [index: number]: number +} +const suggestedMinWidths: indexableNumber = { + 0: 4, + 1: 4, + 2: 4, + 3: 6, + 4: 11, + 5: 12, + 6: 24, + 7: 24, + 8: 10, + 9: 25, + 10: 10, +} + + diff --git a/src/connector/TypeScript-REST/tdengine_rest.ts b/src/connector/TypeScript-REST/tdengine_rest.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d61cca21442311ccabed637ae89e38c620892bb --- /dev/null +++ b/src/connector/TypeScript-REST/tdengine_rest.ts @@ -0,0 +1,14 @@ + +import {TDConnect,Options} from './src/connect'; +let options:Options = { + host : '127.0.0.1', + port : 6041, + path : '/rest/sql', + user : 'root', + passwd : 'taosdata' +} +let connect = function connect(option:Options){ + return new TDConnect(option); +} + +export {options,connect} \ No newline at end of file diff --git a/src/connector/TypeScript-REST/tsconfig.json b/src/connector/TypeScript-REST/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..8e115328c6b74de8a1f2042f627dbbab1f98cff4 --- /dev/null +++ b/src/connector/TypeScript-REST/tsconfig.json @@ -0,0 +1,101 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + // "incremental": true, /* Enable incremental compilation */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ + // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "resolveJsonModule": true, /* Enable importing .json files */ + // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./tsc/", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ + // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ + // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/src/connector/jdbc/readme.md b/src/connector/jdbc/readme.md index 3c52ebb00ad3d6d9d32b9fd1400b0b12facd0576..9bad1effb7523b1395b2c7c8156b5f4f4e47840e 100644 --- a/src/connector/jdbc/readme.md +++ b/src/connector/jdbc/readme.md @@ -4,7 +4,7 @@ TDengine 提供了遵循 JDBC 标准(3.0)API 规范的 `taos-jdbcdriver` 实 `taos-jdbcdriver` 的实现包括 2 种形式: JDBC-JNI 和 JDBC-RESTful(taos-jdbcdriver-2.0.18 开始支持 JDBC-RESTful)。 JDBC-JNI 通过调用客户端 libtaos.so(或 taos.dll )的本地方法实现, JDBC-RESTful 则在内部封装了 RESTful 接口实现。 -![tdengine-connector](https://www.taosdata.com/cn/documentation/user/pages/images/tdengine-jdbc-connector.png) +![tdengine-connector](https://github.com/taosdata/TDengine/blob/develop/documentation20/cn/images/tdengine-jdbc-connector.png) 上图显示了 3 种 Java 应用使用连接器访问 TDengine 的方式: diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java index 6343a802af280415b4d21f56476eb4403b4608ac..3cd6f45bf0db314f9cc45a7ccb2c31428a427fdb 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/AbstractDatabaseMetaData.java @@ -1,7 +1,10 @@ package com.taosdata.jdbc; +import com.taosdata.jdbc.utils.StringUtils; + import java.sql.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; public abstract class AbstractDatabaseMetaData extends WrapperImpl implements DatabaseMetaData { @@ -550,9 +553,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da } protected ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types, Connection connection) throws SQLException { - if (catalog == null || catalog.isEmpty()) - return null; - if (!isAvailableCatalog(connection, catalog)) + if (!StringUtils.isEmpty(catalog) && !isAvailableCatalog(connection, catalog)) return new EmptyResultSet(); DatabaseMetaDataResultSet resultSet = new DatabaseMetaDataResultSet(); @@ -561,8 +562,26 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da // set row data List rowDataList = new ArrayList<>(); try (Statement stmt = connection.createStatement()) { - stmt.execute("use " + catalog); - try (ResultSet tables = stmt.executeQuery("show tables")) { + List dbs = new ArrayList<>(); + if (!StringUtils.isEmpty(catalog)) { + dbs.add(catalog); + } else { + ResultSet dbRs = stmt.executeQuery("show databases"); + while (dbRs.next()) { + dbs.add(dbRs.getString("name")); + } + } + if (dbs.isEmpty()) { + return new EmptyResultSet(); + } + for (String db : dbs) { + StringBuilder sql = new StringBuilder().append("show ").append(db).append(".tables "); + StringBuilder Ssql = new StringBuilder().append("show ").append(db).append(".stables "); + if (!StringUtils.isEmpty(tableNamePattern)) { + sql.append("like '").append(tableNamePattern).append("'"); + Ssql.append("like '").append(tableNamePattern).append("'"); + } + ResultSet tables = stmt.executeQuery(sql.toString()); while (tables.next()) { TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); rowData.setStringValue(1, catalog); //TABLE_CAT @@ -572,8 +591,7 @@ public abstract class AbstractDatabaseMetaData extends WrapperImpl implements Da rowData.setStringValue(5, ""); //REMARKS rowDataList.add(rowData); } - } - try (ResultSet stables = stmt.executeQuery("show stables")) { + ResultSet stables = stmt.executeQuery(Ssql.toString()); while (stables.next()) { TSDBResultSetRowData rowData = new TSDBResultSetRowData(10); rowData.setStringValue(1, catalog); //TABLE_CAT diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java index af036e6025e071cd39d3dac38de62bb8a2689c50..c2687ba8792e4a7a2144f61b14332c763a24af89 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBConnection.java @@ -1,13 +1,15 @@ package com.taosdata.jdbc; import java.sql.*; -import java.util.Properties; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; public class TSDBConnection extends AbstractConnection { private TSDBJNIConnector connector; private final TSDBDatabaseMetaData databaseMetaData; private boolean batchFetch; + private CopyOnWriteArrayList statements = new CopyOnWriteArrayList<>(); public Boolean getBatchFetch() { return this.batchFetch; @@ -67,11 +69,25 @@ public class TSDBConnection extends AbstractConnection { } public void close() throws SQLException { - if (isClosed) { + if (isClosed) return; + synchronized (this) { + if (isClosed) { + return; + } + for (Statement statement : statements) { + statement.close(); + } + this.connector.closeConnection(); + this.isClosed = true; } - this.connector.closeConnection(); - this.isClosed = true; + } + + public void unregisterStatement(Statement stmt) { + this.statements.remove(stmt); + } + public void registerStatement(Statement stmt) { + this.statements.addIfAbsent(stmt); } public boolean isClosed() throws SQLException { diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java index 093baef3cac5b33e6be74248a289addbc1e18e9d..3cc28b4de68cae7bcf337b12ba924454d5653706 100755 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBJNIConnector.java @@ -338,7 +338,7 @@ public class TSDBJNIConnector { public void addBatch(long stmt) throws SQLException { int code = addBatchImp(stmt, this.taos); - if (code != TSDBConstants.JNI_SUCCESS){ + if (code != TSDBConstants.JNI_SUCCESS) { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, stmtErrorMsgImp(stmt, this.taos)); } } @@ -361,13 +361,24 @@ public class TSDBJNIConnector { /*************************************************************************************************/ // NOTE: schemaless-lines public void insertLines(String[] lines, SchemalessProtocolType protocolType, SchemalessTimestampType timestampType) throws SQLException { - int code = insertLinesImp(lines, this.taos, protocolType.ordinal(), timestampType.ordinal()); - if (code != TSDBConstants.JNI_SUCCESS) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_UNKNOWN, "failed to insertLines"); + long pSql = schemalessInsertImp(lines, this.taos, protocolType.ordinal(), timestampType.ordinal()); + try { + if (pSql == TSDBConstants.JNI_CONNECTION_NULL) { + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_CONNECTION_NULL); + } + if (pSql == TSDBConstants.JNI_OUT_OF_MEMORY) { + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_OUT_OF_MEMORY); + } + + int code = this.getErrCode(pSql); + if (code != TSDBConstants.JNI_SUCCESS) { + String msg = this.getErrMsg(pSql); + throw TSDBError.createSQLException(code, msg); + } + } finally { + this.freeResultSetImp(this.taos, pSql); } } - private native int insertLinesImp(String[] lines, long conn, int type, int precision); - - + private native long schemalessInsertImp(String[] lines, long conn, int type, int precision); } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java index 003324d27a57c3557f0bb3205fcee208aa776ed5..e1e15d0332ca465c31c2ef2726b181716298378e 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSet.java @@ -19,7 +19,6 @@ import com.google.common.primitives.Longs; import com.google.common.primitives.Shorts; import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; @@ -53,7 +52,7 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { return rowData; } - public TSDBResultSet(TSDBStatement statement, TSDBJNIConnector connector, long resultSetPointer) throws SQLException { + public TSDBResultSet(TSDBStatement statement, TSDBJNIConnector connector, long resultSetPointer, int timestampPrecision) throws SQLException { this.statement = statement; this.jniConnector = connector; this.resultSetPointer = resultSetPointer; @@ -69,7 +68,8 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_JNI_NUM_OF_FIELDS_0); } this.rowData = new TSDBResultSetRowData(this.columnMetaDataList.size()); - this.blockData = new TSDBResultSetBlockData(this.columnMetaDataList, this.columnMetaDataList.size()); + this.blockData = new TSDBResultSetBlockData(this.columnMetaDataList, this.columnMetaDataList.size(), timestampPrecision); + this.timestampPrecision = timestampPrecision; } public boolean next() throws SQLException { @@ -268,7 +268,7 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { checkAvailability(columnIndex, this.columnMetaDataList.size()); if (this.getBatchFetch()) - return this.blockData.getString(columnIndex).getBytes(); + return this.blockData.getBytes(columnIndex -1); Object value = this.rowData.getObject(columnIndex); this.lastWasNull = value == null; @@ -343,7 +343,7 @@ public class TSDBResultSet extends AbstractResultSet implements ResultSet { @Override public BigDecimal getBigDecimal(int columnIndex) throws SQLException { if (this.getBatchFetch()) - return new BigDecimal(this.blockData.getLong(columnIndex - 1)); + return BigDecimal.valueOf(this.blockData.getDouble(columnIndex - 1)); this.lastWasNull = this.rowData.wasNull(columnIndex); if (lastWasNull) diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java index a74c9cbb8831c5b1142b5ddd3b6b17f95249b873..8dcd66ad4751c27139e73a9d77bc524026805e6a 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetBlockData.java @@ -25,10 +25,15 @@ import java.nio.ShortBuffer; import java.sql.SQLDataException; import java.sql.SQLException; import java.sql.Timestamp; +import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import com.google.common.primitives.Shorts; +import com.taosdata.jdbc.enums.TimestampPrecision; import com.taosdata.jdbc.utils.NullType; public class TSDBResultSetBlockData { @@ -39,9 +44,12 @@ public class TSDBResultSetBlockData { private List columnMetaDataList; private ArrayList colData; - public TSDBResultSetBlockData(List colMeta, int numOfCols) { + private int timestampPrecision; + + public TSDBResultSetBlockData(List colMeta, int numOfCols, int timestampPrecision) { this.columnMetaDataList = colMeta; this.colData = new ArrayList<>(numOfCols); + this.timestampPrecision = timestampPrecision; } public TSDBResultSetBlockData() { @@ -169,12 +177,46 @@ public class TSDBResultSetBlockData { public String getString(int col) throws SQLException { Object obj = get(col); if (obj == null) { - return new NullType().toString(); +// return new NullType().toString(); + return null; } + if (obj instanceof String) + return (String) obj; + + if (obj instanceof byte[]) { + String charset = TaosGlobalConfig.getCharset(); + try { + return new String((byte[]) obj, charset); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e.getMessage()); + } + } return obj.toString(); } + public byte[] getBytes(int col) throws SQLException { + + Object obj = get(col); + if (obj == null) { + return null; + } + if (obj instanceof byte[]) + return (byte[]) obj; + if (obj instanceof String) + return ((String) obj).getBytes(); + if (obj instanceof Long) + return Longs.toByteArray((long) obj); + if (obj instanceof Integer) + return Ints.toByteArray((int) obj); + if (obj instanceof Short) + return Shorts.toByteArray((short) obj); + if (obj instanceof Byte) + return new byte[]{(byte) obj}; + + return obj.toString().getBytes(); + } + public int getInt(int col) { Object obj = get(col); if (obj == null) { @@ -184,14 +226,18 @@ public class TSDBResultSetBlockData { int type = this.columnMetaDataList.get(col).getColType(); switch (type) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: + return (boolean) obj ? 1 : 0; case TSDBConstants.TSDB_DATA_TYPE_TINYINT: + return (byte) obj; case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: + return (short) obj; case TSDBConstants.TSDB_DATA_TYPE_INT: { return (int) obj; } case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { return ((Long) obj).intValue(); + case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { + return ((Long) ((Timestamp) obj).getTime()).intValue(); } case TSDBConstants.TSDB_DATA_TYPE_FLOAT: @@ -218,19 +264,25 @@ public class TSDBResultSetBlockData { int type = this.columnMetaDataList.get(col).getColType(); switch (type) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: + return (boolean) obj; case TSDBConstants.TSDB_DATA_TYPE_TINYINT: + return ((byte) obj == 0) ? Boolean.FALSE : Boolean.TRUE; case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: + return ((short) obj == 0) ? Boolean.FALSE : Boolean.TRUE; case TSDBConstants.TSDB_DATA_TYPE_INT: { - return ((int) obj == 0L) ? Boolean.FALSE : Boolean.TRUE; + return ((int) obj == 0) ? Boolean.FALSE : Boolean.TRUE; } case TSDBConstants.TSDB_DATA_TYPE_BIGINT: + return (((long) obj) == 0L) ? Boolean.FALSE : Boolean.TRUE; + case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { - return (((Long) obj) == 0L) ? Boolean.FALSE : Boolean.TRUE; + return ((Timestamp) obj).getTime() == 0L ? Boolean.FALSE : Boolean.TRUE; } case TSDBConstants.TSDB_DATA_TYPE_FLOAT: + return (((float) obj) == 0f) ? Boolean.FALSE : Boolean.TRUE; case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { - return (((Double) obj) == 0) ? Boolean.FALSE : Boolean.TRUE; + return (((double) obj) == 0) ? Boolean.FALSE : Boolean.TRUE; } case TSDBConstants.TSDB_DATA_TYPE_NCHAR: @@ -258,17 +310,31 @@ public class TSDBResultSetBlockData { int type = this.columnMetaDataList.get(col).getColType(); switch (type) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: + return (boolean) obj ? 1 : 0; case TSDBConstants.TSDB_DATA_TYPE_TINYINT: + return (byte) obj; case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: + return (short) obj; case TSDBConstants.TSDB_DATA_TYPE_INT: { return (int) obj; } case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { return (long) obj; + case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { + Timestamp ts = (Timestamp) obj; + switch (this.timestampPrecision) { + case TimestampPrecision.MS: + default: + return ts.getTime(); + case TimestampPrecision.US: + return ts.getTime() * 1000 + ts.getNanos() / 1000 % 1000; + case TimestampPrecision.NS: + return ts.getTime() * 1000_000 + ts.getNanos() % 1000_000; + } } case TSDBConstants.TSDB_DATA_TYPE_FLOAT: + return ((Float) obj).longValue(); case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { return ((Double) obj).longValue(); } @@ -284,6 +350,17 @@ public class TSDBResultSetBlockData { } public Timestamp getTimestamp(int col) throws SQLException { + Object obj = get(col); + if (obj == null) { + return null; + } + + int type = this.columnMetaDataList.get(col).getColType(); + if (type == TSDBConstants.TSDB_DATA_TYPE_BIGINT) + return parseTimestampColumnData((long) obj); + if (type == TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP) + return (Timestamp) obj; + return new Timestamp(getLong(col)); } @@ -296,17 +373,31 @@ public class TSDBResultSetBlockData { int type = this.columnMetaDataList.get(col).getColType(); switch (type) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: + return (boolean) obj ? 1 : 0; case TSDBConstants.TSDB_DATA_TYPE_TINYINT: + return (byte) obj; case TSDBConstants.TSDB_DATA_TYPE_SMALLINT: + return (short) obj; case TSDBConstants.TSDB_DATA_TYPE_INT: { return (int) obj; } case TSDBConstants.TSDB_DATA_TYPE_BIGINT: - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { return (long) obj; + case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { + Timestamp ts = (Timestamp) obj; + switch (this.timestampPrecision) { + case TimestampPrecision.MS: + default: + return ts.getTime(); + case TimestampPrecision.US: + return ts.getTime() * 1000 + ts.getNanos() / 1000 % 1000; + case TimestampPrecision.NS: + return ts.getTime() * 1000_000 + ts.getNanos() % 1000_000; + } } case TSDBConstants.TSDB_DATA_TYPE_FLOAT: + return Double.parseDouble(String.valueOf(obj)); case TSDBConstants.TSDB_DATA_TYPE_DOUBLE: { return (double) obj; } @@ -367,7 +458,15 @@ public class TSDBResultSetBlockData { return val; } - case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: + case TSDBConstants.TSDB_DATA_TYPE_TIMESTAMP: { + LongBuffer lb = (LongBuffer) this.colData.get(col); + long val = lb.get(this.rowIndex); + if (NullType.isBigIntNull(val)) { + return null; + } + + return parseTimestampColumnData(val); + } case TSDBConstants.TSDB_DATA_TYPE_BIGINT: { LongBuffer lb = (LongBuffer) this.colData.get(col); long val = lb.get(this.rowIndex); @@ -408,13 +507,14 @@ public class TSDBResultSetBlockData { return null; } - return new String(dest); + return dest; } case TSDBConstants.TSDB_DATA_TYPE_JSON: case TSDBConstants.TSDB_DATA_TYPE_NCHAR: { ByteBuffer bb = (ByteBuffer) this.colData.get(col); - bb.position((fieldSize + BINARY_LENGTH_OFFSET) * this.rowIndex); +// bb.position((fieldSize * 4 + 2 + 1) * this.rowIndex); + bb.position(bb.capacity() / numOfRows * this.rowIndex); int length = bb.getShort(); byte[] dest = new byte[length]; bb.get(dest, 0, length); @@ -432,4 +532,21 @@ public class TSDBResultSetBlockData { return 0; } + + private Timestamp parseTimestampColumnData(long value) { + if (TimestampPrecision.MS == timestampPrecision) + return new Timestamp(value); + + if (TimestampPrecision.US == timestampPrecision) { + long epochSec = value / 1000_000L; + long nanoAdjustment = value % 1000_000L * 1000L; + return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); + } + if (TimestampPrecision.NS == timestampPrecision) { + long epochSec = value / 1000_000_000L; + long nanoAdjustment = value % 1000_000_000L; + return Timestamp.from(Instant.ofEpochSecond(epochSec, nanoAdjustment)); + } + return null; + } } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java index 5d2b98a516c0d0086628e242570b03db9b28c3ff..258a9ad6146c4376da759feb19324dfff5a7e513 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBResultSetRowData.java @@ -14,8 +14,6 @@ *****************************************************************************/ package com.taosdata.jdbc; -import com.taosdata.jdbc.utils.NullType; - import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.sql.SQLException; @@ -132,7 +130,7 @@ public class TSDBResultSetRowData { public int getInt(int col, int nativeType) throws SQLException { Object obj = data.get(col - 1); if (obj == null) - return NullType.getIntNull(); + return 0; switch (nativeType) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: @@ -213,7 +211,7 @@ public class TSDBResultSetRowData { public long getLong(int col, int nativeType) throws SQLException { Object obj = data.get(col - 1); if (obj == null) { - return NullType.getBigIntNull(); + return 0; } switch (nativeType) { @@ -282,7 +280,7 @@ public class TSDBResultSetRowData { public float getFloat(int col, int nativeType) { Object obj = data.get(col - 1); if (obj == null) - return NullType.getFloatNull(); + return 0; switch (nativeType) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: @@ -301,7 +299,7 @@ public class TSDBResultSetRowData { case TSDBConstants.TSDB_DATA_TYPE_BIGINT: return (Long) obj; default: - return NullType.getFloatNull(); + return 0; } } @@ -322,7 +320,7 @@ public class TSDBResultSetRowData { public double getDouble(int col, int nativeType) { Object obj = data.get(col - 1); if (obj == null) - return NullType.getDoubleNull(); + return 0; switch (nativeType) { case TSDBConstants.TSDB_DATA_TYPE_BOOL: @@ -341,7 +339,7 @@ public class TSDBResultSetRowData { case TSDBConstants.TSDB_DATA_TYPE_BIGINT: return (Long) obj; default: - return NullType.getDoubleNull(); + return 0; } } @@ -454,7 +452,7 @@ public class TSDBResultSetRowData { milliseconds = ts / 1_000; fracNanoseconds = (int) (ts * 1_000 % 1_000_000_000); if (fracNanoseconds < 0) { - if (milliseconds == 0 ){ + if (milliseconds == 0) { milliseconds = -1; } fracNanoseconds += 1_000_000_000; @@ -465,7 +463,7 @@ public class TSDBResultSetRowData { milliseconds = ts / 1_000_000; fracNanoseconds = (int) (ts % 1_000_000_000); if (fracNanoseconds < 0) { - if (milliseconds == 0 ){ + if (milliseconds == 0) { milliseconds = -1; } fracNanoseconds += 1_000_000_000; diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java index ce877987e6e9073defbff62e283910ee34366c4d..c4cf2bafbf5f07a5e7148257eea4026dc2e3abb2 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBStatement.java @@ -28,72 +28,86 @@ public class TSDBStatement extends AbstractStatement { TSDBStatement(TSDBConnection connection) { this.connection = connection; + connection.registerStatement(this); } public ResultSet executeQuery(String sql) throws SQLException { - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - //TODO: - // this is an unreasonable implementation, if the paratemer is a insert statement, - // the JNI connector will execute the sql at first and return a pointer: pSql, - // we use this pSql and invoke the isUpdateQuery(long pSql) method to decide . - // but the insert sql is already executed in database. - //execute query - long pSql = this.connection.getConnector().executeQuery(sql); - // if pSql is create/insert/update/delete/alter SQL - if (this.connection.getConnector().isUpdateQuery(pSql)) { - this.connection.getConnector().freeResultSet(pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); + synchronized (this) { + if (isClosed()) { + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); + } + if (this.resultSet != null && !this.resultSet.isClosed()) + this.resultSet.close(); + //TODO: + // this is an unreasonable implementation, if the paratemer is a insert statement, + // the JNI connector will execute the sql at first and return a pointer: pSql, + // we use this pSql and invoke the isUpdateQuery(long pSql) method to decide . + // but the insert sql is already executed in database. + //execute query + long pSql = this.connection.getConnector().executeQuery(sql); + // if pSql is create/insert/update/delete/alter SQL + if (this.connection.getConnector().isUpdateQuery(pSql)) { + this.connection.getConnector().freeResultSet(pSql); + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEQUERY); + } + int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql); + resultSet = new TSDBResultSet(this, this.connection.getConnector(), pSql, timestampPrecision); + resultSet.setBatchFetch(this.connection.getBatchFetch()); + return resultSet; } - TSDBResultSet res = new TSDBResultSet(this, this.connection.getConnector(), pSql); - int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql); - res.setTimestampPrecision(timestampPrecision); - res.setBatchFetch(this.connection.getBatchFetch()); - return res; } public int executeUpdate(String sql) throws SQLException { - if (isClosed()) - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - - long pSql = this.connection.getConnector().executeQuery(sql); - // if pSql is create/insert/update/delete/alter SQL - if (!this.connection.getConnector().isUpdateQuery(pSql)) { + synchronized (this) { + if (isClosed()) + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); + if (this.resultSet != null && !this.resultSet.isClosed()) + this.resultSet.close(); + + long pSql = this.connection.getConnector().executeQuery(sql); + // if pSql is create/insert/update/delete/alter SQL + if (!this.connection.getConnector().isUpdateQuery(pSql)) { + this.connection.getConnector().freeResultSet(pSql); + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEUPDATE); + } + int affectedRows = this.connection.getConnector().getAffectedRows(pSql); this.connection.getConnector().freeResultSet(pSql); - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_INVALID_WITH_EXECUTEUPDATE); + return affectedRows; } - int affectedRows = this.connection.getConnector().getAffectedRows(pSql); - this.connection.getConnector().freeResultSet(pSql); - return affectedRows; } public void close() throws SQLException { if (isClosed) return; + connection.unregisterStatement(this); if (this.resultSet != null && !this.resultSet.isClosed()) this.resultSet.close(); isClosed = true; } public boolean execute(String sql) throws SQLException { - // check if closed - if (isClosed()) { - throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); - } - - // execute query - long pSql = this.connection.getConnector().executeQuery(sql); - // if pSql is create/insert/update/delete/alter SQL - if (this.connection.getConnector().isUpdateQuery(pSql)) { - this.affectedRows = this.connection.getConnector().getAffectedRows(pSql); - this.connection.getConnector().freeResultSet(pSql); - return false; + synchronized (this) { + // check if closed + if (isClosed()) { + throw TSDBError.createSQLException(TSDBErrorNumbers.ERROR_STATEMENT_CLOSED); + } + if (this.resultSet != null && !this.resultSet.isClosed()) + this.resultSet.close(); + + // execute query + long pSql = this.connection.getConnector().executeQuery(sql); + // if pSql is create/insert/update/delete/alter SQL + if (this.connection.getConnector().isUpdateQuery(pSql)) { + this.affectedRows = this.connection.getConnector().getAffectedRows(pSql); + this.connection.getConnector().freeResultSet(pSql); + return false; + } + + int timestampPrecision = this.connection.getConnector().getResultTimePrecision(pSql); + this.resultSet = new TSDBResultSet(this, this.connection.getConnector(), pSql, timestampPrecision); + this.resultSet.setBatchFetch(this.connection.getBatchFetch()); + return true; } - - this.resultSet = new TSDBResultSet(this, this.connection.getConnector(), pSql); - this.resultSet.setBatchFetch(this.connection.getBatchFetch()); - return true; } public ResultSet getResultSet() throws SQLException { diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java index d74f7755b24f1eb59059fb5ad5ead48d420ec7f6..2a535fc8fa629a3f6d4780b8f03b397aca443824 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBSubscribe.java @@ -14,6 +14,8 @@ *****************************************************************************/ package com.taosdata.jdbc; +import com.taosdata.jdbc.enums.TimestampPrecision; + import java.sql.SQLException; public class TSDBSubscribe { @@ -41,7 +43,7 @@ public class TSDBSubscribe { } else if (resultSetPointer == TSDBConstants.JNI_NULL_POINTER) { return null; } else { - return new TSDBResultSet(null, this.connecter, resultSetPointer); + return new TSDBResultSet(null, this.connecter, resultSetPointer, TimestampPrecision.UNKNOWN); } } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java index 4558dfa84bfccacf9f0d4fa2d7991c8bd0546b30..aee575b266ed9abfce427b8f08481aac8fad00eb 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/enums/TimestampPrecision.java @@ -4,4 +4,5 @@ public class TimestampPrecision { public static final int MS = 0; public static final int US = 1; public static final int NS = 2; + public static final int UNKNOWN = 9999; } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java index 599ee85a6bbdb2a612faf1434f4921f071ea348e..2819173da852fb7f7ca3a62c21fdfab7c9e98b5d 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/rs/RestfulResultSet.java @@ -482,9 +482,6 @@ public class RestfulResultSet extends AbstractResultSet implements ResultSet { return Shorts.toByteArray((short) value); if (value instanceof Byte) return new byte[]{(byte) value}; - if (value instanceof Timestamp) { - return Utils.formatTimestamp((Timestamp) value).getBytes(); - } return value.toString().getBytes(); } diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..5cd7091c3385aedf4c1f7e7435ddbb4d803c3c62 --- /dev/null +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/utils/StringUtils.java @@ -0,0 +1,7 @@ +package com.taosdata.jdbc.utils; + +public class StringUtils { + public static boolean isEmpty(final CharSequence cs) { + return cs == null || cs.length() == 0; + } +} diff --git a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java index 709f740e486e8bcfe06a44d14f67cf3cf5b32264..6cf2d06df4ddfbc8a5530c966b13eb48a977dad3 100644 --- a/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java +++ b/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ws/BlockResultSet.java @@ -645,8 +645,6 @@ public class BlockResultSet extends AbstractWSResultSet { } if (value instanceof Float) return (float) value; - if (value instanceof Double) - return (float) (double) value; int taosType = fields.get(columnIndex - 1).getTaosType(); switch (taosType) { @@ -670,6 +668,12 @@ public class BlockResultSet extends AbstractWSResultSet { throwRangeException(value.toString(), columnIndex, Types.FLOAT); return tmp.floatValue(); } + case TSDB_DATA_TYPE_DOUBLE:{ + Double tmp = (double) value; + if (tmp < Float.MIN_VALUE || tmp > Float.MAX_VALUE) + throwRangeException(value.toString(), columnIndex, Types.FLOAT); + return Float.parseFloat(String.valueOf(tmp)); + } case TSDB_DATA_TYPE_NCHAR: case TSDB_DATA_TYPE_JSON: @@ -700,7 +704,7 @@ public class BlockResultSet extends AbstractWSResultSet { if (value instanceof Double) return (double) value; if (value instanceof Float) - return (float) value; + return Double.parseDouble(String.valueOf(value)); int taosType = fields.get(columnIndex - 1).getTaosType(); switch (taosType) { @@ -763,9 +767,6 @@ public class BlockResultSet extends AbstractWSResultSet { return Shorts.toByteArray((short) value); if (value instanceof Byte) return new byte[]{(byte) value}; - if (value instanceof Timestamp) { - return Utils.formatTimestamp((Timestamp) value).getBytes(); - } return value.toString().getBytes(); } diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java index 47d39b5e1046f15ec3a2d5525a1f9ed8ba9bef34..75480356e02c260ac3ad3e7c678f8fd881bf1b0a 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/JsonTagTest.java @@ -9,7 +9,9 @@ import org.junit.runners.MethodSorters; import java.sql.*; import java.util.ArrayList; +import java.util.HashSet; import java.util.Random; +import java.util.Set; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(CatalogRunner.class) @@ -1129,14 +1131,14 @@ public class JsonTagTest { ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); String s = ""; int count = 0; + Set set = new HashSet<>(); while (resultSet.next()) { count++; - s = resultSet.getString(2); - + set.add(resultSet.getString(2)); } Assert.assertEquals(8, count); - Assert.assertEquals("\"femail\"", s); - close(resultSet); + Assert.assertTrue(set.contains("\"femail\"")); + Assert.assertTrue(set.contains("\"收到货\"")); } @Test diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java index cb6133015c0256de99ea4db02bedeb982ce7491d..d620168c80b86e073d0a6fee1d43e1d9cb942b70 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/TSDBDatabaseMetaDataTest.java @@ -727,8 +727,8 @@ public class TSDBDatabaseMetaDataTest { Assert.assertEquals(26, columns.getInt("COLUMN_SIZE")); // DECIMAL_DIGITS Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt("DECIMAL_DIGITS")); + Assert.assertEquals(0, columns.getInt(9)); + Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); Assert.assertEquals(null, columns.getString(9)); Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); // NUM_PREC_RADIX @@ -773,8 +773,8 @@ public class TSDBDatabaseMetaDataTest { Assert.assertEquals(12, columns.getInt("COLUMN_SIZE")); // DECIMAL_DIGITS Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt("DECIMAL_DIGITS")); + Assert.assertEquals(0, columns.getInt(9)); + Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); Assert.assertEquals(null, columns.getString(9)); Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); // NUM_PREC_RADIX diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4925c14cd850a1d07c2e5c99026ee238a2deb61c --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockJsonTagTest.java @@ -0,0 +1,1338 @@ +package com.taosdata.jdbc.block; + +import com.taosdata.jdbc.TSDBDriver; +import com.taosdata.jdbc.TSDBPreparedStatement; +import com.taosdata.jdbc.annotation.CatalogRunner; +import com.taosdata.jdbc.annotation.Description; +import com.taosdata.jdbc.annotation.TestTarget; +import org.junit.*; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; + +import java.sql.*; +import java.util.*; + +/** + * fetch_block for json tag test + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@RunWith(CatalogRunner.class) +@TestTarget(alias = "JsonTag", author = "huolibo", version = "2.0.38") +public class TSDBBlockJsonTagTest { + private static final String dbName = "json_tag_test"; + private static Connection connection; + private static Statement statement; + private static final String superSql = "create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"; + private static final String[] sql = { + "insert into jsons1_1 using jsons1 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(now, 1, false, 'json1', '你是') (1591060608000, 23, true, '等等', 'json')", + "insert into jsons1_2 using jsons1 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060628000, 2, true, 'json2', 'sss')", + "insert into jsons1_3 using jsons1 tags('{\"tag1\":false,\"tag2\":\"beijing\"}') values (1591060668000, 3, false, 'json3', 'efwe')", + "insert into jsons1_4 using jsons1 tags('{\"tag1\":null,\"tag2\":\"shanghai\",\"tag3\":\"hello\"}') values (1591060728000, 4, true, 'json4', '323sd')", + "insert into jsons1_5 using jsons1 tags('{\"tag1\":1.232, \"tag2\":null}') values(1591060928000, 1, false, '你就会', 'ewe')", + "insert into jsons1_6 using jsons1 tags('{\"tag1\":11,\"tag2\":\"\",\"tag2\":null}') values(1591061628000, 11, false, '你就会','')", + "insert into jsons1_7 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')", + // test duplicate key using the first one. + "CREATE TABLE if not exists jsons1_8 using jsons1 tags('{\"tag1\":null, \"tag1\":true, \"tag1\":45, \"1tag$\":2, \" \":90}')", + + }; + + private static final String[] invalidJsonInsertSql = { + // test empty json string, save as tag is NULL + "insert into jsons1_9 using jsons1 tags('\t') values (1591062328000, 24, NULL, '你就会', '2sdw')", + }; + + private static final String[] invalidJsonCreateSql = { + "CREATE TABLE if not exists jsons1_10 using jsons1 tags('')", + "CREATE TABLE if not exists jsons1_11 using jsons1 tags(' ')", + "CREATE TABLE if not exists jsons1_12 using jsons1 tags('{}')", + "CREATE TABLE if not exists jsons1_13 using jsons1 tags('null')", + }; + + // test invalidate json + private static final String[] errorJsonInsertSql = { + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('\"efwewf\"')", + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('3333')", + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('33.33')", + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('false')", + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('[1,true]')", + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{222}')", + "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"fe\"}')", + }; + + private static final String[] errorSelectSql = { + "select * from jsons1 where jtag->tag1='beijing'", + "select * from jsons1 where jtag->'location'", + "select * from jsons1 where jtag->''", + "select * from jsons1 where jtag->''=9", + "select -> from jsons1", + "select ? from jsons1", + "select * from jsons1 where contains", + "select * from jsons1 where jtag->", + "select jtag->location from jsons1", + "select jtag contains location from jsons1", + "select * from jsons1 where jtag contains location", + "select * from jsons1 where jtag contains ''", + "select * from jsons1 where jtag contains 'location'='beijing'", + // test where with json tag + "select * from jsons1_1 where jtag is not null", + "select * from jsons1 where jtag='{\"tag1\":11,\"tag2\":\"\"}'", + "select * from jsons1 where jtag->'tag1'={}" + }; + + @Test + @Description("insert json tag") + public void case01_InsertTest() throws SQLException { + for (String sql : sql) { + statement.execute(sql); + } + for (String sql : invalidJsonInsertSql) { + statement.execute(sql); + } + for (String sql : invalidJsonCreateSql) { + statement.execute(sql); + } + } + + @Test + @Description("error json tag insert") + public void case02_ErrorJsonInsertTest() { + int count = 0; + for (String sql : errorJsonInsertSql) { + try { + statement.execute(sql); + } catch (SQLException e) { + count++; + } + } + Assert.assertEquals(errorJsonInsertSql.length, count); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when json value is array") + public void case02_ArrayErrorTest() throws SQLException { + statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":[1,true]}')"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when json value is empty") + public void case02_EmptyValueErrorTest() throws SQLException { + statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":{}}')"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when json key is not ASCII") + public void case02_AbnormalKeyErrorTest1() throws SQLException { + statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"。loc\":\"fff\"}')"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when json key is '\\t'") + public void case02_AbnormalKeyErrorTest2() throws SQLException { + statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\t\":\"fff\"}')"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when json key is chinese") + public void case02_AbnormalKeyErrorTest3() throws SQLException { + statement.execute("CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"试试\":\"fff\"}')"); + } + + @Test + @Description("alter json tag") + public void case03_AlterTag() throws SQLException { + statement.execute("ALTER TABLE jsons1_1 SET TAG jtag='{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}'"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when add json tag") + public void case03_AddTagErrorTest() throws SQLException { + statement.execute("ALTER STABLE jsons1 add tag tag2 nchar(20)"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when delete json tag") + public void case03_dropTagErrorTest() throws SQLException { + statement.execute("ALTER STABLE jsons1 drop tag jtag"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when set some json tag value") + public void case03_AlterTagErrorTest() throws SQLException { + statement.execute("ALTER TABLE jsons1_1 SET TAG jtag=4"); + } + + @Test + @Description("exception will throw when select syntax error") + public void case04_SelectErrorTest() { + int count = 0; + for (String sql : errorSelectSql) { + try { + statement.execute(sql); + } catch (SQLException e) { + count++; + } + } + Assert.assertEquals(errorSelectSql.length, count); + } + + @Test + @Description("normal select stable") + public void case04_select01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select dataint from jsons1"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); + close(resultSet); + } + + @Test + @Description("select all column from stable") + public void case04_select02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); + close(resultSet); + } + + @Test + @Description("select json tag from stable") + public void case04_select03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); + ResultSetMetaData metaData = resultSet.getMetaData(); + metaData.getColumnTypeName(1); + int count = 0; + Set set = new HashSet<>(); + while (resultSet.next()) { + count++; + set.add(resultSet.getString(1)); + } + Assert.assertTrue(set.contains("{\"tag1\":null,\"1tag$\":2,\" \":90}")); + Assert.assertTrue(set.contains("{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}")); + Assert.assertEquals(sql.length + invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); + close(resultSet); + } + + @Test + @Description("where condition tag is null") + public void case04_select04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(invalidJsonInsertSql.length + invalidJsonCreateSql.length, count); + close(resultSet); + } + + @Test + @Description("where condition tag is not null") + public void case04_select05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1 where jtag is not null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(sql.length, count); + close(resultSet); + } + + @Test + @Description("select json tag") + public void case04_select06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1_8"); + resultSet.next(); + String result = resultSet.getString(1); + Assert.assertEquals("{\"tag1\":null,\"1tag$\":2,\" \":90}", result); + close(resultSet); + } + + @Test + @Description("select json tag") + public void case04_select07() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1_1"); + resultSet.next(); + String result = resultSet.getString(1); + Assert.assertEquals("{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}", result); + close(resultSet); + } + + @Test + @Description("select not exist json tag") + public void case04_select08() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1_9"); + resultSet.next(); + String result = resultSet.getString(1); + Assert.assertNull(result); + close(resultSet); + } + + @Test + @Description("select a json tag") + public void case04_select09() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_1"); + resultSet.next(); + String result = resultSet.getString(1); + Assert.assertEquals("\"femail\"", result); + close(resultSet); + } + + @Test + @Description("select a json tag, the value is empty") + public void case04_select10() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_6"); + resultSet.next(); + String result = resultSet.getString(1); + Assert.assertEquals("\"\"", result); + close(resultSet); + } + + @Test + @Description("select a json tag, the value is int") + public void case04_select11() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag2' from jsons1_1"); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertEquals("35", string); + close(resultSet); + } + + @Test + @Description("select a json tag, the value is boolean") + public void case04_select12() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag3' from jsons1_1"); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertEquals("true", string); + close(resultSet); + } + + @Test + @Description("select a json tag, the value is null") + public void case04_select13() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_4"); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertEquals("null", string); + close(resultSet); + } + + @Test + @Description("select a json tag, the value is double") + public void case04_select14() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_5"); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertEquals("1.232000000", string); + close(resultSet); + } + + @Test + @Description("select a json tag, the key is not exist") + public void case04_select15() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag10' from jsons1_4"); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertNull(string); + close(resultSet); + } + + @Test + @Description("select a json tag, the result number equals tables number") + public void case04_select16() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(sql.length + invalidJsonCreateSql.length + invalidJsonInsertSql.length, count); + close(resultSet); + } + + @Test + @Description("where condition '=' for string") + public void case04_select19() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("select and where conditon '=' for string") + public void case04_select20() throws SQLException { + ResultSet resultSet = statement.executeQuery("select dataint,tbname,jtag->'tag1',jtag from jsons1 where jtag->'tag2'='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition result is null") + public void case04_select21() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition equation has chinese") + public void case04_select23() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='收到货'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition support '>' for character") + public void case05_symbolOperation01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>'beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition support '>=' for character") + public void case05_symbolOperation02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'>='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where condition support '<' for character") + public void case05_symbolOperation03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<'beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition support '<=' in character") + public void case05_symbolOperation04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'<='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(4, count); + close(resultSet); + } + + @Test + @Description("where condition support '!=' in character") + public void case05_symbolOperation05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'!='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where condition support '=' empty") + public void case05_symbolOperation06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2'=''"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + // where json value is int + @Test + @Description("where condition support '=' for int") + public void case06_selectValue01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=5"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where conditional support '<' for int") + public void case06_selectValue02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<54"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where condition support '<=' for int") + public void case06_selectValue03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=11"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where conditional support '>' for int") + public void case06_selectValue04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>4"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition support '>=' for int") + public void case06_selectValue05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=5"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where conditional support '!=' for int") + public void case06_selectValue06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=5"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where conditional support '!=' for int") + public void case06_selectValue07() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=55"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where conditional support '!=' for int and result is nothing") + public void case06_selectValue08() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=10"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition support '=' for double") + public void case07_selectValue01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=1.232"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition support '<' for double") + public void case07_doubleOperation01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<1.232"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition support '<=' for double") + public void case07_doubleOperation02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'<=1.232"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition support '>' for double") + public void case07_doubleOperation03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>1.23"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where condition support '>=' for double") + public void case07_doubleOperation04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'>=1.232"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test + @Description("where condition support '!=' for double") + public void case07_doubleOperation05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=1.232"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition support '!=' for double") + public void case07_doubleOperation06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=3.232"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(3, count); + close(resultSet); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when denominator is zero") + public void case07_doubleOperation07() throws SQLException { + statement.executeQuery("select * from jsons1 where jtag->'tag1'/0=3"); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when invalid operation") + public void case07_doubleOperation08() throws SQLException { + statement.executeQuery("select * from jsons1 where jtag->'tag1'/5=1"); + } + + @Test + @Description("where condition support '=' for boolean") + public void case08_boolOperation01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=true"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition support '=' for boolean") + public void case08_boolOperation02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition support '!=' for boolean") + public void case08_boolOperation03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'!=false"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test(expected = SQLException.class) + @Description("exception will throw when '>' operation for boolean") + public void case08_boolOperation04() throws SQLException { + statement.executeQuery("select * from jsons1 where jtag->'tag1'>false"); + } + + @Test + @Description("where conditional support '=null'") + public void case09_select01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where conditional support 'is null'") + public void case09_select02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition support 'is not null'") + public void case09_select03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag is not null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(8, count); + close(resultSet); + } + + @Test + @Description("where condition support one tag '='") + public void case09_select04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag_no_exist'=3"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition support one tag 'is null'") + public void case09_select05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(invalidJsonInsertSql.length, count); + close(resultSet); + } + + @Test + @Description("where condition support one tag 'is null'") + public void case09_select06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag4' is null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(sql.length + invalidJsonInsertSql.length, count); + close(resultSet); + } + + @Test + @Description("where condition support one tag 'is not null'") + public void case09_select07() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag3' is not null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(4, count); + close(resultSet); + } + + @Test + @Description("contains") + public void case09_select10() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag1'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(8, count); + close(resultSet); + } + + @Test + @Description("contains") + public void case09_select11() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag3'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(4, count); + close(resultSet); + } + + @Test + @Description("contains with no exist tag") + public void case09_select12() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag contains 'tag_no_exist'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition with and") + public void case10_selectAndOr01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition with 'or'") + public void case10_selectAndOr02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false or jtag->'tag2'='beijing'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition with 'and'") + public void case10_selectAndOr03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition with 'or'") + public void case10_selectAndOr04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition with 'or' and contains") + public void case10_selectAndOr05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' is not null and jtag contains 'tag3'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(4, count); + close(resultSet); + } + + @Test + @Description("where condition with 'and' and contains") + public void case10_selectAndOr06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1'='femail' and jtag contains 'tag3'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("test with tbname/normal column") + public void case11_selectTbName01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("test with tbname/normal column") + public void case11_selectTbName02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("test with tbname/normal column") + public void case11_selectTbName03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=3"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("test with tbname/normal column") + public void case11_selectTbName04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=23"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("where condition like") + public void case12_selectWhere01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag2' like 'bei%'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition like") + public void case12_selectWhere02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select *,tbname from jsons1 where jtag->'tag1' like 'fe%' and jtag->'tag2' is not null"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test(expected = SQLException.class) + @Description("where condition in no support in") + public void case12_selectWhere03() throws SQLException { + statement.executeQuery("select * from jsons1 where jtag->'tag1' in ('beijing')"); + } + + @Test + @Description("where condition match") + public void case12_selectWhere04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition match") + public void case12_selectWhere05() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match 'ma$'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("where condition match") + public void case12_selectWhere06() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag2' match 'jing$'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(2, count); + close(resultSet); + } + + @Test + @Description("where condition match") + public void case12_selectWhere07() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from jsons1 where jtag->'tag1' match '收到'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("insert distinct") + public void case13_selectDistinct01() throws SQLException { + statement.execute("insert into jsons1_14 using jsons1 tags('{\"tag1\":\"收到货\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '你就会', 'dws')"); + } + + @Test + @Description("distinct json tag") + public void case13_selectDistinct02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select distinct jtag->'tag1' from jsons1"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(8, count); + close(resultSet); + } + + @Test + @Description("distinct json tag") + public void case13_selectDistinct03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select distinct jtag from jsons1"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(9, count); + close(resultSet); + } + + @Test + @Description("insert json tag") + public void case14_selectDump01() throws SQLException { + statement.execute("INSERT INTO jsons1_15 using jsons1 tags('{\"tbname\":\"tt\",\"databool\":true,\"datastr\":\"是是是\"}') values(1591060828000, 4, false, 'jjsf', \"你就会\")"); + } + + @Test + @Description("test duplicate key with normal column") + public void case14_selectDump02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select *,tbname,jtag from jsons1 where jtag->'datastr' match '是' and datastr match 'js'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(1, count); + close(resultSet); + } + + @Test + @Description("test duplicate key with normal column") + public void case14_selectDump03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select tbname,jtag->'tbname' from jsons1 where jtag->'tbname'='tt' and tbname='jsons1_14'"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(0, count); + close(resultSet); + } + + @Test + @Description("insert json tag for join test") + public void case15_selectJoin01() throws SQLException { + statement.execute("create table if not exists jsons2(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); + statement.execute("insert into jsons2_1 using jsons2 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 2, false, 'json2', '你是2')"); + statement.execute("insert into jsons2_2 using jsons2 tags('{\"tag1\":5,\"tag2\":null}') values (1591060628000, 2, true, 'json2', 'sss')"); + + statement.execute("create table if not exists jsons3(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); + statement.execute("insert into jsons3_1 using jsons3 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 3, false, 'json3', '你是3')"); + statement.execute("insert into jsons3_2 using jsons3 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060638000, 2, true, 'json3', 'sss')"); + } + + @Test + @Description("select json tag from join") + public void case15_selectJoin02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); + resultSet.next(); + Assert.assertEquals("sss", resultSet.getString(1)); + close(resultSet); + } + + @Test + @Description("group by and order by json tag desc") + public void case16_selectGroupOrder01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(8, count); + close(resultSet); + } + + @Test + @Description("group by and order by json tag asc") + public void case16_selectGroupOrder02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' asc"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(8, count); + close(resultSet); + } + + @Test + @Description("stddev with group by json tag") + public void case17_selectStddev01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); + String s = ""; + int count = 0; + Set set = new HashSet<>(); + while (resultSet.next()) { + count++; + set.add(resultSet.getString(2)); + } + Assert.assertEquals(8, count); + Assert.assertTrue(set.contains("\"femail\"")); + Assert.assertTrue(set.contains("\"收到货\"")); + } + + @Test + @Description("subquery json tag") + public void case18_selectSubquery01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select * from (select jtag, dataint from jsons1)"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(11, count); + close(resultSet); + } + + @Test + @Description("subquery some json tags") + public void case18_selectSubquery02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); + + ResultSetMetaData metaData = resultSet.getMetaData(); + String columnName = metaData.getColumnName(1); + Assert.assertEquals("jtag->'tag1'", columnName); + + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(11, count); + close(resultSet); + } + + @Test + @Description("query some json tags from subquery") + public void case18_selectSubquery04() throws SQLException { + ResultSet resultSet = statement.executeQuery("select ts,tbname,jtag->'tag1' from (select jtag->'tag1',tbname,ts from jsons1 order by ts)"); + int count = 0; + while (resultSet.next()) { + count++; + } + Assert.assertEquals(11, count); + close(resultSet); + } + + @Test + @Description("query metadata for json") + public void case19_selectMetadata01() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag from jsons1"); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnType = metaData.getColumnType(1); + String columnTypeName = metaData.getColumnTypeName(1); + Assert.assertEquals(Types.OTHER, columnType); + Assert.assertEquals("JSON", columnTypeName); + close(resultSet); + } + + @Test + @Description("query metadata for json") + public void case19_selectMetadata02() throws SQLException { + ResultSet resultSet = statement.executeQuery("select *,jtag from jsons1"); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnType = metaData.getColumnType(6); + String columnTypeName = metaData.getColumnTypeName(6); + Assert.assertEquals(Types.OTHER, columnType); + Assert.assertEquals("JSON", columnTypeName); + close(resultSet); + } + + @Test + @Description("query metadata for one json result") + public void case19_selectMetadata03() throws SQLException { + ResultSet resultSet = statement.executeQuery("select jtag->'tag1' from jsons1_6"); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnType = metaData.getColumnType(1); + String columnTypeName = metaData.getColumnTypeName(1); + Assert.assertEquals(Types.OTHER, columnType); + Assert.assertEquals("JSON", columnTypeName); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertEquals("11", string); + close(resultSet); + } + + @Test + @Description("stmt batch insert with json tag") + public void case20_batchInsert() throws SQLException { + String jsonTag = "{\"tag1\":\"fff\",\"tag2\":5,\"tag3\":true}"; + statement.execute("drop table if exists jsons5"); + statement.execute("CREATE STABLE IF NOT EXISTS jsons5 (ts timestamp, dataInt int, dataStr nchar(20)) TAGS(jtag json)"); + + String sql = "INSERT INTO ? USING jsons5 TAGS (?) VALUES ( ?,?,? )"; + + try (PreparedStatement pst = connection.prepareStatement(sql)) { + TSDBPreparedStatement ps = pst.unwrap(TSDBPreparedStatement.class); + // 设定数据表名: + ps.setTableName("batch_test"); + // 设定 TAGS 取值 setTagNString or setTagJson: +// ps.setTagNString(0, jsonTag); + ps.setTagJson(0, jsonTag); + + // VALUES 部分以逐列的方式进行设置: + int numOfRows = 4; + ArrayList ts = new ArrayList<>(); + for (int i = 0; i < numOfRows; i++) { + ts.add(System.currentTimeMillis() + i); + } + ps.setTimestamp(0, ts); + + Random r = new Random(); + int random = 10 + r.nextInt(5); + ArrayList c1 = new ArrayList<>(); + for (int i = 0; i < numOfRows; i++) { + if (i % random == 0) { + c1.add(null); + } else { + c1.add(r.nextInt()); + } + } + ps.setInt(1, c1); + + ArrayList c2 = new ArrayList<>(); + for (int i = 0; i < numOfRows; i++) { + c2.add("分支" + i % 4); + } + ps.setNString(2, c2, 10); + + // AddBatch 之后,缓存并未清空。为避免混乱,并不推荐在 ExecuteBatch 之前再次绑定新一批的数据: + ps.columnDataAddBatch(); + // 执行绑定数据后的语句: + ps.columnDataExecuteBatch(); + } + + ResultSet resultSet = statement.executeQuery("select jtag from batch_test"); + ResultSetMetaData metaData = resultSet.getMetaData(); + String columnName = metaData.getColumnName(1); + Assert.assertEquals("jtag", columnName); + Assert.assertEquals("JSON", metaData.getColumnTypeName(1)); + resultSet.next(); + String string = resultSet.getString(1); + Assert.assertEquals(jsonTag, string); + resultSet.close(); + resultSet = statement.executeQuery("select jtag->'tag2' from batch_test"); + resultSet.next(); + long l = resultSet.getLong(1); + Assert.assertEquals(5, l); + resultSet.close(); + } + + private void close(ResultSet resultSet) { + try { + if (null != resultSet) { + resultSet.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @BeforeClass + public static void beforeClass() { + String host = "127.0.0.1"; + final String url = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + try { + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); + connection = DriverManager.getConnection(url, properties); + statement = connection.createStatement(); + statement.execute("drop database if exists " + dbName); + statement.execute("create database if not exists " + dbName); + statement.execute("use " + dbName); + statement.execute(superSql); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @AfterClass + public static void afterClass() { + try { + if (null != statement) { + statement.execute("drop database " + dbName); + statement.close(); + } + if (null != connection) { + connection.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + + } +} diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java new file mode 100644 index 0000000000000000000000000000000000000000..205ad2c0dc3b4bf5db884a6e28fcc8015160ef76 --- /dev/null +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/block/TSDBBlockResultSetTest.java @@ -0,0 +1,687 @@ +package com.taosdata.jdbc.block; + +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import com.google.common.primitives.Shorts; +import com.taosdata.jdbc.TSDBDriver; +import com.taosdata.jdbc.TSDBResultSet; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.sql.*; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Properties; + +public class TSDBBlockResultSetTest { + + private static final String host = "127.0.0.1"; + private static Connection conn; + private static Statement stmt; + private static ResultSet rs; + + @Test + public void wasNull() throws SQLException { + Assert.assertFalse(rs.wasNull()); + } + + @Test + public void getString() throws SQLException { + String f10 = rs.getString("f10"); + Assert.assertEquals("涛思数据", f10); + f10 = rs.getString(10); + Assert.assertEquals("涛思数据", f10); + } + + @Test + public void getBoolean() throws SQLException { + Boolean f9 = rs.getBoolean("f9"); + Assert.assertEquals(true, f9); + f9 = rs.getBoolean(9); + Assert.assertEquals(true, f9); + } + + @Test + public void getByte() throws SQLException { + byte f8 = rs.getByte("f8"); + Assert.assertEquals(10, f8); + f8 = rs.getByte(8); + Assert.assertEquals(10, f8); + } + + @Test + public void getShort() throws SQLException { + short f7 = rs.getShort("f7"); + Assert.assertEquals(10, f7); + f7 = rs.getShort(7); + Assert.assertEquals(10, f7); + } + + @Test + public void getInt() throws SQLException { + int f2 = rs.getInt("f2"); + Assert.assertEquals(1, f2); + f2 = rs.getInt(2); + Assert.assertEquals(1, f2); + } + + @Test + public void getLong() throws SQLException { + long f3 = rs.getLong("f3"); + Assert.assertEquals(100, f3); + f3 = rs.getLong(3); + Assert.assertEquals(100, f3); + } + + @Test + public void getFloat() throws SQLException { + float f4 = rs.getFloat("f4"); + Assert.assertEquals(3.1415f, f4, 0f); + f4 = rs.getFloat(4); + Assert.assertEquals(3.1415f, f4, 0f); + } + + @Test + public void getDouble() throws SQLException { + double f5 = rs.getDouble("f5"); + Assert.assertEquals(3.1415926, f5, 0.0); + f5 = rs.getDouble(5); + Assert.assertEquals(3.1415926, f5, 0.0); + } + + @Test + public void getBigDecimal() throws SQLException { + BigDecimal f1 = rs.getBigDecimal("f1"); + Assert.assertEquals(1609430400000L, f1.longValue()); + + BigDecimal f2 = rs.getBigDecimal("f2"); + Assert.assertEquals(1, f2.intValue()); + + BigDecimal f3 = rs.getBigDecimal("f3"); + Assert.assertEquals(100L, f3.longValue()); + + BigDecimal f4 = rs.getBigDecimal("f4"); + Assert.assertEquals(3.1415f, f4.floatValue(), 0.00000f); + + BigDecimal f5 = rs.getBigDecimal("f5"); + Assert.assertEquals(3.1415926, f5.doubleValue(), 0.0000000); + + BigDecimal f7 = rs.getBigDecimal("f7"); + Assert.assertEquals(10, f7.intValue()); + + BigDecimal f8 = rs.getBigDecimal("f8"); + Assert.assertEquals(10, f8.intValue()); + } + + @Test + public void getBytes() throws SQLException { + byte[] f1 = rs.getBytes("f1"); + Assert.assertEquals("2021-01-01 00:00:00.0", new String(f1)); + + byte[] f2 = rs.getBytes("f2"); + Assert.assertEquals(1, Ints.fromByteArray(f2)); + + byte[] f3 = rs.getBytes("f3"); + Assert.assertEquals(100L, Longs.fromByteArray(f3)); + + byte[] f4 = rs.getBytes("f4"); + Assert.assertEquals(3.1415f, Float.parseFloat(new String(f4)), 0.000000f); + + byte[] f5 = rs.getBytes("f5"); + Assert.assertEquals(3.1415926, Double.parseDouble(new String(f5)), 0.000000f); + + byte[] f6 = rs.getBytes("f6"); + Assert.assertTrue(Arrays.equals("abc".getBytes(), f6)); + + byte[] f7 = rs.getBytes("f7"); + Assert.assertEquals((short) 10, Shorts.fromByteArray(f7)); + + byte[] f8 = rs.getBytes("f8"); + Assert.assertEquals(1, f8.length); + Assert.assertEquals((byte) 10, f8[0]); + + byte[] f9 = rs.getBytes("f9"); + Assert.assertEquals("true", new String(f9)); + + byte[] f10 = rs.getBytes("f10"); + Assert.assertEquals("涛思数据", new String(f10)); + } + + @Test + public void getDate() throws SQLException, ParseException { + Date f1 = rs.getDate("f1"); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Assert.assertEquals(sdf.parse("2021-01-01"), f1); + } + + @Test + public void getTime() throws SQLException { + Time f1 = rs.getTime("f1"); + Assert.assertNotNull(f1); + Assert.assertEquals("00:00:00", f1.toString()); + } + + @Test + public void getTimestamp() throws SQLException { + Timestamp f1 = rs.getTimestamp("f1"); + Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); + f1 = rs.getTimestamp(1); + Assert.assertEquals("2021-01-01 00:00:00.0", f1.toString()); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getAsciiStream() throws SQLException { + rs.getAsciiStream("f1"); + } + + @SuppressWarnings("deprecation") + @Test(expected = SQLFeatureNotSupportedException.class) + public void getUnicodeStream() throws SQLException { + rs.getUnicodeStream("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getBinaryStream() throws SQLException { + rs.getBinaryStream("f1"); + } + + @Test + public void getWarnings() throws SQLException { + Assert.assertNull(rs.getWarnings()); + } + + @Test + public void clearWarnings() throws SQLException { + rs.clearWarnings(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getCursorName() throws SQLException { + rs.getCursorName(); + } + + @Test + public void getMetaData() throws SQLException { + ResultSetMetaData meta = rs.getMetaData(); + Assert.assertNotNull(meta); + } + + @Test + public void getObject() throws SQLException, ParseException { + Object f1 = rs.getObject("f1"); + Assert.assertEquals(Timestamp.class, f1.getClass()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.sss"); + java.util.Date date = sdf.parse("2021-01-01 00:00:00.000"); + Assert.assertEquals(new Timestamp(date.getTime()), f1); + + Object f2 = rs.getObject("f2"); + Assert.assertEquals(Integer.class, f2.getClass()); + Assert.assertEquals(1, f2); + + Object f3 = rs.getObject("f3"); + Assert.assertEquals(Long.class, f3.getClass()); + Assert.assertEquals(100L, f3); + + Object f4 = rs.getObject("f4"); + Assert.assertEquals(Float.class, f4.getClass()); + Assert.assertEquals(3.1415f, f4); + + Object f5 = rs.getObject("f5"); + Assert.assertEquals(Double.class, f5.getClass()); + Assert.assertEquals(3.1415926, f5); + + Object f6 = rs.getObject("f6"); + Assert.assertEquals(byte[].class, f6.getClass()); + Assert.assertEquals("abc", new String((byte[]) f6)); + + Object f7 = rs.getObject("f7"); + Assert.assertEquals(Short.class, f7.getClass()); + Assert.assertEquals((short) 10, f7); + + Object f8 = rs.getObject("f8"); + Assert.assertEquals(Byte.class, f8.getClass()); + Assert.assertEquals((byte) 10, f8); + + Object f9 = rs.getObject("f9"); + Assert.assertEquals(Boolean.class, f9.getClass()); + Assert.assertEquals(true, f9); + + Object f10 = rs.getObject("f10"); + Assert.assertEquals(String.class, f10.getClass()); + Assert.assertEquals("涛思数据", f10); + } + + @Test(expected = SQLException.class) + public void findColumn() throws SQLException { + int columnIndex = rs.findColumn("f1"); + Assert.assertEquals(1, columnIndex); + columnIndex = rs.findColumn("f2"); + Assert.assertEquals(2, columnIndex); + columnIndex = rs.findColumn("f3"); + Assert.assertEquals(3, columnIndex); + columnIndex = rs.findColumn("f4"); + Assert.assertEquals(4, columnIndex); + columnIndex = rs.findColumn("f5"); + Assert.assertEquals(5, columnIndex); + columnIndex = rs.findColumn("f6"); + Assert.assertEquals(6, columnIndex); + columnIndex = rs.findColumn("f7"); + Assert.assertEquals(7, columnIndex); + columnIndex = rs.findColumn("f8"); + Assert.assertEquals(8, columnIndex); + columnIndex = rs.findColumn("f9"); + Assert.assertEquals(9, columnIndex); + columnIndex = rs.findColumn("f10"); + Assert.assertEquals(10, columnIndex); + + rs.findColumn("f11"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getCharacterStream() throws SQLException { + rs.getCharacterStream(1); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void isBeforeFirst() throws SQLException { + rs.isBeforeFirst(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void isAfterLast() throws SQLException { + rs.isAfterLast(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void isFirst() throws SQLException { + rs.isFirst(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void isLast() throws SQLException { + rs.isLast(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void beforeFirst() throws SQLException { + rs.beforeFirst(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void afterLast() throws SQLException { + rs.afterLast(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void first() throws SQLException { + rs.first(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void last() throws SQLException { + rs.last(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getRow() throws SQLException { + rs.getRow(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void absolute() throws SQLException { + rs.absolute(-1); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void relative() throws SQLException { + rs.relative(-1); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void previous() throws SQLException { + rs.previous(); + } + + @Test + public void setFetchDirection() throws SQLException { + rs.setFetchDirection(ResultSet.FETCH_FORWARD); + Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); + rs.setFetchDirection(ResultSet.FETCH_UNKNOWN); + Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); + } + + @Test + public void getFetchDirection() throws SQLException { + Assert.assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); + } + + @Test + public void setFetchSize() throws SQLException { + rs.setFetchSize(0); + Assert.assertEquals(0, rs.getFetchSize()); + } + + @Test + public void getFetchSize() throws SQLException { + Assert.assertEquals(0, rs.getFetchSize()); + } + + @Test + public void getType() throws SQLException { + Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); + } + + @Test + public void getConcurrency() throws SQLException { + Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void rowUpdated() throws SQLException { + rs.rowUpdated(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void rowInserted() throws SQLException { + rs.rowInserted(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void rowDeleted() throws SQLException { + rs.rowDeleted(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateNull() throws SQLException { + rs.updateNull("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateBoolean() throws SQLException { + rs.updateBoolean(1, false); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateByte() throws SQLException { + rs.updateByte(1, (byte) 0); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateShort() throws SQLException { + rs.updateShort(1, (short) 0); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateInt() throws SQLException { + rs.updateInt(1, 1); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateLong() throws SQLException { + rs.updateLong(1, 1L); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateFloat() throws SQLException { + rs.updateFloat(1, 1f); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateDouble() throws SQLException { + rs.updateDouble(1, 1.0); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateBigDecimal() throws SQLException { + rs.updateBigDecimal(1, new BigDecimal(1)); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateString() throws SQLException { + rs.updateString(1, "abc"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateBytes() throws SQLException { + rs.updateBytes(1, new byte[]{}); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateDate() throws SQLException { + rs.updateDate(1, new Date(System.currentTimeMillis())); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateTime() throws SQLException { + rs.updateTime(1, new Time(System.currentTimeMillis())); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateTimestamp() throws SQLException { + rs.updateTimestamp(1, new Timestamp(System.currentTimeMillis())); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateAsciiStream() throws SQLException { + rs.updateAsciiStream(1, null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateBinaryStream() throws SQLException { + rs.updateBinaryStream(1, null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateCharacterStream() throws SQLException { + rs.updateCharacterStream(1, null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateObject() throws SQLException { + rs.updateObject(1, null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void insertRow() throws SQLException { + rs.insertRow(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateRow() throws SQLException { + rs.updateRow(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void deleteRow() throws SQLException { + rs.deleteRow(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void refreshRow() throws SQLException { + rs.refreshRow(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void cancelRowUpdates() throws SQLException { + rs.cancelRowUpdates(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void moveToInsertRow() throws SQLException { + rs.moveToInsertRow(); + } + + @Test + public void getStatement() throws SQLException { + Statement stmt = rs.getStatement(); + Assert.assertNotNull(stmt); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void moveToCurrentRow() throws SQLException { + rs.moveToCurrentRow(); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getRef() throws SQLException { + rs.getRef(1); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getBlob() throws SQLException { + rs.getBlob("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getClob() throws SQLException { + rs.getClob("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getArray() throws SQLException { + rs.getArray("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getURL() throws SQLException { + rs.getURL("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateRef() throws SQLException { + rs.updateRef("f1", null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateBlob() throws SQLException { + rs.updateBlob(1, (InputStream) null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateClob() throws SQLException { + rs.updateClob(1, (Reader) null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateArray() throws SQLException { + rs.updateArray(1, null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getRowId() throws SQLException { + rs.getRowId("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateRowId() throws SQLException { + rs.updateRowId(1, null); + } + + @Test + public void getHoldability() throws SQLException { + Assert.assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability()); + } + + @Test + public void isClosed() throws SQLException { + Assert.assertFalse(rs.isClosed()); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateNString() throws SQLException { + rs.updateNString(1, null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateNClob() throws SQLException { + rs.updateNClob(1, (Reader) null); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getNClob() throws SQLException { + rs.getNClob("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getSQLXML() throws SQLException { + rs.getSQLXML("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateSQLXML() throws SQLException { + rs.updateSQLXML(1, null); + } + + @Test + public void getNString() throws SQLException { + String f10 = rs.getNString("f10"); + Assert.assertEquals("涛思数据", f10); + f10 = rs.getNString(10); + Assert.assertEquals("涛思数据", f10); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void getNCharacterStream() throws SQLException { + rs.getNCharacterStream("f1"); + } + + @Test(expected = SQLFeatureNotSupportedException.class) + public void updateNCharacterStream() throws SQLException { + rs.updateNCharacterStream(1, null); + } + + @Test + public void unwrap() throws SQLException { + TSDBResultSet unwrap = rs.unwrap(TSDBResultSet.class); + Assert.assertNotNull(unwrap); + } + + @Test + public void isWrapperFor() throws SQLException { + Assert.assertTrue(rs.isWrapperFor(TSDBResultSet.class)); + } + + @BeforeClass + public static void beforeClass() { + try { + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); + conn = DriverManager.getConnection("jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata", properties); + stmt = conn.createStatement(); + stmt.execute("create database if not exists restful_test"); + stmt.execute("use restful_test"); + stmt.execute("drop table if exists weather"); + stmt.execute("create table if not exists weather(f1 timestamp, f2 int, f3 bigint, f4 float, f5 double, f6 binary(64), f7 smallint, f8 tinyint, f9 bool, f10 nchar(64))"); + stmt.execute("insert into restful_test.weather values('2021-01-01 00:00:00.000', 1, 100, 3.1415, 3.1415926, 'abc', 10, 10, true, '涛思数据')"); + rs = stmt.executeQuery("select * from restful_test.weather"); + rs.next(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @AfterClass + public static void afterClass() { + try { + if (rs != null) + rs.close(); + if (stmt != null) + stmt.close(); + if (conn != null) { + Statement statement = conn.createStatement(); + statement.execute("drop database if exists restful_test"); + statement.close(); + conn.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java index c85c6f95a93df565cd5ff8eca91c0beeac3b3c02..f5cc99cde4bad36c84af9b432df7a83e5f663219 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/cases/NanoSecondTimestampJNITest.java @@ -71,18 +71,16 @@ public class NanoSecondTimestampJNITest { long ns = ms * 1000_000L + random.nextInt(1000_000); // when - ResultSet rs = null; try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("insert into weather(ts, temperature, humidity) values(" + ns + ", 12.3, 4)"); - rs = stmt.executeQuery("select * from weather"); + ResultSet rs = stmt.executeQuery("select * from weather"); rs.next(); + // then + long actual = rs.getLong(1); + Assert.assertEquals(ns, actual); + actual = rs.getLong("ts"); + Assert.assertEquals(ns, actual); } - - // then - long actual = rs.getLong(1); - Assert.assertEquals(ns, actual); - actual = rs.getLong("ts"); - Assert.assertEquals(ns, actual); } @Test @@ -91,18 +89,16 @@ public class NanoSecondTimestampJNITest { String timestampStr = "2021-01-01 12:00:00.123456789"; // when - ResultSet rs; try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("insert into weather(ts, temperature, humidity) values('" + timestampStr + "', 12.3, 4)"); - rs = stmt.executeQuery("select * from weather"); + ResultSet rs = stmt.executeQuery("select * from weather"); rs.next(); + // then + String actual = rs.getString(1); + Assert.assertEquals(timestampStr, actual); + actual = rs.getString("ts"); + Assert.assertEquals(timestampStr, actual); } - - // then - String actual = rs.getString(1); - Assert.assertEquals(timestampStr, actual); - actual = rs.getString("ts"); - Assert.assertEquals(timestampStr, actual); } @Test @@ -123,19 +119,17 @@ public class NanoSecondTimestampJNITest { } // when - ResultSet rs = null; try (Statement stmt = conn.createStatement()) { - rs = stmt.executeQuery("select * from weather"); + ResultSet rs = stmt.executeQuery("select * from weather"); rs.next(); + // then + Timestamp actual = rs.getTimestamp(1); + Assert.assertEquals(ts, actual); + actual = rs.getTimestamp("ts"); + Assert.assertEquals(ts, actual); + Assert.assertEquals(timeMillis, actual.getTime()); + Assert.assertEquals(nanoAdjustment, actual.getNanos()); } - - // then - Timestamp actual = rs.getTimestamp(1); - Assert.assertEquals(ts, actual); - actual = rs.getTimestamp("ts"); - Assert.assertEquals(ts, actual); - Assert.assertEquals(timeMillis, actual.getTime()); - Assert.assertEquals(nanoAdjustment, actual.getNanos()); } @Before diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java index 8bdc269843d3c817f3790671715d0aa0567b7053..4ac43033d67b471cb58d83aff711dda48db4f9a3 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulDatabaseMetaDataTest.java @@ -732,8 +732,8 @@ public class RestfulDatabaseMetaDataTest { Assert.assertEquals(26, columns.getInt("COLUMN_SIZE")); // DECIMAL_DIGITS Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt("DECIMAL_DIGITS")); + Assert.assertEquals(0, columns.getInt(9)); + Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); Assert.assertEquals(null, columns.getString(9)); Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); // NUM_PREC_RADIX @@ -778,8 +778,8 @@ public class RestfulDatabaseMetaDataTest { Assert.assertEquals(12, columns.getInt("COLUMN_SIZE")); // DECIMAL_DIGITS Assert.assertEquals("DECIMAL_DIGITS", meta.getColumnLabel(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt(9)); - Assert.assertEquals(Integer.MIN_VALUE, columns.getInt("DECIMAL_DIGITS")); + Assert.assertEquals(0, columns.getInt(9)); + Assert.assertEquals(0, columns.getInt("DECIMAL_DIGITS")); Assert.assertEquals(null, columns.getString(9)); Assert.assertEquals(null, columns.getString("DECIMAL_DIGITS")); // NUM_PREC_RADIX diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java index 0d19768486592b3032898ea67c6fa92aa47bb0bc..df04711eb4400e5028fc1f20e8e1c9e06cb23a57 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulJsonTagTest.java @@ -8,6 +8,8 @@ import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import java.sql.*; +import java.util.HashSet; +import java.util.Set; /** * Most of the functionality is consistent with {@link com.taosdata.jdbc.JsonTagTest}, @@ -1143,13 +1145,14 @@ public class RestfulJsonTagTest { ResultSet resultSet = statement.executeQuery("select stddev(dataint) from jsons1 group by jtag->'tag1'"); String s = ""; int count = 0; + Set set = new HashSet<>(); while (resultSet.next()) { count++; - s = resultSet.getString(2); - + set.add(resultSet.getString(2)); } Assert.assertEquals(8, count); - Assert.assertEquals("\"femail\"", s); + Assert.assertTrue(set.contains("\"femail\"")); + Assert.assertTrue(set.contains("\"收到货\"")); close(resultSet); } diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java index c1ca31ae388f577a33cc6f3a6bc943ce52112507..b1ca634a21a811561a8da1d2475b1f63ff15fb00 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/rs/RestfulResultSetTest.java @@ -133,7 +133,7 @@ public class RestfulResultSetTest { @Test public void getBytes() throws SQLException { byte[] f1 = rs.getBytes("f1"); - Assert.assertEquals("2021-01-01 00:00:00.000", new String(f1)); + Assert.assertEquals("2021-01-01 00:00:00.0", new String(f1)); byte[] f2 = rs.getBytes("f2"); Assert.assertEquals(1, Ints.fromByteArray(f2)); diff --git a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java index 666ac910e76d9d1f379d8dfa964a10705bee7097..4709c8586874f8379ac0546eb937139486d06c16 100644 --- a/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java +++ b/src/connector/jdbc/src/test/java/com/taosdata/jdbc/ws/WSJsonTagTest.java @@ -1146,7 +1146,7 @@ public class WSJsonTagTest { } Assert.assertEquals(8, count); - Assert.assertEquals("\"femail\"", s); + Assert.assertEquals("\"收到货\"", s); close(resultSet); } diff --git a/src/connector/node-red-contrib-tdengine/package-lock.json b/src/connector/node-red-contrib-tdengine/package-lock.json index 3d2f9977419c62649b3eb332014f4baaa7b0810f..5c462bd2eae697b502fa4adbe85a7eccc97c069f 100644 --- a/src/connector/node-red-contrib-tdengine/package-lock.json +++ b/src/connector/node-red-contrib-tdengine/package-lock.json @@ -1656,9 +1656,9 @@ } }, "minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", "dev": true }, "minipass": { diff --git a/src/connector/nodejs/nodetaos/cinterface.js b/src/connector/nodejs/nodetaos/cinterface.js index 0a81a0c79b21b2c2869e8e747df76e673c65b2eb..e04b55d9a5fd47fb6ecd50bb0ac360eefb907930 100644 --- a/src/connector/nodejs/nodetaos/cinterface.js +++ b/src/connector/nodejs/nodetaos/cinterface.js @@ -328,13 +328,6 @@ function CTaosInterface(config = null, pass = false) { //void taos_unsubscribe(TAOS_SUB *tsub); 'taos_unsubscribe': [ref.types.void, [ref.types.void_ptr]], - // Continuous Query - //TAOS_STREAM *taos_open_stream(TAOS *taos, char *sqlstr, void (*fp)(void *param, TAOS_RES *, TAOS_ROW row), - // int64_t stime, void *param, void (*callback)(void *)); - 'taos_open_stream': [ref.types.void_ptr, [ref.types.void_ptr, ref.types.char_ptr, ref.types.void_ptr, ref.types.int64, ref.types.void_ptr, ref.types.void_ptr]], - //void taos_close_stream(TAOS_STREAM *tstr); - 'taos_close_stream': [ref.types.void, [ref.types.void_ptr]], - //Schemaless insert //TAOS_RES* taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol,int precision) // 'taos_schemaless_insert': [ref.types.void_ptr, [ref.types.void_ptr, ref.types.char_ptr, ref.types.int, ref.types.int, ref.types.int]] @@ -717,51 +710,6 @@ CTaosInterface.prototype.unsubscribe = function unsubscribe(subscription) { this.libtaos.taos_unsubscribe(subscription); } -// Continuous Query -CTaosInterface.prototype.openStream = function openStream(connection, sql, callback, stime, stoppingCallback, param = ref.ref(ref.NULL)) { - try { - sql = ref.allocCString(sql); - } - catch (err) { - throw "Attribute Error: sql string is expected as a str"; - } - var cti = this; - let asyncCallbackWrapper = function (param2, result2, row) { - let fields = cti.fetchFields_a(result2); - let precision = cti.libtaos.taos_result_precision(result2); - let blocks = new Array(fields.length); - blocks.fill(null); - let numOfRows2 = 1; - let offset = 0; - if (numOfRows2 > 0) { - for (let i = 0; i < fields.length; i++) { - if (!convertFunctions[fields[i]['type']]) { - throw new errors.DatabaseError("Invalid data type returned from database"); - } - blocks[i] = convertFunctions[fields[i]['type']](row, numOfRows2, fields[i]['bytes'], offset, precision); - offset += fields[i]['bytes'] * numOfRows2; - } - } - callback(param2, result2, blocks, fields); - } - asyncCallbackWrapper = ffi.Callback(ref.types.void, [ref.types.void_ptr, ref.types.void_ptr, ref.refType(ref.types.void_ptr2)], asyncCallbackWrapper); - asyncStoppingCallbackWrapper = ffi.Callback(ref.types.void, [ref.types.void_ptr], stoppingCallback); - let streamHandle = this.libtaos.taos_open_stream(connection, sql, asyncCallbackWrapper, stime, param, asyncStoppingCallbackWrapper); - if (ref.isNull(streamHandle)) { - throw new errors.TDError('Failed to open a stream with TDengine'); - return false; - } - else { - console.log("Succesfully opened stream"); - return streamHandle; - } -} - -CTaosInterface.prototype.closeStream = function closeStream(stream) { - this.libtaos.taos_close_stream(stream); - console.log("Closed stream"); -} - //Schemaless insert API /** * TAOS* taos, char* lines[], int numLines, int protocol,int precision) diff --git a/src/connector/nodejs/nodetaos/cursor.js b/src/connector/nodejs/nodetaos/cursor.js index 5969d4f344affa49ebbf81329729bff4733e116b..54431d9e98489481e3bdaa9433ef38177ce51b63 100644 --- a/src/connector/nodejs/nodetaos/cursor.js +++ b/src/connector/nodejs/nodetaos/cursor.js @@ -438,43 +438,7 @@ TDengineCursor.prototype.consumeData = async function consumeData(subscription, TDengineCursor.prototype.unsubscribe = function unsubscribe(subscription) { this._chandle.unsubscribe(subscription); } -/** - * Open a stream with TDengine to run the sql query periodically in the background - * @param {string} sql - The query to run - * @param {function} callback - The callback function to run after each query, accepting inputs as param, result handle, data, fields meta data - * @param {number} stime - The time of the stream starts in the form of epoch milliseconds. If 0 is given, the start time is set as the current time. - * @param {function} stoppingCallback - The callback function to run when the continuous query stops. It takes no inputs - * @param {object} param - A parameter that is passed to the main callback function - * @return {Buffer} A buffer pointing to the stream handle - * @since 1.3.0 - */ -TDengineCursor.prototype.openStream = function openStream(sql, callback, stime = 0, stoppingCallback, param = {}) { - let buf = ref.alloc('Object'); - ref.writeObject(buf, 0, param); - let asyncCallbackWrapper = function (param2, result2, blocks, fields) { - let data = []; - let num_of_rows = blocks[0].length; - for (let j = 0; j < num_of_rows; j++) { - data.push([]); - let rowBlock = new Array(fields.length); - for (let k = 0; k < fields.length; k++) { - rowBlock[k] = blocks[k][j]; - } - data[data.length - 1] = rowBlock; - } - callback(param2, result2, blocks, fields); - } - return this._chandle.openStream(this._connection._conn, sql, asyncCallbackWrapper, stime, stoppingCallback, buf); -} -/** - * Close a stream - * @param {Buffer} - A buffer pointing to the handle of the stream to be closed - * @since 1.3.0 - */ -TDengineCursor.prototype.closeStream = function closeStream(stream) { - this._chandle.closeStream(stream); -} /** * schemaless insert * @param {*} connection a valid database connection diff --git a/src/connector/nodejs/package.json b/src/connector/nodejs/package.json index 398ed59522ae9c31a26ee7db73dca5b02b517c9e..cd1e6fba43ee44693a6611b37d5b664109db5b34 100644 --- a/src/connector/nodejs/package.json +++ b/src/connector/nodejs/package.json @@ -1,6 +1,6 @@ { "name": "td2.0-connector", - "version": "2.0.10", + "version": "2.0.11", "description": "A Node.js connector for TDengine.", "main": "tdengine.js", "directories": { diff --git a/src/connector/python/LICENSE b/src/connector/python/LICENSE deleted file mode 100644 index 79a9d730868bfe5d3fa01d679a4abfe9ee7811f0..0000000000000000000000000000000000000000 --- a/src/connector/python/LICENSE +++ /dev/null @@ -1,12 +0,0 @@ - Copyright (c) 2019 TAOS Data, Inc. - -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 . diff --git a/src/connector/python/README.md b/src/connector/python/README.md index e4fce45a59bea74ea64a5da082767579459d4196..c48a2dac4ba52324f761e29ea4fc72d186a30309 100644 --- a/src/connector/python/README.md +++ b/src/connector/python/README.md @@ -17,12 +17,6 @@ Or with git url: pip install git+https://github.com/taosdata/taos-connector-python.git ``` -If you have installed TDengine server or client with prebuilt packages, then you can install the connector from path: - -```bash -pip install /usr/local/taos/connector/python -``` - ## Source Code [TDengine](https://github.com/taosdata/TDengine) connector for Python source code is hosted on [GitHub](https://github.com/taosdata/taos-connector-python). @@ -361,71 +355,6 @@ if __name__ == "__main__": test_subscribe_callback(connect()) ``` -### Stream - -```python -from taos import * -from ctypes import * -import time - -def stream_callback(p_param, p_result, p_row): - # type: (c_void_p, c_void_p, c_void_p) -> None - if p_result is None or p_row is None: - return - result = TaosResult(p_result) - row = TaosRow(result, p_row) - try: - ts, count = row() - p = cast(p_param, POINTER(Counter)) - p.contents.count += count - print("[%s] inserted %d in 5s, total count: %d" % (ts.strftime("%Y-%m-%d %H:%M:%S"), count, p.contents.count)) - except Exception as err: - print(err) - raise err - - -class Counter(Structure): - _fields_ = [ - ("count", c_int), - ] - - def __str__(self): - return "%d" % self.count - - -def test_stream(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_stream" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.select_db(dbname) - conn.execute("create table if not exists log(ts timestamp, n int)") - - result = conn.query("select count(*) from log interval(5s)") - assert result.field_count == 2 - counter = Counter() - counter.count = 0 - stream = conn.stream("select count(*) from log interval(5s)", stream_callback, param=byref(counter)) - - for _ in range(0, 20): - conn.execute("insert into log values(now,0)(now+1s, 1)(now + 2s, 2)") - time.sleep(2) - - stream.close() - conn.execute("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err - - -if __name__ == "__main__": - test_stream(connect()) - -``` - ### Insert with line protocol ```python diff --git a/src/connector/python/examples/bind-multi.py b/src/connector/python/examples/bind-multi.py deleted file mode 100644 index 8530253aef58079e01f5eb71d8e12ab1649b7731..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/bind-multi.py +++ /dev/null @@ -1,50 +0,0 @@ -# encoding:UTF-8 -from taos import * - -conn = connect() - -dbname = "pytest_taos_stmt_multi" -conn.execute("drop database if exists %s" % dbname) -conn.execute("create database if not exists %s" % dbname) -conn.select_db(dbname) - -conn.execute( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, \ - ti tinyint, si smallint, ii int, bi bigint, tu tinyint unsigned, \ - su smallint unsigned, iu int unsigned, bu bigint unsigned, \ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", -) - -stmt = conn.statement("insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - -params = new_multi_binds(16) -params[0].timestamp((1626861392589, 1626861392590, 1626861392591)) -params[1].bool((True, None, False)) -params[2].tinyint([-128, -128, None]) # -128 is tinyint null -params[3].tinyint([0, 127, None]) -params[4].smallint([3, None, 2]) -params[5].int([3, 4, None]) -params[6].bigint([3, 4, None]) -params[7].tinyint_unsigned([3, 4, None]) -params[8].smallint_unsigned([3, 4, None]) -params[9].int_unsigned([3, 4, None]) -params[10].bigint_unsigned([3, 4, None]) -params[11].float([3, None, 1]) -params[12].double([3, None, 1.2]) -params[13].binary(["abc", "dddafadfadfadfadfa", None]) -params[14].nchar(["涛思数据", None, "a long string with 中文字符"]) -params[15].timestamp([None, None, 1626861392591]) -stmt.bind_param_batch(params) -stmt.execute() - - -result = stmt.use_result() -assert result.affected_rows == 3 -result.close() - -result = conn.query("select * from log") -for row in result: - print(row) -result.close() -stmt.close() -conn.close() \ No newline at end of file diff --git a/src/connector/python/examples/bind-row.py b/src/connector/python/examples/bind-row.py deleted file mode 100644 index 4ab9a9167ad23a6167c6586aac30ae6941dcee6d..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/bind-row.py +++ /dev/null @@ -1,57 +0,0 @@ -from taos import * - -conn = connect() - -dbname = "pytest_taos_stmt" -conn.execute("drop database if exists %s" % dbname) -conn.execute("create database if not exists %s" % dbname) -conn.select_db(dbname) - -conn.execute( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, \ - ti tinyint, si smallint, ii int, bi bigint, tu tinyint unsigned, \ - su smallint unsigned, iu int unsigned, bu bigint unsigned, \ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", -) - -stmt = conn.statement("insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - -params = new_bind_params(16) -params[0].timestamp(1626861392589) -params[1].bool(True) -params[2].null() -params[3].tinyint(2) -params[4].smallint(3) -params[5].int(4) -params[6].bigint(5) -params[7].tinyint_unsigned(6) -params[8].smallint_unsigned(7) -params[9].int_unsigned(8) -params[10].bigint_unsigned(9) -params[11].float(10.1) -params[12].double(10.11) -params[13].binary("hello") -params[14].nchar("stmt") -params[15].timestamp(1626861392589) -stmt.bind_param(params) - -params[0].timestamp(1626861392590) -params[15].null() -stmt.bind_param(params) -stmt.execute() - - -result = stmt.use_result() -assert result.affected_rows == 2 -# No need to explicitly close, but ok for you -# result.close() - -result = conn.query("select * from log") - -for row in result: - print(row) - -# No need to explicitly close, but ok for you -# result.close() -# stmt.close() -# conn.close() diff --git a/src/connector/python/examples/demo.py b/src/connector/python/examples/demo.py deleted file mode 100644 index 3bc09046f3a33557e513425c06373c66958f2a2f..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/demo.py +++ /dev/null @@ -1,12 +0,0 @@ -import taos - -conn = taos.connect(host='127.0.0.1', - user='root', - password='taosdata', - database='log') -cursor = conn.cursor() - -sql = "select * from log.log limit 10" -cursor.execute(sql) -for row in cursor: - print(row) diff --git a/src/connector/python/examples/insert-lines.py b/src/connector/python/examples/insert-lines.py deleted file mode 100644 index 1d20af7e9bcac23deb70c1dbd058bb86dd5585a5..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/insert-lines.py +++ /dev/null @@ -1,23 +0,0 @@ -import taos -from taos import SmlProtocol, SmlPrecision - -conn = taos.connect() -dbname = "pytest_line" -conn.execute("drop database if exists %s" % dbname) -conn.execute("create database if not exists %s precision 'us'" % dbname) -conn.select_db(dbname) - -lines = [ - 'st,t1=3i64,t2=4f64,t3="t3" c1=3i64,c3=L"pass",c2=false,c4=4f64 1626006833639000000', -] -conn.schemaless_insert(lines, taos.SmlProtocol.LINE_PROTOCOL, taos.SmlPrecision.NOT_CONFIGURED) -print("inserted") - -conn.schemaless_insert(lines, taos.SmlProtocol.LINE_PROTOCOL, taos.SmlPrecision.NOT_CONFIGURED) - -result = conn.query("show tables") -for row in result: - print(row) - - -conn.execute("drop database if exists %s" % dbname) diff --git a/src/connector/python/examples/pep-249.py b/src/connector/python/examples/pep-249.py deleted file mode 100644 index 971a3c401f00b982096b8d429f65bce73cca4760..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/pep-249.py +++ /dev/null @@ -1,9 +0,0 @@ -import taos - -conn = taos.connect() -cursor = conn.cursor() - -cursor.execute("show databases") -results = cursor.fetchall() -for row in results: - print(row) diff --git a/src/connector/python/examples/query-objectively.py b/src/connector/python/examples/query-objectively.py deleted file mode 100644 index 104347cbf91e29e62fef26477b475053a8b8bc3e..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/query-objectively.py +++ /dev/null @@ -1,12 +0,0 @@ -import taos - -conn = taos.connect() -conn.execute("create database if not exists pytest") - -result = conn.query("show databases") -num_of_fields = result.field_count -for field in result.fields: - print(field) -for row in result: - print(row) -conn.execute("drop database pytest") diff --git a/src/connector/python/examples/stream.py b/src/connector/python/examples/stream.py deleted file mode 100644 index 73cbd03c493f4441d661f924bf648bc8992aeb0a..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/stream.py +++ /dev/null @@ -1,59 +0,0 @@ -from taos import * -from ctypes import * -import time - -def stream_callback(p_param, p_result, p_row): - # type: (c_void_p, c_void_p, c_void_p) -> None - if p_result is None or p_row is None: - return - result = TaosResult(p_result) - row = TaosRow(result, p_row) - try: - ts, count = row() - p = cast(p_param, POINTER(Counter)) - p.contents.count += count - print("[%s] inserted %d in 5s, total count: %d" % (ts.strftime("%Y-%m-%d %H:%M:%S"), count, p.contents.count)) - except Exception as err: - print(err) - raise err - - -class Counter(Structure): - _fields_ = [ - ("count", c_int), - ] - - def __str__(self): - return "%d" % self.count - - -def test_stream(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_stream" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.select_db(dbname) - conn.execute("create table if not exists log(ts timestamp, n int)") - - result = conn.query("select count(*) from log interval(5s)") - assert result.field_count == 2 - counter = Counter() - counter.count = 0 - stream = conn.stream("select count(*) from log interval(5s)", stream_callback, param=byref(counter)) - - for _ in range(0, 20): - conn.execute("insert into log values(now,0)(now+1s, 1)(now + 2s, 2)") - time.sleep(2) - - stream.close() - conn.execute("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err - - -if __name__ == "__main__": - test_stream(connect()) diff --git a/src/connector/python/examples/subscribe-async.py b/src/connector/python/examples/subscribe-async.py deleted file mode 100644 index 49156de7edfb4322d7888727c28b76868cf6a16a..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/subscribe-async.py +++ /dev/null @@ -1,46 +0,0 @@ -from taos import * -from ctypes import * - -import time - - -def subscribe_callback(p_sub, p_result, p_param, errno): - # type: (c_void_p, c_void_p, c_void_p, c_int) -> None - print("# fetch in callback") - result = TaosResult(c_void_p(p_result)) - result.check_error(errno) - for row in result.rows_iter(): - ts, n = row() - print(ts, n) - - -def test_subscribe_callback(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_subscribe_callback" - try: - print("drop if exists") - conn.execute("drop database if exists %s" % dbname) - print("create database") - conn.execute("create database if not exists %s" % dbname) - print("create table") - # conn.execute("use %s" % dbname) - conn.execute("create table if not exists %s.log(ts timestamp, n int)" % dbname) - - print("# subscribe with callback") - sub = conn.subscribe(False, "test", "select * from %s.log" % dbname, 1000, subscribe_callback) - - for i in range(10): - conn.execute("insert into %s.log values(now, %d)" % (dbname, i)) - time.sleep(0.7) - sub.close() - - conn.execute("drop database if exists %s" % dbname) - # conn.close() - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - # conn.close() - raise err - - -if __name__ == "__main__": - test_subscribe_callback(connect()) diff --git a/src/connector/python/examples/subscribe-sync.py b/src/connector/python/examples/subscribe-sync.py deleted file mode 100644 index 3a7f65f460280924ed3a577fe55b975fbf12c1a3..0000000000000000000000000000000000000000 --- a/src/connector/python/examples/subscribe-sync.py +++ /dev/null @@ -1,53 +0,0 @@ -import taos -import random - -conn = taos.connect() -dbname = "pytest_taos_subscribe" -conn.execute("drop database if exists %s" % dbname) -conn.execute("create database if not exists %s" % dbname) -conn.select_db(dbname) -conn.execute("create table if not exists log(ts timestamp, n int)") -for i in range(10): - conn.execute("insert into log values(now, %d)" % i) - -sub = conn.subscribe(False, "test", "select * from log", 1000) -print("# consume from begin") -for ts, n in sub.consume(): - print(ts, n) - -print("# consume new data") -for i in range(5): - conn.execute("insert into log values(now, %d)(now+1s, %d)" % (i, i)) - result = sub.consume() - for ts, n in result: - print(ts, n) - -sub.close(True) -print("# keep progress consume") -sub = conn.subscribe(False, "test", "select * from log", 1000) -result = sub.consume() -rows = result.fetch_all() -# consume from latest subscription needs root privilege(for /var/lib/taos). -assert result.row_count == 0 -print("## consumed ", len(rows), "rows") - -print("# consume with a stop condition") -for i in range(10): - conn.execute("insert into log values(now, %d)" % random.randint(0, 10)) - result = sub.consume() - try: - ts, n = next(result) - print(ts, n) - if n > 5: - result.stop_query() - print("## stopped") - break - except StopIteration: - continue - -sub.close() - -# sub.close() - -conn.execute("drop database if exists %s" % dbname) -# conn.close() diff --git a/src/connector/python/pyproject.toml b/src/connector/python/pyproject.toml deleted file mode 100644 index 69e3351712b647712a88d7067545ea12ed86506d..0000000000000000000000000000000000000000 --- a/src/connector/python/pyproject.toml +++ /dev/null @@ -1,30 +0,0 @@ -[tool.poetry] -name = "taospy" -version = "2.1.2" -description = "TDengine connector for python" -authors = ["Taosdata Inc. "] -license = "AGPL-3.0" -readme = "README.md" -packages = [ - {include = "taos"} -] - -[tool.poetry.dependencies] -python = "^2.7 || ^3.4" -typing = "*" - -[tool.poetry.dev-dependencies] -pytest = [ - { version = "^4.6", python = ">=2.7,<3.0" }, - { version = "^6.2", python = ">=3.7,<4.0" } -] -pdoc = { version = "^7.1.1", python = "^3.7" } -mypy = { version = "^0.910", python = "^3.6" } -black = [{ version = "^21.*", python = ">=3.6.2,<4.0" }] - -[build-system] -requires = ["poetry-core>=1.0.0"] -build-backend = "poetry.core.masonry.api" - -[tool.black] -line-length = 119 diff --git a/src/connector/python/setup.py b/src/connector/python/setup.py deleted file mode 100644 index 8f1dfafe4762e4a55a6d3e7c645c945a67a10f68..0000000000000000000000000000000000000000 --- a/src/connector/python/setup.py +++ /dev/null @@ -1,34 +0,0 @@ -import setuptools - -with open("README.md", "r") as fh: - long_description = fh.read() - -setuptools.setup( - name="taos", - version="2.1.1", - author="Taosdata Inc.", - author_email="support@taosdata.com", - description="TDengine python client package", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/taosdata/TDengine/tree/develop/src/connector/python", - packages=setuptools.find_packages(), - classifiers=[ - "Environment :: Console", - "Environment :: MacOS X", - "Environment :: Win32 (MS Windows)", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", - "Operating System :: MacOS", - "Programming Language :: Python :: 2.7", - "Operating System :: Linux", - "Operating System :: POSIX :: Linux", - "Operating System :: Microsoft :: Windows", - "Operating System :: Microsoft :: Windows :: Windows 10", - ], -) diff --git a/src/connector/python/taos/__init__.py b/src/connector/python/taos/__init__.py deleted file mode 100644 index 739265ef579b6a5127df8ee592b73293f113a2ef..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/__init__.py +++ /dev/null @@ -1,485 +0,0 @@ -# encoding:UTF-8 -""" -# TDengine Connector for Python - -[TDengine](https://github.com/taosdata/TDengine) connector for Python enables python programs to access TDengine, - using an API which is compliant with the Python DB API 2.0 (PEP-249). It uses TDengine C client library for client server communications. - -## Install - -```sh -git clone --depth 1 https://github.com/taosdata/TDengine.git -pip install ./TDengine/src/connector/python -``` - -## Source Code - -[TDengine](https://github.com/taosdata/TDengine) connector for Python source code is hosted on [GitHub](https://github.com/taosdata/TDengine/tree/develop/src/connector/python). - -## Examples - -### Query with PEP-249 API - -```python -import taos - -conn = taos.connect() -cursor = conn.cursor() - -cursor.execute("show databases") -results = cursor.fetchall() -for row in results: - print(row) -cursor.close() -conn.close() -``` - -### Query with objective API - -```python -import taos - -conn = taos.connect() -conn.exec("create database if not exists pytest") - -result = conn.query("show databases") -num_of_fields = result.field_count -for field in result.fields: - print(field) -for row in result: - print(row) -result.close() -conn.exec("drop database pytest") -conn.close() -``` - -### Query with async API - -```python -from taos import * -from ctypes import * -import time - -def fetch_callback(p_param, p_result, num_of_rows): - print("fetched ", num_of_rows, "rows") - p = cast(p_param, POINTER(Counter)) - result = TaosResult(p_result) - - if num_of_rows == 0: - print("fetching completed") - p.contents.done = True - result.close() - return - if num_of_rows < 0: - p.contents.done = True - result.check_error(num_of_rows) - result.close() - return None - - for row in result.rows_iter(num_of_rows): - # print(row) - None - p.contents.count += result.row_count - result.fetch_rows_a(fetch_callback, p_param) - - - -def query_callback(p_param, p_result, code): - # type: (c_void_p, c_void_p, c_int) -> None - if p_result is None: - return - result = TaosResult(p_result) - if code == 0: - result.fetch_rows_a(fetch_callback, p_param) - result.check_error(code) - - -class Counter(Structure): - _fields_ = [("count", c_int), ("done", c_bool)] - - def __str__(self): - return "{ count: %d, done: %s }" % (self.count, self.done) - - -def test_query(conn): - # type: (TaosConnection) -> None - counter = Counter(count=0) - conn.query_a("select * from log.log", query_callback, byref(counter)) - - while not counter.done: - print("wait query callback") - time.sleep(1) - print(counter) - conn.close() - - -if __name__ == "__main__": - test_query(connect()) -``` - -### Statement API - Bind row after row - -```python -from taos import * - -conn = connect() - -dbname = "pytest_taos_stmt" -conn.exec("drop database if exists %s" % dbname) -conn.exec("create database if not exists %s" % dbname) -conn.select_db(dbname) - -conn.exec( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, \\ - ti tinyint, si smallint, ii int, bi bigint, tu tinyint unsigned, \\ - su smallint unsigned, iu int unsigned, bu bigint unsigned, \\ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", -) - -stmt = conn.statement("insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - -params = new_bind_params(16) -params[0].timestamp(1626861392589) -params[1].bool(True) -params[2].null() -params[3].tinyint(2) -params[4].smallint(3) -params[5].int(4) -params[6].bigint(5) -params[7].tinyint_unsigned(6) -params[8].smallint_unsigned(7) -params[9].int_unsigned(8) -params[10].bigint_unsigned(9) -params[11].float(10.1) -params[12].double(10.11) -params[13].binary("hello") -params[14].nchar("stmt") -params[15].timestamp(1626861392589) -stmt.bind_param(params) - -params[0].timestamp(1626861392590) -params[15].null() -stmt.bind_param(params) -stmt.execute() - - -result = stmt.use_result() -assert result.affected_rows == 2 -result.close() - -result = conn.query("select * from log") - -for row in result: - print(row) -result.close() -stmt.close() -conn.close() - -``` - -### Statement API - Bind multi rows - -```python -from taos import * - -conn = connect() - -dbname = "pytest_taos_stmt" -conn.exec("drop database if exists %s" % dbname) -conn.exec("create database if not exists %s" % dbname) -conn.select_db(dbname) - -conn.exec( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, \\ - ti tinyint, si smallint, ii int, bi bigint, tu tinyint unsigned, \\ - su smallint unsigned, iu int unsigned, bu bigint unsigned, \\ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", -) - -stmt = conn.statement("insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - -params = new_multi_binds(16) -params[0].timestamp((1626861392589, 1626861392590, 1626861392591)) -params[1].bool((True, None, False)) -params[2].tinyint([-128, -128, None]) # -128 is tinyint null -params[3].tinyint([0, 127, None]) -params[4].smallint([3, None, 2]) -params[5].int([3, 4, None]) -params[6].bigint([3, 4, None]) -params[7].tinyint_unsigned([3, 4, None]) -params[8].smallint_unsigned([3, 4, None]) -params[9].int_unsigned([3, 4, None]) -params[10].bigint_unsigned([3, 4, None]) -params[11].float([3, None, 1]) -params[12].double([3, None, 1.2]) -params[13].binary(["abc", "dddafadfadfadfadfa", None]) -params[14].nchar(["涛思数据", None, "a long string with 中文字符"]) -params[15].timestamp([None, None, 1626861392591]) -stmt.bind_param_batch(params) -stmt.execute() - - -result = stmt.use_result() -assert result.affected_rows == 3 -result.close() - -result = conn.query("select * from log") -for row in result: - print(row) -result.close() -stmt.close() -conn.close() -``` - -### Statement API - Subscribe - -```python -import taos - -conn = taos.connect() -dbname = "pytest_taos_subscribe_callback" -conn.exec("drop database if exists %s" % dbname) -conn.exec("create database if not exists %s" % dbname) -conn.select_db(dbname) -conn.exec("create table if not exists log(ts timestamp, n int)") -for i in range(10): - conn.exec("insert into log values(now, %d)" % i) - -sub = conn.subscribe(True, "test", "select * from log", 1000) -print("# consume from begin") -for ts, n in sub.consume(): - print(ts, n) - -print("# consume new data") -for i in range(5): - conn.exec("insert into log values(now, %d)(now+1s, %d)" % (i, i)) - result = sub.consume() - for ts, n in result: - print(ts, n) - -print("# consume with a stop condition") -for i in range(10): - conn.exec("insert into log values(now, %d)" % int(random() * 10)) - result = sub.consume() - try: - ts, n = next(result) - print(ts, n) - if n > 5: - result.stop_query() - print("## stopped") - break - except StopIteration: - continue - -sub.close() - -conn.exec("drop database if exists %s" % dbname) -conn.close() -``` - -### Statement API - Subscribe asynchronously with callback - -```python -from taos import * -from ctypes import * - -import time - - -def subscribe_callback(p_sub, p_result, p_param, errno): - # type: (c_void_p, c_void_p, c_void_p, c_int) -> None - print("# fetch in callback") - result = TaosResult(p_result) - result.check_error(errno) - for row in result.rows_iter(): - ts, n = row() - print(ts, n) - - -def test_subscribe_callback(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_subscribe_callback" - try: - conn.exec("drop database if exists %s" % dbname) - conn.exec("create database if not exists %s" % dbname) - conn.select_db(dbname) - conn.exec("create table if not exists log(ts timestamp, n int)") - - print("# subscribe with callback") - sub = conn.subscribe(False, "test", "select * from log", 1000, subscribe_callback) - - for i in range(10): - conn.exec("insert into log values(now, %d)" % i) - time.sleep(0.7) - sub.close() - - conn.exec("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.exec("drop database if exists %s" % dbname) - conn.close() - raise err - - -if __name__ == "__main__": - test_subscribe_callback(connect()) - -``` - -### Statement API - Stream - -```python -from taos import * -from ctypes import * - -def stream_callback(p_param, p_result, p_row): - # type: (c_void_p, c_void_p, c_void_p) -> None - - if p_result is None or p_row is None: - return - result = TaosResult(p_result) - row = TaosRow(result, p_row) - try: - ts, count = row() - p = cast(p_param, POINTER(Counter)) - p.contents.count += count - print("[%s] inserted %d in 5s, total count: %d" % (ts.strftime("%Y-%m-%d %H:%M:%S"), count, p.contents.count)) - - except Exception as err: - print(err) - raise err - - -class Counter(ctypes.Structure): - _fields_ = [ - ("count", c_int), - ] - - def __str__(self): - return "%d" % self.count - - -def test_stream(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_stream" - try: - conn.exec("drop database if exists %s" % dbname) - conn.exec("create database if not exists %s" % dbname) - conn.select_db(dbname) - conn.exec("create table if not exists log(ts timestamp, n int)") - - result = conn.query("select count(*) from log interval(5s)") - assert result.field_count == 2 - counter = Counter() - counter.count = 0 - stream = conn.stream("select count(*) from log interval(5s)", stream_callback, param=byref(counter)) - - for _ in range(0, 20): - conn.exec("insert into log values(now,0)(now+1s, 1)(now + 2s, 2)") - time.sleep(2) - stream.close() - conn.exec("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.exec("drop database if exists %s" % dbname) - conn.close() - raise err - - -if __name__ == "__main__": - test_stream(connect()) -``` - -### Insert with line protocol - -```python -import taos - -conn = taos.connect() -dbname = "pytest_line" -conn.exec("drop database if exists %s" % dbname) -conn.exec("create database if not exists %s precision 'us'" % dbname) -conn.select_db(dbname) - -lines = [ - 'st,t1=3i64,t2=4f64,t3="t3" c1=3i64,c3=L"passit",c2=false,c4=4f64 1626006833639000000', - 'st,t1=4i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000', - 'stf,t1=4i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin_stf",c2=false,c5=5f64,c6=7u64 1626006933641000000', -] -conn.schemaless_insert(lines, 0, "ns") -print("inserted") - -lines = [ - 'stf,t1=5i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin_stf",c2=false,c5=5f64,c6=7u64 1626006933641000000', -] -conn.schemaless_insert(lines, 0, "ns") - -result = conn.query("show tables") -for row in result: - print(row) -result.close() - - -conn.exec("drop database if exists %s" % dbname) -conn.close() - -``` - -## License - AGPL-3.0 - -Keep same with [TDengine](https://github.com/taosdata/TDengine). -""" -from .connection import TaosConnection - -# For some reason, the following is needed for VS Code (through PyLance) to -# recognize that "error" is a valid module of the "taos" package. -from .error import * -from .bind import * -from .field import * -from .cursor import * -from .result import * -from .statement import * -from .subscription import * -from .schemaless import * - -from taos._version import __version__ - -# Globals -threadsafety = 0 -paramstyle = "pyformat" - -__all__ = [ - "__version__", - # functions - "connect", - "new_bind_param", - "new_bind_params", - "new_multi_binds", - "new_multi_bind", - # objects - "TaosBind", - "TaosConnection", - "TaosCursor", - "TaosResult", - "TaosRows", - "TaosRow", - "TaosStmt", - "PrecisionEnum", - "SmlPrecision", - "SmlProtocol" -] - -def connect(*args, **kwargs): - # type: (..., ...) -> TaosConnection - """Function to return a TDengine connector object - - Current supporting keyword parameters: - @dsn: Data source name as string - @user: Username as string(optional) - @password: Password as string(optional) - @host: Hostname(optional) - @database: Database name(optional) - - @rtype: TDengineConnector - """ - return TaosConnection(*args, **kwargs) diff --git a/src/connector/python/taos/_version.py b/src/connector/python/taos/_version.py deleted file mode 100644 index f811561263c557cf534e90ff763373bccacb20b6..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/_version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = '2.1.2' diff --git a/src/connector/python/taos/bind.py b/src/connector/python/taos/bind.py deleted file mode 100644 index 8f39278c960c285f4a8c0bfc1d8b198bb4a56f4c..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/bind.py +++ /dev/null @@ -1,457 +0,0 @@ -# encoding:UTF-8 -import ctypes -from .constants import FieldType -from .error import * -from .precision import * -from datetime import datetime -from ctypes import * -import sys - -_datetime_epoch = datetime.utcfromtimestamp(0) - -def _is_not_none(obj): - return obj != None - -class TaosBind(ctypes.Structure): - _fields_ = [ - ("buffer_type", c_int), - ("buffer", c_void_p), - ("buffer_length", c_size_t), - ("length", POINTER(c_size_t)), - ("is_null", POINTER(c_int)), - ("is_unsigned", c_int), - ("error", POINTER(c_int)), - ("u", c_int64), - ("allocated", c_int), - ] - - def null(self): - self.buffer_type = FieldType.C_NULL - self.is_null = pointer(c_int(1)) - - def bool(self, value): - self.buffer_type = FieldType.C_BOOL - self.buffer = cast(pointer(c_bool(value)), c_void_p) - self.buffer_length = sizeof(c_bool) - - def tinyint(self, value): - self.buffer_type = FieldType.C_TINYINT - self.buffer = cast(pointer(c_int8(value)), c_void_p) - self.buffer_length = sizeof(c_int8) - - def smallint(self, value): - self.buffer_type = FieldType.C_SMALLINT - self.buffer = cast(pointer(c_int16(value)), c_void_p) - self.buffer_length = sizeof(c_int16) - - def int(self, value): - self.buffer_type = FieldType.C_INT - self.buffer = cast(pointer(c_int32(value)), c_void_p) - self.buffer_length = sizeof(c_int32) - - def bigint(self, value): - self.buffer_type = FieldType.C_BIGINT - self.buffer = cast(pointer(c_int64(value)), c_void_p) - self.buffer_length = sizeof(c_int64) - - def float(self, value): - self.buffer_type = FieldType.C_FLOAT - self.buffer = cast(pointer(c_float(value)), c_void_p) - self.buffer_length = sizeof(c_float) - - def double(self, value): - self.buffer_type = FieldType.C_DOUBLE - self.buffer = cast(pointer(c_double(value)), c_void_p) - self.buffer_length = sizeof(c_double) - - def binary(self, value): - buffer = None - length = 0 - if isinstance(value, str): - bytes = value.encode("utf-8") - buffer = create_string_buffer(bytes) - length = len(bytes) - else: - buffer = value - length = len(value) - self.buffer_type = FieldType.C_BINARY - self.buffer = cast(buffer, c_void_p) - self.buffer_length = length - self.length = pointer(c_size_t(self.buffer_length)) - - def timestamp(self, value, precision=PrecisionEnum.Milliseconds): - if type(value) is datetime: - if precision == PrecisionEnum.Milliseconds: - ts = int(round((value - _datetime_epoch).total_seconds() * 1000)) - elif precision == PrecisionEnum.Microseconds: - ts = int(round((value - _datetime_epoch).total_seconds() * 10000000)) - else: - raise PrecisionError("datetime do not support nanosecond precision") - elif type(value) is float: - if precision == PrecisionEnum.Milliseconds: - ts = int(round(value * 1000)) - elif precision == PrecisionEnum.Microseconds: - ts = int(round(value * 10000000)) - else: - raise PrecisionError("time float do not support nanosecond precision") - elif isinstance(value, int) and not isinstance(value, bool): - ts = value - elif isinstance(value, str): - value = datetime.fromisoformat(value) - if precision == PrecisionEnum.Milliseconds: - ts = int(round(value * 1000)) - elif precision == PrecisionEnum.Microseconds: - ts = int(round(value * 10000000)) - else: - raise PrecisionError("datetime do not support nanosecond precision") - - self.buffer_type = FieldType.C_TIMESTAMP - self.buffer = cast(pointer(c_int64(ts)), c_void_p) - self.buffer_length = sizeof(c_int64) - - def nchar(self, value): - buffer = None - length = 0 - if isinstance(value, str): - bytes = value.encode("utf-8") - buffer = create_string_buffer(bytes) - length = len(bytes) - else: - buffer = value - length = len(value) - self.buffer_type = FieldType.C_NCHAR - self.buffer = cast(buffer, c_void_p) - self.buffer_length = length - self.length = pointer(c_size_t(self.buffer_length)) - - def json(self, value): - buffer = None - length = 0 - if isinstance(value, str): - bytes = value.encode("utf-8") - buffer = create_string_buffer(bytes) - length = len(bytes) - else: - buffer = value - length = len(value) - self.buffer_type = FieldType.C_JSON - self.buffer = cast(buffer, c_void_p) - self.buffer_length = length - self.length = pointer(c_size_t(self.buffer_length)) - - def tinyint_unsigned(self, value): - self.buffer_type = FieldType.C_TINYINT_UNSIGNED - self.buffer = cast(pointer(c_uint8(value)), c_void_p) - self.buffer_length = sizeof(c_uint8) - - def smallint_unsigned(self, value): - self.buffer_type = FieldType.C_SMALLINT_UNSIGNED - self.buffer = cast(pointer(c_uint16(value)), c_void_p) - self.buffer_length = sizeof(c_uint16) - - def int_unsigned(self, value): - self.buffer_type = FieldType.C_INT_UNSIGNED - self.buffer = cast(pointer(c_uint32(value)), c_void_p) - self.buffer_length = sizeof(c_uint32) - - def bigint_unsigned(self, value): - self.buffer_type = FieldType.C_BIGINT_UNSIGNED - self.buffer = cast(pointer(c_uint64(value)), c_void_p) - self.buffer_length = sizeof(c_uint64) - - -def _datetime_to_timestamp(value, precision): - # type: (datetime | float | int | str | c_int64, PrecisionEnum) -> c_int64 - if value is None: - return FieldType.C_BIGINT_NULL - if type(value) is datetime: - if precision == PrecisionEnum.Milliseconds: - return int(round((value - _datetime_epoch).total_seconds() * 1000)) - elif precision == PrecisionEnum.Microseconds: - return int(round((value - _datetime_epoch).total_seconds() * 10000000)) - else: - raise PrecisionError("datetime do not support nanosecond precision") - elif type(value) is float: - if precision == PrecisionEnum.Milliseconds: - return int(round(value * 1000)) - elif precision == PrecisionEnum.Microseconds: - return int(round(value * 10000000)) - else: - raise PrecisionError("time float do not support nanosecond precision") - elif isinstance(value, int) and not isinstance(value, bool): - return c_int64(value) - elif isinstance(value, str): - value = datetime.fromisoformat(value) - if precision == PrecisionEnum.Milliseconds: - return int(round(value * 1000)) - elif precision == PrecisionEnum.Microseconds: - return int(round(value * 10000000)) - else: - raise PrecisionError("datetime do not support nanosecond precision") - elif isinstance(value, c_int64): - return value - return FieldType.C_BIGINT_NULL - - -class TaosMultiBind(ctypes.Structure): - _fields_ = [ - ("buffer_type", c_int), - ("buffer", c_void_p), - ("buffer_length", c_size_t), - ("length", POINTER(c_int32)), - ("is_null", c_char_p), - ("num", c_int), - ] - - def null(self, num): - self.buffer_type = FieldType.C_NULL - self.is_null = cast((c_char * num)(*[1 for _ in range(num)]), c_char_p) - self.buffer = c_void_p(None) - self.num = num - - def bool(self, values): - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_int8 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_BOOL_NULL for v in values]) - - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - self.buffer_type = FieldType.C_BOOL - self.buffer_length = sizeof(c_bool) - - def tinyint(self, values): - self.buffer_type = FieldType.C_TINYINT - self.buffer_length = sizeof(c_int8) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_int8 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_TINYINT_NULL for v in values]) - - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def smallint(self, values): - self.buffer_type = FieldType.C_SMALLINT - self.buffer_length = sizeof(c_int16) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_int16 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_SMALLINT_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def int(self, values): - self.buffer_type = FieldType.C_INT - self.buffer_length = sizeof(c_int32) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_int32 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_INT_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def bigint(self, values): - self.buffer_type = FieldType.C_BIGINT - self.buffer_length = sizeof(c_int64) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_int64 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_BIGINT_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def float(self, values): - self.buffer_type = FieldType.C_FLOAT - self.buffer_length = sizeof(c_float) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_float * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_FLOAT_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def double(self, values): - self.buffer_type = FieldType.C_DOUBLE - self.buffer_length = sizeof(c_double) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_double * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_DOUBLE_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def _str_to_buffer(self, values): - self.num = len(values) - is_null = [1 if v is None else 0 for v in values] - self.is_null = cast((c_byte * self.num)(*is_null), c_char_p) - - if sum(is_null) == self.num: - self.length = (c_int32 * len(values))(0 * self.num) - return - if sys.version_info < (3, 0): - _bytes = [bytes(value) if value is not None else None for value in values] - buffer_length = max(len(b) + 1 for b in _bytes if b is not None) - buffers = [ - create_string_buffer(b, buffer_length) if b is not None else create_string_buffer(buffer_length) - for b in _bytes - ] - buffer_all = b''.join(v[:] for v in buffers) - self.buffer = cast(c_char_p(buffer_all), c_void_p) - else: - _bytes = [value.encode("utf-8") if value is not None else None for value in values] - buffer_length = max(len(b) for b in _bytes if b is not None) - self.buffer = cast( - c_char_p( - b"".join( - [ - create_string_buffer(b, buffer_length) - if b is not None - else create_string_buffer(buffer_length) - for b in _bytes - ] - ) - ), - c_void_p, - ) - self.length = (c_int32 * len(values))(*[len(b) if b is not None else 0 for b in _bytes]) - self.buffer_length = buffer_length - def binary(self, values): - self.buffer_type = FieldType.C_BINARY - self._str_to_buffer(values) - - def timestamp(self, values, precision=PrecisionEnum.Milliseconds): - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_int64 * len(values) - buffer = buffer_type(*[_datetime_to_timestamp(value, precision) for value in values]) - - self.buffer_type = FieldType.C_TIMESTAMP - self.buffer = cast(buffer, c_void_p) - self.buffer_length = sizeof(c_int64) - self.num = len(values) - - def nchar(self, values): - # type: (list[str]) -> None - self.buffer_type = FieldType.C_NCHAR - self._str_to_buffer(values) - - def json(self, values): - # type: (list[str]) -> None - self.buffer_type = FieldType.C_JSON - self._str_to_buffer(values) - - def tinyint_unsigned(self, values): - self.buffer_type = FieldType.C_TINYINT_UNSIGNED - self.buffer_length = sizeof(c_uint8) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_uint8 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_TINYINT_UNSIGNED_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def smallint_unsigned(self, values): - self.buffer_type = FieldType.C_SMALLINT_UNSIGNED - self.buffer_length = sizeof(c_uint16) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_uint16 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_SMALLINT_UNSIGNED_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def int_unsigned(self, values): - self.buffer_type = FieldType.C_INT_UNSIGNED - self.buffer_length = sizeof(c_uint32) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_uint32 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_INT_UNSIGNED_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - def bigint_unsigned(self, values): - self.buffer_type = FieldType.C_BIGINT_UNSIGNED - self.buffer_length = sizeof(c_uint64) - - try: - buffer = cast(values, c_void_p) - except: - buffer_type = c_uint64 * len(values) - try: - buffer = buffer_type(*values) - except: - buffer = buffer_type(*[v if v is not None else FieldType.C_BIGINT_UNSIGNED_NULL for v in values]) - self.buffer = cast(buffer, c_void_p) - self.num = len(values) - - -def new_bind_param(): - # type: () -> TaosBind - return TaosBind() - - -def new_bind_params(size): - # type: (int) -> Array[TaosBind] - return (TaosBind * size)() - - -def new_multi_bind(): - # type: () -> TaosMultiBind - return TaosMultiBind() - - -def new_multi_binds(size): - # type: (int) -> Array[TaosMultiBind] - return (TaosMultiBind * size)() diff --git a/src/connector/python/taos/cinterface.py b/src/connector/python/taos/cinterface.py deleted file mode 100644 index be39d2291a908b9349599ba13e92a205696516c7..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/cinterface.py +++ /dev/null @@ -1,921 +0,0 @@ -# encoding:UTF-8 - -import ctypes -import platform -import inspect -from ctypes import * - -try: - from typing import Any -except: - pass - -from .error import * -from .bind import * -from .field import * -from .schemaless import * - -_UNSUPPORTED = {} - -# stream callback -stream_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p) -stream_callback2_type = CFUNCTYPE(None, c_void_p) - -# C interface class -class TaosOption: - Locale = (0,) - Charset = (1,) - Timezone = (2,) - ConfigDir = (3,) - ShellActivityTimer = (4,) - MaxOptions = (5,) - - -def _load_taos_linux(): - return ctypes.CDLL("libtaos.so") - - -def _load_taos_darwin(): - return ctypes.CDLL("libtaos.dylib") - - -def _load_taos_windows(): - return ctypes.windll.LoadLibrary("taos") - - -def _load_taos(): - load_func = { - "Linux": _load_taos_linux, - "Darwin": _load_taos_darwin, - "Windows": _load_taos_windows, - } - pf = platform.system() - if load_func[pf] is None: - raise InterfaceError("unsupported platform: %s" % pf) - try: - return load_func[pf]() - except Exception as err: - raise InterfaceError("unable to load taos C library: %s" % err) - - -_libtaos = _load_taos() - -_libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField) -_libtaos.taos_init.restype = None -_libtaos.taos_connect.restype = ctypes.c_void_p -_libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p) -_libtaos.taos_errstr.restype = ctypes.c_char_p -_libtaos.taos_subscribe.restype = ctypes.c_void_p -_libtaos.taos_consume.restype = ctypes.c_void_p -_libtaos.taos_fetch_lengths.restype = ctypes.POINTER(ctypes.c_int) -_libtaos.taos_free_result.restype = None -_libtaos.taos_query.restype = ctypes.POINTER(ctypes.c_void_p) - -try: - _libtaos.taos_stmt_errstr.restype = c_char_p -except AttributeError: - None -finally: - None - - -_libtaos.taos_options.restype = None - - -def taos_options(option, *args): - # type: (TaosOption, Any) -> None - _libtaos.taos_options(option, *args) - - -def taos_init(): - # type: () -> None - """ - C: taos_init - """ - _libtaos.taos_init() - - -_libtaos.taos_cleanup.restype = None - - -def taos_cleanup(): - # type: () -> None - """Cleanup workspace.""" - _libtaos.taos_cleanup() - - -_libtaos.taos_get_client_info.restype = c_char_p - - -def taos_get_client_info(): - # type: () -> str - """Get client version info.""" - return _libtaos.taos_get_client_info().decode("utf-8") - - -_libtaos.taos_get_server_info.restype = c_char_p -_libtaos.taos_get_server_info.argtypes = (c_void_p,) - - -def taos_get_server_info(connection): - # type: (c_void_p) -> str - """Get server version as string.""" - return _libtaos.taos_get_server_info(connection).decode("utf-8") - - -_libtaos.taos_close.restype = None -_libtaos.taos_close.argtypes = (c_void_p,) - - -def taos_close(connection): - # type: (c_void_p) -> None - """Close the TAOS* connection""" - _libtaos.taos_close(connection) - - -_libtaos.taos_connect.restype = c_void_p -_libtaos.taos_connect.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16 - - -def taos_connect(host=None, user="root", password="taosdata", db=None, port=0): - # type: (None|str, str, str, None|str, int) -> c_void_p - """Create TDengine database connection. - - - host: server hostname/FQDN - - user: user name - - password: user password - - db: database name (optional) - - port: server port - - @rtype: c_void_p, TDengine handle - """ - # host - try: - _host = c_char_p(host.encode("utf-8")) if host is not None else None - except AttributeError: - raise AttributeError("host is expected as a str") - - # user - try: - _user = c_char_p(user.encode("utf-8")) - except AttributeError: - raise AttributeError("user is expected as a str") - - # password - try: - _password = c_char_p(password.encode("utf-8")) - except AttributeError: - raise AttributeError("password is expected as a str") - - # db - try: - _db = c_char_p(db.encode("utf-8")) if db is not None else None - except AttributeError: - raise AttributeError("db is expected as a str") - - # port - try: - _port = c_uint16(port) - except TypeError: - raise TypeError("port is expected as an uint16") - - connection = cast(_libtaos.taos_connect(_host, _user, _password, _db, _port), c_void_p) - - if connection.value is None: - raise ConnectionError("connect to TDengine failed") - return connection - - -_libtaos.taos_connect_auth.restype = c_void_p -_libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16 - -_libtaos.taos_connect_auth.restype = c_void_p -_libtaos.taos_connect_auth.argtypes = c_char_p, c_char_p, c_char_p, c_char_p, c_uint16 - - -def taos_connect_auth(host=None, user="root", auth="", db=None, port=0): - # type: (None|str, str, str, None|str, int) -> c_void_p - """Connect server with auth token. - - - host: server hostname/FQDN - - user: user name - - auth: base64 encoded auth token - - db: database name (optional) - - port: server port - - @rtype: c_void_p, TDengine handle - """ - # host - try: - _host = c_char_p(host.encode("utf-8")) if host is not None else None - except AttributeError: - raise AttributeError("host is expected as a str") - - # user - try: - _user = c_char_p(user.encode("utf-8")) - except AttributeError: - raise AttributeError("user is expected as a str") - - # auth - try: - _auth = c_char_p(auth.encode("utf-8")) - except AttributeError: - raise AttributeError("password is expected as a str") - - # db - try: - _db = c_char_p(db.encode("utf-8")) if db is not None else None - except AttributeError: - raise AttributeError("db is expected as a str") - - # port - try: - _port = c_int(port) - except TypeError: - raise TypeError("port is expected as an int") - - connection = c_void_p(_libtaos.taos_connect_auth(_host, _user, _auth, _db, _port)) - - if connection.value is None: - raise ConnectionError("connect to TDengine failed") - return connection - - -_libtaos.taos_query.restype = c_void_p -_libtaos.taos_query.argtypes = c_void_p, c_char_p - - -def taos_query(connection, sql): - # type: (c_void_p, str) -> c_void_p - """Run SQL - - - sql: str, sql string to run - - @return: TAOS_RES*, result pointer - - """ - try: - ptr = c_char_p(sql.encode("utf-8")) - res = c_void_p(_libtaos.taos_query(connection, ptr)) - errno = taos_errno(res) - if errno != 0: - errstr = taos_errstr(res) - taos_free_result(res) - raise ProgrammingError(errstr, errno) - return res - except AttributeError: - raise AttributeError("sql is expected as a string") - - -async_query_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_int) -_libtaos.taos_query_a.restype = None -_libtaos.taos_query_a.argtypes = c_void_p, c_char_p, async_query_callback_type, c_void_p - - -def taos_query_a(connection, sql, callback, param): - # type: (c_void_p, str, async_query_callback_type, c_void_p) -> c_void_p - _libtaos.taos_query_a(connection, c_char_p(sql.encode("utf-8")), async_query_callback_type(callback), param) - - -async_fetch_rows_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_int) -_libtaos.taos_fetch_rows_a.restype = None -_libtaos.taos_fetch_rows_a.argtypes = c_void_p, async_fetch_rows_callback_type, c_void_p - - -def taos_fetch_rows_a(result, callback, param): - # type: (c_void_p, async_fetch_rows_callback_type, c_void_p) -> c_void_p - _libtaos.taos_fetch_rows_a(result, async_fetch_rows_callback_type(callback), param) - - -def taos_affected_rows(result): - # type: (c_void_p) -> c_int - """The affected rows after runing query""" - return _libtaos.taos_affected_rows(result) - - -subscribe_callback_type = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p, c_int) -_libtaos.taos_subscribe.restype = c_void_p -# _libtaos.taos_subscribe.argtypes = c_void_p, c_int, c_char_p, c_char_p, subscribe_callback_type, c_void_p, c_int - - -def taos_subscribe(connection, restart, topic, sql, interval, callback=None, param=None): - # type: (c_void_p, bool, str, str, c_int, subscribe_callback_type, c_void_p | None) -> c_void_p - """Create a subscription - @restart boolean, - @sql string, sql statement for data query, must be a 'select' statement. - @topic string, name of this subscription - """ - if callback != None: - callback = subscribe_callback_type(callback) - return c_void_p( - _libtaos.taos_subscribe( - connection, - 1 if restart else 0, - c_char_p(topic.encode("utf-8")), - c_char_p(sql.encode("utf-8")), - callback, - c_void_p(param), - interval, - ) - ) - - -_libtaos.taos_consume.restype = c_void_p -_libtaos.taos_consume.argstype = (c_void_p,) - - -def taos_consume(sub): - """Consume data of a subscription""" - return c_void_p(_libtaos.taos_consume(sub)) - - -_libtaos.taos_unsubscribe.restype = None -_libtaos.taos_unsubscribe.argstype = c_void_p, c_int - - -def taos_unsubscribe(sub, keep_progress): - """Cancel a subscription""" - _libtaos.taos_unsubscribe(sub, 1 if keep_progress else 0) - - -def taos_use_result(result): - """Use result after calling self.query, it's just for 1.6.""" - fields = [] - pfields = taos_fetch_fields_raw(result) - for i in range(taos_field_count(result)): - fields.append( - { - "name": pfields[i].name, - "bytes": pfields[i].bytes, - "type": pfields[i].type, - } - ) - - return fields - - -_libtaos.taos_fetch_block.restype = c_int -_libtaos.taos_fetch_block.argtypes = c_void_p, c_void_p - - -def taos_fetch_block_raw(result): - pblock = ctypes.c_void_p(0) - num_of_rows = _libtaos.taos_fetch_block(result, ctypes.byref(pblock)) - if num_of_rows == 0: - return None, 0 - return pblock, abs(num_of_rows) - - -def taos_fetch_block(result, fields=None, field_count=None): - pblock = ctypes.c_void_p(0) - num_of_rows = _libtaos.taos_fetch_block(result, ctypes.byref(pblock)) - if num_of_rows == 0: - return None, 0 - precision = taos_result_precision(result) - if fields is None: - fields = taos_fetch_fields(result) - if field_count is None: - field_count = taos_field_count(result) - blocks = [None] * field_count - fieldLen = taos_fetch_lengths(result, field_count) - for i in range(len(fields)): - data = ctypes.cast(pblock, ctypes.POINTER(ctypes.c_void_p))[i] - if fields[i]["type"] not in CONVERT_FUNC: - raise DatabaseError("Invalid data type returned from database") - blocks[i] = CONVERT_FUNC_BLOCK[fields[i]["type"]](data, num_of_rows, fieldLen[i], precision) - - return blocks, abs(num_of_rows) - - -_libtaos.taos_fetch_row.restype = c_void_p -_libtaos.taos_fetch_row.argtypes = (c_void_p,) - - -def taos_fetch_row_raw(result): - # type: (c_void_p) -> c_void_p - row = c_void_p(_libtaos.taos_fetch_row(result)) - if row: - return row - return None - - -def taos_fetch_row(result, fields): - # type: (c_void_p, Array[TaosField]) -> tuple(c_void_p, int) - pblock = ctypes.c_void_p(0) - pblock = taos_fetch_row_raw(result) - if pblock: - num_of_rows = 1 - precision = taos_result_precision(result) - field_count = taos_field_count(result) - blocks = [None] * field_count - field_lens = taos_fetch_lengths(result, field_count) - for i in range(field_count): - data = ctypes.cast(pblock, ctypes.POINTER(ctypes.c_void_p))[i] - if fields[i].type not in CONVERT_FUNC: - raise DatabaseError("Invalid data type returned from database") - if data is None: - blocks[i] = [None] - else: - blocks[i] = CONVERT_FUNC[fields[i].type](data, num_of_rows, field_lens[i], precision) - else: - return None, 0 - return blocks, abs(num_of_rows) - - -_libtaos.taos_free_result.argtypes = (c_void_p,) - - -def taos_free_result(result): - # type: (c_void_p) -> None - if result != None: - _libtaos.taos_free_result(result) - - -_libtaos.taos_field_count.restype = c_int -_libtaos.taos_field_count.argstype = (c_void_p,) - - -def taos_field_count(result): - # type: (c_void_p) -> int - return _libtaos.taos_field_count(result) - - -def taos_num_fields(result): - # type: (c_void_p) -> int - return _libtaos.taos_num_fields(result) - - -_libtaos.taos_fetch_fields.restype = c_void_p -_libtaos.taos_fetch_fields.argstype = (c_void_p,) - - -def taos_fetch_fields_raw(result): - # type: (c_void_p) -> c_void_p - return c_void_p(_libtaos.taos_fetch_fields(result)) - - -def taos_fetch_fields(result): - # type: (c_void_p) -> TaosFields - fields = taos_fetch_fields_raw(result) - count = taos_field_count(result) - return TaosFields(fields, count) - - -def taos_fetch_lengths(result, field_count=None): - # type: (c_void_p, int) -> Array[int] - """Make sure to call taos_fetch_row or taos_fetch_block before fetch_lengths""" - lens = _libtaos.taos_fetch_lengths(result) - if field_count is None: - field_count = taos_field_count(result) - if not lens: - raise OperationalError("field length empty, use taos_fetch_row/block before it") - return lens[:field_count] - - -def taos_result_precision(result): - # type: (c_void_p) -> c_int - return _libtaos.taos_result_precision(result) - - -_libtaos.taos_errno.restype = c_int -_libtaos.taos_errno.argstype = (c_void_p,) - - -def taos_errno(result): - # type: (ctypes.c_void_p) -> c_int - """Return the error number.""" - return _libtaos.taos_errno(result) - - -_libtaos.taos_errstr.restype = c_char_p -_libtaos.taos_errstr.argstype = (c_void_p,) - - -def taos_errstr(result=c_void_p(None)): - # type: (ctypes.c_void_p) -> str - """Return the error styring""" - return _libtaos.taos_errstr(result).decode("utf-8") - - -_libtaos.taos_stop_query.restype = None -_libtaos.taos_stop_query.argstype = (c_void_p,) - - -def taos_stop_query(result): - # type: (ctypes.c_void_p) -> None - """Stop current query""" - return _libtaos.taos_stop_query(result) - - -try: - _libtaos.taos_load_table_info.restype = c_int - _libtaos.taos_load_table_info.argstype = (c_void_p, c_char_p) -except Exception as err: - _UNSUPPORTED["taos_open_stream"] = err - - -def taos_load_table_info(connection, tables): - # type: (ctypes.c_void_p, str) -> None - """Stop current query""" - _check_if_supported() - errno = _libtaos.taos_load_table_info(connection, c_char_p(tables.encode("utf-8"))) - if errno != 0: - msg = taos_errstr() - raise OperationalError(msg, errno) - - -_libtaos.taos_validate_sql.restype = c_int -_libtaos.taos_validate_sql.argstype = (c_void_p, c_char_p) - - -def taos_validate_sql(connection, sql): - # type: (ctypes.c_void_p, str) -> None | str - """Get taosd server info""" - errno = _libtaos.taos_validate_sql(connection, ctypes.c_char_p(sql.encode("utf-8"))) - if errno != 0: - msg = taos_errstr() - return msg - return None - - -_libtaos.taos_print_row.restype = c_int -_libtaos.taos_print_row.argstype = (c_char_p, c_void_p, c_void_p, c_int) - - -def taos_print_row(row, fields, num_fields, buffer_size=4096): - # type: (ctypes.c_void_p, ctypes.c_void_p | TaosFields, int, int) -> str - """Print an row to string""" - p = ctypes.create_string_buffer(buffer_size) - if isinstance(fields, TaosFields): - _libtaos.taos_print_row(p, row, fields.as_ptr(), num_fields) - else: - _libtaos.taos_print_row(p, row, fields, num_fields) - if p: - return p.value.decode("utf-8") - raise OperationalError("taos_print_row failed") - - -_libtaos.taos_select_db.restype = c_int -_libtaos.taos_select_db.argstype = (c_void_p, c_char_p) - - -def taos_select_db(connection, db): - # type: (ctypes.c_void_p, str) -> None - """Select database, eq to sql: use """ - res = _libtaos.taos_select_db(connection, ctypes.c_char_p(db.encode("utf-8"))) - if res != 0: - raise DatabaseError("select database error", res) - - -try: - _libtaos.taos_open_stream.restype = c_void_p - _libtaos.taos_open_stream.argstype = c_void_p, c_char_p, stream_callback_type, c_int64, c_void_p, Any -except Exception as err: - _UNSUPPORTED["taos_open_stream"] = err - - -def taos_open_stream(connection, sql, callback, stime=0, param=None, callback2=None): - # type: (ctypes.c_void_p, str, stream_callback_type, c_int64, c_void_p, c_void_p) -> ctypes.pointer - _check_if_supported() - if callback2 != None: - callback2 = stream_callback2_type(callback2) - """Open an stream""" - return c_void_p( - _libtaos.taos_open_stream( - connection, ctypes.c_char_p(sql.encode("utf-8")), stream_callback_type(callback), stime, param, callback2 - ) - ) - - -_libtaos.taos_close_stream.restype = None -_libtaos.taos_close_stream.argstype = (c_void_p,) - - -def taos_close_stream(stream): - # type: (c_void_p) -> None - """Open an stream""" - return _libtaos.taos_close_stream(stream) - - -_libtaos.taos_stmt_init.restype = c_void_p -_libtaos.taos_stmt_init.argstype = (c_void_p,) - - -def taos_stmt_init(connection): - # type: (c_void_p) -> (c_void_p) - """Create a statement query - @param(connection): c_void_p TAOS* - @rtype: c_void_p, *TAOS_STMT - """ - return c_void_p(_libtaos.taos_stmt_init(connection)) - - -_libtaos.taos_stmt_prepare.restype = c_int -_libtaos.taos_stmt_prepare.argstype = (c_void_p, c_char_p, c_int) - - -def taos_stmt_prepare(stmt, sql): - # type: (ctypes.c_void_p, str) -> None - """Prepare a statement query - @stmt: c_void_p TAOS_STMT* - """ - buffer = sql.encode("utf-8") - res = _libtaos.taos_stmt_prepare(stmt, ctypes.c_char_p(buffer), len(buffer)) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -_libtaos.taos_stmt_close.restype = c_int -_libtaos.taos_stmt_close.argstype = (c_void_p,) - - -def taos_stmt_close(stmt): - # type: (ctypes.c_void_p) -> None - """Close a statement query - @stmt: c_void_p TAOS_STMT* - """ - res = _libtaos.taos_stmt_close(stmt) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -try: - _libtaos.taos_stmt_errstr.restype = c_char_p - _libtaos.taos_stmt_errstr.argstype = (c_void_p,) -except Exception as err: - _UNSUPPORTED["taos_stmt_set_tbname"] = err - - -def taos_stmt_errstr(stmt): - # type: (ctypes.c_void_p) -> str - """Get error message from stetement query - @stmt: c_void_p TAOS_STMT* - """ - _check_if_supported() - err = c_char_p(_libtaos.taos_stmt_errstr(stmt)) - if err: - return err.value.decode("utf-8") - - -try: - _libtaos.taos_stmt_set_tbname.restype = c_int - _libtaos.taos_stmt_set_tbname.argstype = (c_void_p, c_char_p) -except Exception as err: - _UNSUPPORTED["taos_stmt_set_tbname"] = err - - -def taos_stmt_set_tbname(stmt, name): - # type: (ctypes.c_void_p, str) -> None - """Set table name of a statement query if exists. - @stmt: c_void_p TAOS_STMT* - """ - _check_if_supported() - res = _libtaos.taos_stmt_set_tbname(stmt, c_char_p(name.encode("utf-8"))) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -try: - _libtaos.taos_stmt_set_tbname_tags.restype = c_int - _libtaos.taos_stmt_set_tbname_tags.argstype = (c_void_p, c_char_p, c_void_p) -except Exception as err: - _UNSUPPORTED["taos_stmt_set_tbname_tags"] = err - - -def taos_stmt_set_tbname_tags(stmt, name, tags): - # type: (c_void_p, str, c_void_p) -> None - """Set table name with tags bind params. - @stmt: c_void_p TAOS_STMT* - """ - _check_if_supported() - res = _libtaos.taos_stmt_set_tbname_tags(stmt, ctypes.c_char_p(name.encode("utf-8")), tags) - - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -_libtaos.taos_stmt_is_insert.restype = c_int -_libtaos.taos_stmt_is_insert.argstype = (c_void_p, POINTER(c_int)) - - -def taos_stmt_is_insert(stmt): - # type: (ctypes.c_void_p) -> bool - """Set table name with tags bind params. - @stmt: c_void_p TAOS_STMT* - """ - is_insert = ctypes.c_int() - res = _libtaos.taos_stmt_is_insert(stmt, ctypes.byref(is_insert)) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - return is_insert == 0 - - -_libtaos.taos_stmt_num_params.restype = c_int -_libtaos.taos_stmt_num_params.argstype = (c_void_p, POINTER(c_int)) - - -def taos_stmt_num_params(stmt): - # type: (ctypes.c_void_p) -> int - """Params number of the current statement query. - @stmt: TAOS_STMT* - """ - num_params = ctypes.c_int() - res = _libtaos.taos_stmt_num_params(stmt, ctypes.byref(num_params)) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - return num_params.value - - -_libtaos.taos_stmt_bind_param.restype = c_int -_libtaos.taos_stmt_bind_param.argstype = (c_void_p, c_void_p) - - -def taos_stmt_bind_param(stmt, bind): - # type: (ctypes.c_void_p, Array[TaosBind]) -> None - """Bind params in the statement query. - @stmt: TAOS_STMT* - @bind: TAOS_BIND* - """ - # ptr = ctypes.cast(bind, POINTER(TaosBind)) - # ptr = pointer(bind) - res = _libtaos.taos_stmt_bind_param(stmt, bind) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -try: - _libtaos.taos_stmt_bind_param_batch.restype = c_int - _libtaos.taos_stmt_bind_param_batch.argstype = (c_void_p, c_void_p) -except Exception as err: - _UNSUPPORTED["taos_stmt_bind_param_batch"] = err - - -def taos_stmt_bind_param_batch(stmt, bind): - # type: (ctypes.c_void_p, Array[TaosMultiBind]) -> None - """Bind params in the statement query. - @stmt: TAOS_STMT* - @bind: TAOS_BIND* - """ - # ptr = ctypes.cast(bind, POINTER(TaosMultiBind)) - # ptr = pointer(bind) - _check_if_supported() - res = _libtaos.taos_stmt_bind_param_batch(stmt, bind) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -try: - _libtaos.taos_stmt_bind_single_param_batch.restype = c_int - _libtaos.taos_stmt_bind_single_param_batch.argstype = (c_void_p, c_void_p, c_int) -except Exception as err: - _UNSUPPORTED["taos_stmt_bind_single_param_batch"] = err - - -def taos_stmt_bind_single_param_batch(stmt, bind, col): - # type: (ctypes.c_void_p, Array[TaosMultiBind], c_int) -> None - """Bind params in the statement query. - @stmt: TAOS_STMT* - @bind: TAOS_MULTI_BIND* - @col: column index - """ - _check_if_supported() - res = _libtaos.taos_stmt_bind_single_param_batch(stmt, bind, col) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -_libtaos.taos_stmt_add_batch.restype = c_int -_libtaos.taos_stmt_add_batch.argstype = (c_void_p,) - - -def taos_stmt_add_batch(stmt): - # type: (ctypes.c_void_p) -> None - """Add current params into batch - @stmt: TAOS_STMT* - """ - res = _libtaos.taos_stmt_add_batch(stmt) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -_libtaos.taos_stmt_execute.restype = c_int -_libtaos.taos_stmt_execute.argstype = (c_void_p,) - - -def taos_stmt_execute(stmt): - # type: (ctypes.c_void_p) -> None - """Execute a statement query - @stmt: TAOS_STMT* - """ - res = _libtaos.taos_stmt_execute(stmt) - if res != 0: - raise StatementError(msg=taos_stmt_errstr(stmt), errno=res) - - -_libtaos.taos_stmt_use_result.restype = c_void_p -_libtaos.taos_stmt_use_result.argstype = (c_void_p,) - - -def taos_stmt_use_result(stmt): - # type: (ctypes.c_void_p) -> None - """Get result of the statement. - @stmt: TAOS_STMT* - """ - result = c_void_p(_libtaos.taos_stmt_use_result(stmt)) - if result is None: - raise StatementError(taos_stmt_errstr(stmt)) - return result - - -try: - _libtaos.taos_schemaless_insert.restype = c_void_p - _libtaos.taos_schemaless_insert.argstype = c_void_p, c_void_p, c_int, c_int, c_int -except Exception as err: - _UNSUPPORTED["taos_schemaless_insert"] = err - - -def taos_schemaless_insert(connection, lines, protocol, precision): - # type: (c_void_p, list[str] | tuple(str), SmlProtocol, SmlPrecision) -> int - _check_if_supported() - num_of_lines = len(lines) - lines = (c_char_p(line.encode("utf-8")) for line in lines) - lines_type = ctypes.c_char_p * num_of_lines - p_lines = lines_type(*lines) - res = c_void_p(_libtaos.taos_schemaless_insert(connection, p_lines, num_of_lines, protocol, precision)) - errno = taos_errno(res) - affected_rows = taos_affected_rows(res) - if errno != 0: - errstr = taos_errstr(res) - taos_free_result(res) - raise SchemalessError(errstr, errno, affected_rows) - - taos_free_result(res) - return affected_rows - - -def _check_if_supported(): - func = inspect.stack()[1][3] - if func in _UNSUPPORTED: - raise InterfaceError("C function %s is not supported in v%s: %s" % (func, taos_get_client_info(), _UNSUPPORTED[func])) - - -def unsupported_methods(): - for m, e in range(_UNSUPPORTED): - print("unsupported %s: %s", m, e) - - -class CTaosInterface(object): - def __init__(self, config=None): - """ - Function to initialize the class - @host : str, hostname to connect - @user : str, username to connect to server - @password : str, password to connect to server - @db : str, default db to use when log in - @config : str, config directory - - @rtype : None - """ - if config is None: - self._config = ctypes.c_char_p(None) - else: - try: - self._config = ctypes.c_char_p(config.encode("utf-8")) - except AttributeError: - raise AttributeError("config is expected as a str") - - if config is not None: - taos_options(3, self._config) - - taos_init() - - @property - def config(self): - """Get current config""" - return self._config - - def connect(self, host=None, user="root", password="taosdata", db=None, port=0): - """ - Function to connect to server - - @rtype: c_void_p, TDengine handle - """ - return taos_connect(host, user, password, db, port) - - -if __name__ == "__main__": - cinter = CTaosInterface() - conn = cinter.connect() - result = cinter.query(conn, "show databases") - - print("Query Affected rows: {}".format(cinter.affected_rows(result))) - - fields = taos_fetch_fields_raw(result) - - data, num_of_rows = taos_fetch_block(result, fields) - - print(data) - - cinter.free_result(result) - cinter.close(conn) diff --git a/src/connector/python/taos/connection.py b/src/connector/python/taos/connection.py deleted file mode 100644 index dc8225ab33c84930214eb8f0d8ba47f6f31a5adf..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/connection.py +++ /dev/null @@ -1,204 +0,0 @@ -# encoding:UTF-8 -from types import FunctionType -from .cinterface import * -from .cursor import TaosCursor -from .subscription import TaosSubscription -from .statement import TaosStmt -from .stream import TaosStream -from .result import * - - -class TaosConnection(object): - """TDengine connection object""" - - def __init__(self, *args, **kwargs): - self._conn = None - self._host = None - self._user = "root" - self._password = "taosdata" - self._database = None - self._port = 0 - self._config = None - self._chandle = None - - self.config(**kwargs) - - def config(self, **kwargs): - # host - if "host" in kwargs: - self._host = kwargs["host"] - - # user - if "user" in kwargs: - self._user = kwargs["user"] - - # password - if "password" in kwargs: - self._password = kwargs["password"] - - # database - if "database" in kwargs: - self._database = kwargs["database"] - - # port - if "port" in kwargs: - self._port = kwargs["port"] - - # config - if "config" in kwargs: - self._config = kwargs["config"] - - self._chandle = CTaosInterface(self._config) - self._conn = self._chandle.connect(self._host, self._user, self._password, self._database, self._port) - - def close(self): - """Close current connection.""" - if self._conn: - taos_close(self._conn) - self._conn = None - - @property - def client_info(self): - # type: () -> str - return taos_get_client_info() - - @property - def server_info(self): - # type: () -> str - return taos_get_server_info(self._conn) - - def select_db(self, database): - # type: (str) -> None - taos_select_db(self._conn, database) - - def execute(self, sql): - # type: (str) -> int - """Simplely execute sql ignoring the results""" - return self.query(sql).affected_rows - - def query(self, sql): - # type: (str) -> TaosResult - result = taos_query(self._conn, sql) - return TaosResult(result, True, self) - - def query_a(self, sql, callback, param): - # type: (str, async_query_callback_type, c_void_p) -> None - """Asynchronously query a sql with callback function""" - taos_query_a(self._conn, sql, callback, param) - - def subscribe(self, restart, topic, sql, interval, callback=None, param=None): - # type: (bool, str, str, int, subscribe_callback_type, c_void_p) -> TaosSubscription - """Create a subscription.""" - if self._conn is None: - return None - sub = taos_subscribe(self._conn, restart, topic, sql, interval, callback, param) - return TaosSubscription(sub, callback != None) - - def statement(self, sql=None): - # type: (str | None) -> TaosStmt - if self._conn is None: - return None - stmt = taos_stmt_init(self._conn) - if sql != None: - taos_stmt_prepare(stmt, sql) - - return TaosStmt(stmt) - - def load_table_info(self, tables): - # type: (str) -> None - taos_load_table_info(self._conn, tables) - - def stream(self, sql, callback, stime=0, param=None, callback2=None): - # type: (str, Callable[[Any, TaosResult, TaosRows], None], int, Any, c_void_p) -> TaosStream - # cb = cast(callback, stream_callback_type) - # ref = byref(cb) - - stream = taos_open_stream(self._conn, sql, callback, stime, param, callback2) - return TaosStream(stream) - - def schemaless_insert(self, lines, protocol, precision): - # type: (list[str], SmlProtocol, SmlPrecision) -> int - """ - 1.Line protocol and schemaless support - - ## Example - - ```python - import taos - conn = taos.connect() - conn.exec("drop database if exists test") - conn.select_db("test") - lines = [ - 'ste,t2=5,t3=L"ste" c1=true,c2=4,c3="string" 1626056811855516532', - ] - conn.schemaless_insert(lines, 0, "ns") - ``` - - 2.OpenTSDB telnet style API format support - - ## Example - import taos - conn = taos.connect() - conn.exec("drop database if exists test") - conn.select_db("test") - lines = [ - 'cpu_load 1626056811855516532ns 2.0f32 id="tb1",host="host0",interface="eth0"', - ] - conn.schemaless_insert(lines, 1, None) - - - 3.OpenTSDB HTTP JSON format support - - ## Example - import taos - conn = taos.connect() - conn.exec("drop database if exists test") - conn.select_db("test") - payload = [''' - { - "metric": "cpu_load_0", - "timestamp": 1626006833610123, - "value": 55.5, - "tags": - { - "host": "ubuntu", - "interface": "eth0", - "Id": "tb0" - } - } - '''] - conn.schemaless_insert(lines, 2, None) - - """ - print(lines, protocol, precision) - return taos_schemaless_insert(self._conn, lines, protocol, precision) - - - def cursor(self): - # type: () -> TaosCursor - """Return a new Cursor object using the connection.""" - return TaosCursor(self) - - def commit(self): - """Commit any pending transaction to the database. - - Since TDengine do not support transactions, the implement is void functionality. - """ - pass - - def rollback(self): - """Void functionality""" - pass - - def clear_result_set(self): - """Clear unused result set on this connection.""" - pass - - def __del__(self): - self.close() - - -if __name__ == "__main__": - conn = TaosConnection() - conn.close() - print("Hello world") diff --git a/src/connector/python/taos/constants.py b/src/connector/python/taos/constants.py deleted file mode 100644 index 34044a15fc0cd73323552f1b4b8c280d6cad5a9b..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/constants.py +++ /dev/null @@ -1,47 +0,0 @@ -# encoding:UTF-8 - -"""Constants in TDengine python -""" - -import ctypes, struct - - -class FieldType(object): - """TDengine Field Types""" - - # type_code - C_NULL = 0 - C_BOOL = 1 - C_TINYINT = 2 - C_SMALLINT = 3 - C_INT = 4 - C_BIGINT = 5 - C_FLOAT = 6 - C_DOUBLE = 7 - C_BINARY = 8 - C_TIMESTAMP = 9 - C_NCHAR = 10 - C_TINYINT_UNSIGNED = 11 - C_SMALLINT_UNSIGNED = 12 - C_INT_UNSIGNED = 13 - C_BIGINT_UNSIGNED = 14 - C_JSON = 15 - # NULL value definition - # NOTE: These values should change according to C definition in tsdb.h - C_BOOL_NULL = 0x02 - C_TINYINT_NULL = -128 - C_TINYINT_UNSIGNED_NULL = 255 - C_SMALLINT_NULL = -32768 - C_SMALLINT_UNSIGNED_NULL = 65535 - C_INT_NULL = -2147483648 - C_INT_UNSIGNED_NULL = 4294967295 - C_BIGINT_NULL = -9223372036854775808 - C_BIGINT_UNSIGNED_NULL = 18446744073709551615 - C_FLOAT_NULL = ctypes.c_float(struct.unpack(" name (mandatory) - > type_code (mandatory) - > display_size - > internal_size - > precision - > scale - > null_ok - - This attribute will be None for operations that do not return rows or - if the cursor has not had an operation invoked via the .execute*() method yet. - - .rowcount:This read-only attribute specifies the number of rows that the last - .execute*() produced (for DQL statements like SELECT) or affected - """ - - def __init__(self, connection=None): - self._description = [] - self._rowcount = -1 - self._connection = None - self._result = None - self._fields = None - self._block = None - self._block_rows = -1 - self._block_iter = 0 - self._affected_rows = 0 - self._logfile = "" - - if connection is not None: - self._connection = connection - - def __iter__(self): - return self - - def __next__(self): - return self._taos_next() - - def next(self): - return self._taos_next() - - def _taos_next(self): - if self._result is None or self._fields is None: - raise OperationalError("Invalid use of fetch iterator") - - if self._block_rows <= self._block_iter: - block, self._block_rows = taos_fetch_row(self._result, self._fields) - if self._block_rows == 0: - raise StopIteration - self._block = list(map(tuple, zip(*block))) - self._block_iter = 0 - - data = self._block[self._block_iter] - self._block_iter += 1 - - return data - - @property - def description(self): - """Return the description of the object.""" - return self._description - - @property - def rowcount(self): - """Return the rowcount of the object""" - return self._rowcount - - @property - def affected_rows(self): - """Return the rowcount of insertion""" - return self._affected_rows - - def callproc(self, procname, *args): - """Call a stored database procedure with the given name. - - Void functionality since no stored procedures. - """ - pass - - def log(self, logfile): - self._logfile = logfile - - def close(self): - """Close the cursor.""" - if self._connection is None: - return False - - self._reset_result() - self._connection = None - - return True - - def execute(self, operation, params=None): - """Prepare and execute a database operation (query or command).""" - if not operation: - return None - - if not self._connection: - # TODO : change the exception raised here - raise ProgrammingError("Cursor is not connected") - - self._reset_result() - - stmt = operation - if params is not None: - pass - - # global querySeqNum - # querySeqNum += 1 - # localSeqNum = querySeqNum # avoid race condition - # print(" >> Exec Query ({}): {}".format(localSeqNum, str(stmt))) - self._result = taos_query(self._connection._conn, stmt) - # print(" << Query ({}) Exec Done".format(localSeqNum)) - if self._logfile: - with open(self._logfile, "a") as logfile: - logfile.write("%s;\n" % operation) - - if taos_field_count(self._result) == 0: - affected_rows = taos_affected_rows(self._result) - self._affected_rows += affected_rows - return affected_rows - else: - self._fields = taos_fetch_fields(self._result) - return self._handle_result() - - def executemany(self, operation, seq_of_parameters): - """Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.""" - pass - - def fetchone(self): - """Fetch the next row of a query result set, returning a single sequence, or None when no more data is available.""" - pass - - def fetchmany(self): - pass - - def istype(self, col, dataType): - if dataType.upper() == "BOOL": - if self._description[col][1] == FieldType.C_BOOL: - return True - if dataType.upper() == "TINYINT": - if self._description[col][1] == FieldType.C_TINYINT: - return True - if dataType.upper() == "TINYINT UNSIGNED": - if self._description[col][1] == FieldType.C_TINYINT_UNSIGNED: - return True - if dataType.upper() == "SMALLINT": - if self._description[col][1] == FieldType.C_SMALLINT: - return True - if dataType.upper() == "SMALLINT UNSIGNED": - if self._description[col][1] == FieldType.C_SMALLINT_UNSIGNED: - return True - if dataType.upper() == "INT": - if self._description[col][1] == FieldType.C_INT: - return True - if dataType.upper() == "INT UNSIGNED": - if self._description[col][1] == FieldType.C_INT_UNSIGNED: - return True - if dataType.upper() == "BIGINT": - if self._description[col][1] == FieldType.C_BIGINT: - return True - if dataType.upper() == "BIGINT UNSIGNED": - if self._description[col][1] == FieldType.C_BIGINT_UNSIGNED: - return True - if dataType.upper() == "FLOAT": - if self._description[col][1] == FieldType.C_FLOAT: - return True - if dataType.upper() == "DOUBLE": - if self._description[col][1] == FieldType.C_DOUBLE: - return True - if dataType.upper() == "BINARY": - if self._description[col][1] == FieldType.C_BINARY: - return True - if dataType.upper() == "TIMESTAMP": - if self._description[col][1] == FieldType.C_TIMESTAMP: - return True - if dataType.upper() == "NCHAR": - if self._description[col][1] == FieldType.C_NCHAR: - return True - if dataType.upper() == "JSON": - if self._description[col][1] == FieldType.C_JSON: - return True - - return False - - def fetchall_row(self): - """Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation.""" - if self._result is None or self._fields is None: - raise OperationalError("Invalid use of fetchall") - - buffer = [[] for i in range(len(self._fields))] - self._rowcount = 0 - while True: - block, num_of_fields = taos_fetch_row(self._result, self._fields) - errno = taos_errno(self._result) - if errno != 0: - raise ProgrammingError(taos_errstr(self._result), errno) - if num_of_fields == 0: - break - self._rowcount += num_of_fields - for i in range(len(self._fields)): - buffer[i].extend(block[i]) - return list(map(tuple, zip(*buffer))) - - def fetchall(self): - if self._result is None: - raise OperationalError("Invalid use of fetchall") - fields = self._fields if self._fields is not None else taos_fetch_fields(self._result) - buffer = [[] for i in range(len(fields))] - self._rowcount = 0 - while True: - block, num_of_fields = taos_fetch_block(self._result, self._fields) - errno = taos_errno(self._result) - if errno != 0: - raise ProgrammingError(taos_errstr(self._result), errno) - if num_of_fields == 0: - break - self._rowcount += num_of_fields - for i in range(len(self._fields)): - buffer[i].extend(block[i]) - return list(map(tuple, zip(*buffer))) - - def stop_query(self): - if self._result != None: - taos_stop_query(self._result) - - def nextset(self): - """ """ - pass - - def setinputsize(self, sizes): - pass - - def setutputsize(self, size, column=None): - pass - - def _reset_result(self): - """Reset the result to unused version.""" - self._description = [] - self._rowcount = -1 - if self._result is not None: - taos_free_result(self._result) - self._result = None - self._fields = None - self._block = None - self._block_rows = -1 - self._block_iter = 0 - self._affected_rows = 0 - - def _handle_result(self): - """Handle the return result from query.""" - self._description = [] - for ele in self._fields: - self._description.append((ele["name"], ele["type"], None, None, None, None, False)) - - return self._result - - def __del__(self): - self.close() diff --git a/src/connector/python/taos/error.py b/src/connector/python/taos/error.py deleted file mode 100644 index 122466fe3c448ec551fb910c402ad14bb6c93336..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/error.py +++ /dev/null @@ -1,111 +0,0 @@ -# encoding:UTF-8 -"""Python exceptions -""" - - -class Error(Exception): - def __init__(self, msg=None, errno=0xffff): - self.msg = msg - self.errno = errno - self._full_msg = "[0x%04x]: %s" % (self.errno & 0xffff, self.msg) - - def __str__(self): - return self._full_msg - - -class Warning(Exception): - """Exception raised for important warnings like data truncations while inserting.""" - - pass - - -class InterfaceError(Error): - """Exception raised for errors that are related to the database interface rather than the database itself.""" - - pass - - -class DatabaseError(Error): - """Exception raised for errors that are related to the database.""" - - pass - -class ConnectionError(Error): - """Exceptin raised for connection failed""" - pass - -class DataError(DatabaseError): - """Exception raised for errors that are due to problems with the processed data like division by zero, numeric value out of range.""" - - pass - - -class OperationalError(DatabaseError): - """Exception raised for errors that are related to the database's operation and not necessarily under the control of the programmer""" - - pass - - -class IntegrityError(DatabaseError): - """Exception raised when the relational integrity of the database is affected.""" - - pass - - -class InternalError(DatabaseError): - """Exception raised when the database encounters an internal error.""" - - pass - - -class ProgrammingError(DatabaseError): - """Exception raised for programming errors.""" - - pass - - -class NotSupportedError(DatabaseError): - """Exception raised in case a method or database API was used which is not supported by the database,.""" - - pass - - -class StatementError(DatabaseError): - """Exception raised in STMT API.""" - - pass - -class ResultError(DatabaseError): - """Result related APIs.""" - - pass - -class SchemalessError(DatabaseError): - """taos_schemaless_insert errors.""" - - def __init__(self, msg=None, errno=0xffff, affected_rows=0): - DatabaseError.__init__(self, msg, errno) - self.affected_rows = affected_rows - - def __str__(self): - return self._full_msg + "(affected rows: %d)" % self.affected_rows - - # @property - # def affected_rows(self): - # return self.affected_rows - - -class StatementError(DatabaseError): - """Exception raised in STMT API.""" - - pass - -class ResultError(DatabaseError): - """Result related APIs.""" - - pass - -class LinesError(DatabaseError): - """taos_insert_lines errors.""" - - pass \ No newline at end of file diff --git a/src/connector/python/taos/field.py b/src/connector/python/taos/field.py deleted file mode 100644 index a6d64422e238b46b096a5ae62c42566666f226ad..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/field.py +++ /dev/null @@ -1,309 +0,0 @@ -# encoding:UTF-8 -import ctypes -import math -import datetime -from ctypes import * - -from .constants import FieldType -from .error import * - -_datetime_epoch = datetime.datetime.fromtimestamp(0) - -def _convert_millisecond_to_datetime(milli): - return _datetime_epoch + datetime.timedelta(seconds=milli / 1000.0) - - -def _convert_microsecond_to_datetime(micro): - return _datetime_epoch + datetime.timedelta(seconds=micro / 1000000.0) - - -def _convert_nanosecond_to_datetime(nanosec): - return nanosec - - -def _crow_timestamp_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C bool row to python row""" - _timestamp_converter = _convert_millisecond_to_datetime - if precision == FieldType.C_TIMESTAMP_MILLI: - _timestamp_converter = _convert_millisecond_to_datetime - elif precision == FieldType.C_TIMESTAMP_MICRO: - _timestamp_converter = _convert_microsecond_to_datetime - elif precision == FieldType.C_TIMESTAMP_NANO: - _timestamp_converter = _convert_nanosecond_to_datetime - else: - raise DatabaseError("Unknown precision returned from database") - - return [ - None if ele == FieldType.C_BIGINT_NULL else _timestamp_converter(ele) - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_int64))[: abs(num_of_rows)] - ] - - -def _crow_bool_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C bool row to python row""" - return [ - None if ele == FieldType.C_BOOL_NULL else bool(ele) - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_byte))[: abs(num_of_rows)] - ] - - -def _crow_tinyint_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C tinyint row to python row""" - return [ - None if ele == FieldType.C_TINYINT_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_byte))[: abs(num_of_rows)] - ] - - -def _crow_tinyint_unsigned_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C tinyint row to python row""" - return [ - None if ele == FieldType.C_TINYINT_UNSIGNED_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte))[: abs(num_of_rows)] - ] - - -def _crow_smallint_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C smallint row to python row""" - return [ - None if ele == FieldType.C_SMALLINT_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_short))[: abs(num_of_rows)] - ] - - -def _crow_smallint_unsigned_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C smallint row to python row""" - return [ - None if ele == FieldType.C_SMALLINT_UNSIGNED_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_ushort))[: abs(num_of_rows)] - ] - - -def _crow_int_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C int row to python row""" - return [ - None if ele == FieldType.C_INT_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[: abs(num_of_rows)] - ] - - -def _crow_int_unsigned_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C int row to python row""" - return [ - None if ele == FieldType.C_INT_UNSIGNED_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_uint))[: abs(num_of_rows)] - ] - - -def _crow_bigint_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C bigint row to python row""" - return [ - None if ele == FieldType.C_BIGINT_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_int64))[: abs(num_of_rows)] - ] - - -def _crow_bigint_unsigned_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C bigint row to python row""" - return [ - None if ele == FieldType.C_BIGINT_UNSIGNED_NULL else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_uint64))[: abs(num_of_rows)] - ] - - -def _crow_float_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C float row to python row""" - return [ - None if math.isnan(ele) else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_float))[: abs(num_of_rows)] - ] - - -def _crow_double_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C double row to python row""" - return [ - None if math.isnan(ele) else ele - for ele in ctypes.cast(data, ctypes.POINTER(ctypes.c_double))[: abs(num_of_rows)] - ] - - -def _crow_binary_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C binary row to python row""" - assert nbytes is not None - return [ - None if ele.value[0:1] == FieldType.C_BINARY_NULL else ele.value.decode("utf-8") - for ele in (ctypes.cast(data, ctypes.POINTER(ctypes.c_char * nbytes)))[: abs(num_of_rows)] - ] - - -def _crow_nchar_to_python(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C nchar row to python row""" - assert nbytes is not None - res = [] - for i in range(abs(num_of_rows)): - try: - if num_of_rows >= 0: - tmpstr = ctypes.c_char_p(data) - res.append(tmpstr.value.decode("utf-8")) - else: - res.append( - ( - ctypes.cast( - data + nbytes * i, - ctypes.POINTER(ctypes.c_wchar * (nbytes // 4)), - ) - )[0].value - ) - except ValueError: - res.append(None) - - return res - - -def _crow_binary_to_python_block(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C binary row to python row""" - assert nbytes is not None - res = [] - for i in range(abs(num_of_rows)): - rbyte = ctypes.cast(data + nbytes * i, ctypes.POINTER(ctypes.c_short))[:1].pop() - chars = ctypes.cast(c_char_p(data + nbytes * i + 2), ctypes.POINTER(c_char * rbyte)) - buffer = create_string_buffer(rbyte + 1) - buffer[:rbyte] = chars[0][:rbyte] - if rbyte == 1 and buffer[0] == b'\xff': - res.append(None) - else: - res.append(cast(buffer, c_char_p).value.decode("utf-8")) - return res - - -def _crow_nchar_to_python_block(data, num_of_rows, nbytes=None, precision=FieldType.C_TIMESTAMP_UNKNOWN): - """Function to convert C nchar row to python row""" - assert nbytes is not None - res = [] - for i in range(abs(num_of_rows)): - rbyte = ctypes.cast(data + nbytes * i, ctypes.POINTER(ctypes.c_short))[:1].pop() - chars = ctypes.cast(c_char_p(data + nbytes * i + 2), ctypes.POINTER(c_char * rbyte)) - buffer = create_string_buffer(rbyte + 1) - buffer[:rbyte] = chars[0][:rbyte] - if rbyte == 4 and buffer[:4] == b'\xff'*4: - res.append(None) - else: - res.append(cast(buffer, c_char_p).value.decode("utf-8")) - return res - - -CONVERT_FUNC = { - FieldType.C_BOOL: _crow_bool_to_python, - FieldType.C_TINYINT: _crow_tinyint_to_python, - FieldType.C_SMALLINT: _crow_smallint_to_python, - FieldType.C_INT: _crow_int_to_python, - FieldType.C_BIGINT: _crow_bigint_to_python, - FieldType.C_FLOAT: _crow_float_to_python, - FieldType.C_DOUBLE: _crow_double_to_python, - FieldType.C_BINARY: _crow_binary_to_python, - FieldType.C_TIMESTAMP: _crow_timestamp_to_python, - FieldType.C_NCHAR: _crow_nchar_to_python, - FieldType.C_TINYINT_UNSIGNED: _crow_tinyint_unsigned_to_python, - FieldType.C_SMALLINT_UNSIGNED: _crow_smallint_unsigned_to_python, - FieldType.C_INT_UNSIGNED: _crow_int_unsigned_to_python, - FieldType.C_BIGINT_UNSIGNED: _crow_bigint_unsigned_to_python, - FieldType.C_JSON: _crow_nchar_to_python, -} - -CONVERT_FUNC_BLOCK = { - FieldType.C_BOOL: _crow_bool_to_python, - FieldType.C_TINYINT: _crow_tinyint_to_python, - FieldType.C_SMALLINT: _crow_smallint_to_python, - FieldType.C_INT: _crow_int_to_python, - FieldType.C_BIGINT: _crow_bigint_to_python, - FieldType.C_FLOAT: _crow_float_to_python, - FieldType.C_DOUBLE: _crow_double_to_python, - FieldType.C_BINARY: _crow_binary_to_python_block, - FieldType.C_TIMESTAMP: _crow_timestamp_to_python, - FieldType.C_NCHAR: _crow_nchar_to_python_block, - FieldType.C_TINYINT_UNSIGNED: _crow_tinyint_unsigned_to_python, - FieldType.C_SMALLINT_UNSIGNED: _crow_smallint_unsigned_to_python, - FieldType.C_INT_UNSIGNED: _crow_int_unsigned_to_python, - FieldType.C_BIGINT_UNSIGNED: _crow_bigint_unsigned_to_python, - FieldType.C_JSON: _crow_nchar_to_python_block, -} - -# Corresponding TAOS_FIELD structure in C - - -class TaosField(ctypes.Structure): - _fields_ = [ - ("_name", ctypes.c_char * 65), - ("_type", ctypes.c_uint8), - ("_bytes", ctypes.c_uint16), - ] - - @property - def name(self): - return self._name.decode("utf-8") - - @property - def length(self): - """alias to self.bytes""" - return self._bytes - - @property - def bytes(self): - return self._bytes - - @property - def type(self): - return self._type - - def __dict__(self): - return {"name": self.name, "type": self.type, "bytes": self.length} - - def __str__(self): - return "{name: %s, type: %d, bytes: %d}" % (self.name, self.type, self.length) - - def __getitem__(self, item): - return getattr(self, item) - - -class TaosFields(object): - def __init__(self, fields, count): - if isinstance(fields, c_void_p): - self._fields = cast(fields, POINTER(TaosField)) - if isinstance(fields, POINTER(TaosField)): - self._fields = fields - self._count = count - self._iter = 0 - - def as_ptr(self): - return self._fields - - @property - def count(self): - return self._count - - @property - def fields(self): - return self._fields - - def __next__(self): - return self._next_field() - - def next(self): - return self._next_field() - - def _next_field(self): - if self._iter < self.count: - field = self._fields[self._iter] - self._iter += 1 - return field - else: - raise StopIteration - - def __getitem__(self, item): - return self._fields[item] - - def __iter__(self): - return self - - def __len__(self): - return self.count diff --git a/src/connector/python/taos/precision.py b/src/connector/python/taos/precision.py deleted file mode 100644 index d67da592cce6d2121ec8f2eed78a30d6fa0c446b..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/precision.py +++ /dev/null @@ -1,12 +0,0 @@ -class PrecisionEnum(object): - """Precision enums""" - - Milliseconds = 0 - Microseconds = 1 - Nanoseconds = 2 - - -class PrecisionError(Exception): - """Python datetime does not support nanoseconds error""" - - pass diff --git a/src/connector/python/taos/result.py b/src/connector/python/taos/result.py deleted file mode 100644 index 05085a493eb8ffede536476f1ddf3bcb083d82f8..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/result.py +++ /dev/null @@ -1,263 +0,0 @@ -from .cinterface import * - -# from .connection import TaosConnection -from .error import * - -from ctypes import c_void_p - - -class TaosResult(object): - """TDengine result interface""" - - def __init__(self, result, close_after=False, conn=None): - # type: (c_void_p, bool, TaosConnection) -> TaosResult - # to make the __del__ order right - self._conn = conn - self._close_after = close_after - if isinstance(result, c_void_p): - self._result = result - else: - self._result = c_void_p(result) - - self._fields = None - self._field_count = None - self._precision = None - - self._block = None - self._block_length = None - self._row_count = 0 - - def __iter__(self): - return self - - def __next__(self): - return self._next_row() - - def next(self): - # fetch next row - return self._next_row() - - def _next_row(self): - if self._result is None or self.fields is None: - raise OperationalError("Invalid use of fetch iterator") - - if self._block is None or self._block_iter >= self._block_length: - self._block, self._block_length = self.fetch_block() - self._block_iter = 0 - # self._row_count += self._block_length - - raw = self._block[self._block_iter] - self._block_iter += 1 - return raw - - @property - def fields(self): - """fields definitions of the current result""" - if self._result is None: - raise ResultError("no result object setted") - if self._fields is None: - self._fields = taos_fetch_fields(self._result) - - return self._fields - - @property - def field_count(self): - """Field count of the current result, eq to taos_field_count(result)""" - return self.fields.count - - @property - def row_count(self): - """Return the rowcount of the object""" - return self._row_count - - @property - def precision(self): - if self._precision is None: - self._precision = taos_result_precision(self._result) - return self._precision - - @property - def affected_rows(self): - return taos_affected_rows(self._result) - - # @property - def field_lengths(self): - return taos_fetch_lengths(self._result, self.field_count) - - def rows_iter(self, num_of_rows=None): - return TaosRows(self, num_of_rows) - - def blocks_iter(self): - return TaosBlocks(self) - - def fetch_block(self): - if self._result is None: - raise OperationalError("Invalid use of fetch iterator") - - block, length = taos_fetch_block_raw(self._result) - if length == 0: - raise StopIteration - precision = self.precision - field_count = self.field_count - fields = self.fields - blocks = [None] * field_count - lengths = self.field_lengths() - for i in range(field_count): - data = ctypes.cast(block, ctypes.POINTER(ctypes.c_void_p))[i] - if fields[i].type not in CONVERT_FUNC_BLOCK: - raise DatabaseError("Invalid data type returned from database") - blocks[i] = CONVERT_FUNC_BLOCK[fields[i].type](data, length, lengths[i], precision) - - return list(map(tuple, zip(*blocks))), length - - def fetch_all(self): - if self._result is None: - raise OperationalError("Invalid use of fetchall") - - if self._fields is None: - self._fields = taos_fetch_fields(self._result) - buffer = [[] for i in range(len(self._fields))] - self._row_count = 0 - while True: - block, num_of_fields = taos_fetch_block(self._result, self._fields) - errno = taos_errno(self._result) - if errno != 0: - raise ProgrammingError(taos_errstr(self._result), errno) - if num_of_fields == 0: - break - self._row_count += num_of_fields - for i in range(len(self._fields)): - buffer[i].extend(block[i]) - return list(map(tuple, zip(*buffer))) - - def fetch_all_into_dict(self): - """Fetch all rows and convert it to dict""" - names = [field.name for field in self.fields] - rows = self.fetch_all() - return list(dict(zip(names, row)) for row in rows) - - def fetch_rows_a(self, callback, param): - taos_fetch_rows_a(self._result, callback, param) - - def stop_query(self): - return taos_stop_query(self._result) - - def errno(self): - """**DO NOT** use this directly unless you know what you are doing""" - return taos_errno(self._result) - - def errstr(self): - return taos_errstr(self._result) - - def check_error(self, errno=None, close=True): - if errno is None: - errno = self.errno() - if errno != 0: - msg = self.errstr() - self.close() - raise OperationalError(msg, errno) - - def close(self): - """free result object.""" - if self._result != None and self._close_after: - taos_free_result(self._result) - self._result = None - self._fields = None - self._field_count = None - self._field_lengths = None - - def __del__(self): - self.close() - - -class TaosRows: - """TDengine result rows iterator""" - - def __init__(self, result, num_of_rows=None): - self._result = result - self._num_of_rows = num_of_rows - - def __iter__(self): - return self - - def __next__(self): - return self._next_row() - - def next(self): - return self._next_row() - - def _next_row(self): - if self._result is None: - raise OperationalError("Invalid use of fetch iterator") - if self._num_of_rows != None and self._num_of_rows <= self._result._row_count: - raise StopIteration - - row = taos_fetch_row_raw(self._result._result) - if not row: - raise StopIteration - self._result._row_count += 1 - return TaosRow(self._result, row) - - @property - def row_count(self): - """Return the rowcount of the object""" - return self._result._row_count - - -class TaosRow: - def __init__(self, result, row): - self._result = result - self._row = row - - def __str__(self): - return taos_print_row(self._row, self._result.fields, self._result.field_count) - - def __call__(self): - return self.as_tuple() - - def _astuple(self): - return self.as_tuple() - - def __iter__(self): - return self.as_tuple() - - def as_ptr(self): - return self._row - - def as_tuple(self): - precision = self._result.precision - field_count = self._result.field_count - blocks = [None] * field_count - fields = self._result.fields - field_lens = self._result.field_lengths() - for i in range(field_count): - data = ctypes.cast(self._row, ctypes.POINTER(ctypes.c_void_p))[i] - if fields[i].type not in CONVERT_FUNC: - raise DatabaseError("Invalid data type returned from database") - if data is None: - blocks[i] = None - else: - blocks[i] = CONVERT_FUNC[fields[i].type](data, 1, field_lens[i], precision)[0] - return tuple(blocks) - - def as_dict(self): - values = self.as_tuple() - names = self._result.fields - dict(zip(names, values)) - - - -class TaosBlocks: - """TDengine result blocks iterator""" - - def __init__(self, result): - self._result = result - - def __iter__(self): - return self - - def __next__(self): - return self._result.fetch_block() - - def next(self): - return self._result.fetch_block() diff --git a/src/connector/python/taos/schemaless.py b/src/connector/python/taos/schemaless.py deleted file mode 100644 index 35967412f78a63e67d63f0e58bbf903f21fb275a..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/schemaless.py +++ /dev/null @@ -1,17 +0,0 @@ - -class SmlPrecision: - """Schemaless timestamp precision constants""" - NOT_CONFIGURED = 0 # C.TSDB_SML_TIMESTAMP_NOT_CONFIGURED - HOURS = 1 - MINUTES = 2 - SECONDS = 3 - MILLI_SECONDS = 4 - MICRO_SECONDS = 5 - NANO_SECONDS = 6 - -class SmlProtocol: - """Schemaless protocol constants""" - UNKNOWN_PROTOCOL = 0 - LINE_PROTOCOL = 1 - TELNET_PROTOCOL = 2 - JSON_PROTOCOL = 3 \ No newline at end of file diff --git a/src/connector/python/taos/statement.py b/src/connector/python/taos/statement.py deleted file mode 100644 index 155e98173b7f920640aa84d0fcda618d2669bb1e..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/statement.py +++ /dev/null @@ -1,85 +0,0 @@ -from taos.cinterface import * -from taos.error import * -from taos.result import * - - -class TaosStmt(object): - """TDengine STMT interface""" - - def __init__(self, stmt, conn = None): - self._conn = conn - self._stmt = stmt - - def set_tbname(self, name): - """Set table name if needed. - - Note that the set_tbname* method should only used in insert statement - """ - if self._stmt is None: - raise StatementError("Invalid use of set_tbname") - taos_stmt_set_tbname(self._stmt, name) - - def prepare(self, sql): - # type: (str) -> None - taos_stmt_prepare(self._stmt, sql) - - def set_tbname_tags(self, name, tags): - # type: (str, Array[TaosBind]) -> None - """Set table name with tags, tags is array of BindParams""" - if self._stmt is None: - raise StatementError("Invalid use of set_tbname") - taos_stmt_set_tbname_tags(self._stmt, name, tags) - - def bind_param(self, params, add_batch=True): - # type: (Array[TaosBind], bool) -> None - if self._stmt is None: - raise StatementError("Invalid use of stmt") - taos_stmt_bind_param(self._stmt, params) - if add_batch: - taos_stmt_add_batch(self._stmt) - - def bind_param_batch(self, binds, add_batch=True): - # type: (Array[TaosMultiBind], bool) -> None - if self._stmt is None: - raise StatementError("Invalid use of stmt") - taos_stmt_bind_param_batch(self._stmt, binds) - if add_batch: - taos_stmt_add_batch(self._stmt) - - def add_batch(self): - if self._stmt is None: - raise StatementError("Invalid use of stmt") - taos_stmt_add_batch(self._stmt) - - def execute(self): - if self._stmt is None: - raise StatementError("Invalid use of execute") - taos_stmt_execute(self._stmt) - - def use_result(self): - result = taos_stmt_use_result(self._stmt) - return TaosResult(result) - - def close(self): - """Close stmt.""" - if self._stmt is None: - return - taos_stmt_close(self._stmt) - self._stmt = None - - def __del__(self): - self.close() - - -if __name__ == "__main__": - from taos.connection import TaosConnection - - conn = TaosConnection() - - stmt = conn.statement("select * from log.log limit 10") - stmt.execute() - result = stmt.use_result() - for row in result: - print(row) - stmt.close() - conn.close() diff --git a/src/connector/python/taos/stream.py b/src/connector/python/taos/stream.py deleted file mode 100644 index fe3c8c85e3279511972293882224bf20c30dfa64..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/stream.py +++ /dev/null @@ -1,22 +0,0 @@ -from taos.cinterface import * -from taos.error import * -from taos.result import * - - -class TaosStream(object): - """TDengine Stream interface""" - - def __init__(self, stream): - self._raw = stream - - def as_ptr(self): - return self._raw - - def close(self): - """Close stmt.""" - if self._raw is not None: - taos_close_stream(self._raw) - self._raw = None - - def __del__(self): - self.close() diff --git a/src/connector/python/taos/subscription.py b/src/connector/python/taos/subscription.py deleted file mode 100644 index 3c6958b6f8d55791b9753a84a4bbd7653bdae780..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/subscription.py +++ /dev/null @@ -1,49 +0,0 @@ -from taos.result import TaosResult -from .cinterface import * -from .error import * - - -class TaosSubscription(object): - """TDengine subscription object""" - - def __init__(self, sub, with_callback = False): - self._sub = sub - self._with_callback = with_callback - - def consume(self): - """Consume rows of a subscription""" - if self._sub is None: - raise OperationalError("Invalid use of consume") - if self._with_callback: - raise OperationalError("DONOT use consume method in an subscription with callback") - result = taos_consume(self._sub) - return TaosResult(result) - - def close(self, keepProgress=True): - """Close the Subscription.""" - if self._sub is None: - return False - - taos_unsubscribe(self._sub, keepProgress) - self._sub = None - return True - - def __del__(self): - self.close() - - -if __name__ == "__main__": - from .connection import TaosConnection - - conn = TaosConnection(host="127.0.0.1", user="root", password="taosdata", database="test") - - # Generate a cursor object to run SQL commands - sub = conn.subscribe(True, "test", "select * from meters;", 1000) - - for i in range(0, 10): - data = sub.consume() - for d in data: - print(d) - - sub.close() - conn.close() diff --git a/src/connector/python/taos/timestamp.py b/src/connector/python/taos/timestamp.py deleted file mode 100644 index ab5679fdf12e2942aa94f76716ff98e6d2a88d69..0000000000000000000000000000000000000000 --- a/src/connector/python/taos/timestamp.py +++ /dev/null @@ -1,17 +0,0 @@ - -class TimestampType(object): - """Choose which type that parsing TDengine timestamp data to - - - DATETIME: use python datetime.datetime, note that it does not support nanosecond precision, - and python taos will use raw c_int64 as a fallback for nanosecond results. - - NUMPY: use numpy.datetime64 type. - - RAW: use raw c_int64. - - TAOS: use taos' TaosTimestamp. - """ - DATETIME = 0, - NUMPY = 1, - RAW = 2, - TAOS = 3, - -class TaosTimestamp: - pass diff --git a/src/connector/python/tests/test-td6231.py b/src/connector/python/tests/test-td6231.py deleted file mode 100644 index e55d22c10734eedcbd5be8012eaeb3fb3d51e381..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test-td6231.py +++ /dev/null @@ -1,50 +0,0 @@ -from taos import * - -conn = connect() - -dbname = "pytest_taos_stmt_multi" -conn.execute("drop database if exists %s" % dbname) -conn.execute("create database if not exists %s" % dbname) -conn.select_db(dbname) - -conn.execute( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, \ - ti tinyint, si smallint, ii int, bi bigint, tu tinyint unsigned, \ - su smallint unsigned, iu int unsigned, bu bigint unsigned, \ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", -) - -stmt = conn.statement("insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - -params = new_multi_binds(16) -params[0].timestamp((1626861392589, 1626861392590, 1626861392591)) -params[1].bool((True, None, False)) -params[2].tinyint([-128, -128, None]) # -128 is tinyint null -params[3].tinyint([0, 127, None]) -params[4].smallint([3, None, 2]) -params[5].int([3, 4, None]) -params[6].bigint([3, 4, None]) -params[7].tinyint_unsigned([3, 4, None]) -params[8].smallint_unsigned([3, 4, None]) -params[9].int_unsigned([3, 4, None]) -params[10].bigint_unsigned([3, 4, None]) -params[11].float([3, None, 1]) -params[12].double([3, None, 1.2]) -params[13].binary(["abc", "dddafadfadfadfadfa", None]) -# params[14].nchar(["涛思数据", None, "a long string with 中文字符"]) -params[14].nchar([None, None, None]) -params[15].timestamp([None, None, 1626861392591]) -stmt.bind_param_batch(params) -stmt.execute() - - -result = stmt.use_result() -assert result.affected_rows == 3 -result.close() - -result = conn.query("select * from log") -for row in result: - print(row) -result.close() -stmt.close() -conn.close() diff --git a/src/connector/python/tests/test_ctaos.py b/src/connector/python/tests/test_ctaos.py deleted file mode 100644 index 7b9566931f2b29dcbdc8646d2f087ebf40e716cc..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_ctaos.py +++ /dev/null @@ -1,162 +0,0 @@ -from taos.cinterface import * -from taos.precision import * -from taos.bind import * - -import time -import datetime -import pytest - -@pytest.fixture -def conn(): - return CTaosInterface().connect() - - -def test_simple(conn, caplog): - dbname = "pytest_ctaos_simple" - try: - res = taos_query(conn, "create database if not exists %s" % dbname) - taos_free_result(res) - - taos_select_db(conn, dbname) - - res = taos_query( - conn, - "create table if not exists log(ts timestamp, level tinyint, content binary(100), ipaddr binary(134))", - ) - taos_free_result(res) - - res = taos_query(conn, "insert into log values(now, 1, 'hello', 'test')") - taos_free_result(res) - - res = taos_query(conn, "select level,content,ipaddr from log limit 1") - - fields = taos_fetch_fields_raw(res) - field_count = taos_field_count(res) - - fields = taos_fetch_fields(res) - for field in fields: - print(field) - - # field_lengths = taos_fetch_lengths(res, field_count) - # if not field_lengths: - # raise "fetch lengths error" - - row = taos_fetch_row_raw(res) - rowstr = taos_print_row(row, fields, field_count) - assert rowstr == "1 hello test" - - row, num = taos_fetch_row(res, fields) - print(row) - taos_free_result(res) - taos_query(conn, "drop database if exists " + dbname) - taos_close(conn) - except Exception as err: - taos_query(conn, "drop database if exists " + dbname) - raise err - - -def test_stmt(conn, caplog): - dbname = "pytest_ctaos_stmt" - try: - res = taos_query(conn, "drop database if exists %s" % dbname) - taos_free_result(res) - res = taos_query(conn, "create database if not exists %s" % dbname) - taos_free_result(res) - - taos_select_db(conn, dbname) - - res = taos_query( - conn, - "create table if not exists log(ts timestamp, nil tinyint, ti tinyint, si smallint, ii int,\ - bi bigint, tu tinyint unsigned, su smallint unsigned, iu int unsigned, bu bigint unsigned, \ - ff float, dd double, bb binary(100), nn nchar(100))", - ) - taos_free_result(res) - - stmt = taos_stmt_init(conn) - - taos_stmt_prepare(stmt, "insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - - params = new_bind_params(14) - params[0].timestamp(1626861392589, PrecisionEnum.Milliseconds) - params[1].null() - params[2].tinyint(2) - params[3].smallint(3) - params[4].int(4) - params[5].bigint(5) - params[6].tinyint_unsigned(6) - params[7].smallint_unsigned(7) - params[8].int_unsigned(8) - params[9].bigint_unsigned(9) - params[10].float(10.1) - params[11].double(10.11) - params[12].binary("hello") - params[13].nchar("stmt") - taos_stmt_bind_param(stmt, params) - taos_stmt_add_batch(stmt) - taos_stmt_execute(stmt) - - res = taos_query(conn, "select * from log limit 1") - - fields = taos_fetch_fields(res) - filed_count = taos_field_count(res) - - row = taos_fetch_row_raw(res) - rowstr = taos_print_row(row, fields, filed_count, 100) - - taos_free_result(res) - taos_query(conn, "drop database if exists " + dbname) - taos_close(conn) - - assert rowstr == "1626861392589 NULL 2 3 4 5 6 7 8 9 10.100000 10.110000 hello stmt" - except Exception as err: - taos_query(conn, "drop database if exists " + dbname) - raise err - -def stream_callback(param, result, row): - # type: (c_void_p, c_void_p, c_void_p) -> None - try: - if result == None or row == None: - return - result = c_void_p(result) - row = c_void_p(row) - fields = taos_fetch_fields_raw(result) - num_fields = taos_field_count(result) - s = taos_print_row(row, fields, num_fields) - print(s) - taos_stop_query(result) - except Exception as err: - print(err) - -def test_stream(conn, caplog): - dbname = "pytest_ctaos_stream" - try: - res = taos_query(conn, "create database if not exists %s" % dbname) - taos_free_result(res) - - taos_select_db(conn, dbname) - - res = taos_query( - conn, - "create table if not exists log(ts timestamp, n int)", - ) - taos_free_result(res) - - res = taos_query(conn, "select count(*) from log interval(5s)") - cc = taos_num_fields(res) - assert cc == 2 - - stream = taos_open_stream(conn, "select count(*) from log interval(5s)", stream_callback, 0, None, None) - print("waiting for data") - time.sleep(1) - - for i in range(0, 2): - res = taos_query(conn, "insert into log values(now,0)(now+1s, 1)(now + 2s, 2)") - taos_free_result(res) - time.sleep(2) - taos_close_stream(stream) - taos_query(conn, "drop database if exists " + dbname) - taos_close(conn) - except Exception as err: - taos_query(conn, "drop database if exists " + dbname) - raise err diff --git a/src/connector/python/tests/test_info.py b/src/connector/python/tests/test_info.py deleted file mode 100644 index bddfec7ef9ddbc203adfcadd262839048466592c..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_info.py +++ /dev/null @@ -1,23 +0,0 @@ -from taos.cinterface import * - -from taos import * - -import pytest - -@pytest.fixture -def conn(): - return connect() - -def test_client_info(): - print(taos_get_client_info()) - None - -def test_server_info(conn): - # type: (TaosConnection) -> None - print(conn.client_info) - print(conn.server_info) - None - -if __name__ == "__main__": - test_client_info() - test_server_info(connect()) diff --git a/src/connector/python/tests/test_lines.py b/src/connector/python/tests/test_lines.py deleted file mode 100644 index 51d23b8e891d398b404086fdb2ff2910dcc1eb0a..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_lines.py +++ /dev/null @@ -1,118 +0,0 @@ -from taos.error import OperationalError, SchemalessError -from taos import connect, new_bind_params, PrecisionEnum -from taos import * - -from ctypes import * -import taos -import pytest - - -@pytest.fixture -def conn(): - # type: () -> taos.TaosConnection - return connect() - - -def test_schemaless_insert_update_2(conn): - # type: (TaosConnection) -> None - - dbname = "test_schemaless_insert_update_2" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s update 2 precision 'ns'" % dbname) - conn.select_db(dbname) - - lines = [ - 'st,t1=4i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin, abc",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000', - ] - res = conn.schemaless_insert(lines, 1, 0) - print("affected rows: ", res) - assert(res == 1) - - result = conn.query("select * from st") - [before] = result.fetch_all_into_dict() - assert(before["c3"] == "passitagin, abc") - - lines = [ - 'st,t1=4i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000', - ] - res = conn.schemaless_insert(lines, 1, 0) - result = conn.query("select * from st") - [after] = result.fetch_all_into_dict() - assert(after["c3"] == "passitagin") - - conn.execute("drop database if exists %s" % dbname) - conn.close() - - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - print(err) - raise err - -def test_schemaless_insert(conn): - # type: (TaosConnection) -> None - - dbname = "pytest_taos_schemaless_insert" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s update 2 precision 'ns'" % dbname) - conn.select_db(dbname) - - lines = [ - 'st,t1=3i64,t2=4f64,t3="t3" c1=3i64,c3=L"passit",c2=false,c4=4f64 1626006833639000000', - 'st,t1=4i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin, abc",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000', - 'stf,t1=4i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin_stf",c2=false,c5=5f64,c6=7u64 1626006933641000000', - ] - res = conn.schemaless_insert(lines, 1, 0) - print("affected rows: ", res) - assert(res == 3) - - lines = [ - 'stf,t1=5i64,t3="t4",t2=5f64,t4=5f64 c1=3i64,c3=L"passitagin_stf",c2=false,c5=5f64,c6=7u64 1626006933641000000', - ] - res = conn.schemaless_insert(lines, 1, 0) - print("affected rows: ", res) - assert(res == 1) - result = conn.query("select * from st") - - dict2 = result.fetch_all_into_dict() - print(dict2) - result.row_count - all = result.rows_iter() - for row in all: - print(row) - result.close() - assert(result.row_count == 2) - - # error test - lines = [ - ',t1=3i64,t2=4f64,t3="t3" c1=3i64,c3=L"passit",c2=false,c4=4f64 1626006833639000000', - ] - try: - res = conn.schemaless_insert(lines, 1, 0) - print(res) - # assert(False) - except SchemalessError as err: - pass - - result = conn.query("select * from st") - result.row_count - all = result.rows_iter() - for row in all: - print(row) - result.close() - - conn.execute("drop database if exists %s" % dbname) - conn.close() - - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - print(err) - raise err - - -if __name__ == "__main__": - test_schemaless_insert(connect()) - test_schemaless_insert_update_2(connect()) diff --git a/src/connector/python/tests/test_query.py b/src/connector/python/tests/test_query.py deleted file mode 100644 index f4e139b1f14df29e8b6304dd2ca03519ea274f43..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_query.py +++ /dev/null @@ -1,43 +0,0 @@ -from datetime import datetime -import taos -import pytest - -@pytest.fixture -def conn(): - return taos.connect() - -def test_query(conn): - """This test will use fetch_block for rows fetching, significantly faster than rows_iter""" - result = conn.query("select * from log.log limit 10000") - fields = result.fields - for field in fields: - print("field: %s" % field) - start = datetime.now() - for row in result: - # print(row) - None - end = datetime.now() - elapsed = end - start - print("elapsed time: ", elapsed) - result.close() - conn.close() - -def test_query_row_iter(conn): - """This test will use fetch_row for each row fetching, this is the only way in async callback""" - result = conn.query("select * from log.log limit 10000") - fields = result.fields - for field in fields: - print("field: %s" % field) - start = datetime.now() - for row in result.rows_iter(): - # print(row) - None - end = datetime.now() - elapsed = end - start - print("elapsed time: ", elapsed) - result.close() - conn.close() - -if __name__ == "__main__": - test_query(taos.connect(database = "log")) - test_query_row_iter(taos.connect(database = "log")) diff --git a/src/connector/python/tests/test_query_a.py b/src/connector/python/tests/test_query_a.py deleted file mode 100644 index 2b4be5695a87f1fd1017435b13983df7c4f70f06..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_query_a.py +++ /dev/null @@ -1,66 +0,0 @@ -from taos import * -from ctypes import * -import taos -import pytest -import time - - -@pytest.fixture -def conn(): - return taos.connect() - -def fetch_callback(p_param, p_result, num_of_rows): - print("fetched ", num_of_rows, "rows") - p = cast(p_param, POINTER(Counter)) - result = TaosResult(p_result) - - if num_of_rows == 0: - print("fetching completed") - p.contents.done = True - result.close() - return - if num_of_rows < 0: - p.contents.done = True - result.check_error(num_of_rows) - result.close() - return None - - for row in result.rows_iter(num_of_rows): - # print(row) - None - p.contents.count += result.row_count - result.fetch_rows_a(fetch_callback, p_param) - - - -def query_callback(p_param, p_result, code): - # type: (c_void_p, c_void_p, c_int) -> None - if p_result == None: - return - result = TaosResult(p_result) - if code == 0: - result.fetch_rows_a(fetch_callback, p_param) - result.check_error(code) - - -class Counter(Structure): - _fields_ = [("count", c_int), ("done", c_bool)] - - def __str__(self): - return "{ count: %d, done: %s }" % (self.count, self.done) - - -def test_query(conn): - # type: (TaosConnection) -> None - counter = Counter(count=0) - conn.query_a("select * from log.log", query_callback, byref(counter)) - - while not counter.done: - print("wait query callback") - time.sleep(1) - print(counter) - conn.close() - - -if __name__ == "__main__": - test_query(taos.connect()) diff --git a/src/connector/python/tests/test_stmt.py b/src/connector/python/tests/test_stmt.py deleted file mode 100644 index 3368ecb6a9336a4295790f2cd55314ac9bb6290e..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_stmt.py +++ /dev/null @@ -1,150 +0,0 @@ -# encoding:UTF-8 -from taos import * - -from ctypes import * -from datetime import datetime -import taos -import pytest - -@pytest.fixture -def conn(): - # type: () -> taos.TaosConnection - return connect() - -def test_stmt_insert(conn): - # type: (TaosConnection) -> None - - dbname = "pytest_taos_stmt" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.select_db(dbname) - - conn.execute( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, ti tinyint, si smallint, ii int,\ - bi bigint, tu tinyint unsigned, su smallint unsigned, iu int unsigned, bu bigint unsigned, \ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", - ) - conn.load_table_info("log") - - - stmt = conn.statement("insert into log values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") - params = new_bind_params(16) - params[0].timestamp(1626861392589, PrecisionEnum.Milliseconds) - params[1].bool(True) - params[2].null() - params[3].tinyint(2) - params[4].smallint(3) - params[5].int(4) - params[6].bigint(5) - params[7].tinyint_unsigned(6) - params[8].smallint_unsigned(7) - params[9].int_unsigned(8) - params[10].bigint_unsigned(9) - params[11].float(10.1) - params[12].double(10.11) - params[13].binary("hello") - params[14].nchar("stmt") - params[15].timestamp(1626861392589, PrecisionEnum.Milliseconds) - - stmt.bind_param(params) - stmt.execute() - - result = stmt.use_result() - assert result.affected_rows == 1 - result.close() - stmt.close() - - stmt = conn.statement("select * from log") - stmt.execute() - result = stmt.use_result() - row = result.next() - print(row) - assert row[2] == None - for i in range(3, 11): - assert row[i] == i - 1 - #float == may not work as expected - # assert row[10] == c_float(10.1) - assert row[12] == 10.11 - assert row[13] == "hello" - assert row[14] == "stmt" - - conn.execute("drop database if exists %s" % dbname) - conn.close() - - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err - -def test_stmt_insert_multi(conn): - # type: (TaosConnection) -> None - - dbname = "pytest_taos_stmt_multi" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.select_db(dbname) - - conn.execute( - "create table if not exists log(ts timestamp, bo bool, nil tinyint, ti tinyint, si smallint, ii int,\ - bi bigint, tu tinyint unsigned, su smallint unsigned, iu int unsigned, bu bigint unsigned, \ - ff float, dd double, bb binary(100), nn nchar(100), tt timestamp)", - ) - conn.load_table_info("log") - - start = datetime.now() - stmt = conn.statement("insert into log values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") - - params = new_multi_binds(16) - params[0].timestamp((1626861392589, 1626861392590, 1626861392591)) - params[1].bool((True, None, False)) - params[2].tinyint([-128, -128, None]) # -128 is tinyint null - params[3].tinyint([0, 127, None]) - params[4].smallint([3, None, 2]) - params[5].int([3, 4, None]) - params[6].bigint([3, 4, None]) - params[7].tinyint_unsigned([3, 4, None]) - params[8].smallint_unsigned([3, 4, None]) - params[9].int_unsigned([3, 4, None]) - params[10].bigint_unsigned([3, 4, None]) - params[11].float([3, None, 1]) - params[12].double([3, None, 1.2]) - params[13].binary(["abc", "dddafadfadfadfadfa", None]) - params[14].nchar(["涛思数据", None, "a long string with 中文字符"]) - params[15].timestamp([None, None, 1626861392591]) - stmt.bind_param_batch(params) - - stmt.execute() - end = datetime.now() - print("elapsed time: ", end - start) - result = stmt.use_result() - assert result.affected_rows == 3 - result.close() - stmt.close() - - stmt = conn.statement("select * from log") - stmt.execute() - result = stmt.use_result() - for row in result: - print(row) - result.close() - - stmt.close() - - # start = datetime.now() - # conn.query("insert into log values(1626861392660, true, NULL, 0, 3,3,3,3,3,3,3,3.0,3.0, 'abc','涛思数据',NULL)(1626861392661, true, NULL, 0, 3,3,3,3,3,3,3,3.0,3.0, 'abc','涛思数据',NULL)(1626861392662, true, NULL, 0, 3,3,3,3,3,3,3,3.0,3.0, 'abc','涛思数据',NULL)") - - # end = datetime.now() - # print("elapsed time: ", end - start) - - conn.execute("drop database if exists %s" % dbname) - conn.close() - - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err -if __name__ == "__main__": - test_stmt_insert(connect()) - test_stmt_insert_multi(connect()) \ No newline at end of file diff --git a/src/connector/python/tests/test_stream.py b/src/connector/python/tests/test_stream.py deleted file mode 100644 index 32ec4c5999c975be907cf69a42a04b5f4dd5d54c..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_stream.py +++ /dev/null @@ -1,71 +0,0 @@ -from taos.cinterface import * -from taos.precision import * -from taos.bind import * -from taos import * -from ctypes import * -import time -import pytest - - -@pytest.fixture -def conn(): - return connect() - - -def stream_callback(p_param, p_result, p_row): - # type: (c_void_p, c_void_p, c_void_p) -> None - - if p_result == None or p_row == None: - return - result = TaosResult(p_result) - row = TaosRow(result, p_row) - try: - ts, count = row.as_tuple() - print(ts, count) - p = cast(p_param, POINTER(Counter)) - p.contents.count += count - print("[%s] inserted %d in 5s, total count: %d" % (ts.strftime("%Y-%m-%d %H:%M:%S"), count, p.contents.count)) - - except Exception as err: - print(err) - raise err - - -class Counter(ctypes.Structure): - _fields_ = [ - ("count", c_int), - ] - - def __str__(self): - return "%d" % self.count - - -def test_stream(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_stream" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.select_db(dbname) - conn.execute("create table if not exists log(ts timestamp, n int)") - - result = conn.query("select count(*) from log interval(5s)") - assert result.field_count == 2 - counter = Counter() - counter.count = 0 - stream = conn.stream("select count(*) from log interval(5s)", stream_callback, param=byref(counter)) - - for _ in range(0, 20): - conn.execute("insert into log values(now,0)(now+1s, 1)(now + 2s, 2)") - time.sleep(2) - stream.close() - conn.execute("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err - - -if __name__ == "__main__": - test_stream(connect()) diff --git a/src/connector/python/tests/test_subscribe.py b/src/connector/python/tests/test_subscribe.py deleted file mode 100644 index d8acd60e4f3b32bb87a9663b3f7dc43a73f2877b..0000000000000000000000000000000000000000 --- a/src/connector/python/tests/test_subscribe.py +++ /dev/null @@ -1,100 +0,0 @@ -from taos.subscription import TaosSubscription -from taos import * -from ctypes import * -import taos -import pytest -import time -from random import random - - -@pytest.fixture -def conn(): - return taos.connect() - - -def test_subscribe(conn): - # type: (TaosConnection) -> None - - dbname = "pytest_taos_subscribe_callback" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.select_db(dbname) - conn.execute("create table if not exists log(ts timestamp, n int)") - for i in range(10): - conn.execute("insert into log values(now, %d)" % i) - - sub = conn.subscribe(True, "test", "select * from log", 1000) - print("# consume from begin") - for ts, n in sub.consume(): - print(ts, n) - - print("# consume new data") - for i in range(5): - conn.execute("insert into log values(now, %d)(now+1s, %d)" % (i, i)) - result = sub.consume() - for ts, n in result: - print(ts, n) - - print("# consume with a stop condition") - for i in range(10): - conn.execute("insert into log values(now, %d)" % int(random() * 10)) - result = sub.consume() - try: - ts, n = next(result) - print(ts, n) - if n > 5: - result.stop_query() - print("## stopped") - break - except StopIteration: - continue - - sub.close() - - conn.execute("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err - - -def subscribe_callback(p_sub, p_result, p_param, errno): - # type: (c_void_p, c_void_p, c_void_p, c_int) -> None - print("callback") - result = TaosResult(c_void_p(p_result)) - result.check_error(errno) - for row in result.rows_iter(): - ts, n = row() - print(ts, n) - - -def test_subscribe_callback(conn): - # type: (TaosConnection) -> None - dbname = "pytest_taos_subscribe_callback" - try: - conn.execute("drop database if exists %s" % dbname) - conn.execute("create database if not exists %s" % dbname) - conn.execute("use %s" % dbname) - conn.execute("create table if not exists log(ts timestamp, n int)") - - print("# subscribe with callback") - sub = conn.subscribe(False, "test", "select * from log", 1000, subscribe_callback) - - for i in range(10): - conn.execute("insert into log values(now, %d)" % i) - time.sleep(0.7) - sub.close() - - conn.execute("drop database if exists %s" % dbname) - conn.close() - except Exception as err: - conn.execute("drop database if exists %s" % dbname) - conn.close() - raise err - - -if __name__ == "__main__": - test_subscribe(taos.connect()) - test_subscribe_callback(taos.connect()) diff --git a/src/dnode/src/dnodeMain.c b/src/dnode/src/dnodeMain.c index 0580761de1c8768ed6fdb1c8f3ea6c7b4fa0836b..b58b198fa225af7895cb02e37ef568016bb08eca 100644 --- a/src/dnode/src/dnodeMain.c +++ b/src/dnode/src/dnodeMain.c @@ -173,7 +173,7 @@ int32_t dnodeInitSystem() { dnodeInitTmr(); if (dnodeCreateDir(tsLogDir) < 0) { - printf("failed to create dir: %s, reason: %s\n", tsLogDir, strerror(errno)); + printf("failed to initialize dir: %s, reason: %s\n", tsLogDir, strerror(errno)); return -1; } @@ -261,7 +261,7 @@ static int32_t dnodeInitStorage() { // storage module init if (tsDiskCfgNum == 1 && dnodeCreateDir(tsDataDir) < 0) { - dError("failed to create dir: %s, reason: %s", tsDataDir, strerror(errno)); + dError("failed to initialize dir: %s, reason: %s", tsDataDir, strerror(errno)); return -1; } diff --git a/src/inc/taosdef.h b/src/inc/taosdef.h index 8f31e1860fe2a1fa08b3eb65466a0f23b656f95d..436f6cc3abcd8b062d81810b0c426c3e7cf9c167 100644 --- a/src/inc/taosdef.h +++ b/src/inc/taosdef.h @@ -276,7 +276,17 @@ do { \ #define TSDB_MAX_REPLICA 5 -#define TSDB_TBNAME_COLUMN_INDEX (-1) +#define TSDB_TBNAME_COLUMN_INDEX (-1) +#define TSDB_TSWIN_START_COLUMN_INDEX (-2) +#define TSDB_TSWIN_STOP_COLUMN_INDEX (-3) +#define TSDB_TSWIN_DURATION_COLUMN_INDEX (-4) +#define TSDB_QUERY_START_COLUMN_INDEX (-5) +#define TSDB_QUERY_STOP_COLUMN_INDEX (-6) +#define TSDB_QUERY_DURATION_COLUMN_INDEX (-7) +#define TSDB_MIN_VALID_COLUMN_INDEX (-7) + +#define TSDB_COL_IS_TSWIN_COL(_i) ((_i) <= TSDB_TSWIN_START_COLUMN_INDEX && (_i) >= TSDB_QUERY_DURATION_COLUMN_INDEX) + #define TSDB_UD_COLUMN_INDEX (-1000) #define TSDB_RES_COL_ID (-5000) diff --git a/src/kit/shell/src/shellEngine.c b/src/kit/shell/src/shellEngine.c index e74d81cc59ad58e28eefb94008ea1fd2411625f2..53101483099f40c1ce0cbbb1a94f20b46ca391af 100644 --- a/src/kit/shell/src/shellEngine.c +++ b/src/kit/shell/src/shellEngine.c @@ -565,6 +565,9 @@ static void shellPrintNChar(const char *str, int length, int width) { if (bytes <= 0) { break; } + if (pos + bytes > length) { + break; + } int w = 0; #ifdef WINDOWS w = bytes; @@ -575,15 +578,11 @@ static void shellPrintNChar(const char *str, int length, int width) { w = wcwidth(wc); } #endif + pos += bytes; if (w <= 0) { continue; } - pos += bytes; - if (pos > length) { - break; - } - if (width <= 0) { printf("%lc", wc); continue; diff --git a/src/kit/shell/src/shellLinux.c b/src/kit/shell/src/shellLinux.c index a78590aab8351451585204e0540998082a54a9a7..fb9de558956795513f954119cdb404b116e1c49d 100644 --- a/src/kit/shell/src/shellLinux.c +++ b/src/kit/shell/src/shellLinux.c @@ -48,10 +48,10 @@ static struct argp_option options[] = { {"check", 'k', "CHECK", 0, "Check tables."}, {"database", 'd', "DATABASE", 0, "Database to use when connecting to the server."}, {"timezone", 'z', "TIMEZONE", 0, "Time zone of the shell, default is local."}, - {"netrole", 'n', "NETROLE", 0, "Net role when network connectivity test, default is startup, options: client|server|rpc|startup|sync|speen|fqdn."}, + {"netrole", 'n', "NETROLE", 0, "Net role when network connectivity test, default is startup, options: client|server|rpc|startup|sync|speed|fqdn."}, {"pktlen", 'l', "PKTLEN", 0, "Packet length used for net test, default is 1000 bytes."}, {"pktnum", 'N', "PKTNUM", 0, "Packet numbers used for net test, default is 100."}, - {"pkttype", 'S', "PKTTYPE", 0, "Packet type used for net test, default is TCP."}, + {"pkttype", 'S', "PKTTYPE", 0, "Choose packet type used for net test, default is TCP. Only speed test could be either TCP or UDP."}, {0}}; static error_t parse_opt(int key, char *arg, struct argp_state *state) { diff --git a/src/kit/taos-tools b/src/kit/taos-tools index e15409c5184167a96a9fe9ade026387073443d2f..e8108de4dd12e82f7d5896282227da7557f8dac2 160000 --- a/src/kit/taos-tools +++ b/src/kit/taos-tools @@ -1 +1 @@ -Subproject commit e15409c5184167a96a9fe9ade026387073443d2f +Subproject commit e8108de4dd12e82f7d5896282227da7557f8dac2 diff --git a/src/mnode/src/mnodeDnode.c b/src/mnode/src/mnodeDnode.c index c9ea2f1af4be64d5301e77e44f30d2f7f7833dd3..93d754d70dfd90efbf166497e309a2659bc1c1a3 100644 --- a/src/mnode/src/mnodeDnode.c +++ b/src/mnode/src/mnodeDnode.c @@ -84,6 +84,9 @@ static char* offlineReason[] = { "timezone not match", "locale not match", "charset not match", + "flowctrl not match", + "slaveQuery not match", + "adjustMaster not match", "unknown", }; @@ -1249,7 +1252,10 @@ static int32_t mnodeRetrieveVnodes(SShowObj *pShow, char *data, int32_t rows, vo char * pWrite; int32_t cols = 0; - if (0 == rows) return 0; + if (0 == rows) { + pShow->pIter = NULL; + return 0; + } pDnode = (SDnodeObj *)(pShow->pIter); if (pDnode != NULL) { diff --git a/src/mnode/src/mnodeShow.c b/src/mnode/src/mnodeShow.c index bebb73eca2c48b8920bcbdc6a22e70aaf509046f..169cd10b7e0bda62eb75c38e8ec241e6b9a76c40 100644 --- a/src/mnode/src/mnodeShow.c +++ b/src/mnode/src/mnodeShow.c @@ -121,7 +121,7 @@ static int32_t mnodeProcessShowMsg(SMnodeMsg *pMsg) { } if (!tsMnodeShowMetaFp[pShowMsg->type] || !tsMnodeShowRetrieveFp[pShowMsg->type]) { - mWarn("show type:%s is not support", mnodeGetShowType(pShowMsg->type)); + mWarn("show type:%s is not supported", mnodeGetShowType(pShowMsg->type)); return TSDB_CODE_COM_OPS_NOT_SUPPORT; } diff --git a/src/os/inc/osSysinfo.h b/src/os/inc/osSysinfo.h index e2408058f068165506c7e6ffbc6e4ec3dee9a93c..31de826eed359b4245a2bc819acf32e934c4b129 100644 --- a/src/os/inc/osSysinfo.h +++ b/src/os/inc/osSysinfo.h @@ -41,7 +41,6 @@ bool taosGetProcMemory(float *memoryUsedMB) ; bool taosGetSysMemory(float *memoryUsedMB); void taosPrintOsInfo(); void taosPrintDiskInfo(); -int taosSystem(const char * cmd) ; void taosKillSystem(); bool taosGetSystemUid(char *uid); char *taosGetCmdlineByPID(int pid); diff --git a/src/os/src/detail/osSysinfo.c b/src/os/src/detail/osSysinfo.c index 06c58d43067ce5941975f97c169a2718640bac2a..ba3301747c9cc862bad85664311dca1eb4bcfa92 100644 --- a/src/os/src/detail/osSysinfo.c +++ b/src/os/src/detail/osSysinfo.c @@ -605,33 +605,6 @@ void taosKillSystem() { kill(tsProcId, 2); } -int taosSystem(const char *cmd) { - FILE *fp; - int res; - char buf[1024]; - if (cmd == NULL) { - uError("taosSystem cmd is NULL!"); - return -1; - } - - if ((fp = popen(cmd, "r")) == NULL) { - uError("popen cmd:%s error: %s", cmd, strerror(errno)); - return -1; - } else { - while (fgets(buf, sizeof(buf), fp)) { - uDebug("popen result:%s", buf); - } - - if ((res = pclose(fp)) == -1) { - uError("close popen file pointer fp error!"); - } else { - uDebug("popen res is :%d", res); - } - - return res; - } -} - void taosSetCoreDump() { if (0 == tsEnableCoreFile) { return; diff --git a/src/os/src/detail/osTime.c b/src/os/src/detail/osTime.c index fb8c2a5ae6e469545e3f1439fb1cc02fdb234e51..1575b3100f78a17b9bbe9dcb29b971054c55b294 100644 --- a/src/os/src/detail/osTime.c +++ b/src/os/src/detail/osTime.c @@ -83,16 +83,10 @@ void deltaToUtcInitOnce() { static int64_t parseFraction(char* str, char** end, int32_t timePrec); static int32_t parseTimeWithTz(char* timestr, int64_t* time, int32_t timePrec, char delim); -static int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec, char delim); -static int32_t parseLocaltimeWithDst(char* timestr, int64_t* time, int32_t timePrec, char delim); +static int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec, char delim, bool withDST); static char* forwardToTimeStringEnd(char* str); static bool checkTzPresent(char *str, int32_t len); -static int32_t (*parseLocaltimeFp[]) (char* timestr, int64_t* time, int32_t timePrec, char delim) = { - parseLocaltime, - parseLocaltimeWithDst -}; - int32_t taosGetTimestampSec() { return (int32_t)time(NULL); } int32_t taosParseTime(char* timestr, int64_t* time, int32_t len, int32_t timePrec, int8_t day_light) { @@ -101,13 +95,13 @@ int32_t taosParseTime(char* timestr, int64_t* time, int32_t len, int32_t timePre if (checkTzPresent(timestr, len)) { return parseTimeWithTz(timestr, time, timePrec, 'T'); } else { - return (*parseLocaltimeFp[day_light])(timestr, time, timePrec, 'T'); + return parseLocaltime(timestr, time, timePrec, 'T', day_light); } } else { if (checkTzPresent(timestr, len)) { return parseTimeWithTz(timestr, time, timePrec, 0); } else { - return (*parseLocaltimeFp[day_light])(timestr, time, timePrec, 0); + return parseLocaltime(timestr, time, timePrec, 0, day_light); } } } @@ -322,9 +316,12 @@ int32_t parseTimeWithTz(char* timestr, int64_t* time, int32_t timePrec, char del return 0; } -int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec, char delim) { +int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec, char delim, bool withDST) { *time = 0; struct tm tm = {0}; + if (withDST) { + tm.tm_isdst = -1; + } char* str; if (delim == 'T') { @@ -336,7 +333,11 @@ int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec, char deli } if (str == NULL) { - return -1; + //if parse failed, try "%Y-%m-%d" format + str = strptime(timestr, "%Y-%m-%d", &tm); + if (str == NULL) { + return -1; + } } #ifdef _MSC_VER @@ -345,45 +346,14 @@ int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec, char deli #endif #endif - int64_t seconds = user_mktime64(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, timezone); - - int64_t fraction = 0; - - if (*str == '.') { - /* parse the second fraction part */ - if ((fraction = parseFraction(str + 1, &str, timePrec)) < 0) { - return -1; - } - } - - int64_t factor = (timePrec == TSDB_TIME_PRECISION_MILLI) ? 1000 : - (timePrec == TSDB_TIME_PRECISION_MICRO ? 1000000 : 1000000000); - *time = factor * seconds + fraction; - - return 0; -} - -int32_t parseLocaltimeWithDst(char* timestr, int64_t* time, int32_t timePrec, char delim) { - *time = 0; - struct tm tm = {0}; - tm.tm_isdst = -1; - - char* str; - if (delim == 'T') { - str = strptime(timestr, "%Y-%m-%dT%H:%M:%S", &tm); - } else if (delim == 0) { - str = strptime(timestr, "%Y-%m-%d %H:%M:%S", &tm); + int64_t seconds; + if (!withDST) { + seconds = user_mktime64(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, timezone); } else { - str = NULL; + /* mktime will be affected by TZ, set by using taos_options */ + seconds = mktime(&tm); } - if (str == NULL) { - return -1; - } - - /* mktime will be affected by TZ, set by using taos_options */ - int64_t seconds = mktime(&tm); - int64_t fraction = 0; if (*str == '.') { @@ -396,6 +366,7 @@ int32_t parseLocaltimeWithDst(char* timestr, int64_t* time, int32_t timePrec, ch int64_t factor = (timePrec == TSDB_TIME_PRECISION_MILLI) ? 1000 : (timePrec == TSDB_TIME_PRECISION_MICRO ? 1000000 : 1000000000); *time = factor * seconds + fraction; + return 0; } diff --git a/src/os/src/windows/wString.c b/src/os/src/windows/wString.c index 96a604ae6e3bfb2088a376894c7083a9514ae67f..1d7cfd9af19a73ea2f56530eac3d33493c25c699 100644 --- a/src/os/src/windows/wString.c +++ b/src/os/src/windows/wString.c @@ -93,9 +93,9 @@ int32_t twcslen(const wchar_t *wcs) { } int32_t tasoUcs4Compare(void *f1_ucs4, void *f2_ucs4, int32_t bytes) { - for (int32_t i = 0; i < bytes; ++i) { - int32_t f1 = *(int32_t *)((char *)f1_ucs4 + i * 4); - int32_t f2 = *(int32_t *)((char *)f2_ucs4 + i * 4); + for (int32_t i = 0; i < bytes; i += TSDB_NCHAR_SIZE) { + int32_t f1 = *(int32_t *)((char *)f1_ucs4 + i); + int32_t f2 = *(int32_t *)((char *)f2_ucs4 + i); if ((f1 == 0 && f2 != 0) || (f1 != 0 && f2 == 0)) { return f1 - f2; diff --git a/src/os/src/windows/wSysinfo.c b/src/os/src/windows/wSysinfo.c index 46a75e9a00aea994c44b64d0d3e2bd854643ae1d..d1dada0b1de196f7e0f8d4159a691eece7353ae9 100644 --- a/src/os/src/windows/wSysinfo.c +++ b/src/os/src/windows/wSysinfo.c @@ -259,11 +259,6 @@ void taosKillSystem() { exit(0); } -int taosSystem(const char *cmd) { - uError("taosSystem not support"); - return -1; -} - int flock(int fd, int option) { return 0; } LONG WINAPI FlCrashDump(PEXCEPTION_POINTERS ep) { diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt index 6ac3878df901923ed5a5fcc77fe6d63969be3a59..097e7215d7c7abf01e459e6129ca0c445246dfa0 100644 --- a/src/plugins/CMakeLists.txt +++ b/src/plugins/CMakeLists.txt @@ -59,13 +59,16 @@ ELSE () CONFIGURE_COMMAND cmake -E echo "taosadapter no need cmake to config" PATCH_COMMAND COMMAND git clean -f -d - BUILD_COMMAND CGO_CFLAGS=-I${CMAKE_CURRENT_SOURCE_DIR}/../inc CGO_LDFLAGS=-L${CMAKE_BINARY_DIR}/build/lib go build -ldflags "-s -w -X github.com/taosdata/taosadapter/version.Version=${taos_version} -X github.com/taosdata/taosadapter/version.CommitID=${taosadapter_commit_sha1}" + BUILD_COMMAND + COMMAND CGO_CFLAGS=-I${CMAKE_CURRENT_SOURCE_DIR}/../inc CGO_LDFLAGS=-L${CMAKE_BINARY_DIR}/build/lib go build -ldflags "-s -w -X github.com/taosdata/taosadapter/version.Version=${taos_version} -X github.com/taosdata/taosadapter/version.CommitID=${taosadapter_commit_sha1}" + COMMAND CGO_CFLAGS=-I${CMAKE_CURRENT_SOURCE_DIR}/../inc CGO_LDFLAGS=-L${CMAKE_BINARY_DIR}/build/lib go build -o taosadapter-debug -ldflags "-X github.com/taosdata/taosadapter/version.Version=${taos_version} -X github.com/taosdata/taosadapter/version.CommitID=${taosadapter_commit_sha1}" INSTALL_COMMAND COMMAND curl -sL https://github.com/upx/upx/releases/download/v3.96/upx-3.96-${PLATFORM_ARCH_STR}_linux.tar.xz -o upx.tar.xz && tar -xvJf upx.tar.xz -C ${CMAKE_BINARY_DIR} --strip-components 1 > /dev/null && ${CMAKE_BINARY_DIR}/upx taosadapter || : COMMAND cmake -E copy taosadapter ${CMAKE_BINARY_DIR}/build/bin COMMAND cmake -E make_directory ${CMAKE_BINARY_DIR}/test/cfg/ COMMAND cmake -E copy ./example/config/taosadapter.toml ${CMAKE_BINARY_DIR}/test/cfg/ COMMAND cmake -E copy ./taosadapter.service ${CMAKE_BINARY_DIR}/test/cfg/ + COMMAND cmake -E copy taosadapter-debug ${CMAKE_BINARY_DIR}/build/bin ) ELSEIF (TD_DARWIN) include(ExternalProject) @@ -78,12 +81,15 @@ ELSE () CONFIGURE_COMMAND cmake -E echo "taosadapter no need cmake to config" PATCH_COMMAND COMMAND git clean -f -d - BUILD_COMMAND CGO_CFLAGS=-I${CMAKE_CURRENT_SOURCE_DIR}/../inc CGO_LDFLAGS=-L${CMAKE_BINARY_DIR}/build/lib go build -ldflags "-s -w -X github.com/taosdata/taosadapter/version.Version=${taos_version} -X github.com/taosdata/taosadapter/version.CommitID=${taosadapter_commit_sha1}" + BUILD_COMMAND + COMMAND CGO_CFLAGS=-I${CMAKE_CURRENT_SOURCE_DIR}/../inc CGO_LDFLAGS=-L${CMAKE_BINARY_DIR}/build/lib go build -ldflags "-s -w -X github.com/taosdata/taosadapter/version.Version=${taos_version} -X github.com/taosdata/taosadapter/version.CommitID=${taosadapter_commit_sha1}" + COMMAND CGO_CFLAGS=-I${CMAKE_CURRENT_SOURCE_DIR}/../inc CGO_LDFLAGS=-L${CMAKE_BINARY_DIR}/build/lib go build -o taosadapter-debug -ldflags "-X github.com/taosdata/taosadapter/version.Version=${taos_version} -X github.com/taosdata/taosadapter/version.CommitID=${taosadapter_commit_sha1}" INSTALL_COMMAND COMMAND cmake -E copy taosadapter ${CMAKE_BINARY_DIR}/build/bin COMMAND cmake -E make_directory ${CMAKE_BINARY_DIR}/test/cfg/ COMMAND cmake -E copy ./example/config/taosadapter.toml ${CMAKE_BINARY_DIR}/test/cfg/ COMMAND cmake -E copy ./taosadapter.service ${CMAKE_BINARY_DIR}/test/cfg/ + COMMAND cmake -E copy taosadapter-debug ${CMAKE_BINARY_DIR}/build/bin ) ELSE () MESSAGE("${Yellow} Windows system still use original embedded httpd ${ColourReset}") diff --git a/src/plugins/http/src/httpParser.c b/src/plugins/http/src/httpParser.c index f3eaabf704dfc2949f2d321441a3f46f7a793eb4..7c68e6c98ea27c7156c508686f154eb2a1842c73 100644 --- a/src/plugins/http/src/httpParser.c +++ b/src/plugins/http/src/httpParser.c @@ -186,7 +186,7 @@ static int32_t httpOnRequestLine(HttpParser *pParser, char *method, char *target if (pContext->decodeMethod != NULL) { httpTrace("context:%p, fd:%d, decode method is %s", pContext, pContext->fd, pContext->decodeMethod->module); } else { - httpError("context:%p, fd:%d, the url is not support, target:%s", pContext, pContext->fd, target); + httpError("context:%p, fd:%d, the url is not supported, target:%s", pContext, pContext->fd, target); httpOnError(pParser, 0, TSDB_CODE_HTTP_UNSUPPORT_URL); return -1; } diff --git a/src/plugins/http/src/httpUtil.c b/src/plugins/http/src/httpUtil.c index f30ac7326eef20f4abf5558b288f16f6ee313b42..c49d561e2b552bd6dfdeb2a7d161da5ad75d3628 100644 --- a/src/plugins/http/src/httpUtil.c +++ b/src/plugins/http/src/httpUtil.c @@ -350,10 +350,10 @@ int32_t httpShrinkTableName(HttpContext *pContext, int32_t pos, char *name) { return pos; } - MD5_CTX context; - MD5Init(&context); - MD5Update(&context, (uint8_t *)name, (uint32_t)len); - MD5Final(&context); + T_MD5_CTX context; + tMD5Init(&context); + tMD5Update(&context, (uint8_t *)name, (uint32_t)len); + tMD5Final(&context); int32_t table_name = httpAddToSqlCmdBuffer( pContext, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", context.digest[0], diff --git a/src/plugins/taosadapter b/src/plugins/taosadapter index 09807060e5f6f4353a31e135521cd4d1f11df7ae..f005d7bd83f8509716c07d126f374f1ed2bc59f2 160000 --- a/src/plugins/taosadapter +++ b/src/plugins/taosadapter @@ -1 +1 @@ -Subproject commit 09807060e5f6f4353a31e135521cd4d1f11df7ae +Subproject commit f005d7bd83f8509716c07d126f374f1ed2bc59f2 diff --git a/src/query/inc/qAggMain.h b/src/query/inc/qAggMain.h index ae5574888fadf262ddf8fa5018ae0a9e530c16da..8c650f11d833d0360471f48ef86b476174179e6e 100644 --- a/src/query/inc/qAggMain.h +++ b/src/query/inc/qAggMain.h @@ -30,59 +30,68 @@ extern "C" { #include "tsdb.h" #include "qUdf.h" -#define TSDB_FUNC_INVALID_ID -1 -#define TSDB_FUNC_COUNT 0 -#define TSDB_FUNC_SUM 1 -#define TSDB_FUNC_AVG 2 -#define TSDB_FUNC_MIN 3 -#define TSDB_FUNC_MAX 4 -#define TSDB_FUNC_STDDEV 5 -#define TSDB_FUNC_PERCT 6 -#define TSDB_FUNC_APERCT 7 -#define TSDB_FUNC_FIRST 8 -#define TSDB_FUNC_LAST 9 -#define TSDB_FUNC_LAST_ROW 10 -#define TSDB_FUNC_TOP 11 -#define TSDB_FUNC_BOTTOM 12 -#define TSDB_FUNC_SPREAD 13 -#define TSDB_FUNC_TWA 14 -#define TSDB_FUNC_LEASTSQR 15 - -#define TSDB_FUNC_TS 16 -#define TSDB_FUNC_TS_DUMMY 17 -#define TSDB_FUNC_TAG_DUMMY 18 -#define TSDB_FUNC_TS_COMP 19 - -#define TSDB_FUNC_TAG 20 -#define TSDB_FUNC_PRJ 21 - -#define TSDB_FUNC_TAGPRJ 22 -#define TSDB_FUNC_SCALAR_EXPR 23 -#define TSDB_FUNC_DIFF 24 - -#define TSDB_FUNC_FIRST_DST 25 -#define TSDB_FUNC_LAST_DST 26 -#define TSDB_FUNC_STDDEV_DST 27 -#define TSDB_FUNC_INTERP 28 - -#define TSDB_FUNC_RATE 29 -#define TSDB_FUNC_IRATE 30 -#define TSDB_FUNC_TID_TAG 31 -#define TSDB_FUNC_DERIVATIVE 32 - -#define TSDB_FUNC_CSUM 33 -#define TSDB_FUNC_MAVG 34 -#define TSDB_FUNC_SAMPLE 35 - -#define TSDB_FUNC_BLKINFO 36 - -#define TSDB_FUNC_ELAPSED 37 -#define TSDB_FUNC_HISTOGRAM 38 -#define TSDB_FUNC_UNIQUE 39 -#define TSDB_FUNC_MODE 40 -#define TSDB_FUNC_TAIL 41 - -#define TSDB_FUNC_MAX_NUM 42 +#define TSDB_FUNC_INVALID_ID -1 +#define TSDB_FUNC_COUNT 0 +#define TSDB_FUNC_SUM 1 +#define TSDB_FUNC_AVG 2 +#define TSDB_FUNC_MIN 3 +#define TSDB_FUNC_MAX 4 +#define TSDB_FUNC_STDDEV 5 +#define TSDB_FUNC_PERCT 6 +#define TSDB_FUNC_APERCT 7 +#define TSDB_FUNC_FIRST 8 +#define TSDB_FUNC_LAST 9 +#define TSDB_FUNC_LAST_ROW 10 +#define TSDB_FUNC_TOP 11 +#define TSDB_FUNC_BOTTOM 12 +#define TSDB_FUNC_SPREAD 13 +#define TSDB_FUNC_TWA 14 +#define TSDB_FUNC_LEASTSQR 15 + +#define TSDB_FUNC_TS 16 +#define TSDB_FUNC_TS_DUMMY 17 +#define TSDB_FUNC_TAG_DUMMY 18 +#define TSDB_FUNC_TS_COMP 19 + +#define TSDB_FUNC_TAG 20 +#define TSDB_FUNC_PRJ 21 + +#define TSDB_FUNC_TAGPRJ 22 +#define TSDB_FUNC_SCALAR_EXPR 23 +#define TSDB_FUNC_DIFF 24 + +#define TSDB_FUNC_FIRST_DST 25 +#define TSDB_FUNC_LAST_DST 26 +#define TSDB_FUNC_STDDEV_DST 27 +#define TSDB_FUNC_INTERP 28 + +#define TSDB_FUNC_RATE 29 +#define TSDB_FUNC_IRATE 30 +#define TSDB_FUNC_TID_TAG 31 +#define TSDB_FUNC_DERIVATIVE 32 + +#define TSDB_FUNC_CSUM 33 +#define TSDB_FUNC_MAVG 34 +#define TSDB_FUNC_SAMPLE 35 + +#define TSDB_FUNC_BLKINFO 36 + +#define TSDB_FUNC_ELAPSED 37 +#define TSDB_FUNC_HISTOGRAM 38 +#define TSDB_FUNC_UNIQUE 39 +#define TSDB_FUNC_MODE 40 +#define TSDB_FUNC_TAIL 41 +#define TSDB_FUNC_STATE_COUNT 42 +#define TSDB_FUNC_STATE_DURATION 43 +#define TSDB_FUNC_WSTART 44 +#define TSDB_FUNC_WSTOP 45 +#define TSDB_FUNC_WDURATION 46 +#define TSDB_FUNC_QSTART 47 +#define TSDB_FUNC_QSTOP 48 +#define TSDB_FUNC_QDURATION 49 +#define TSDB_FUNC_HYPERLOGLOG 50 + +#define TSDB_FUNC_MAX_NUM 51 #define TSDB_FUNCSTATE_SO 0x1u // single output #define TSDB_FUNCSTATE_MO 0x2u // dynamic number of output, not multinumber of output e.g., TOP/BOTTOM @@ -178,7 +187,7 @@ typedef struct SQLFunctionCtx { uint32_t order; // asc|desc int16_t inputType; int32_t inputBytes; - + int16_t outputType; int32_t outputBytes; // size of results, determined by function and input column data type int32_t interBufBytes; // internal buffer size @@ -206,6 +215,8 @@ typedef struct SQLFunctionCtx { SHashObj **pUniqueSet; // for unique function SHashObj **pModeSet; // for mode function + STimeWindow qWindow; // for _qstart/_qstop/_qduration column + int32_t allocRows; // rows allocated for output buffer } SQLFunctionCtx; typedef struct SAggFunctionInfo { @@ -228,7 +239,12 @@ typedef struct SAggFunctionInfo { int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionId, int32_t param, int16_t *type, int32_t *len, int32_t *interBytes, int16_t extLength, bool isSuperTable, SUdfInfo* pUdfInfo); +int16_t getTimeWindowFunctionID(int16_t colIndex); + +bool isTimeWindowFunction(int32_t functionId); int32_t isValidFunction(const char* name, int32_t len); +bool isValidStateOper(char *oper, int32_t len); + #define IS_STREAM_QUERY_VALID(x) (((x)&TSDB_FUNCSTATE_STREAM) != 0) #define IS_MULTIOUTPUT(x) (((x)&TSDB_FUNCSTATE_MO) != 0) diff --git a/src/query/inc/qExecutor.h b/src/query/inc/qExecutor.h index a8b781718cafa7fdb381205609e97ea6f96fd409..db92d8db891dc520582544651eb5f055dcd5839e 100644 --- a/src/query/inc/qExecutor.h +++ b/src/query/inc/qExecutor.h @@ -230,6 +230,7 @@ typedef struct SQueryAttr { bool stabledev; // super table stddev query bool tsCompQuery; // is tscomp query bool diffQuery; // is diff query + bool stateQuery; // is state query bool simpleAgg; bool pointInterpQuery; // point interpolation query bool needTableSeqScan; // need scan table by table diff --git a/src/query/inc/qExtbuffer.h b/src/query/inc/qExtbuffer.h index abcf11bfa54d1950edc7e42e8b76b0121fcc4c2c..e8533add9054a6e1e3ade394fdd26fe4ff5462f4 100644 --- a/src/query/inc/qExtbuffer.h +++ b/src/query/inc/qExtbuffer.h @@ -254,7 +254,7 @@ int32_t compare_d(tOrderDescriptor *, int32_t numOfRow1, int32_t s1, char *data1 struct SSDataBlock; int32_t compare_aRv(struct SSDataBlock* pBlock, SArray* colIndex, int32_t numOfCols, int32_t rowIndex, char** buffer, int32_t order); -int32_t columnValueAscendingComparator(char *f1, char *f2, int32_t type, int32_t bytes); +int32_t columnValueAscendingComparator(char *f1, char *f2, int32_t type, int32_t bytes, bool lenFirst); #ifdef __cplusplus } diff --git a/src/query/inc/qResultbuf.h b/src/query/inc/qResultbuf.h index c8779f8130ff9bfb63ae60fd823d2ae01529c092..5191ddab46411032e25f4663122b04931281b132 100644 --- a/src/query/inc/qResultbuf.h +++ b/src/query/inc/qResultbuf.h @@ -78,8 +78,8 @@ typedef struct SDiskbasedResultBuf { #define DEFAULT_INTERN_BUF_PAGE_SIZE (1024L) // in bytes #define PAGE_INFO_INITIALIZER (SPageDiskInfo){-1, -1} -#define MAX_UNIQUE_RESULT_ROWS (1000) -#define MAX_UNIQUE_RESULT_SIZE (1024*1024*1) +#define MAX_UNIQUE_RESULT_ROWS (10000) +#define MAX_UNIQUE_RESULT_SIZE (1024*1024*10) #define MAX_MODE_INNER_RESULT_ROWS (1000000) #define MAX_MODE_INNER_RESULT_SIZE (1024*1024*10) /** diff --git a/src/query/src/qAggMain.c b/src/query/src/qAggMain.c index 1657070fcf07ec33ae98085c1101f93bf02ea732..b9834b45b0d89c66e886365bd525001b995ca7a6 100644 --- a/src/query/src/qAggMain.c +++ b/src/query/src/qAggMain.c @@ -29,6 +29,7 @@ #include "queryLog.h" #include "qUdf.h" #include "tcompare.h" +#include "hashfunc.h" #define GET_INPUT_DATA_LIST(x) ((char *)((x)->pInput)) #define GET_INPUT_DATA(x, y) (GET_INPUT_DATA_LIST(x) + (y) * (x)->inputBytes) @@ -211,6 +212,14 @@ typedef struct { }; } SDiffFuncInfo; + +typedef struct { + union { + int64_t countPrev; + int64_t durationStart; + }; +} SStateInfo; + typedef struct { double lower; // >lower double upper; // <=upper @@ -248,11 +257,157 @@ typedef struct { char data[]; } TailUnit; -typedef struct STailInfo { +typedef struct { int32_t num; TailUnit **res; } STailInfo; +static void *getOutputInfo(SQLFunctionCtx *pCtx) { + SResultRowCellInfo *pResInfo = GET_RES_INFO(pCtx); + + // only the first_stage_merge is directly written data into final output buffer + if (pCtx->stableQuery && pCtx->currentStage != MERGE_STAGE) { + return pCtx->pOutput; + } else { // during normal table query and super table at the secondary_stage, result is written to intermediate buffer + return GET_ROWCELL_INTERBUF(pResInfo); + } +} + +/* hyperloglog start */ +#define HLL_BUCKET_BITS 14 // The bits of the bucket +#define HLL_DATA_BITS (64-HLL_BUCKET_BITS) +#define HLL_BUCKETS (1<>3; j++) { + if (*word == 0) { + bucketHisto[0] += 8; + } else { + bytes = (uint8_t*) word; + bucketHisto[bytes[0]]++; + bucketHisto[bytes[1]]++; + bucketHisto[bytes[2]]++; + bucketHisto[bytes[3]]++; + bucketHisto[bytes[4]]++; + bucketHisto[bytes[5]]++; + bucketHisto[bytes[6]]++; + bucketHisto[bytes[7]]++; + } + word++; + } +} +static double hllTau(double x) { + if (x == 0. || x == 1.) return 0.; + double zPrime; + double y = 1.0; + double z = 1 - x; + do { + x = sqrt(x); + zPrime = z; + y *= 0.5; + z -= pow(1 - x, 2)*y; + } while(zPrime != z); + return z / 3; +} + +static double hllSigma(double x) { + if (x == 1.0) return INFINITY; + double zPrime; + double y = 1; + double z = x; + do { + x *= x; + zPrime = z; + z += x * y; + y += y; + } while(zPrime != z); + return z; +} + +// estimate the cardinality, the algorithm refer this paper: "New cardinality estimation algorithms for HyperLogLog sketches" +static uint64_t hllCountCnt(uint8_t *buckets) { + double m = HLL_BUCKETS; + int32_t buckethisto[64] = {0}; + hllBucketHisto(buckets,buckethisto); + + double z = m * hllTau((m-buckethisto[HLL_DATA_BITS+1])/(double)m); + for (int j = HLL_DATA_BITS; j >= 1; --j) { + z += buckethisto[j]; + z *= 0.5; + } + z += m * hllSigma(buckethisto[0]/(double)m); + double E = (double)llroundl(HLL_ALPHA_INF*m*m/z); + + return (uint64_t) E; +} + +static uint8_t hllCountNum(void *ele, int32_t elesize, int32_t *buk) { + uint64_t hash = MurmurHash3_64(ele,elesize); + int32_t index = hash & HLL_BUCKET_MASK; + hash >>= HLL_BUCKET_BITS; + hash |= ((uint64_t)1<size; ++i) { + char *val = GET_INPUT_DATA(pCtx, i); + if (isNull(val, pCtx->inputType)) { + continue; + } + int32_t elesize = pCtx->inputBytes; + if(IS_VAR_DATA_TYPE(pCtx->inputType)) { + elesize = varDataLen(val); + val = varDataVal(val); + } + int32_t index = 0; + uint8_t count = hllCountNum(val,elesize,&index); + uint8_t oldcount = pHLLInfo->buckets[index]; + if (count > oldcount) { + pHLLInfo->buckets[index] = count; + } + } + GET_RES_INFO(pCtx)->numOfRes = 1; +} + +static void hll_func_merge(SQLFunctionCtx *pCtx) { + SResultRowCellInfo *pResInfo = GET_RES_INFO(pCtx); + SHLLInfo *pHLLInfo = (SHLLInfo *)GET_ROWCELL_INTERBUF(pResInfo); + + SHLLInfo *pData = (SHLLInfo *)GET_INPUT_DATA_LIST(pCtx); + for (int i = 0; i < HLL_BUCKETS; i++) { + if (pData->buckets[i] > pHLLInfo->buckets[i]) { + pHLLInfo->buckets[i] = pData->buckets[i]; + } + } +} + +static void hll_func_finalizer(SQLFunctionCtx *pCtx) { + SHLLInfo *pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)); + + GET_RES_INFO(pCtx)->numOfRes = 1; + *(uint64_t *)(pCtx->pOutput) = hllCountCnt(pInfo->buckets); + doFinalizer(pCtx); +} +/* hyperloglog end */ + int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionId, int32_t param, int16_t *type, int32_t *bytes, int32_t *interBytes, int16_t extLength, bool isSuperTable, SUdfInfo* pUdfInfo) { if (!isValidDataType(dataType)) { @@ -319,6 +474,13 @@ int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionI return TSDB_CODE_SUCCESS; } + if (functionId == TSDB_FUNC_STATE_COUNT || functionId == TSDB_FUNC_STATE_DURATION) { + *type = TSDB_DATA_TYPE_BIGINT; + *bytes = sizeof(int64_t); + *interBytes = sizeof(SStateInfo); + return TSDB_CODE_SUCCESS; + } + if (functionId == TSDB_FUNC_CSUM) { if (IS_SIGNED_NUMERIC_TYPE(dataType)) { *type = TSDB_DATA_TYPE_BIGINT; @@ -413,6 +575,11 @@ int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionI *bytes = (sizeof(STailInfo) + (sizeof(TailUnit) + dataBytes + POINTER_BYTES + extLength) * param); *interBytes = *bytes; + return TSDB_CODE_SUCCESS; + } else if (functionId == TSDB_FUNC_HYPERLOGLOG) { + *type = TSDB_DATA_TYPE_BINARY; + *bytes = sizeof(SHLLInfo); + *interBytes = sizeof(SHLLInfo); return TSDB_CODE_SUCCESS; } else if (functionId == TSDB_FUNC_SAMPLE) { *type = TSDB_DATA_TYPE_BINARY; @@ -569,11 +736,15 @@ int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionI // the output column may be larger than sizeof(STopBotInfo) *interBytes = (int32_t)size; + } else if (functionId == TSDB_FUNC_HYPERLOGLOG) { + *type = TSDB_DATA_TYPE_UBIGINT; + *bytes = sizeof(uint64_t); + *interBytes = sizeof(SHLLInfo); } else if (functionId == TSDB_FUNC_SAMPLE) { - *type = (int16_t)dataType; - *bytes = dataBytes; - size_t size = sizeof(SSampleFuncInfo) + dataBytes*param + sizeof(int64_t)*param + extLength*param; - *interBytes = (int32_t)size; + *type = (int16_t)dataType; + *bytes = dataBytes; + size_t size = sizeof(SSampleFuncInfo) + dataBytes*param + sizeof(int64_t)*param + extLength*param; + *interBytes = (int32_t)size; } else if (functionId == TSDB_FUNC_LAST_ROW) { *type = (int16_t)dataType; *bytes = dataBytes; @@ -598,6 +769,10 @@ int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionI return TSDB_CODE_SUCCESS; } +bool isTimeWindowFunction(int32_t functionId) { + return ((functionId >= TSDB_FUNC_WSTART) && (functionId <= TSDB_FUNC_QDURATION)); +} + // TODO use hash table int32_t isValidFunction(const char* name, int32_t len) { @@ -625,6 +800,76 @@ int32_t isValidFunction(const char* name, int32_t len) { return -1; } +bool isValidStateOper(char *oper, int32_t len){ + return strncmp(oper, "lt", len) == 0 || strncmp(oper, "gt", len) == 0 || strncmp(oper, "le", len) == 0 || + strncmp(oper, "ge", len) == 0 || strncmp(oper, "ne", len) == 0 || strncmp(oper, "eq", len) == 0; +} + +#define STATEOPER(OPER, COMP, TYPE) if (strncmp(oper->pz, OPER, oper->nLen) == 0) {\ +if (pVar->nType == TSDB_DATA_TYPE_BIGINT && *(TYPE)data COMP pVar->i64) return true;\ +else if(pVar->nType == TSDB_DATA_TYPE_DOUBLE && *(TYPE)data COMP pVar->dKey) return true;\ +else return false;} + +#define STATEJUDGE(TYPE) STATEOPER("lt", <, TYPE)\ +STATEOPER("gt", >, TYPE)\ +STATEOPER("le", <=, TYPE)\ +STATEOPER("ge", >=, TYPE)\ +STATEOPER("ne", !=, TYPE)\ +STATEOPER("eq", ==, TYPE) + +static bool isStateOperTrue(void *data, int16_t type, tVariant *oper, tVariant *pVar){ + switch (type) { + case TSDB_DATA_TYPE_INT: { + STATEJUDGE(int32_t *) + break; + } + case TSDB_DATA_TYPE_UINT: { + STATEJUDGE(uint32_t *) + break; + } + + case TSDB_DATA_TYPE_BIGINT: { + STATEJUDGE(int64_t *) + break; + }case TSDB_DATA_TYPE_UBIGINT: { + STATEJUDGE(uint64_t *) + break; + } + case TSDB_DATA_TYPE_DOUBLE: { + STATEJUDGE(double *) + break; + } + + case TSDB_DATA_TYPE_FLOAT: { + STATEJUDGE(float *) + break; + } + + case TSDB_DATA_TYPE_SMALLINT: { + STATEJUDGE(int16_t *) + break; + } + + case TSDB_DATA_TYPE_USMALLINT: { + STATEJUDGE(uint16_t *) + break; + } + + case TSDB_DATA_TYPE_TINYINT: { + STATEJUDGE(int8_t *) + break; + } + + case TSDB_DATA_TYPE_UTINYINT: { + STATEJUDGE(uint8_t *) + break; + } + default: + qError("error input type"); + } + return false; +} + static bool function_setup(SQLFunctionCtx *pCtx, SResultRowCellInfo* pResultInfo) { if (pResultInfo->initialized) { return false; @@ -2318,18 +2563,6 @@ static void copyTopBotRes(SQLFunctionCtx *pCtx, int32_t type) { tfree(pData); } -static void *getOutputInfo(SQLFunctionCtx *pCtx) { - SResultRowCellInfo *pResInfo = GET_RES_INFO(pCtx); - - // only the first_stage_merge is directly written data into final output buffer - if (pCtx->stableQuery && pCtx->currentStage != MERGE_STAGE) { - return pCtx->pOutput; - } else { // during normal table query and super table at the secondary_stage, result is written to intermediate buffer - return GET_ROWCELL_INTERBUF(pResInfo); - } -} - - /* * keep the intermediate results during scan data blocks in the format of: * +-----------------------------------+-------------one value pair-----------+------------next value pair-----------+ @@ -3414,23 +3647,24 @@ static void diff_function(SQLFunctionCtx *pCtx) { if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) { continue; } - if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) { - continue; - } if (pDiffInfo->valueAssigned) { - *pOutput = (int32_t)(pData[i] - pDiffInfo->i64Prev); // direct previous may be null - *pTimestamp = (tsList != NULL)? tsList[i]:0; - pOutput += 1; - pTimestamp += 1; + int32_t diff = (int32_t)(pData[i] - pDiffInfo->i64Prev); + if (diff >= 0 || !pDiffInfo->ignoreNegative) { + *pOutput = (int32_t)(pData[i] - pDiffInfo->i64Prev); // direct previous may be null + *pTimestamp = (tsList != NULL)? tsList[i]:0; + pOutput += 1; + pTimestamp += 1; + notNullElems++; + } } pDiffInfo->i64Prev = pData[i]; pDiffInfo->valueAssigned = true; - notNullElems++; } break; }; + case TSDB_DATA_TYPE_BIGINT: { int64_t *pData = (int64_t *)data; int64_t *pOutput = (int64_t *)pCtx->pOutput; @@ -3439,23 +3673,24 @@ static void diff_function(SQLFunctionCtx *pCtx) { if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) { continue; } - if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) { - continue; - } if (pDiffInfo->valueAssigned) { - *pOutput = pData[i] - pDiffInfo->i64Prev; // direct previous may be null - *pTimestamp = (tsList != NULL)? tsList[i]:0; - pOutput += 1; - pTimestamp += 1; + int64_t diff = pData[i] - pDiffInfo->i64Prev; + if (diff >= 0 || !pDiffInfo->ignoreNegative) { + *pOutput = pData[i] - pDiffInfo->i64Prev; // direct previous may be null + *pTimestamp = (tsList != NULL)? tsList[i]:0; + pOutput += 1; + pTimestamp += 1; + notNullElems++; + } } pDiffInfo->i64Prev = pData[i]; pDiffInfo->valueAssigned = true; - notNullElems++; } break; } + case TSDB_DATA_TYPE_DOUBLE: { double *pData = (double *)data; double *pOutput = (double *)pCtx->pOutput; @@ -3464,23 +3699,24 @@ static void diff_function(SQLFunctionCtx *pCtx) { if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) { continue; } - if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) { - continue; - } - if (pDiffInfo->valueAssigned) { // initial value is not set yet - SET_DOUBLE_VAL(pOutput, pData[i] - pDiffInfo->d64Prev); // direct previous may be null - *pTimestamp = (tsList != NULL)? tsList[i]:0; - pOutput += 1; - pTimestamp += 1; + if (pDiffInfo->valueAssigned) { + double diff = pData[i] - pDiffInfo->d64Prev; + if (diff >= 0 || !pDiffInfo->ignoreNegative) { + SET_DOUBLE_VAL(pOutput, pData[i] - pDiffInfo->d64Prev); // direct previous may be null + *pTimestamp = (tsList != NULL)? tsList[i]:0; + pOutput += 1; + pTimestamp += 1; + notNullElems++; + } } pDiffInfo->d64Prev = pData[i]; pDiffInfo->valueAssigned = true; - notNullElems++; } break; } + case TSDB_DATA_TYPE_FLOAT: { float *pData = (float *)data; float *pOutput = (float *)pCtx->pOutput; @@ -3489,23 +3725,24 @@ static void diff_function(SQLFunctionCtx *pCtx) { if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) { continue; } - if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) { - continue; - } - if (pDiffInfo->valueAssigned) { // initial value is not set yet - *pOutput = (float)(pData[i] - pDiffInfo->d64Prev); // direct previous may be null - *pTimestamp = (tsList != NULL)? tsList[i]:0; - pOutput += 1; - pTimestamp += 1; + if (pDiffInfo->valueAssigned) { + float diff = (float)(pData[i] - pDiffInfo->d64Prev); + if (diff >= 0 || !pDiffInfo->ignoreNegative) { + *pOutput = (float)(pData[i] - pDiffInfo->d64Prev); + *pTimestamp = (tsList != NULL)? tsList[i]:0; + pOutput += 1; + pTimestamp += 1; + notNullElems++; + } } pDiffInfo->d64Prev = pData[i]; pDiffInfo->valueAssigned = true; - notNullElems++; } break; } + case TSDB_DATA_TYPE_SMALLINT: { int16_t *pData = (int16_t *)data; int16_t *pOutput = (int16_t *)pCtx->pOutput; @@ -3514,20 +3751,20 @@ static void diff_function(SQLFunctionCtx *pCtx) { if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) { continue; } - if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) { - continue; - } - if (pDiffInfo->valueAssigned) { // initial value is not set yet - *pOutput = (int16_t)(pData[i] - pDiffInfo->i64Prev); // direct previous may be null - *pTimestamp = (tsList != NULL)? tsList[i]:0; - pOutput += 1; - pTimestamp += 1; + if (pDiffInfo->valueAssigned) { + int16_t diff = (int16_t)(pData[i] - pDiffInfo->i64Prev); + if (diff >= 0 || !pDiffInfo->ignoreNegative) { + *pOutput = (int16_t)(pData[i] - pDiffInfo->i64Prev); + *pTimestamp = (tsList != NULL)? tsList[i]:0; + pOutput += 1; + pTimestamp += 1; + notNullElems++; + } } pDiffInfo->i64Prev = pData[i]; pDiffInfo->valueAssigned = true; - notNullElems++; } break; } @@ -3540,23 +3777,24 @@ static void diff_function(SQLFunctionCtx *pCtx) { if (pCtx->hasNull && isNull((char *)&pData[i], pCtx->inputType)) { continue; } - if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) { - continue; - } - if (pDiffInfo->valueAssigned) { // initial value is not set yet - *pOutput = (int8_t)(pData[i] - pDiffInfo->i64Prev); // direct previous may be null - *pTimestamp = (tsList != NULL)? tsList[i]:0; - pOutput += 1; - pTimestamp += 1; + if (pDiffInfo->valueAssigned) { + int8_t diff = (int8_t)(pData[i] - pDiffInfo->i64Prev); + if (diff >= 0 || !pDiffInfo->ignoreNegative) { + *pOutput = (int8_t)(pData[i] - pDiffInfo->i64Prev); + *pTimestamp = (tsList != NULL)? tsList[i]:0; + pOutput += 1; + pTimestamp += 1; + notNullElems++; + } } pDiffInfo->i64Prev = pData[i]; pDiffInfo->valueAssigned = true; - notNullElems++; } break; } + default: qError("error input type"); } @@ -3575,7 +3813,7 @@ static void diff_function(SQLFunctionCtx *pCtx) { aAggs[TSDB_FUNC_TAGPRJ].xFunction(tagCtx); } } - int32_t forwardStep = (isFirstBlock) ? notNullElems - 1 : notNullElems; + int32_t forwardStep = (isFirstBlock) ? notNullElems : notNullElems; GET_RES_INFO(pCtx)->numOfRes += forwardStep; } @@ -5261,7 +5499,7 @@ static void unique_function(SQLFunctionCtx *pCtx) { do_unique_function(pCtx, pInfo, k, pData, NULL, pCtx->inputBytes, pCtx->inputType); if (sizeof(SUniqueFuncInfo) + pInfo->num * (sizeof(UniqueUnit) + pCtx->inputBytes + pCtx->tagInfo.tagsLen) >= MAX_UNIQUE_RESULT_SIZE - || (pInfo->num > MAX_UNIQUE_RESULT_ROWS)){ + || (pInfo->num > pCtx->param[0].i64)){ GET_RES_INFO(pCtx)->numOfRes = -1; // mark out of memory return; } @@ -5282,7 +5520,7 @@ static void unique_function_merge(SQLFunctionCtx *pCtx) { do_unique_function(pCtx, pOutput, timestamp, data, tags, pCtx->outputBytes, pCtx->outputType); if (sizeof(SUniqueFuncInfo) + pOutput->num * (sizeof(UniqueUnit) + pCtx->outputBytes + pCtx->tagInfo.tagsLen) >= MAX_UNIQUE_RESULT_SIZE - || (pOutput->num > MAX_UNIQUE_RESULT_ROWS)){ + || (pOutput->num > pCtx->param[0].i64)){ GET_RES_INFO(pCtx)->numOfRes = -1; // mark out of memory return; } @@ -5317,7 +5555,7 @@ static void unique_func_finalizer(SQLFunctionCtx *pCtx) { } SortSupporter support = {0}; // user specify the order of output by sort the result according to timestamp - if (pCtx->param[2].i64 == PRIMARYKEY_TIMESTAMP_COL_INDEX) { + if (pCtx->param[2].i64 == PRIMARYKEY_TIMESTAMP_COL_INDEX || pCtx->param[2].i64 == TSDB_RES_COL_ID) { support.dataOffset = 0; support.comparFn = compareInt64Val; } else{ @@ -5600,7 +5838,10 @@ static void tail_func_finalizer(SQLFunctionCtx *pCtx) { // }else{ // GET_RES_INFO(pCtx)->numOfRes = pRes->num; // } - if (GET_RES_INFO(pCtx)->numOfRes <= 0) return; + if (GET_RES_INFO(pCtx)->numOfRes <= 0) { + doFinalizer(pCtx); + return; + } taosqsort(pRes->res, pRes->num, POINTER_BYTES, NULL, tailComparFn); @@ -5608,6 +5849,7 @@ static void tail_func_finalizer(SQLFunctionCtx *pCtx) { void *data = calloc(size, GET_RES_INFO(pCtx)->numOfRes); if(!data){ qError("calloc error in tail_func_finalizer: size:%d, num:%d", (int32_t)size, GET_RES_INFO(pCtx)->numOfRes); + doFinalizer(pCtx); return; } for(int32_t i = 0; i < GET_RES_INFO(pCtx)->numOfRes; i++){ @@ -5616,7 +5858,7 @@ static void tail_func_finalizer(SQLFunctionCtx *pCtx) { SortSupporter support = {0}; // user specify the order of output by sort the result according to timestamp - if (pCtx->param[2].i64 != PRIMARYKEY_TIMESTAMP_COL_INDEX) { + if (pCtx->param[2].i64 != PRIMARYKEY_TIMESTAMP_COL_INDEX && pCtx->param[2].i64 != TSDB_RES_COL_ID) { support.dataOffset = sizeof(int64_t); support.comparFn = getComparFunc(type, 0); taosqsort(data, (size_t)GET_RES_INFO(pCtx)->numOfRes, size, &support, sortCompareFn); @@ -5627,6 +5869,165 @@ static void tail_func_finalizer(SQLFunctionCtx *pCtx) { doFinalizer(pCtx); } + +static void state_count_function(SQLFunctionCtx *pCtx) { + SResultRowCellInfo *pResInfo = GET_RES_INFO(pCtx); + SStateInfo *pStateInfo = GET_ROWCELL_INTERBUF(pResInfo); + + char *data = GET_INPUT_DATA_LIST(pCtx); + int64_t *pOutput = (int64_t *)pCtx->pOutput; + + for (int32_t i = 0; i < pCtx->size; i++,pOutput++,data += pCtx->inputBytes) { + if (pCtx->hasNull && isNull(data, pCtx->inputType)) { + setNull(pOutput, TSDB_DATA_TYPE_BIGINT, 0); + continue; + } + if (isStateOperTrue(data, pCtx->inputType, &pCtx->param[0], &pCtx->param[1])){ + *pOutput = ++pStateInfo->countPrev; + }else{ + *pOutput = -1; + pStateInfo->countPrev = 0; + } + } + + for (int t = 0; t < pCtx->tagInfo.numOfTagCols; ++t) { + SQLFunctionCtx* tagCtx = pCtx->tagInfo.pTagCtxList[t]; + if (tagCtx->functionId == TSDB_FUNC_TAG_DUMMY) { + aAggs[TSDB_FUNC_TAGPRJ].xFunction(tagCtx); + } + } + pResInfo->numOfRes += pCtx->size; +} + +static void state_duration_function(SQLFunctionCtx *pCtx) { + SResultRowCellInfo *pResInfo = GET_RES_INFO(pCtx); + SStateInfo *pStateInfo = GET_ROWCELL_INTERBUF(pResInfo); + + char *data = GET_INPUT_DATA_LIST(pCtx); + TSKEY* tsList = GET_TS_LIST(pCtx); + int64_t *pOutput = (int64_t *)pCtx->pOutput; + + for (int32_t i = 0; i < pCtx->size; i++,pOutput++,data += pCtx->inputBytes) { + if (pCtx->hasNull && isNull(data, pCtx->inputType)) { + setNull(pOutput, TSDB_DATA_TYPE_BIGINT, 0); + continue; + } + if (isStateOperTrue(data, pCtx->inputType, &pCtx->param[0], &pCtx->param[1])){ + if (pStateInfo->durationStart == 0) { + *pOutput = 0; + pStateInfo->durationStart = tsList[i]; + } else { + *pOutput = (tsList[i] - pStateInfo->durationStart)/pCtx->param[2].i64; + } + } else{ + *pOutput = -1; + pStateInfo->durationStart = 0; + } + } + + for (int t = 0; t < pCtx->tagInfo.numOfTagCols; ++t) { + SQLFunctionCtx* tagCtx = pCtx->tagInfo.pTagCtxList[t]; + if (tagCtx->functionId == TSDB_FUNC_TAG_DUMMY) { + aAggs[TSDB_FUNC_TAGPRJ].xFunction(tagCtx); + } + } + pResInfo->numOfRes += pCtx->size; +} + +int16_t getTimeWindowFunctionID(int16_t colIndex) { + switch (colIndex) { + case TSDB_TSWIN_START_COLUMN_INDEX: { + return TSDB_FUNC_WSTART; + } + case TSDB_TSWIN_STOP_COLUMN_INDEX: { + return TSDB_FUNC_WSTOP; + } + case TSDB_TSWIN_DURATION_COLUMN_INDEX: { + return TSDB_FUNC_WDURATION; + } + case TSDB_QUERY_START_COLUMN_INDEX: { + return TSDB_FUNC_QSTART; + } + case TSDB_QUERY_STOP_COLUMN_INDEX: { + return TSDB_FUNC_QSTOP; + } + case TSDB_QUERY_DURATION_COLUMN_INDEX: { + return TSDB_FUNC_QDURATION; + } + default: + return TSDB_FUNC_INVALID_ID; + } +} + +static void window_start_function(SQLFunctionCtx *pCtx) { + if (pCtx->functionId == TSDB_FUNC_WSTART) { + SET_VAL(pCtx, pCtx->size, 1); + *(int64_t *)(pCtx->pOutput) = pCtx->startTs; + } else { //TSDB_FUNC_QSTART + int32_t size = MIN(pCtx->size, pCtx->allocRows); //size cannot exceeds allocated rows + SET_VAL(pCtx, pCtx->size, size); + //INC_INIT_VAL(pCtx, size); + char *output = pCtx->pOutput; + for (int32_t i = 0; i < size; ++i) { + if (pCtx->qWindow.skey == INT64_MIN) { + *(TKEY *)output = TSDB_DATA_TIMESTAMP_NULL; + } else { + memcpy(output, &pCtx->qWindow.skey, pCtx->outputBytes); + } + output += pCtx->outputBytes; + } + } +} + +static void window_stop_function(SQLFunctionCtx *pCtx) { + if (pCtx->functionId == TSDB_FUNC_WSTOP) { + SET_VAL(pCtx, pCtx->size, 1); + *(int64_t *)(pCtx->pOutput) = pCtx->endTs; + } else { //TSDB_FUNC_QSTOP + int32_t size = MIN(pCtx->size, pCtx->allocRows); //size cannot exceeds allocated rows + SET_VAL(pCtx, pCtx->size, size); + //INC_INIT_VAL(pCtx, size); + char *output = pCtx->pOutput; + for (int32_t i = 0; i < size; ++i) { + if (pCtx->qWindow.ekey == INT64_MAX) { + *(TKEY *)output = TSDB_DATA_TIMESTAMP_NULL; + } else { + memcpy(output, &pCtx->qWindow.ekey, pCtx->outputBytes); + } + output += pCtx->outputBytes; + } + } +} + +static void window_duration_function(SQLFunctionCtx *pCtx) { + int64_t duration; + if (pCtx->functionId == TSDB_FUNC_WDURATION) { + SET_VAL(pCtx, pCtx->size, 1); + duration = pCtx->endTs - pCtx->startTs; + if (duration < 0) { + duration = -duration; + } + *(int64_t *)(pCtx->pOutput) = duration; + } else { //TSDB_FUNC_QDURATION + int32_t size = MIN(pCtx->size, pCtx->allocRows); //size cannot exceeds allocated rows + SET_VAL(pCtx, pCtx->size, size); + //INC_INIT_VAL(pCtx, size); + duration = pCtx->qWindow.ekey - pCtx->qWindow.skey; + if (duration < 0) { + duration = -duration; + } + char *output = pCtx->pOutput; + for (int32_t i = 0; i < size; ++i) { + if (pCtx->qWindow.skey == INT64_MIN || pCtx->qWindow.ekey == INT64_MAX) { + *(int64_t *)output = TSDB_DATA_BIGINT_NULL; + } else { + memcpy(output, &duration, pCtx->outputBytes); + } + output += pCtx->outputBytes; + } + } +} + ///////////////////////////////////////////////////////////////////////////////////////////// /* * function compatible list. @@ -5639,16 +6040,16 @@ static void tail_func_finalizer(SQLFunctionCtx *pCtx) { * */ int32_t functionCompatList[] = { - // count, sum, avg, min, max, stddev, percentile, apercentile, first, last - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - // last_row,top, bottom, spread, twa, leastsqr, ts, ts_dummy, tag_dummy, ts_comp - 4, -1, -1, 1, 1, 1, 1, 1, 1, -1, - // tag, colprj, tagprj, arithm, diff, first_dist, last_dist, stddev_dst, interp rate, irate - 1, 1, 1, 1, -1, 1, 1, 1, 5, 1, 1, - // tid_tag, deriv, csum, mavg, sample, - 6, 8, -1, -1, -1, - // block_info,elapsed,histogram,unique,mode,tail - 7, 1, -1, -1, 1, -1 + // count, sum, avg, min, max, stddev, percentile, apercentile, first, last + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + // last_row, top, bottom, spread, twa, leastsqr, ts, ts_dummy, tag_dummy, ts_comp + 4, -1, -1, 1, 1, 1, 1, 1, 1, -1, + // tag, colprj, tagprj, arithm, diff, first_dist, last_dist, stddev_dst, interp rate, irate + 1, 1, 1, 1, -1, 1, 1, 1, 5, 1, 1, + // tid_tag, deriv, csum, mavg, sample, block_info, elapsed, histogram, unique, mode, tail + 6, 8, -1, -1, -1, 7, 1, -1, -1, 1, -1, + // stateCount, stateDuration, wstart, wstop, wduration, qstart, qstop, qduration, hyperloglog + 1, 1, 1, 1, 1, 1, 1, 1, 1, }; SAggFunctionInfo aAggs[TSDB_FUNC_MAX_NUM] = {{ @@ -6146,16 +6547,124 @@ SAggFunctionInfo aAggs[TSDB_FUNC_MAX_NUM] = {{ mode_function_merge, dataBlockRequired, }, - { - // 41 - "tail", - TSDB_FUNC_TAIL, - TSDB_FUNC_TAIL, - TSDB_BASE_FUNC_MO | TSDB_FUNCSTATE_SELECTIVITY, - tail_function_setup, - tail_function, - tail_func_finalizer, - tail_func_merge, - tailFuncRequired, - } + { + // 41 + "tail", + TSDB_FUNC_TAIL, + TSDB_FUNC_TAIL, + TSDB_BASE_FUNC_MO | TSDB_FUNCSTATE_SELECTIVITY, + tail_function_setup, + tail_function, + tail_func_finalizer, + tail_func_merge, + tailFuncRequired, + }, + { + // 42 + "stateCount", + TSDB_FUNC_STATE_COUNT, + TSDB_FUNC_INVALID_ID, + TSDB_BASE_FUNC_SO | TSDB_FUNCSTATE_NEED_TS, + function_setup, + state_count_function, + doFinalizer, + noop1, + dataBlockRequired, + }, + { + // 43 + "stateDuration", + TSDB_FUNC_STATE_DURATION, + TSDB_FUNC_INVALID_ID, + TSDB_BASE_FUNC_SO | TSDB_FUNCSTATE_NEED_TS, + function_setup, + state_duration_function, + doFinalizer, + noop1, + dataBlockRequired, + }, + { + // 44 + "_wstart", + TSDB_FUNC_WSTART, + TSDB_FUNC_WSTART, + TSDB_BASE_FUNC_SO | TSDB_FUNCSTATE_SELECTIVITY, + function_setup, + window_start_function, + doFinalizer, + copy_function, + dataBlockRequired, + }, + { + // 45 + "_wstop", + TSDB_FUNC_WSTOP, + TSDB_FUNC_WSTOP, + TSDB_BASE_FUNC_SO | TSDB_FUNCSTATE_SELECTIVITY, + function_setup, + window_stop_function, + doFinalizer, + copy_function, + dataBlockRequired, + }, + { + // 46 + "_wduration", + TSDB_FUNC_WDURATION, + TSDB_FUNC_WDURATION, + TSDB_BASE_FUNC_SO | TSDB_FUNCSTATE_SELECTIVITY, + function_setup, + window_duration_function, + doFinalizer, + copy_function, + dataBlockRequired, + }, + { + // 47 + "_qstart", + TSDB_FUNC_QSTART, + TSDB_FUNC_QSTART, + TSDB_BASE_FUNC_MO | TSDB_FUNCSTATE_SELECTIVITY, + function_setup, + window_start_function, + doFinalizer, + copy_function, + dataBlockRequired, + }, + { + // 48 + "_qstop", + TSDB_FUNC_QSTOP, + TSDB_FUNC_QSTOP, + TSDB_BASE_FUNC_MO | TSDB_FUNCSTATE_SELECTIVITY, + function_setup, + window_stop_function, + doFinalizer, + copy_function, + dataBlockRequired, + }, + { + // 49 + "_qduration", + TSDB_FUNC_QDURATION, + TSDB_FUNC_QDURATION, + TSDB_BASE_FUNC_MO | TSDB_FUNCSTATE_SELECTIVITY, + function_setup, + window_duration_function, + doFinalizer, + copy_function, + dataBlockRequired, + }, + { + // 50 + "hyperloglog", + TSDB_FUNC_HYPERLOGLOG, + TSDB_FUNC_HYPERLOGLOG, + TSDB_BASE_FUNC_SO, + function_setup, + hll_function, + hll_func_finalizer, + hll_func_merge, + dataBlockRequired, + } }; diff --git a/src/query/src/qExecutor.c b/src/query/src/qExecutor.c index 9279b66e646d9e73ff1a74f7f27740e1e6098c05..5dad98840b88355d970a967c9615c481c972fc39 100644 --- a/src/query/src/qExecutor.c +++ b/src/query/src/qExecutor.c @@ -283,28 +283,25 @@ static int compareRowData(const void *a, const void *b, const void *userData) { return (in1 != NULL && in2 != NULL) ? supporter->comFunc(in1, in2) : 0; } -static void sortGroupResByOrderList(SGroupResInfo *pGroupResInfo, SQueryRuntimeEnv *pRuntimeEnv, SSDataBlock* pDataBlock) { - if (pRuntimeEnv->pQueryAttr->pGroupbyExpr == NULL || pRuntimeEnv->pQueryAttr->pGroupbyExpr->numOfGroupCols <= 0){ +static void sortGroupResByOrderList(SGroupResInfo *pGroupResInfo, SQueryRuntimeEnv *pRuntimeEnv, SSDataBlock* pDataBlock, SQLFunctionCtx *pCtx) { + // first groupby column is sort column + SColIndex* pFirstGroupCol = taosArrayGet(pRuntimeEnv->pQueryAttr->pGroupbyExpr->columnInfo, 0); + if (pFirstGroupCol == NULL) { return; } - if (pRuntimeEnv->pQueryAttr->order.orderColId <= 0){ - return; - } - - SColIndex* pColIndex = taosArrayGet(pRuntimeEnv->pQueryAttr->pGroupbyExpr->columnInfo, 0); - + // get dataOffset and index on pRuntimeEnv->pQueryAttr->pExpr1 int16_t dataOffset = 0; int16_t type = 0; for (int32_t j = 0; j < pDataBlock->info.numOfCols; ++j) { SColumnInfoData* pColInfoData = (SColumnInfoData *)taosArrayGet(pDataBlock->pDataBlock, j); - if (pColInfoData->info.colId == pColIndex->colId) { - type = pColInfoData->info.type; + if (pCtx[j].colId == pFirstGroupCol->colId) { + type = pRuntimeEnv->pQueryAttr->pExpr1[j].base.resType; break; } - dataOffset += pColInfoData->info.bytes; } + SRowCompSupporter support = {.pRuntimeEnv = pRuntimeEnv, .dataOffset = dataOffset, .comFunc = getComparFunc(type, 0)}; taosArraySortPWithExt(pGroupResInfo->pRows, compareRowData, &support); } @@ -385,7 +382,7 @@ int32_t getNumOfResult(SQueryRuntimeEnv *pRuntimeEnv, SQLFunctionCtx* pCtx, int3 * the number of output result is decided by main output */ if (hasMainFunction && (id == TSDB_FUNC_TS || id == TSDB_FUNC_TAG || id == TSDB_FUNC_TAGPRJ || - id == TSDB_FUNC_TS_DUMMY || id == TSDB_FUNC_TAG_DUMMY)) { + id == TSDB_FUNC_TS_DUMMY || id == TSDB_FUNC_TAG_DUMMY || isTimeWindowFunction(id))) { continue; } @@ -461,7 +458,8 @@ static bool isProjQuery(SQueryAttr *pQueryAttr) { } static bool hasNull(SColIndex* pColIndex, SDataStatis *pStatis) { - if (TSDB_COL_IS_TAG(pColIndex->flag) || TSDB_COL_IS_UD_COL(pColIndex->flag) || pColIndex->colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) { + if (TSDB_COL_IS_TAG(pColIndex->flag) || TSDB_COL_IS_UD_COL(pColIndex->flag) || + TSDB_COL_IS_TSWIN_COL(pColIndex->colId) || pColIndex->colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) { return false; } @@ -953,6 +951,7 @@ static void doApplyFunctions(SQueryRuntimeEnv* pRuntimeEnv, SQLFunctionCtx* pCtx pCtx[k].size = forwardStep; pCtx[k].startTs = pWin->skey; + pCtx[k].endTs = pWin->ekey; // keep it temporarialy char* start = pCtx[k].pInput; @@ -1190,7 +1189,7 @@ static void doSetInputDataBlock(SOperatorInfo* pOperator, SQLFunctionCtx* pCtx, setArithParams((SScalarExprSupport*)pCtx[i].param[1].pz, &pOperator->pExpr[i], pBlock); } else { SColIndex* pCol = &pOperator->pExpr[i].base.colInfo; - if (TSDB_COL_IS_NORMAL_COL(pCol->flag) || (pCtx[i].functionId == TSDB_FUNC_BLKINFO) || + if ((TSDB_COL_IS_NORMAL_COL(pCol->flag) && !TSDB_COL_IS_TSWIN_COL(pCol->colId)) || (pCtx[i].functionId == TSDB_FUNC_BLKINFO) || (TSDB_COL_IS_TAG(pCol->flag) && pOperator->pRuntimeEnv->scanFlag == MERGE_STAGE)) { SColIndex* pColIndex = &pOperator->pExpr[i].base.colInfo; SColumnInfoData* p = taosArrayGet(pBlock->pDataBlock, pColIndex->colIndex); @@ -1698,7 +1697,6 @@ static void doSessionWindowAggImpl(SOperatorInfo* pOperator, SSWindowOperatorInf } else { // start a new session window SResultRow* pResult = NULL; - pInfo->curWindow.ekey = pInfo->curWindow.skey; int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.tid, &pInfo->curWindow, masterScan, &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput, pBInfo->rowCellInfoOffset); @@ -1719,7 +1717,6 @@ static void doSessionWindowAggImpl(SOperatorInfo* pOperator, SSWindowOperatorInf SResultRow* pResult = NULL; - pInfo->curWindow.ekey = pInfo->curWindow.skey; int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.tid, &pInfo->curWindow, masterScan, &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput, pBInfo->rowCellInfoOffset); @@ -1842,7 +1839,7 @@ static bool functionNeedToExecute(SQueryRuntimeEnv *pRuntimeEnv, SQLFunctionCtx void setBlockStatisInfo(SQLFunctionCtx *pCtx, SSDataBlock* pSDataBlock, SColIndex* pColIndex) { SDataStatis *pStatis = NULL; - if (pSDataBlock->pBlockStatis != NULL && TSDB_COL_IS_NORMAL_COL(pColIndex->flag)) { + if (pSDataBlock->pBlockStatis != NULL && TSDB_COL_IS_NORMAL_COL(pColIndex->flag) && !TSDB_COL_IS_TSWIN_COL(pColIndex->colId)) { pStatis = &pSDataBlock->pBlockStatis[pColIndex->colIndex]; pCtx->preAggVals.statis = *pStatis; @@ -1908,7 +1905,7 @@ static int32_t setCtxTagColumnInfo(SQLFunctionCtx *pCtx, int32_t numOfOutput) { } static SQLFunctionCtx* createSQLFunctionCtx(SQueryRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput, - int32_t** rowCellInfoOffset) { + int32_t** rowCellInfoOffset, int32_t numOfRows) { SQueryAttr* pQueryAttr = pRuntimeEnv->pQueryAttr; SQLFunctionCtx * pFuncCtx = (SQLFunctionCtx *)calloc(numOfOutput, sizeof(SQLFunctionCtx)); @@ -1938,7 +1935,7 @@ static SQLFunctionCtx* createSQLFunctionCtx(SQueryRuntimeEnv* pRuntimeEnv, SExpr pCtx->inputType = pSqlExpr->colType; if (pRuntimeEnv->pQueryAttr->interBytesForGlobal > INT16_MAX && (pSqlExpr->functionId == TSDB_FUNC_UNIQUE || pSqlExpr->functionId == TSDB_FUNC_MODE - || pSqlExpr->functionId == TSDB_FUNC_TAIL)){ + || pSqlExpr->functionId == TSDB_FUNC_TAIL || pSqlExpr->functionId == TSDB_FUNC_SAMPLE)) { pCtx->inputBytes = pRuntimeEnv->pQueryAttr->interBytesForGlobal; }else{ pCtx->inputBytes = pSqlExpr->colBytes; @@ -1958,6 +1955,9 @@ static SQLFunctionCtx* createSQLFunctionCtx(SQueryRuntimeEnv* pRuntimeEnv, SExpr pCtx->end.key = INT64_MIN; pCtx->startTs = INT64_MIN; + pCtx->qWindow = pQueryAttr->window; + pCtx->allocRows = numOfRows; + pCtx->numOfParams = pSqlExpr->numOfParams; for (int32_t j = 0; j < pCtx->numOfParams; ++j) { int16_t type = pSqlExpr->param[j].nType; @@ -2042,7 +2042,6 @@ static int32_t setupQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv, int32_t numOf SQueryAttr *pQueryAttr = pRuntimeEnv->pQueryAttr; pRuntimeEnv->prevGroupId = INT32_MIN; - pRuntimeEnv->pQueryAttr = pQueryAttr; pRuntimeEnv->pResultRowHashTable = taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK); pRuntimeEnv->pResultRowListSet = taosHashInit(numOfTables * 10, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK); @@ -2661,7 +2660,7 @@ static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableMsg* pQueryMsg, bool return; } - if (pQueryAttr->groupbyColumn && pQueryAttr->order.order == TSDB_ORDER_DESC) { + if ((pQueryAttr->groupbyColumn || pQueryAttr->stateQuery) && pQueryAttr->order.order == TSDB_ORDER_DESC) { pQueryAttr->order.order = TSDB_ORDER_ASC; if (pQueryAttr->window.skey > pQueryAttr->window.ekey) { SWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY); @@ -3174,7 +3173,7 @@ int32_t loadDataBlockOnDemand(SQueryRuntimeEnv* pRuntimeEnv, STableScanInfo* pTa pTableScanInfo->rowCellInfoOffset) != TSDB_CODE_SUCCESS) { longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY); } - } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->diffQuery) && (!pQueryAttr->pointInterpQuery)) { // stable aggregate, not interval aggregate or normal column aggregate + } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->pointInterpQuery)) { // stable aggregate, not interval aggregate or normal column aggregate doSetTableGroupOutputBuf(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pTableScanInfo->pCtx, pTableScanInfo->rowCellInfoOffset, pTableScanInfo->numOfOutput, pRuntimeEnv->current->groupIndex); @@ -3926,7 +3925,8 @@ static bool hasMainOutput(SQueryAttr *pQueryAttr) { for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) { int32_t functionId = pQueryAttr->pExpr1[i].base.functionId; - if (functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_TAG && functionId != TSDB_FUNC_TAGPRJ) { + if (functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_TAG && + functionId != TSDB_FUNC_TAGPRJ && !isTimeWindowFunction(functionId)) { return true; } } @@ -4874,7 +4874,7 @@ static int32_t setupQueryHandle(void* tsdb, SQueryRuntimeEnv* pRuntimeEnv, int64 } STsdbQueryCond cond = createTsdbQueryCond(pQueryAttr, &pQueryAttr->window); - if (pQueryAttr->tsCompQuery || pQueryAttr->pointInterpQuery) { + if (pQueryAttr->tsCompQuery || pQueryAttr->pointInterpQuery || pQueryAttr->needTableSeqScan) { cond.type = BLOCK_LOAD_TABLE_SEQ_ORDER; } @@ -5641,7 +5641,8 @@ SOperatorInfo* createGlobalAggregateOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, pInfo->bufCapacity = 200; // TD-10899 pInfo->udfInfo = pUdfInfo; pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pInfo->bufCapacity * pInfo->resultRowFactor); - pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset); + pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset, + pInfo->bufCapacity * pInfo->resultRowFactor); pInfo->orderColumnList = getOrderCheckColumns(pRuntimeEnv->pQueryAttr); pInfo->groupColumnList = getResultGroupCheckColumns(pRuntimeEnv->pQueryAttr); @@ -5960,7 +5961,7 @@ static SSDataBlock* doAggregate(void* param, bool* newgroup) { doAggregateImpl(pOperator, pQueryAttr->window.skey, pInfo->pCtx, pBlock); // if all pCtx is completed, then query should be over if(allCtxCompleted(pOperator, pInfo->pCtx)) - break; + break; } doSetOperatorCompleted(pOperator); @@ -6925,7 +6926,6 @@ static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorI } } else { SResultRow* pResult = NULL; - pInfo->curWindow.ekey = pInfo->curWindow.skey; int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.tid, &pInfo->curWindow, masterScan, &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput, pBInfo->rowCellInfoOffset); @@ -6945,8 +6945,6 @@ static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorI } SResultRow* pResult = NULL; - - pInfo->curWindow.ekey = pInfo->curWindow.skey; int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.tid, &pInfo->curWindow, masterScan, &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput, pBInfo->rowCellInfoOffset); @@ -7127,7 +7125,7 @@ static SSDataBlock* hashGroupbyAggregate(void* param, bool* newgroup) { initGroupResInfo(&pRuntimeEnv->groupResInfo, &pInfo->binfo.resultRowInfo); if (!pRuntimeEnv->pQueryAttr->stableQuery) { - sortGroupResByOrderList(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pInfo->binfo.pRes); + sortGroupResByOrderList(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pInfo->binfo.pRes, pInfo->binfo.pCtx); } toSSDataBlock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pInfo->binfo.pRes); @@ -7285,7 +7283,7 @@ SOperatorInfo* createAggregateOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOpera int32_t numOfRows = (int32_t)(getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery)); pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, numOfRows); - pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset); + pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset, numOfRows); initResultRowInfo(&pInfo->binfo.resultRowInfo, 8, TSDB_DATA_TYPE_INT); @@ -7457,7 +7455,7 @@ SOperatorInfo* createMultiTableAggOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SO size_t tableGroup = GET_NUM_OF_TABLEGROUP(pRuntimeEnv); pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, (int32_t) tableGroup); - pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset); + pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset, (int32_t) tableGroup); initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)tableGroup, TSDB_DATA_TYPE_INT); if (pInfo->binfo.pRes == NULL || pInfo->binfo.pCtx == NULL || pInfo->binfo.resultRowInfo.pResult == NULL) { @@ -7502,7 +7500,7 @@ SOperatorInfo* createProjectOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOperato SOptrBasicInfo* pBInfo = &pInfo->binfo; pBInfo->pRes = createOutputBuf(pExpr, numOfOutput, pInfo->bufCapacity); - pBInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pBInfo->rowCellInfoOffset); + pBInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pBInfo->rowCellInfoOffset, pInfo->bufCapacity); initResultRowInfo(&pBInfo->resultRowInfo, 8, TSDB_DATA_TYPE_INT); @@ -7637,7 +7635,7 @@ SOperatorInfo* createTimeIntervalOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOp return NULL; } - pInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->rowCellInfoOffset); + pInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->rowCellInfoOffset, pRuntimeEnv->resultInfo.capacity); pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pRuntimeEnv->resultInfo.capacity); initResultRowInfo(&pInfo->resultRowInfo, 8, TSDB_DATA_TYPE_INT); @@ -7687,7 +7685,7 @@ SOperatorInfo* createTimeEveryOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOpera SOptrBasicInfo* pBInfo = &pInfo->binfo; pBInfo->pRes = createOutputBuf(pExpr, numOfOutput, pInfo->bufCapacity); - pBInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pBInfo->rowCellInfoOffset); + pBInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pBInfo->rowCellInfoOffset, pInfo->bufCapacity); if (pQueryAttr->needReverseScan) { pInfo->rangeStart = taosHashInit(256, taosGetDefaultHashFunction(TSDB_DATA_TYPE_TIMESTAMP), false, false); @@ -7739,7 +7737,8 @@ SOperatorInfo* createStatewindowOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOpe pInfo->colIndex = -1; pInfo->reptScan = false; - pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset); + pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset, + pRuntimeEnv->resultInfo.capacity); pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pRuntimeEnv->resultInfo.capacity); initResultRowInfo(&pInfo->binfo.resultRowInfo, 8, TSDB_DATA_TYPE_INT); @@ -7779,7 +7778,8 @@ SOperatorInfo* createSWindowOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOperato return NULL; } - pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset); + pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset, + pRuntimeEnv->resultInfo.capacity); pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pRuntimeEnv->resultInfo.capacity); initResultRowInfo(&pInfo->binfo.resultRowInfo, 8, TSDB_DATA_TYPE_INT); @@ -7821,7 +7821,7 @@ SOperatorInfo* createMultiTableTimeIntervalOperatorInfo(SQueryRuntimeEnv* pRunti return NULL; } - pInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->rowCellInfoOffset); + pInfo->pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->rowCellInfoOffset, pRuntimeEnv->resultInfo.capacity); pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pRuntimeEnv->resultInfo.capacity); initResultRowInfo(&pInfo->resultRowInfo, 8, TSDB_DATA_TYPE_INT); @@ -7864,7 +7864,8 @@ SOperatorInfo* createGroupbyOperatorInfo(SQueryRuntimeEnv* pRuntimeEnv, SOperato } pInfo->colIndex = -1; // group by column index - pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset); + pInfo->binfo.pCtx = createSQLFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset, + pRuntimeEnv->resultInfo.capacity); SQueryAttr *pQueryAttr = pRuntimeEnv->pQueryAttr; @@ -8389,8 +8390,9 @@ static int32_t getColumnIndexInSource(SQueriedTableInfo *pTableInfo, SSqlExpr *p int32_t j = 0; if (TSDB_COL_IS_TAG(pExpr->colInfo.flag)) { - if (pExpr->colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) { - return TSDB_TBNAME_COLUMN_INDEX; + if (pExpr->colInfo.colId == TSDB_TBNAME_COLUMN_INDEX || + TSDB_COL_IS_TSWIN_COL(pExpr->colInfo.colId)) { + return pExpr->colInfo.colId; } while(j < pTableInfo->numOfTags) { @@ -9173,6 +9175,11 @@ int32_t createQueryFunc(SQueriedTableInfo* pTableInfo, int32_t numOfOutput, SExp SSchema* s = tGetTbnameColumnSchema(); type = s->type; bytes = s->bytes; + } else if (TSDB_COL_IS_TSWIN_COL(pExprs[i].base.colInfo.colId) && + isTimeWindowFunction(pExprs[i].base.functionId)) { + SSchema* s = tGetTimeWindowColumnSchema(pExprs[i].base.colInfo.colId); + type = s->type; + bytes = s->bytes; } else if (pExprs[i].base.colInfo.colId <= TSDB_UD_COLUMN_INDEX && pExprs[i].base.colInfo.colId > TSDB_RES_COL_ID) { // it is a user-defined constant value column assert(pExprs[i].base.functionId == TSDB_FUNC_PRJ); @@ -9185,7 +9192,7 @@ int32_t createQueryFunc(SQueriedTableInfo* pTableInfo, int32_t numOfOutput, SExp } else { int32_t j = getColumnIndexInSource(pTableInfo, &pExprs[i].base, pTagCols); if (TSDB_COL_IS_TAG(pExprs[i].base.colInfo.flag)) { - if (j < TSDB_TBNAME_COLUMN_INDEX || j >= pTableInfo->numOfTags) { + if (j < TSDB_MIN_VALID_COLUMN_INDEX || j >= pTableInfo->numOfTags) { tfree(pExprs); return TSDB_CODE_QRY_INVALID_MSG; } @@ -9218,15 +9225,19 @@ int32_t createQueryFunc(SQueriedTableInfo* pTableInfo, int32_t numOfOutput, SExp } int32_t param = (int32_t)pExprs[i].base.param[0].i64; - if (pExprs[i].base.functionId > 0 && pExprs[i].base.functionId != TSDB_FUNC_SCALAR_EXPR && - (type != pExprs[i].base.colType || bytes != pExprs[i].base.colBytes)) { + if (pExprs[i].base.functionId > 0 && + pExprs[i].base.functionId != TSDB_FUNC_SCALAR_EXPR && + !isTimeWindowFunction(pExprs[i].base.functionId) && + (type != pExprs[i].base.colType || bytes != pExprs[i].base.colBytes)) { tfree(pExprs); return TSDB_CODE_QRY_INVALID_MSG; } // todo remove it - if (pExprs[i].base.functionId != TSDB_FUNC_SCALAR_EXPR && getResultDataInfo(type, bytes, pExprs[i].base.functionId, param, &pExprs[i].base.resType, &pExprs[i].base.resBytes, - &pExprs[i].base.interBytes, 0, isSuperTable, pUdfInfo) != TSDB_CODE_SUCCESS) { + if (pExprs[i].base.functionId != TSDB_FUNC_SCALAR_EXPR && + !isTimeWindowFunction(pExprs[i].base.functionId) && + getResultDataInfo(type, bytes, pExprs[i].base.functionId, param, &pExprs[i].base.resType, &pExprs[i].base.resBytes, + &pExprs[i].base.interBytes, 0, isSuperTable, pUdfInfo) != TSDB_CODE_SUCCESS) { tfree(pExprs); return TSDB_CODE_QRY_INVALID_MSG; } @@ -9439,7 +9450,8 @@ static void doUpdateExprColumnIndex(SQueryAttr *pQueryAttr) { for (int32_t k = 0; k < pQueryAttr->numOfOutput; ++k) { SSqlExpr *pSqlExprMsg = &pQueryAttr->pExpr1[k].base; - if (pSqlExprMsg->functionId == TSDB_FUNC_SCALAR_EXPR) { + if (pSqlExprMsg->functionId == TSDB_FUNC_SCALAR_EXPR || + isTimeWindowFunction(pSqlExprMsg->functionId)) { continue; } @@ -9466,7 +9478,7 @@ static void doUpdateExprColumnIndex(SQueryAttr *pQueryAttr) { } } - assert(f < pQueryAttr->numOfTags || pColIndex->colId == TSDB_TBNAME_COLUMN_INDEX); + assert(f < pQueryAttr->numOfTags || pColIndex->colId <= TSDB_TBNAME_COLUMN_INDEX); } } } @@ -9553,7 +9565,6 @@ SQInfo* createQInfoImpl(SQueryTableMsg* pQueryMsg, SGroupbyExpr* pGroupbyExpr, S pQueryAttr->needTableSeqScan = pQueryMsg->needTableSeqScan; pQueryAttr->needReverseScan = pQueryMsg->needReverseScan; pQueryAttr->stateWindow = pQueryMsg->stateWindow; - pQueryAttr->vgId = vgId; pQueryAttr->pFilters = pFilters; pQueryAttr->range = pQueryMsg->range; @@ -9585,6 +9596,9 @@ SQInfo* createQInfoImpl(SQueryTableMsg* pQueryMsg, SGroupbyExpr* pGroupbyExpr, S if (pExprs[col].base.flist.filterInfo) { ++pQueryAttr->havingNum; } + if (pExprs[col].base.functionId == TSDB_FUNC_STATE_COUNT || pExprs[col].base.functionId == TSDB_FUNC_STATE_DURATION){ + pQueryAttr->stateQuery = true; + } } doUpdateExprColumnIndex(pQueryAttr); diff --git a/src/query/src/qExtbuffer.c b/src/query/src/qExtbuffer.c index 5b210f882415f3995cf4fcde1ba3087397bb75b6..4a4ae3ca422a5e65e74d1c566dcd4c99de4e83a2 100644 --- a/src/query/src/qExtbuffer.c +++ b/src/query/src/qExtbuffer.c @@ -366,7 +366,7 @@ static int32_t tsCompareFunc(TSKEY k1, TSKEY k2, int32_t order) { } } -int32_t columnValueAscendingComparator(char *f1, char *f2, int32_t type, int32_t bytes) { +int32_t columnValueAscendingComparator(char *f1, char *f2, int32_t type, int32_t bytes, bool lenFirst) { if (type == TSDB_DATA_TYPE_JSON){ bool canReturn = true; int32_t result = jsonCompareUnit(f1, f2, &canReturn); @@ -385,33 +385,61 @@ int32_t columnValueAscendingComparator(char *f1, char *f2, int32_t type, int32_t case TSDB_DATA_TYPE_TINYINT: DEFAULT_COMP(GET_INT8_VAL(f1), GET_INT8_VAL(f2)); case TSDB_DATA_TYPE_BINARY: { + bool leftIsNull = isNull(f1, TSDB_DATA_TYPE_BINARY); + bool rightIsNull = isNull(f2, TSDB_DATA_TYPE_BINARY); + if(leftIsNull && rightIsNull) return 0; + else if(leftIsNull) return -1; + else if(rightIsNull) return 1; int32_t len1 = varDataLen(f1); int32_t len2 = varDataLen(f2); - - if (len1 != len2) { - return len1 > len2? 1:-1; - } else { - int32_t ret = strncmp(varDataVal(f1), varDataVal(f2), len1); - if (ret == 0) { + + // length first compare + if(lenFirst) { + if(len1 > len2) + return 1; + else if( len1 < len2) + return -1; + } + // compare context + int32_t ret = strncmp(varDataVal(f1), varDataVal(f2), len1>len2 ? len2:len1); + if (ret == 0) { + if (len1 > len2) + return 1; + else if(len1 < len2) + return -1; + else return 0; - } - return (ret < 0) ? -1 : 1; } - + return (ret < 0) ? -1 : 1; }; case TSDB_DATA_TYPE_NCHAR: { // todo handle the var string compare + bool leftIsNull = isNull(f1, TSDB_DATA_TYPE_NCHAR); + bool rightIsNull = isNull(f2, TSDB_DATA_TYPE_NCHAR); + if(leftIsNull && rightIsNull) return 0; + else if(leftIsNull) return -1; + else if(rightIsNull) return 1; + int32_t len1 = varDataLen(f1); int32_t len2 = varDataLen(f2); - if (len1 != len2) { - return len1 > len2 ? 1 : -1; - } else { - int32_t ret = tasoUcs4Compare(varDataVal(f1), varDataVal(f2), len1); - if (ret == 0) { + // length first compare + if(lenFirst) { + if(len1 > len2) + return 1; + else if( len1 < len2) + return -1; + } + // compare context + int32_t ret = tasoUcs4Compare(varDataVal(f1), varDataVal(f2), len1>len2 ? len2:len1); + if (ret == 0) { + if (len1 > len2) + return 1; + else if(len1 < len2) + return -1; + else return 0; - } - return (ret < 0) ? -1 : 1; } + return (ret < 0) ? -1 : 1; }; case TSDB_DATA_TYPE_UTINYINT: DEFAULT_COMP(GET_UINT8_VAL(f1), GET_UINT8_VAL(f2)); case TSDB_DATA_TYPE_USMALLINT: DEFAULT_COMP(GET_UINT16_VAL(f1), GET_UINT16_VAL(f2)); @@ -442,7 +470,7 @@ int32_t compare_a(tOrderDescriptor *pDescriptor, int32_t numOfRows1, int32_t s1, } } else { SSchemaEx *pSchema = &pDescriptor->pColumnModel->pFields[colIdx]; - int32_t ret = columnValueAscendingComparator(f1, f2, pSchema->field.type, pSchema->field.bytes); + int32_t ret = columnValueAscendingComparator(f1, f2, pSchema->field.type, pSchema->field.bytes, strcmp(pSchema->field.name, TSQL_TBNAME_L) == 0); if (ret == 0) { continue; } else { @@ -471,7 +499,7 @@ int32_t compare_aRv(SSDataBlock* pBlock, SArray* colIndex, int32_t numOfCols, in return ret; } } else { - int32_t ret = columnValueAscendingComparator(data, buffer[i], pColInfo->info.type, pColInfo->info.bytes); + int32_t ret = columnValueAscendingComparator(data, buffer[i], pColInfo->info.type, pColInfo->info.bytes, false); if (ret == 0) { continue; } else { @@ -503,7 +531,7 @@ int32_t compare_d(tOrderDescriptor *pDescriptor, int32_t numOfRows1, int32_t s1, } } else { SSchemaEx *pSchema = &pDescriptor->pColumnModel->pFields[colIdx]; - int32_t ret = columnValueAscendingComparator(f1, f2, pSchema->field.type, pSchema->field.bytes); + int32_t ret = columnValueAscendingComparator(f1, f2, pSchema->field.type, pSchema->field.bytes, strcmp(pSchema->field.name, TSQL_TBNAME_L) == 0); if (ret == 0) { continue; } else { diff --git a/src/query/src/qFilter.c b/src/query/src/qFilter.c index d6a7dac7fcb6f525f6bf599d9d45b72f3d8c60f5..4fcf6fdef03940fe4a3bdb853fb25ff0a0f17fb5 100644 --- a/src/query/src/qFilter.c +++ b/src/query/src/qFilter.c @@ -3609,16 +3609,11 @@ int32_t filterConverNcharColumns(SFilterInfo* info, int32_t rows, bool *gotNchar for (int32_t j = 0; j < rows; ++j) { char *src = FILTER_GET_COL_FIELD_DATA(fi, j); char *dst = FILTER_GET_COL_FIELD_DATA(&nfi, j); - int32_t len = 0; - char *varSrc = varDataVal(src); - size_t k = 0, varSrcLen = varDataLen(src); - while (k < varSrcLen && varSrc[k++] == -1) {} - if (k == varSrcLen) { - /* NULL */ - varDataLen(dst) = (VarDataLenT) varSrcLen; + if(isNull(src, TSDB_DATA_TYPE_NCHAR)){ varDataCopy(dst, src); continue; } + int32_t len = 0; bool ret = taosMbsToUcs4(varDataVal(src), varDataLen(src), varDataVal(dst), bufSize, &len); if(!ret) { qError("filterConverNcharColumns taosMbsToUcs4 error"); diff --git a/src/query/src/qUtil.c b/src/query/src/qUtil.c index 8e39af3e6bc542f958bffd04413e92b4b242a7a3..67dfc130ed58d416500d278c60945114ef8a3fe4 100644 --- a/src/query/src/qUtil.c +++ b/src/query/src/qUtil.c @@ -39,13 +39,10 @@ int32_t getRowNumForMultioutput(SQueryAttr* pQueryAttr, bool topBottomQuery, boo pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_BOTTOM || pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_SAMPLE || pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_HISTOGRAM || - pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_TAIL) { + pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_TAIL || + pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_UNIQUE) { return (int32_t)pQueryAttr->pExpr1[i].base.param[0].i64; } - - if (pQueryAttr->pExpr1[i].base.functionId == TSDB_FUNC_UNIQUE){ - return MAX_UNIQUE_RESULT_ROWS; - } } } diff --git a/src/rpc/src/rpcMain.c b/src/rpc/src/rpcMain.c index dfeca03826d0bb36c4840ef01ad5acb05bf55ec3..47ee0d8e229c3b4e692f4472e7f15cbd72ceb40e 100644 --- a/src/rpc/src/rpcMain.c +++ b/src/rpc/src/rpcMain.c @@ -1541,14 +1541,14 @@ static SRpcHead *rpcDecompressRpcMsg(SRpcHead *pHead) { } static int rpcAuthenticateMsg(void *pMsg, int msgLen, void *pAuth, void *pKey) { - MD5_CTX context; + T_MD5_CTX context; int ret = -1; - MD5Init(&context); - MD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); - MD5Update(&context, (uint8_t *)pMsg, msgLen); - MD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); - MD5Final(&context); + tMD5Init(&context); + tMD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); + tMD5Update(&context, (uint8_t *)pMsg, msgLen); + tMD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); + tMD5Final(&context); if (memcmp(context.digest, pAuth, sizeof(context.digest)) == 0) ret = 0; @@ -1556,13 +1556,13 @@ static int rpcAuthenticateMsg(void *pMsg, int msgLen, void *pAuth, void *pKey) { } static void rpcBuildAuthHead(void *pMsg, int msgLen, void *pAuth, void *pKey) { - MD5_CTX context; + T_MD5_CTX context; - MD5Init(&context); - MD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); - MD5Update(&context, (uint8_t *)pMsg, msgLen); - MD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); - MD5Final(&context); + tMD5Init(&context); + tMD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); + tMD5Update(&context, (uint8_t *)pMsg, msgLen); + tMD5Update(&context, (uint8_t *)pKey, TSDB_KEY_LEN); + tMD5Final(&context); memcpy(pAuth, context.digest, sizeof(context.digest)); } diff --git a/src/sync/src/syncMain.c b/src/sync/src/syncMain.c index a8b5a8f403cb9ca0c897d77db280e5a331c1f32e..be35f3aaf9ed80fb66414e918e920fcd714620e1 100644 --- a/src/sync/src/syncMain.c +++ b/src/sync/src/syncMain.c @@ -871,7 +871,7 @@ static void syncRestartPeer(SSyncPeer *pPeer) { int32_t ret = strcmp(pPeer->fqdn, tsNodeFqdn); if (pPeer->nodeId == 0 || ret > 0 || (ret == 0 && pPeer->port > tsSyncPort)) { sDebug("%s, check peer connection in 1000 ms", pPeer->id); - taosTmrReset(syncCheckPeerConnection, SYNC_CHECK_INTERVAL, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); + taosTmrReset(syncCheckPeerConnection, tsSyncCheckInterval, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); } } @@ -976,7 +976,7 @@ static void syncRecoverFromMaster(SSyncPeer *pPeer) { SSyncMsg msg; syncBuildSyncReqMsg(&msg, pNode->vgId); - taosTmrReset(syncNotStarted, SYNC_CHECK_INTERVAL, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); + taosTmrReset(syncNotStarted, tsSyncCheckInterval, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); if (taosWriteMsg(pPeer->peerFd, &msg, sizeof(SSyncMsg)) != sizeof(SSyncMsg)) { sError("%s, failed to send sync-req to peer", pPeer->id); @@ -1149,14 +1149,14 @@ static void syncSetupPeerConnection(SSyncPeer *pPeer) { uint32_t ip = syncResolvePeerFqdn(pPeer); if (!ip) { - taosTmrReset(syncCheckPeerConnection, SYNC_CHECK_INTERVAL, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); + taosTmrReset(syncCheckPeerConnection, tsSyncCheckInterval, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); return; } SOCKET connFd = taosOpenTcpClientSocket(ip, pPeer->port, 0); if (connFd <= 0) { sDebug("%s, failed to open tcp socket since %s", pPeer->id, strerror(errno)); - taosTmrReset(syncCheckPeerConnection, SYNC_CHECK_INTERVAL, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); + taosTmrReset(syncCheckPeerConnection, tsSyncCheckInterval, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); return; } @@ -1177,7 +1177,7 @@ static void syncSetupPeerConnection(SSyncPeer *pPeer) { } else { sDebug("%s, failed to setup peer connection to server since %s, try later", pPeer->id, strerror(errno)); taosCloseSocket(connFd); - taosTmrReset(syncCheckPeerConnection, SYNC_CHECK_INTERVAL, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); + taosTmrReset(syncCheckPeerConnection, tsSyncCheckInterval, (void *)pPeer->rid, tsSyncTmrCtrl, &pPeer->timer); } } diff --git a/src/tsdb/src/tsdbCommit.c b/src/tsdb/src/tsdbCommit.c index d432c951dd1d91e12c7338aeda9b0619bd949b6d..911eb5e2792bd7321d2a6ed1ed45b2d89636ce80 100644 --- a/src/tsdb/src/tsdbCommit.c +++ b/src/tsdb/src/tsdbCommit.c @@ -44,6 +44,14 @@ typedef struct { SDataCols * pDataCols; } SCommitH; +/* + * millisecond by default + * for TSDB_TIME_PRECISION_MILLI: 3600000L + * TSDB_TIME_PRECISION_MICRO: 3600000000L + * TSDB_TIME_PRECISION_NANO: 3600000000000L + */ +static int64_t tsTickPerHour[] = {3600000L, 3600000000L, 3600000000000L}; + #define TSDB_COMMIT_REPO(ch) TSDB_READ_REPO(&(ch->readh)) #define TSDB_COMMIT_REPO_ID(ch) REPO_ID(TSDB_READ_REPO(&(ch->readh))) #define TSDB_COMMIT_WRITE_FSET(ch) (&((ch)->wSet)) @@ -397,7 +405,7 @@ void tsdbGetRtnSnap(STsdbRepo *pRepo, SRtn *pRtn) { STsdbCfg *pCfg = REPO_CFG(pRepo); TSKEY minKey, midKey, maxKey, now; - now = taosGetTimestamp(pCfg->precision); + now = taosGetTimestamp(pCfg->precision) - tsKeepTimeOffset * tsTickPerHour[pCfg->precision]; minKey = now - pCfg->keep * tsTickPerDay[pCfg->precision]; midKey = now - pCfg->keep2 * tsTickPerDay[pCfg->precision]; maxKey = now - pCfg->keep1 * tsTickPerDay[pCfg->precision]; diff --git a/src/tsdb/src/tsdbRead.c b/src/tsdb/src/tsdbRead.c index 60c7311d4c0f3d784231fceb8a7e2628a5bd4eda..7027602aba7e1fb2b505ff36f85c35f30beecb60 100644 --- a/src/tsdb/src/tsdbRead.c +++ b/src/tsdb/src/tsdbRead.c @@ -183,7 +183,6 @@ static void changeQueryHandleForInterpQuery(TsdbQueryHandleT pHandle); static void doMergeTwoLevelData(STsdbQueryHandle* pQueryHandle, STableCheckInfo* pCheckInfo, SBlock* pBlock); static int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order); static int32_t tsdbReadRowsFromCache(STableCheckInfo* pCheckInfo, TSKEY maxKey, int maxRowsToRead, STimeWindow* win, STsdbQueryHandle* pQueryHandle); -static int32_t tsdbCheckInfoCompar(const void* key1, const void* key2); static int32_t doGetExternalRow(STsdbQueryHandle* pQueryHandle, int16_t type, SMemRef* pMemRef); static void* doFreeColumnInfoData(SArray* pColumnInfoData); static void* destroyTableCheckInfo(SArray* pTableCheckInfo); @@ -333,8 +332,6 @@ static SArray* createCheckInfoFromTableGroup(STsdbQueryHandle* pQueryHandle, STa } } - taosArraySort(pTableCheckInfo, tsdbCheckInfoCompar); - size_t gsize = taosArrayGetSize(pTableCheckInfo); for (int32_t i = 0; i < gsize; ++i) { @@ -2898,7 +2895,7 @@ static bool doHasDataInBuffer(STsdbQueryHandle* pQueryHandle) { return false; } -//todo not unref yet, since it is not support multi-group interpolation query +//todo not unref yet, since it does not support multi-group interpolation query static UNUSED_FUNC void changeQueryHandleForInterpQuery(TsdbQueryHandleT pHandle) { // filter the queried time stamp in the first place STsdbQueryHandle* pQueryHandle = (STsdbQueryHandle*) pHandle; @@ -3911,17 +3908,6 @@ static int32_t tableGroupComparFn(const void *p1, const void *p2, const void *pa return 0; } -static int tsdbCheckInfoCompar(const void* key1, const void* key2) { - if (((STableCheckInfo*)key1)->tableId.tid < ((STableCheckInfo*)key2)->tableId.tid) { - return -1; - } else if (((STableCheckInfo*)key1)->tableId.tid > ((STableCheckInfo*)key2)->tableId.tid) { - return 1; - } else { - ASSERT(false); - return 0; - } -} - void createTableGroupImpl(SArray* pGroups, SArray* pTableList, size_t numOfTables, TSKEY skey, STableGroupSupporter* pSupp, __ext_compar_fn_t compareFn) { STable* pTable = taosArrayGetP(pTableList, 0); diff --git a/src/tsdb/src/tsdbReadImpl.c b/src/tsdb/src/tsdbReadImpl.c index f2678c627fa61aff227ae61749d2ed76ef5e2db8..57b91e5f3d867c79b3739bfe2f88e73239dd2eb6 100644 --- a/src/tsdb/src/tsdbReadImpl.c +++ b/src/tsdb/src/tsdbReadImpl.c @@ -172,28 +172,28 @@ int tsdbSetReadTable(SReadH *pReadh, STable *pTable) { size_t size = taosArrayGetSize(pReadh->aBlkIdx); if (size > 0) { - while (true) { - if (pReadh->cidx >= size) { - pReadh->pBlkIdx = NULL; - break; - } - - SBlockIdx *pBlkIdx = taosArrayGet(pReadh->aBlkIdx, pReadh->cidx); + int64_t left = 0, right = size - 1; + while (left <= right) { + int64_t mid = (left + right) / 2; + SBlockIdx *pBlkIdx = taosArrayGet(pReadh->aBlkIdx, (size_t)mid); if (pBlkIdx->tid == TABLE_TID(pTable)) { if (pBlkIdx->uid == TABLE_UID(pTable)) { pReadh->pBlkIdx = pBlkIdx; } else { pReadh->pBlkIdx = NULL; } - pReadh->cidx++; - break; - } else if (pBlkIdx->tid > TABLE_TID(pTable)) { - pReadh->pBlkIdx = NULL; + break; + } else if (pBlkIdx->tid < TABLE_TID(pTable)) { + left = mid + 1; } else { - pReadh->cidx++; + right = mid - 1; } } + + if (left > right) { + pReadh->pBlkIdx = NULL; + } } else { pReadh->pBlkIdx = NULL; } diff --git a/src/util/inc/hashfunc.h b/src/util/inc/hashfunc.h index 529188849846088106f6576242ef76e2894ccb1b..55835a60c92dc641cdef0f9bb75aa631aac4fddd 100644 --- a/src/util/inc/hashfunc.h +++ b/src/util/inc/hashfunc.h @@ -33,7 +33,8 @@ typedef void (*_hash_free_fn_t)(void *param); */ uint32_t MurmurHash3_32(const char *key, uint32_t len); -/** +uint64_t MurmurHash3_64(const void *key, uint32_t len); + /** * * @param key * @param len diff --git a/src/util/inc/tconfig.h b/src/util/inc/tconfig.h index c0a4986936f7d43d48aa4fac0be6f427f5db32f5..a2c293772213fe804bc49fb2b74b9cc557dca269 100644 --- a/src/util/inc/tconfig.h +++ b/src/util/inc/tconfig.h @@ -20,7 +20,7 @@ extern "C" { #endif -#define TSDB_CFG_MAX_NUM 133 +#define TSDB_CFG_MAX_NUM 136 #define TSDB_CFG_PRINT_LEN 23 #define TSDB_CFG_OPTION_LEN 24 #define TSDB_CFG_VALUE_LEN 41 diff --git a/src/util/inc/tmd5.h b/src/util/inc/tmd5.h index d7fd038f37c9e1698394c90e07aaf9ac6a23590c..d73b6df55626bc9d63d3a4325326d36fbe9ab2ad 100644 --- a/src/util/inc/tmd5.h +++ b/src/util/inc/tmd5.h @@ -31,11 +31,11 @@ typedef struct { uint32_t i[2]; /* number of _bits_ handled mod 2^64 */ uint32_t buf[4]; /* scratch buffer */ uint8_t in[64]; /* input buffer */ - uint8_t digest[16]; /* actual digest after MD5Final call */ -} MD5_CTX; + uint8_t digest[16]; /* actual digest after tMD5Final call */ +} T_MD5_CTX; -void MD5Init(MD5_CTX *mdContext); -void MD5Update(MD5_CTX *mdContext, uint8_t *inBuf, unsigned int inLen); -void MD5Final(MD5_CTX *mdContext); +void tMD5Init(T_MD5_CTX *mdContext); +void tMD5Update(T_MD5_CTX *mdContext, uint8_t *inBuf, unsigned int inLen); +void tMD5Final(T_MD5_CTX *mdContext); #endif diff --git a/src/util/inc/ttoken.h b/src/util/inc/ttoken.h index 17f2bf5a79f9dd2c6650e4b0cb24a492c4d68e3a..79ad074f59578eae44bbb6519822809b367b5337 100644 --- a/src/util/inc/ttoken.h +++ b/src/util/inc/ttoken.h @@ -27,6 +27,14 @@ extern "C" { #define TSQL_TBNAME "TBNAME" #define TSQL_TBNAME_L "tbname" +#define TSQL_TSWIN_START "_wstart" +#define TSQL_TSWIN_STOP "_wstop" +#define TSQL_TSWIN_DURATION "_wduration" + +#define TSQL_QUERY_START "_qstart" +#define TSQL_QUERY_STOP "_qstop" +#define TSQL_QUERY_DURATION "_qduration" + #define TSQL_BLOCK_DIST "_BLOCK_DIST" #define TSQL_BLOCK_DIST_L "_block_dist" diff --git a/src/util/inc/tutil.h b/src/util/inc/tutil.h index a97b731f93c214536c009e94d05edc5c3d6e7ee9..60faa4d5a24082f0c1cf3e5967ece07d68a74e4e 100644 --- a/src/util/inc/tutil.h +++ b/src/util/inc/tutil.h @@ -47,10 +47,10 @@ void jsonKeyMd5(void *pMsg, int msgLen, void *pKey); bool isValidateTag(char *input); static FORCE_INLINE void taosEncryptPass(uint8_t *inBuf, size_t inLen, char *target) { - MD5_CTX context; - MD5Init(&context); - MD5Update(&context, inBuf, (unsigned int)inLen); - MD5Final(&context); + T_MD5_CTX context; + tMD5Init(&context); + tMD5Update(&context, inBuf, (unsigned int)inLen); + tMD5Final(&context); memcpy(target, context.digest, TSDB_KEY_LEN); } diff --git a/src/util/src/tcompare.c b/src/util/src/tcompare.c index fe4ded7742c4080b1a79a5b80b5ab1a702567ad1..2ab5ddbbe0ac1025be72e69fe88050d2aa3f73ad 100644 --- a/src/util/src/tcompare.c +++ b/src/util/src/tcompare.c @@ -180,19 +180,25 @@ int32_t compareDoubleValDesc(const void* pLeft, const void* pRight) { } int32_t compareLenPrefixedStr(const void *pLeft, const void *pRight) { + bool leftIsNull = isNull(pLeft, TSDB_DATA_TYPE_BINARY); + bool rightIsNull = isNull(pRight, TSDB_DATA_TYPE_BINARY); + if(leftIsNull && rightIsNull) return 0; + else if(leftIsNull) return -1; + else if(rightIsNull) return 1; + int32_t len1 = varDataLen(pLeft); int32_t len2 = varDataLen(pRight); - if (len1 != len2) { - return len1 > len2? 1:-1; - } else { - int32_t ret = strncmp(varDataVal(pLeft), varDataVal(pRight), len1); - if (ret == 0) { + int32_t ret = strncmp(varDataVal(pLeft), varDataVal(pRight), len1>len2 ? len2:len1); + if (ret == 0) { + if (len1 > len2) + return 1; + else if(len1 < len2) + return -1; + else return 0; - } else { - return ret > 0 ? 1:-1; - } } + return (ret < 0) ? -1 : 1; } int32_t compareLenPrefixedStrDesc(const void* pLeft, const void* pRight) { @@ -200,19 +206,25 @@ int32_t compareLenPrefixedStrDesc(const void* pLeft, const void* pRight) { } int32_t compareLenPrefixedWStr(const void *pLeft, const void *pRight) { + bool leftIsNull = isNull(pLeft, TSDB_DATA_TYPE_NCHAR); + bool rightIsNull = isNull(pRight, TSDB_DATA_TYPE_NCHAR); + if(leftIsNull && rightIsNull) return 0; + else if(leftIsNull) return -1; + else if(rightIsNull) return 1; + int32_t len1 = varDataLen(pLeft); int32_t len2 = varDataLen(pRight); - if (len1 != len2) { - return len1 > len2? 1:-1; - } else { - int32_t ret = memcmp((wchar_t*) pLeft, (wchar_t*) pRight, len1); - if (ret == 0) { + int32_t ret = tasoUcs4Compare(varDataVal(pLeft), varDataVal(pRight), len1>len2 ? len2:len1); + if (ret == 0) { + if (len1 > len2) + return 1; + else if(len1 < len2) + return -1; + else return 0; - } else { - return ret > 0 ? 1 : -1; - } } + return (ret < 0) ? -1 : 1; } int32_t compareLenPrefixedWStrDesc(const void* pLeft, const void* pRight) { @@ -750,7 +762,8 @@ int32_t jsonCompareUnit(const char* f1, const char* f2, bool* canReturn){ } } -int32_t doCompare(const char* f1, const char* f2, int32_t type, size_t size) { +int32_t +doCompare(const char* f1, const char* f2, int32_t type, size_t size) { if (type == TSDB_DATA_TYPE_JSON){ bool canReturn = true; int32_t result = jsonCompareUnit(f1, f2, &canReturn); @@ -771,33 +784,8 @@ int32_t doCompare(const char* f1, const char* f2, int32_t type, size_t size) { case TSDB_DATA_TYPE_USMALLINT: DEFAULT_COMP(GET_UINT16_VAL(f1), GET_UINT16_VAL(f2)); case TSDB_DATA_TYPE_UINT: DEFAULT_COMP(GET_UINT32_VAL(f1), GET_UINT32_VAL(f2)); case TSDB_DATA_TYPE_UBIGINT: DEFAULT_COMP(GET_UINT64_VAL(f1), GET_UINT64_VAL(f2)); - case TSDB_DATA_TYPE_NCHAR:{ - tstr* t1 = (tstr*) f1; - tstr* t2 = (tstr*) f2; - - if (t1->len != t2->len) { - return t1->len > t2->len? 1:-1; - } - int32_t ret = memcmp((wchar_t*) t1, (wchar_t*) t2, t2->len); - if (ret == 0) { - return ret; - } - return (ret < 0) ? -1 : 1; - } - default: { // todo refactor - tstr* t1 = (tstr*) f1; - tstr* t2 = (tstr*) f2; - - if (t1->len != t2->len) { - return t1->len > t2->len? 1:-1; - } else { - int32_t ret = strncmp(t1->data, t2->data, t1->len); - if (ret == 0) { - return 0; - } else { - return ret < 0? -1:1; - } - } - } + case TSDB_DATA_TYPE_NCHAR: return compareLenPrefixedWStr(f1, f2); + default: // BINARY AND NULL AND SO ON + return compareLenPrefixedStr(f1, f2); } } diff --git a/src/util/src/terror.c b/src/util/src/terror.c index 159ae7cd1d336bdf4ff2b1d58598ab4fd164f35a..cee9245ec79abce96d8990e179cfd457791bf318 100644 --- a/src/util/src/terror.c +++ b/src/util/src/terror.c @@ -334,9 +334,9 @@ TAOS_DEFINE_ERROR(TSDB_CODE_WAL_FILE_CORRUPTED, "WAL file is corrupted TAOS_DEFINE_ERROR(TSDB_CODE_WAL_SIZE_LIMIT, "WAL size exceeds limit") // http -TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_SERVER_OFFLINE, "http server is not onlin") -TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_UNSUPPORT_URL, "url is not support") -TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_INVALID_URL, "invalid url format") +TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_SERVER_OFFLINE, "http server is not online") +TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_UNSUPPORT_URL, "url is not supported") +TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_INVALID_URL, "invalid url format") TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_NO_ENOUGH_MEMORY, "no enough memory") TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_REQUSET_TOO_BIG, "request size is too big") TAOS_DEFINE_ERROR(TSDB_CODE_HTTP_NO_AUTH_INFO, "no auth info input") diff --git a/src/util/src/thashutil.c b/src/util/src/thashutil.c index 4a0208a3d0bf22f21b5f6a05513f435664e746af..545a91daf5f6ebd3721f6d005750f9cf235939cf 100644 --- a/src/util/src/thashutil.c +++ b/src/util/src/thashutil.c @@ -78,6 +78,42 @@ uint32_t MurmurHash3_32(const char *key, uint32_t len) { return h1; } +uint64_t MurmurHash3_64(const void *key, uint32_t len) { + const uint64_t m = 0x87c37b91114253d5; + const int r = 47; + uint32_t seed = 0x12345678; + uint64_t h = seed ^ (len * m); + const uint8_t *data = (const uint8_t *)key; + const uint8_t *end = data + (len-(len&7)); + + while(data != end) { + uint64_t k = *((uint64_t*)data); + + k *= m; + k ^= k >> r; + k *= m; + h ^= k; + h *= m; + data += 8; + } + + switch(len & 7) { + case 7: h ^= (uint64_t)data[6] << 48; /* fall-thru */ + case 6: h ^= (uint64_t)data[5] << 40; /* fall-thru */ + case 5: h ^= (uint64_t)data[4] << 32; /* fall-thru */ + case 4: h ^= (uint64_t)data[3] << 24; /* fall-thru */ + case 3: h ^= (uint64_t)data[2] << 16; /* fall-thru */ + case 2: h ^= (uint64_t)data[1] << 8; /* fall-thru */ + case 1: h ^= (uint64_t)data[0]; + h *= m; /* fall-thru */ + }; + + h ^= h >> r; + h *= m; + h ^= h >> r; + return h; +} + uint32_t taosIntHash_32(const char *key, uint32_t UNUSED_PARAM(len)) { return *(uint32_t *)key; } uint32_t taosIntHash_16(const char *key, uint32_t UNUSED_PARAM(len)) { return *(uint16_t *)key; } uint32_t taosIntHash_8(const char *key, uint32_t UNUSED_PARAM(len)) { return *(uint8_t *)key; } diff --git a/src/util/src/tmd5.c b/src/util/src/tmd5.c index a1fdcc6a0539ad8f7bd804ab039e0e639d20ad3e..4549c95aae855fbcf98a06003940fa86ab4fb461 100644 --- a/src/util/src/tmd5.c +++ b/src/util/src/tmd5.c @@ -2,9 +2,9 @@ *********************************************************************** ** Message-digest routines: ** ** To form the message digest for a message M ** - ** (1) Initialize a context buffer mdContext using MD5Init ** - ** (2) Call MD5Update on mdContext and M ** - ** (3) Call MD5Final on mdContext ** + ** (1) Initialize a context buffer mdContext using tMD5Init ** + ** (2) Call tMD5Update on mdContext and M ** + ** (3) Call tMD5Final on mdContext ** ** The message digest is now in mdContext->digest[0...15] ** *********************************************************************** */ @@ -82,11 +82,11 @@ static uint8_t PADDING[64] = {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x (a) += (b); \ } -/* The routine MD5Init initializes the message-digest context +/* The routine tMD5Init initializes the message-digest context mdContext. All fields are set to zero. */ -void MD5Init(MD5_CTX *mdContext) { - memset(mdContext, 0, sizeof(MD5_CTX)); +void tMD5Init(T_MD5_CTX *mdContext) { + memset(mdContext, 0, sizeof(T_MD5_CTX)); /* Load magic initialization constants. */ mdContext->buf[0] = (uint32_t)0x67452301; @@ -95,11 +95,11 @@ void MD5Init(MD5_CTX *mdContext) { mdContext->buf[3] = (uint32_t)0x10325476; } -/* The routine MD5Update updates the message-digest context to +/* The routine tMD5Update updates the message-digest context to account for the presence of each of the characters inBuf[0..inLen-1] in the message whose digest is being computed. */ -void MD5Update(MD5_CTX *mdContext, uint8_t *inBuf, unsigned int inLen) { +void tMD5Update(T_MD5_CTX *mdContext, uint8_t *inBuf, unsigned int inLen) { uint32_t in[16]; int mdi; unsigned int i, ii; @@ -127,10 +127,10 @@ void MD5Update(MD5_CTX *mdContext, uint8_t *inBuf, unsigned int inLen) { } } -/* The routine MD5Final terminates the message-digest computation and +/* The routine tMD5Final terminates the message-digest computation and ends with the desired message digest in mdContext->digest[0...15]. */ -void MD5Final(MD5_CTX *mdContext) { +void tMD5Final(T_MD5_CTX *mdContext) { uint32_t in[16]; int mdi; unsigned int i, ii; @@ -145,7 +145,7 @@ void MD5Final(MD5_CTX *mdContext) { /* pad out to 56 mod 64 */ padLen = (mdi < 56) ? (56 - mdi) : (120 - mdi); - MD5Update(mdContext, PADDING, padLen); + tMD5Update(mdContext, PADDING, padLen); /* append length in bits and transform */ for (i = 0, ii = 0; i < 14; i++, ii += 4) diff --git a/src/util/src/tnettest.c b/src/util/src/tnettest.c index 7d1076abbf1eb0c35385b769bfc6a88cfd8a21a7..2094c3d4be59c5636c6f987a790c163bd61c2227 100644 --- a/src/util/src/tnettest.c +++ b/src/util/src/tnettest.c @@ -568,7 +568,7 @@ static void taosNetCheckSpeed(char *host, int32_t port, int32_t pkgLen, int32_t compressTmp = tsCompressMsgSize; int32_t maxUdpSize = tsRpcMaxUdpSize; int32_t forceTcp = tsRpcForceTcp; - + //Precheck for FQDN lgenth if (strlen(host) >= TSDB_FQDN_LEN) { uError("FQDN length is too long"); @@ -615,7 +615,7 @@ static void taosNetCheckSpeed(char *host, int32_t port, int32_t pkgLen, reqMsg.handle = NULL; // rpc handle returned to app reqMsg.ahandle = NULL; // app handle set by client tstrncpy((char*)reqMsg.pCont, "nettest speed", pkgLen); - + rpcSendRecv(pRpcConn, &epSet, &reqMsg, &rspMsg); int code = 0; diff --git a/src/util/src/tsocket.c b/src/util/src/tsocket.c index 8d69a87e77bff594e7a99b2a63d4d849214eebe9..0ebe9c8f8af23186fb4cd60824bfa5641d2090a9 100644 --- a/src/util/src/tsocket.c +++ b/src/util/src/tsocket.c @@ -17,6 +17,7 @@ #include "tulog.h" #include "tsocket.h" #include "taoserror.h" +#include "tglobal.h" #ifndef SIGPIPE #define SIGPIPE EPIPE @@ -362,7 +363,7 @@ SOCKET taosOpenTcpClientSocket(uint32_t destIp, uint16_t destPort, uint32_t clie wfd[0].fd = sockFd; wfd[0].events = POLLOUT; - int res = poll(wfd, 1, TCP_CONN_TIMEOUT); + int res = poll(wfd, 1, tsTcpConnTimeout); if (res == -1 || res == 0) { uError("failed to connect socket, ip:0x%x, port:%hu(poll error/conn timeout)", destIp, destPort); taosCloseSocket(sockFd); // diff --git a/src/util/src/ttokenizer.c b/src/util/src/ttokenizer.c index 93883f645195c56011de85136461a43398f14b01..2a17e4ae52f86314d7d1340e95ba56f586f89b97 100644 --- a/src/util/src/ttokenizer.c +++ b/src/util/src/ttokenizer.c @@ -48,8 +48,6 @@ static SKeyword keywordTable[] = { {"OR", TK_OR}, {"AND", TK_AND}, {"NOT", TK_NOT}, - {"EQ", TK_EQ}, - {"NE", TK_NE}, {"ISNULL", TK_ISNULL}, {"NOTNULL", TK_NOTNULL}, {"IS", TK_IS}, @@ -58,10 +56,6 @@ static SKeyword keywordTable[] = { {"GLOB", TK_GLOB}, {"BETWEEN", TK_BETWEEN}, {"IN", TK_IN}, - {"GT", TK_GT}, - {"GE", TK_GE}, - {"LT", TK_LT}, - {"LE", TK_LE}, {"BITAND", TK_BITAND}, {"BITOR", TK_BITOR}, {"LSHIFT", TK_LSHIFT}, @@ -531,6 +525,8 @@ uint32_t tGetToken(char* z, uint32_t* tokenId) { for (i = 1; isdigit(z[i]); i++) { } + uint32_t j = i; + /* here is the 1u/1a/2s/3m/9y */ if ((z[i] == 'b' || z[i] == 'u' || z[i] == 'a' || z[i] == 's' || z[i] == 'm' || z[i] == 'h' || z[i] == 'd' || z[i] == 'n' || z[i] == 'y' || z[i] == 'w' || @@ -565,6 +561,14 @@ uint32_t tGetToken(char* z, uint32_t* tokenId) { } *tokenId = TK_FLOAT; } + + if (*tokenId == TK_INTEGER && z[j] != '\0') { + char c = z[j] | 0x20; + if (c >= 'a' && c <= 'z') { + *tokenId = TK_ID; + } + } + return i; } case '[': { diff --git a/src/util/src/tutil.c b/src/util/src/tutil.c index 8bcef9f32b152082c7ab715ededc996b63558562..7e08178c42cbb7e34a0aec340352916d874a7094 100644 --- a/src/util/src/tutil.c +++ b/src/util/src/tutil.c @@ -455,11 +455,11 @@ char *taosIpStr(uint32_t ipInt) { } void jsonKeyMd5(void *pMsg, int msgLen, void *pKey) { - MD5_CTX context; + T_MD5_CTX context; - MD5Init(&context); - MD5Update(&context, (uint8_t *)pMsg, msgLen); - MD5Final(&context); + tMD5Init(&context); + tMD5Update(&context, (uint8_t *)pMsg, msgLen); + tMD5Final(&context); memcpy(pKey, context.digest, sizeof(context.digest)); } diff --git a/tests/comparisonTest/opentsdb/opentsdbtest/pom.xml b/tests/comparisonTest/opentsdb/opentsdbtest/pom.xml index 55fc281f58544a317f2e423e47b6a7d821296b09..4f963c0812a5cd95ca755736d531db17ab18f704 100644 --- a/tests/comparisonTest/opentsdb/opentsdbtest/pom.xml +++ b/tests/comparisonTest/opentsdb/opentsdbtest/pom.xml @@ -118,7 +118,7 @@ com.fasterxml.jackson.core jackson-databind - 2.10.0.pr1 + 2.12.6.1 diff --git a/tests/develop-test/0-others/json_tag.py b/tests/develop-test/0-others/json_tag.py index 67c2f8f0f0ec5999b4c2e69f17c79f8a8fa5691d..c78e48b6d19bc1b977db417233b6e12c61a66112 100644 --- a/tests/develop-test/0-others/json_tag.py +++ b/tests/develop-test/0-others/json_tag.py @@ -34,7 +34,6 @@ class TDTestCase: def run(self): tdSql.prepare() - print("============== STEP 1 ===== prepare data & validate json string") tdSql.error("create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json, tagint int)") tdSql.error("create table if not exists jsons1(ts timestamp, data json) tags(tagint int)") @@ -379,8 +378,8 @@ class TDTestCase: tdSql.error("select count(*) from jsons1 group by jtag->'tag1' order by jtag") tdSql.query("select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc") tdSql.checkRows(8) - tdSql.checkData(0, 0, 2) - tdSql.checkData(0, 1, '"femail"') + tdSql.checkData(1, 0, 2) + tdSql.checkData(1, 1, '"femail"') tdSql.checkData(2, 0, 1) tdSql.checkData(2, 1, 11) tdSql.checkData(5, 0, 1) @@ -398,8 +397,8 @@ class TDTestCase: tdSql.checkData(2, 1, "false") tdSql.checkData(5, 0, 1) tdSql.checkData(5, 1, 11) - tdSql.checkData(7, 0, 2) - tdSql.checkData(7, 1, '"femail"') + tdSql.checkData(6, 0, 2) + tdSql.checkData(6, 1, '"femail"') # test stddev with group by json tag tdSql.query("select stddev(dataint) from jsons1 group by jtag->'tag1'") @@ -407,8 +406,8 @@ class TDTestCase: tdSql.checkData(0, 1, None) tdSql.checkData(1, 0, 0) tdSql.checkData(1, 1, "null") - tdSql.checkData(7, 0, 11) - tdSql.checkData(7, 1, '"femail"') + tdSql.checkData(6, 0, 11) + tdSql.checkData(6, 1, '"femail"') res = tdSql.getColNameList("select stddev(dataint) from jsons1 group by jsons1.jtag->'tag1'") cname_list = [] @@ -422,8 +421,8 @@ class TDTestCase: tdSql.checkData(0, 1, 4) tdSql.checkData(1, 1, 24) tdSql.checkData(1, 2, None) - tdSql.checkData(10, 1, 1) - tdSql.checkData(10, 2, '"femail"') + tdSql.checkData(8, 1, 1) + tdSql.checkData(8, 2, '"femail"') # test having tdSql.query("select stddev(dataint) from jsons1 group by jtag->'tag1' having stddev(dataint) > 0") @@ -437,7 +436,7 @@ class TDTestCase: tdSql.query("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)") tdSql.checkRows(11) - tdSql.checkData(0, 0, '"femail"') + tdSql.checkData(1, 0, '"femail"') tdSql.checkData(2, 0, 5) res = tdSql.getColNameList("select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)") @@ -531,6 +530,26 @@ class TDTestCase: tdSql.checkData(5, 2, 4096) tdSql.query("describe jsons1_1") tdSql.checkData(5, 2, 4096) + + #test TD-13918 + tdSql.execute("drop table if exists jsons_13918_1") + tdSql.execute("drop table if exists jsons_13918_2") + tdSql.execute("drop table if exists jsons_13918_3") + tdSql.execute("drop table if exists jsons_13918_4") + tdSql.execute("drop table if exists jsons_stb") + tdSql.execute("create table jsons_stb (ts timestamp, dataInt int) tags (jtag json)") + tdSql.error("create table jsons_13918_1 using jsons_stb tags ('nullx')") + tdSql.error("create table jsons_13918_2 using jsons_stb tags (nullx)") + tdSql.error("insert into jsons_13918_3 using jsons_stb tags('NULLx') values(1591061628001, 11)") + tdSql.error("insert into jsons_13918_4 using jsons_stb tags(NULLx) values(1591061628002, 11)") + tdSql.execute("create table jsons_13918_1 using jsons_stb tags ('null')") + tdSql.execute("create table jsons_13918_2 using jsons_stb tags (null)") + tdSql.execute("insert into jsons_13918_1 values(1591061628003, 11)") + tdSql.execute("insert into jsons_13918_2 values(1591061628004, 11)") + tdSql.execute("insert into jsons_13918_3 using jsons_stb tags('NULL') values(1591061628005, 11)") + tdSql.execute("insert into jsons_13918_4 using jsons_stb tags(\"NULL\") values(1591061628006, 11)") + tdSql.query("select * from jsons_stb") + tdSql.checkRows(4) def stop(self): tdSql.close() diff --git a/tests/develop-test/2-query/TD-13414.py b/tests/develop-test/2-query/TD-13414.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff2dbe73f0106fbc5e8fdf117490edc543e7cbd --- /dev/null +++ b/tests/develop-test/2-query/TD-13414.py @@ -0,0 +1,89 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-13414] taos shell coredump when scalar function arithmetic operation has bool operands + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists db") + tdSql.execute("create database if not exists db") + tdSql.execute('use db') + + tdSql.execute('create stable stb(ts timestamp, c0 int) tags (t0 int)') + tdSql.execute('create table ctb using stb tags (1)') + tdSql.execute('create table tb (ts timestamp, c0 int)') + + tdSql.execute('insert into ctb values(now, 1)') + tdSql.execute('insert into tb values(now, 1)') + + tdSql.error('select ceil(1.5) + true from stb') + tdSql.error('select ceil(1.5) + true from ctb') + tdSql.error('select ceil(1.5) + true from tb') + + tdSql.error('select round(c0) + false from stb') + tdSql.error('select round(c0) + false from ctb') + tdSql.error('select round(c0) + false from tb') + + tdSql.error('select cos(1) + true from stb') + tdSql.error('select cos(1) + true from ctb') + tdSql.error('select cos(1) + true from tb') + + tdSql.error('select true - ceil(1.5) from stb') + tdSql.error('select true - ceil(1.5) from ctb') + tdSql.error('select true - ceil(1.5) from tb') + + tdSql.error('select false - round(c0) from stb') + tdSql.error('select false - round(c0) from ctb') + tdSql.error('select false - round(c0) from tb') + + tdSql.error('select true - cos(1) from stb') + tdSql.error('select true - cos(1) from ctb') + tdSql.error('select true - cos(1) from tb') + + tdSql.error('select true + ceil(1.5) - false from stb') + tdSql.error('select true + ceil(1.5) - false from ctb') + tdSql.error('select true + ceil(1.5) - false from tb') + + tdSql.error('select false - round(c0) - false from stb') + tdSql.error('select false - round(c0) - false from ctb') + tdSql.error('select false - round(c0) - false from tb') + + tdSql.error('select true - cos(1) - false from stb') + tdSql.error('select true - cos(1) - false from ctb') + tdSql.error('select true - cos(1) - false from tb') + + tdSql.execute('drop database db') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/TD-13946.py b/tests/develop-test/2-query/TD-13946.py new file mode 100644 index 0000000000000000000000000000000000000000..d08ac0989dc4edda01946f826e690cc41fc62ca1 --- /dev/null +++ b/tests/develop-test/2-query/TD-13946.py @@ -0,0 +1,44 @@ +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import tdDnodes +from math import inf + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-13946]core dump of sampling binary column so that when result from vnode exceeds INT16_MAX bytes + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists td13946") + tdSql.execute("create database td13946") + tdSql.execute("use td13946") + + tdSql.execute("create table st ( ts timestamp, bin binary(100)) tags (t1 int)") + tdSql.execute("create table ct1 using st tags(1)") + tdSql.execute("create table ct2 using st tags(2)") + + for i in range(0, 4000, 2): + tdSql.execute("insert into ct1 values(now + {}a, '{}')".format(i, i)) + tdSql.execute("insert into ct2 values(now + {}a, '{}')".format(i+1, i+1)) + + tdSql.query("select sample(bin, 1000) from td13946.st group by tbname") + + tdSql.execute('drop database td13946') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) + diff --git a/tests/develop-test/2-query/TD-14196.py b/tests/develop-test/2-query/TD-14196.py new file mode 100644 index 0000000000000000000000000000000000000000..c96474e1a0e0fc2339b8cb8fc08f7ad2c5715858 --- /dev/null +++ b/tests/develop-test/2-query/TD-14196.py @@ -0,0 +1,39 @@ +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import tdDnodes +from math import inf + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-13946]core dump of sampling binary column so that when result from vnode exceeds INT16_MAX bytes + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists td14196") + tdSql.execute("create database td14196") + tdSql.execute("use td14196") + + tdSql.execute("create table st ( ts timestamp, dint int) tags (t1 int)") + tdSql.execute("create table ct1 using st tags(1)") + + tdSql.execute("insert into ct1 values(now, 100)") + + tdSql.query("select last(dint)/100 from ct1") + tdSql.checkData(0, 0, 1) + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) + diff --git a/tests/develop-test/2-query/TD-5902.py b/tests/develop-test/2-query/TD-5902.py new file mode 100644 index 0000000000000000000000000000000000000000..b2dd6f972a7fb0529fa873794c824fe5af6aa987 --- /dev/null +++ b/tests/develop-test/2-query/TD-5902.py @@ -0,0 +1,110 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-5902] [Improvement] Support rcf3339 format timestamp in tag + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists db") + tdSql.execute("create database if not exists db") + tdSql.execute('use db') + + tdSql.execute('create stable stb(ts timestamp , c0 int) tags (t0 timestamp)') + + #create using stb tags + tdSql.execute('create table ctb1 using stb tags("2020-02-02T02:00:00")') + tdSql.query('select t0 from ctb1'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 02:00:00") + + tdSql.execute('create table ctb2 using stb tags("2020-02-02T02:00:00+0700")') + tdSql.query('select t0 from ctb2'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 03:00:00") + + tdSql.execute('create table ctb3 using stb tags("2020-02-02T02:00:00+07:00")') + tdSql.query('select t0 from ctb3'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 03:00:00") + + tdSql.execute('create table ctb4 using stb tags("2020-02-02T02:00:00-0800")') + tdSql.query('select t0 from ctb4'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 18:00:00") + + tdSql.execute('create table ctb5 using stb tags("2020-02-02T02:00:00-08:00")') + tdSql.query('select t0 from ctb5'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 18:00:00") + + tdSql.execute('create table ctb6 using stb tags("2020-02-02T02:00:00Z")') + tdSql.query('select t0 from ctb6'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 10:00:00") + + #insert using stb tags + tdSql.execute('insert into ctb7 using stb tags("2020-02-02T02:00:00") values (now, 1)') + tdSql.query('select t0 from ctb7'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 02:00:00") + + tdSql.execute('insert into ctb8 using stb tags("2020-02-02T02:00:00+0700") values (now, 1)') + tdSql.query('select t0 from ctb8'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 03:00:00") + + tdSql.execute('insert into ctb9 using stb tags("2020-02-02T02:00:00+07:00") values (now, 1)') + tdSql.query('select t0 from ctb9'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 03:00:00") + + tdSql.execute('insert into ctb10 using stb tags("2020-02-02T02:00:00-0800") values (now, 1)') + tdSql.query('select t0 from ctb10'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 18:00:00") + + tdSql.execute('insert into ctb11 using stb tags("2020-02-02T02:00:00-08:00") values (now, 1)') + tdSql.query('select t0 from ctb11'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 18:00:00") + + tdSql.execute('insert into ctb12 using stb tags("2020-02-02T02:00:00Z") values (now, 1)') + tdSql.query('select t0 from ctb12'); + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 10:00:00") + + tdSql.execute('drop database db') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/diff_funcs.py b/tests/develop-test/2-query/diff_funcs.py index b7c1a0c0195f306a2e00a9cafc32e56a018bd54b..298292929fe334969defd21a22a35a66837fcbcd 100644 --- a/tests/develop-test/2-query/diff_funcs.py +++ b/tests/develop-test/2-query/diff_funcs.py @@ -144,13 +144,15 @@ class TDTestCase: tdSql.checkData(2, 1, 1.79769e+308) tdSql.query('select diff(c4,1) from tb1;') - tdSql.checkRows(3) + tdSql.checkRows(4) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(1, 1, 2) tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 1, 2147483643) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) tdSql.query('select diff(c4) from tb1;') tdSql.checkRows(4) @@ -168,13 +170,15 @@ class TDTestCase: tdSql.error('select diff(13) from tb1;') tdSql.query('select diff(c4,1) from tb1;') - tdSql.checkRows(3) + tdSql.checkRows(4) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(1, 1, 2) tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 1, 2147483643) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) tdSql.query('select diff(c2) from tb1;') tdSql.checkRows(4) @@ -277,7 +281,7 @@ class TDTestCase: tdSql.error('select diff(c4,1) from stb1 group by c1;') tdSql.query('select diff(c4,1) from stb1 group by tbname;') - tdSql.checkRows(9) + tdSql.checkRows(10) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(0, 2, 'tb1') @@ -287,24 +291,27 @@ class TDTestCase: tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 1, 2147483643) tdSql.checkData(2, 2, 'tb1') - tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 1)) - tdSql.checkData(3, 1, 1) - tdSql.checkData(3, 2, 'tb2') - tdSql.checkData(4, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) - tdSql.checkData(4, 1, 0) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) + tdSql.checkData(3, 2, 'tb1') + tdSql.checkData(4, 0, datetime.datetime(2021, 11, 11, 9, 0, 1)) + tdSql.checkData(4, 1, 1) tdSql.checkData(4, 2, 'tb2') - tdSql.checkData(5, 0, datetime.datetime(2021, 11, 11, 9, 0, 3)) - tdSql.checkData(5, 1, 2) + tdSql.checkData(5, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) + tdSql.checkData(5, 1, 0) tdSql.checkData(5, 2, 'tb2') - tdSql.checkData(6, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) - tdSql.checkData(6, 1, 1) + tdSql.checkData(6, 0, datetime.datetime(2021, 11, 11, 9, 0, 3)) + tdSql.checkData(6, 1, 2) tdSql.checkData(6, 2, 'tb2') - tdSql.checkData(7, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) + tdSql.checkData(7, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(7, 1, 1) tdSql.checkData(7, 2, 'tb2') - tdSql.checkData(8, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(8, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(8, 1, 1) tdSql.checkData(8, 2, 'tb2') + tdSql.checkData(9, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(9, 1, 1) + tdSql.checkData(9, 2, 'tb2') tdSql.error('select diff(c4,1) from tb1 order by c2;') @@ -365,7 +372,7 @@ class TDTestCase: tdSql.error('select diff(c4,1),c1,c2 from tb1;') tdSql.query('select diff(c4,1),t1,ts,tbname,_C0,_c0 from tb1;') - tdSql.checkRows(3) + tdSql.checkRows(4) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(0, 2, 1) @@ -387,17 +394,26 @@ class TDTestCase: tdSql.checkData(2, 4, 'tb1') tdSql.checkData(2, 5, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 6, datetime.datetime(2021, 11, 11, 9, 0, 5)) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) + tdSql.checkData(3, 2, 1) + tdSql.checkData(3, 3, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 4, 'tb1') + tdSql.checkData(3, 5, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 6, datetime.datetime(2021, 11, 11, 9, 0, 6)) tdSql.error('select diff(c4,1),floor(c3) from tb1;') tdSql.error('select diff(c4,1),diff(c4,1) from tb1;') tdSql.query('select diff(c4,1) from tb1 where c2 is not null and c3 is not null;') - tdSql.checkRows(2) + tdSql.checkRows(3) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(0, 1, 3) tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(1, 1, 2147483643) + tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(2, 1, 2) tdSql.query('select diff(c2) from tb1 order by ts desc;') tdSql.checkRows(4) @@ -411,18 +427,10 @@ class TDTestCase: tdSql.checkData(3, 1, -1) tdSql.query('select diff(c4,1) from tb1 order by ts desc;') - tdSql.checkRows(3) - tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) - tdSql.checkData(0, 1, -2147483643) - tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) - tdSql.checkData(1, 1, -2) - tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0)) - tdSql.checkData(2, 1, -1) + tdSql.checkRows(0) tdSql.query('select diff(c4,1) from tb1 order by ts desc limit 3 offset 2;') - tdSql.checkRows(1) - tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0)) - tdSql.checkData(0, 1, -1) + tdSql.checkRows(0) tdSql.error('select diff(c2) from stb1;') @@ -674,13 +682,15 @@ class TDTestCase: tdSql.checkData(2, 1, 1.79769e+308) tdSql.query('select diff(c4,1) from tb1;') - tdSql.checkRows(3) + tdSql.checkRows(4) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(1, 1, 2) tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 1, 2147483643) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) tdSql.query('select diff(c4) from tb1;') tdSql.checkRows(4) @@ -698,13 +708,15 @@ class TDTestCase: tdSql.error('select diff(13) from tb1;') tdSql.query('select diff(c4,1) from tb1;') - tdSql.checkRows(3) + tdSql.checkRows(4) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(1, 1, 2) tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 1, 2147483643) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) tdSql.query('select diff(c2) from tb1;') tdSql.checkRows(4) @@ -807,7 +819,7 @@ class TDTestCase: tdSql.error('select diff(c4,1) from stb1 group by c1;') tdSql.query('select diff(c4,1) from stb1 group by tbname;') - tdSql.checkRows(9) + tdSql.checkRows(10) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(0, 2, 'tb1') @@ -817,24 +829,27 @@ class TDTestCase: tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 1, 2147483643) tdSql.checkData(2, 2, 'tb1') - tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 1)) - tdSql.checkData(3, 1, 1) - tdSql.checkData(3, 2, 'tb2') - tdSql.checkData(4, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) - tdSql.checkData(4, 1, 0) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) + tdSql.checkData(3, 2, 'tb1') + tdSql.checkData(4, 0, datetime.datetime(2021, 11, 11, 9, 0, 1)) + tdSql.checkData(4, 1, 1) tdSql.checkData(4, 2, 'tb2') - tdSql.checkData(5, 0, datetime.datetime(2021, 11, 11, 9, 0, 3)) - tdSql.checkData(5, 1, 2) + tdSql.checkData(5, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) + tdSql.checkData(5, 1, 0) tdSql.checkData(5, 2, 'tb2') - tdSql.checkData(6, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) - tdSql.checkData(6, 1, 1) + tdSql.checkData(6, 0, datetime.datetime(2021, 11, 11, 9, 0, 3)) + tdSql.checkData(6, 1, 2) tdSql.checkData(6, 2, 'tb2') - tdSql.checkData(7, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) + tdSql.checkData(7, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(7, 1, 1) tdSql.checkData(7, 2, 'tb2') - tdSql.checkData(8, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(8, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(8, 1, 1) tdSql.checkData(8, 2, 'tb2') + tdSql.checkData(9, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(9, 1, 1) + tdSql.checkData(9, 2, 'tb2') tdSql.error('select diff(c4,1) from tb1 order by c2;') @@ -895,7 +910,7 @@ class TDTestCase: tdSql.error('select diff(c4,1),c1,c2 from tb1;') tdSql.query('select diff(c4,1),t1,ts,tbname,_C0,_c0 from tb1;') - tdSql.checkRows(3) + tdSql.checkRows(4) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) tdSql.checkData(0, 1, 1) tdSql.checkData(0, 2, 1) @@ -917,17 +932,26 @@ class TDTestCase: tdSql.checkData(2, 4, 'tb1') tdSql.checkData(2, 5, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(2, 6, datetime.datetime(2021, 11, 11, 9, 0, 5)) + tdSql.checkData(3, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 1, 2) + tdSql.checkData(3, 2, 1) + tdSql.checkData(3, 3, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 4, 'tb1') + tdSql.checkData(3, 5, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(3, 6, datetime.datetime(2021, 11, 11, 9, 0, 6)) tdSql.error('select diff(c4,1),floor(c3) from tb1;') tdSql.error('select diff(c4,1),diff(c4,1) from tb1;') tdSql.query('select diff(c4,1) from tb1 where c2 is not null and c3 is not null;') - tdSql.checkRows(2) + tdSql.checkRows(3) tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) tdSql.checkData(0, 1, 3) tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 5)) tdSql.checkData(1, 1, 2147483643) + tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0, 6)) + tdSql.checkData(2, 1, 2) tdSql.query('select diff(c2) from tb1 order by ts desc;') tdSql.checkRows(4) @@ -941,18 +965,10 @@ class TDTestCase: tdSql.checkData(3, 1, -1) tdSql.query('select diff(c4,1) from tb1 order by ts desc;') - tdSql.checkRows(3) - tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0, 4)) - tdSql.checkData(0, 1, -2147483643) - tdSql.checkData(1, 0, datetime.datetime(2021, 11, 11, 9, 0, 2)) - tdSql.checkData(1, 1, -2) - tdSql.checkData(2, 0, datetime.datetime(2021, 11, 11, 9, 0)) - tdSql.checkData(2, 1, -1) + tdSql.checkRows(0) tdSql.query('select diff(c4,1) from tb1 order by ts desc limit 3 offset 2;') - tdSql.checkRows(1) - tdSql.checkData(0, 0, datetime.datetime(2021, 11, 11, 9, 0)) - tdSql.checkData(0, 1, -1) + tdSql.checkRows(0) tdSql.error('select diff(c2) from stb1;') diff --git a/tests/develop-test/2-query/diff_ignore_negative.py b/tests/develop-test/2-query/diff_ignore_negative.py index 68489572288b50343a1a08549155fcd826f1ac94..8074e648c0b07774bea51d35e2a4e8284f9ed019 100644 --- a/tests/develop-test/2-query/diff_ignore_negative.py +++ b/tests/develop-test/2-query/diff_ignore_negative.py @@ -78,13 +78,13 @@ class TDTestCase: tdSql.checkData(0, 1, 1) tdSql.checkData(0, 2, 'ct1') tdSql.checkData(1, 0, datetime.datetime(2022, 1, 20, 15, 10, 22, 4000)) - tdSql.checkData(1, 1, 2) + tdSql.checkData(1, 1, 8) tdSql.checkData(1, 2, 'ct1') tdSql.checkData(2, 0, datetime.datetime(2022, 1, 20, 15, 10, 22, 2000)) tdSql.checkData(2, 1, 11) tdSql.checkData(2, 2, 'ct2') tdSql.checkData(3, 0, datetime.datetime(2022, 1, 20, 15, 10, 22, 4000)) - tdSql.checkData(3, 1, 22) + tdSql.checkData(3, 1, 88) tdSql.checkData(3, 2, 'ct2') tdSql.query('select diff(c2) from st group by tbname') @@ -135,13 +135,13 @@ class TDTestCase: tdSql.checkData(0, 1, 2.0) tdSql.checkData(0, 2, 'ct1') tdSql.checkData(1, 0, datetime.datetime(2022, 1, 20, 15, 10, 22, 4000)) - tdSql.checkData(1, 1, 4.0) + tdSql.checkData(1, 1, 14.0) tdSql.checkData(1, 2, 'ct1') tdSql.checkData(2, 0, datetime.datetime(2022, 1, 20, 15, 10, 22, 2000)) tdSql.checkData(2, 1, 22.0) tdSql.checkData(2, 2, 'ct2') tdSql.checkData(3, 0, datetime.datetime(2022, 1, 20, 15, 10, 22, 4000)) - tdSql.checkData(3, 1, 44.0) + tdSql.checkData(3, 1, 154.0) tdSql.checkData(3, 2, 'ct2') tdSql.execute('drop database diffneg') diff --git a/tests/develop-test/2-query/function_hll.py b/tests/develop-test/2-query/function_hll.py new file mode 100644 index 0000000000000000000000000000000000000000..acbefe5a0458fd1cb65d92eb64f844f9ae1ad966 --- /dev/null +++ b/tests/develop-test/2-query/function_hll.py @@ -0,0 +1,229 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-13893] hyperloglog unique + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists hll") + tdSql.execute("create database if not exists hll") + tdSql.execute('use hll') + + tdSql.execute('create table shll (ts timestamp, dbig bigint, dsmall smallint, dbool bool, dtiny tinyint unsigned, dfloat float, ddouble double, dnchar nchar(4093), dbinary binary(64), dtime timestamp) tags (tbinary nchar(4093), tint int)') + tdSql.execute('create table hll1 using shll tags ("t1", 1)') + tdSql.execute('create table hll2 using shll tags ("t2", 2)') + + tdSql.execute('insert into hll1 values("2021-10-17 00:31:31", 1, -3276, true, 253, 3.32333, 4.984392323, "你好", "sddd", 333) ("2022-01-24 00:31:32", 1, -32767, false, 254, NULL, 4.982392323, "你好吗", "sdf",2323)') + tdSql.execute('insert into hll2 values("2021-10-15 00:31:33", 1, NULL, true, 23, 3.4, 4.982392323, "你好吗", "sdf", 333) ("2021-12-24 00:31:34", 2, 32767, NULL, NULL, NULL, 4.982392323, NULL, "sddd", NULL) ("2022-01-01 08:00:05", 19, 3276, true, 2, 3.323222, 4.92323, "试试", "sddd", 1645434434000)') + tdSql.execute('insert into hll2 values("2021-10-17 00:31:31", NULL, 32767, true, 123, 3.323232333, 4.2, NULL, NULL, NULL) ("2022-01-01 08:00:06", NULL, NULL, NULL, 35, 3.323232333, NULL, "试试", NULL, 1645434434000) ("2022-01-01 08:00:07", 9, 54, true, 25, 3.32333, NULL, "试试", NULL, 1645434434001)') + + ## test normal table + tdSql.query('select hyperloglog(ts) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 6) + + tdSql.query('select hyperloglog(dbig) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 4) + + tdSql.query('select hyperloglog(dsmall) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3) + + tdSql.query('select hyperloglog(dbool) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 1) + + tdSql.query('select hyperloglog(dtiny) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 5) + + tdSql.query('select hyperloglog(dfloat) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 4) + + tdSql.query('select hyperloglog(ddouble) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3) + + tdSql.query('select hyperloglog(dnchar) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 2) + + tdSql.query('select hyperloglog(dbinary) from hll2') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 2) + + ## test super table + tdSql.query('select hyperloglog(dnchar) from shll') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3) + + # test group by + #group by column + tdSql.query('select hyperloglog(dnchar) from shll group by dnchar') + tdSql.checkRows(4) + tdSql.checkData(0, 0, 0) + tdSql.checkData(1, 0, 1) + tdSql.checkData(2, 0, 1) + tdSql.checkData(3, 0, 1) + + tdSql.query('select hyperloglog(dsmall) from shll group by dnchar') + tdSql.checkRows(4) + tdSql.checkData(0, 0, 1) + tdSql.checkData(1, 0, 1) + tdSql.checkData(2, 0, 1) + tdSql.checkData(3, 0, 2) + + tdSql.query('select hyperloglog(dsmall) from hll2 group by dnchar') + tdSql.checkRows(3) + tdSql.checkData(0, 0, 1) + tdSql.checkData(1, 0, 0) + tdSql.checkData(2, 0, 2) + + #group by tbname + tdSql.query('select hyperloglog(dsmall) from shll group by tbname') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 2) + tdSql.checkData(1, 0, 3) + + #group by tag + tdSql.query('select hyperloglog(dnchar) from shll group by tint') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 2) + tdSql.checkData(1, 0, 2) + + #test order by + + + #order by column [desc] + tdSql.query('select hyperloglog(dnchar) from shll group by dnchar order by dnchar desc') + tdSql.checkRows(4) + tdSql.checkData(0, 0, 1) + tdSql.checkData(1, 0, 1) + tdSql.checkData(2, 0, 1) + tdSql.checkData(3, 0, 0) + + #order by tag + tdSql.query('select hyperloglog(dsmall) from shll group by tint order by tint desc') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 3) + tdSql.checkData(1, 0, 2) + + # error + tdSql.error("select hyperloglog(ts,1) from shll") + + #interval + tdSql.query('select hyperloglog(dnchar) from shll interval(1s)') + tdSql.checkRows(7) + tdSql.checkData(0, 1, 1) + tdSql.checkData(1, 1, 1) + tdSql.checkData(2, 0, "2021-12-24 00:31:34") + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 1) + tdSql.checkData(4, 1, 1) + tdSql.checkData(5, 1, 1) + tdSql.checkData(6, 1, 1) + + tdSql.query('select hyperloglog(dnchar) from shll interval(1w)') + tdSql.checkRows(4) + tdSql.checkData(0, 1, 2) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 1) + tdSql.checkData(3, 1, 1) + + + #state_window + tdSql.query('select hyperloglog(dnchar) from hll2 state_window(dsmall)') + tdSql.checkRows(5) + + #session + tdSql.query('select hyperloglog(dbinary) from hll2 session(ts,2w)') + tdSql.checkRows(2) + tdSql.checkData(0, 0, "2021-10-15 00:31:33") + tdSql.checkData(0, 1, 1) + tdSql.checkData(1, 0, "2021-12-24 00:31:34") + tdSql.checkData(1, 1, 1) + + #where + tdSql.query('select hyperloglog(dbinary) from shll where dnchar="试试"') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 1) + tdSql.query('select hyperloglog(dbinary) from shll where ts <= "2022-01-01 08:00:05"') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 2) + + #slimit/soffset + tdSql.query('select hyperloglog(dsmall) from shll group by dnchar slimit 2 soffset 2') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 1) + tdSql.checkData(1, 0, 2) + + #limit/offset + tdSql.query('select hyperloglog(dnchar) from shll interval(1s) limit 1,3') + tdSql.checkRows(3) + tdSql.checkData(0, 0, "2021-10-17 00:31:31") + tdSql.checkData(0, 1, 1) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 1) + + #having + tdSql.query('select hyperloglog(dsmall) from shll group by dnchar having hyperloglog(dsmall)>1') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 2) + + #subquery + tdSql.query('select hyperloglog(dbinary) from (select dbinary from shll where dnchar = "试试")') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 1) + + #union + tdSql.query('select hyperloglog(dtiny) from hll1 union all select hyperloglog(dtiny) from hll2') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 2) + tdSql.checkData(1, 0, 5) + + #join + tdSql.execute('create table shll1 (ts timestamp, dbig bigint, dsmall smallint, dbool bool, dtiny tinyint unsigned, dfloat float, ddouble double, dnchar nchar(4093), dbinary binary(64), dtime timestamp) tags (tbinary nchar(4093), tint int)') + tdSql.execute('create table hll11 using shll1 tags ("t1", 1)') + + tdSql.execute('insert into hll11 values("2021-10-17 00:31:31", 1, -3276, true, 253, 3.32333, 4.984392323, "你好", "sddd", 333) ("2022-01-24 00:31:32", 1, -32767, false, 254, NULL, 4.982392323, "你好吗", "sdf",2323)') + + tdSql.query('select hyperloglog(shll1.ddouble) from shll, shll1 where shll.ts=shll1.ts and shll.tint=shll1.tint') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 2) + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) + diff --git a/tests/develop-test/2-query/function_mode.py b/tests/develop-test/2-query/function_mode.py index 7cc089ab338a4b25f4765ee415cba4a438337a61..910ebbb2c574573722b1f840b2400f6e124d6f7c 100644 --- a/tests/develop-test/2-query/function_mode.py +++ b/tests/develop-test/2-query/function_mode.py @@ -117,15 +117,15 @@ class TDTestCase: tdSql.execute('insert into D002 values("2021-11-17 20:31:31", 1, 3276, true, NULL, 3.32322, 4.982392323, "你好吗", "sdf", 333)') tdSql.query('select mode(num) from d002 group by dbinary') tdSql.checkRows(2) - tdSql.checkData(0, 0, 3276) - tdSql.checkData(1, 0, None) + tdSql.checkData(1, 0, 3276) + tdSql.checkData(0, 0, None) tdSql.query('select mode(dfloat) from d002 group by dbinary') tdSql.checkRows(2) - tdSql.checkData(0, 0, None) + tdSql.checkData(1, 0, None) tdSql.query('select mode(dchar) from d002 group by dbinary') tdSql.checkRows(2) - tdSql.checkData(0, 0, "你好吗") - tdSql.checkData(1, 0, "试试") + tdSql.checkData(1, 0, "你好吗") + tdSql.checkData(0, 0, "试试") tdSql.query('select mode(dchar) from smode group by dchar') tdSql.checkRows(4) tdSql.query('select mode(dbool) from smode group by dchar') @@ -144,7 +144,7 @@ class TDTestCase: tdSql.checkData(1, 1, "d002") #group by tag - tdSql.query('select mode(ddouble) from smode group by location') + tdSql.query('select mode(ddouble) from smode group by location order by location desc') tdSql.checkRows(2) tdSql.checkData(0, 0, 4.982392323) tdSql.checkData(0, 1, "Beijing.haidian") diff --git a/tests/develop-test/2-query/function_state.py b/tests/develop-test/2-query/function_state.py new file mode 100644 index 0000000000000000000000000000000000000000..5a236aa6ac8abb1cb462750d18cd3ff8fdbb8da8 --- /dev/null +++ b/tests/develop-test/2-query/function_state.py @@ -0,0 +1,247 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-11210] function stateCount stateDuration + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists statef") + tdSql.execute("create database if not exists statef PRECISION 'ns'") + tdSql.execute('use statef') + + tdSql.execute('create table sstatef (ts timestamp, dbig bigint, dsmall smallint, dbool bool, dtiny tinyint unsigned, dfloat float, ddouble double, dnchar nchar(4093), dbinary binary(64), dtime timestamp) tags (tbinary nchar(4093), tint int)') + tdSql.execute('create table statef1 using sstatef tags ("t1", 1)') + tdSql.execute('create table statef2 using sstatef tags ("t2", 2)') + + tdSql.execute('insert into statef1 values("2021-10-17 00:31:31", 1, -3276, true, 253, 3.32333, 4.984392323, "你好", "sddd", 333) ("2022-01-24 00:31:32", 1, -32767, false, 254, NULL, 4.982392323, "你好吗", "sdf",2323)') + tdSql.execute('insert into statef2 values("2021-10-15 00:31:33", 1, NULL, true, 23, 3.4, 4.982392323, "你好吗", "sdf", 333) ("2021-12-24 00:31:34", 2, 32767, NULL, NULL, NULL, 4.982392323, NULL, "sddd", NULL) ("2022-01-01 08:00:05", 19, 3276, true, 2, 3.323222, 4.92323, "试试", "sddd", 1645434434000)') + tdSql.execute('insert into statef2 values("2021-10-17 00:31:31", NULL, 32767, true, 123, 3.323232333, 4.2, NULL, NULL, NULL) ("2022-01-01 08:00:06", NULL, NULL, NULL, 35, 3.323232333, NULL, "试试", NULL, 1645434434000) ("2022-01-01 08:00:07", 9, 54, true, 25, 3.32333, NULL, "试试", NULL, 1645434434001)') + + # error + tdSql.error("select stateCount(ts,LE,4.923230000) from statef2") + tdSql.error("select stateCount(dbool,LE,4.923230000) from statef2") + tdSql.error("select stateCount(dnchar,LE,4.923230000) from statef2") + tdSql.error("select stateCount(dbinary,LE,4.923230000) from statef2") + tdSql.error("select stateCount(dtime,LE,4.923230000) from statef2") + tdSql.error("select stateCount(tint,LE,4.923230000) from statef2") + tdSql.error("select stateCount(tbinary,LE,4.923230000) from statef2") + tdSql.error("select stateCount(tbinary,ew,4.923230000) from statef2") + tdSql.error("select stateCount(tbinary,23,4.923230000) from statef2") + tdSql.query("select stateCount(dtiny,le,1e3) from statef2") + tdSql.error("select stateCount(dtiny,le,1e3) from statef") + tdSql.error("select stateDuration(dtiny,le,1e3) from statef") + tdSql.query("select stateDuration(dtiny,le,1e3) from statef2") + tdSql.error("select stateCount(dtiny,le,'1e3') from statef2") + tdSql.error("select stateCount(dtiny,le,le) from statef2") + tdSql.error("select stateDuration(dtiny,le,le) from statef2") + tdSql.error("select stateCount(dtiny,le,2,1s) from statef2") + tdSql.error("select stateDuration(dtiny,le,2,1) from statef2") + tdSql.error("select stateDuration(dtiny,le,2,'1s') from statef2") + tdSql.error("select stateDuration(dtiny,le,2,2s) from statef2") + + tdSql.error("select stateCount(dtiny,le,1e3),top(dtiny,1) from statef2") + tdSql.error("select stateCount(dtiny,le,1e3),first(dbig) from statef2") + tdSql.error("select stateCount(dtiny,le,1e3),ceil(dsmall) from statef2") + + #interval + tdSql.error('select stateCount(dtiny,ne,9.0) from statef2 interval(1s)') + tdSql.error('select stateDuration(dtiny,ne,9.0,1s) from statef2 interval(1s)') + #state_window + tdSql.error('select stateCount(dtiny,ne,9.0) from statef2 state_window(dbool)') + tdSql.error('select stateDuration(dtiny,ne,9.0,1s) from statef2 state_window(dbool)') + #session + tdSql.error('select stateCount(dtiny,ne,9.0) from statef2 session(ts,1w)') + tdSql.error('select stateDuration(dtiny,ne,9.0,1s) from statef2 session(ts,1w)') + + tdSql.error('select stateDuration(dfloat,Ge,3.32323) from (select dfloat from statef2)') + tdSql.error('select stateCount(dfloat,Ge,3.32323) from (select dfloat from statef2)') + + ## test normal table + tdSql.query('select stateCount(dtiny,GT,10) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 0, "2021-10-15 00:31:33") + tdSql.checkData(0, 1, 23) + tdSql.checkData(0, 2, 1) + tdSql.checkData(1, 0, "2021-10-17 00:31:31") + tdSql.checkData(1, 1, 123) + tdSql.checkData(1, 2, 2) + tdSql.checkData(2, 0, "2021-12-24 00:31:34") + tdSql.checkData(2, 1, None) + tdSql.checkData(2, 2, None) + tdSql.checkData(3, 0, "2022-01-01 08:00:05") + tdSql.checkData(3, 1, 2) + tdSql.checkData(3, 2, -1) + tdSql.checkData(4, 0, "2022-01-01 08:00:06") + tdSql.checkData(4, 1, 35) + tdSql.checkData(4, 2, 1) + tdSql.checkData(5, 0, "2022-01-01 08:00:07") + tdSql.checkData(5, 1, 25) + tdSql.checkData(5, 2, 2) + + tdSql.query('select dtiny,ts,stateCount(dtiny,GT,10),*,tbinary from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 1, "2021-10-15 00:31:33") + tdSql.checkData(1, 2, 123) + tdSql.checkData(2, 6, 2) + tdSql.checkData(3, 15, "t2") + + tdSql.query('select stateCount(dtiny,LT,10) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, -1) + tdSql.checkData(1, 2, -1) + tdSql.checkData(3, 2, 1) + tdSql.checkData(4, 2, -1) + + tdSql.query('select stateCount(ddouble,LE,4.923230000) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, -1) + tdSql.checkData(1, 2, 1) + tdSql.checkData(2, 2, -1) + tdSql.checkData(3, 2, 1) + tdSql.checkData(4, 2, None) + tdSql.checkData(5, 2, None) + + tdSql.query('select stateCount(dfloat,Ge,3.32323) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, 1) + tdSql.checkData(1, 2, 2) + tdSql.checkData(2, 2, None) + tdSql.checkData(3, 2, -1) + tdSql.checkData(4, 2, 1) + tdSql.checkData(5, 2, 2) + + tdSql.query('select stateCount(dsmall,eq,3276.0) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, None) + tdSql.checkData(1, 2, -1) + tdSql.checkData(2, 2, -1) + tdSql.checkData(3, 2, 1) + tdSql.checkData(4, 2, None) + tdSql.checkData(5, 2, -1) + + tdSql.query('select stateCount(dbig,ne,9.0) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, 1) + tdSql.checkData(1, 2, None) + tdSql.checkData(2, 2, 2) + tdSql.checkData(3, 2, 3) + tdSql.checkData(4, 2, None) + tdSql.checkData(5, 2, -1) + + tdSql.query('select stateDuration(dtiny,ne,9.0) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, 0) + tdSql.checkData(1, 2, 172798) + tdSql.checkData(2, 2, None) + tdSql.checkData(3, 2, 6766112) + tdSql.checkData(4, 2, 6766113) + tdSql.checkData(5, 2, 6766114) + + tdSql.query('select stateDuration(dtiny,ne,9.0,1h) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, 0) + tdSql.checkData(1, 2, 47) + tdSql.checkData(2, 2, None) + tdSql.checkData(3, 2, 1879) + tdSql.checkData(4, 2, 1879) + tdSql.checkData(5, 2, 1879) + + tdSql.query('select stateDuration(dtiny,ne,9.0,1m) from statef2') + tdSql.checkRows(6) + tdSql.checkData(0, 2, 0) + tdSql.checkData(1, 2, 2879) + tdSql.checkData(2, 2, None) + tdSql.checkData(3, 2, 112768) + tdSql.checkData(4, 2, 112768) + tdSql.checkData(5, 2, 112768) + + ## test super table + tdSql.query('select stateDuration(dtiny,ne,9.0,1s) from sstatef group by tbname') + tdSql.checkRows(8) + tdSql.checkData(0, 2, 0) + tdSql.checkData(1, 2, 8553601) + + #where + tdSql.query('select stateCount(dfloat,Ge,3.32323) from statef2 where dfloat >3.32323') + tdSql.checkRows(4) + tdSql.checkData(0, 2, 1) + tdSql.checkData(1, 2, 2) + tdSql.checkData(2, 2, 3) + tdSql.checkData(3, 2, 4) + + tdSql.query('select stateDuration(dfloat,Ge,3.32323) from statef2 where dfloat <3.4') + tdSql.checkRows(4) + tdSql.checkData(0, 2, 0) + tdSql.checkData(1, 2, -1) + tdSql.checkData(2, 2, 0) + tdSql.checkData(3, 2, 1) + + tdSql.query('select stateDuration(dfloat,Ge,3.32323,1m) from statef2 where dfloat <3.4') + tdSql.checkRows(4) + tdSql.checkData(3, 2, 0) + + #slimit/soffset + tdSql.query('select stateDuration(dtiny,ne,9.0,1s) from sstatef group by tbname slimit 2 soffset 1') + tdSql.checkRows(6) + + #limit/offset + tdSql.query('select stateCount(dfloat,Ge,3.32323) from statef2 limit 1,2') + tdSql.checkRows(2) + tdSql.checkData(0, 0, "2021-10-17 00:31:31") + tdSql.checkData(0, 2, 2) + tdSql.checkData(1, 2, None) + + #having + tdSql.query('select stateDuration(dtiny,ne,9.0,1s) from sstatef group by tbname having stateDuration(dtiny,ne,9.0,1s) > 0') + + #subquery + tdSql.error('select stateDuration(dfloat,Ge,3.32323) from (select ts,dfloat from statef2)') + + #union + tdSql.query('select stateCount(dfloat,Ge,3.32323) from statef1 union all select stateCount(dfloat,Ge,3.32323) from statef2') + tdSql.checkRows(8) + tdSql.checkData(0, 2, 1) + tdSql.checkData(3, 2, 2) + + #join + tdSql.execute('create table sstatef1 (ts timestamp, dbig bigint, dsmall smallint, dbool bool, dtiny tinyint unsigned, dfloat float, ddouble double, dnchar nchar(4093), dbinary binary(64), dtime timestamp) tags (tbinary nchar(4093), tint int)') + tdSql.execute('create table statef11 using sstatef1 tags ("t1", 1)') + + tdSql.execute('insert into statef11 values("2021-10-17 00:31:31", 1, -3276, true, 253, 3.32333, 4.984392323, "你好", "sddd", 333) ("2022-01-24 00:31:32", 1, -32767, false, 254, NULL, 4.982392323, "你好吗", "sdf",2323)') + + tdSql.error('select stateCount(sstatef.dsmall,eq,3276.0) from sstatef, sstatef1 where sstatef.ts=sstatef1.ts and sstatef.tint=sstatef1.tint') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) + diff --git a/tests/develop-test/2-query/function_tail.py b/tests/develop-test/2-query/function_tail.py index a5be3efb906f14c6e7a96cc444c6c90915e2c82a..4b1d2ddb6691adec305735570809b8a6d4deadb9 100644 --- a/tests/develop-test/2-query/function_tail.py +++ b/tests/develop-test/2-query/function_tail.py @@ -116,10 +116,10 @@ class TDTestCase: #group by column tdSql.query('select tail(dtiny,2) from tail2 group by dnchar') tdSql.checkRows(5) - tdSql.checkData(0, 0, "2021-10-15 00:31:33") - tdSql.checkData(0, 1, 23) - tdSql.checkData(2, 0, "2021-12-24 00:31:34") - tdSql.checkData(2, 1, None) + tdSql.checkData(2, 0, "2021-10-15 00:31:33") + tdSql.checkData(2, 1, 23) + tdSql.checkData(1, 0, "2021-12-24 00:31:34") + tdSql.checkData(1, 1, None) tdSql.checkData(4, 0, "2022-01-01 08:00:07") tdSql.checkData(4, 1, 25) tdSql.query('select tail(dtiny,2,1) from tail2 group by dnchar') @@ -130,8 +130,8 @@ class TDTestCase: tdSql.checkData(0, 1, 123) tdSql.checkData(2, 0, "2021-10-17 00:31:31") tdSql.checkData(2, 1, 253) - tdSql.checkData(4, 0, "2022-01-01 08:00:07") - tdSql.checkData(4, 1, 25) + tdSql.checkData(6, 0, "2022-01-01 08:00:07") + tdSql.checkData(6, 1, 25) tdSql.query('select tail(dtiny,2,1) from stail group by dnchar') tdSql.checkRows(5) @@ -321,6 +321,20 @@ class TDTestCase: tdSql.checkData(1, 0, "2022-01-01 08:00:07") tdSql.checkData(1, 1, "试试") + tdSql.query('select tail(dbig, 3) from (select * from stail) order by ts') + tdSql.checkRows(3) + tdSql.checkData(0, 0, "2022-01-01 08:00:06") + tdSql.checkData(0, 1, None) + tdSql.checkData(1, 0, "2022-01-01 08:00:07") + tdSql.checkData(1, 1, 9) + + tdSql.query('select tail(dbig, 3) from (select * from stail) order by ts desc') + tdSql.checkRows(3) + tdSql.checkData(0, 0, "2022-01-24 00:31:32") + tdSql.checkData(0, 1, 1) + tdSql.checkData(1, 0, "2022-01-01 08:00:07") + tdSql.checkData(1, 1, 9) + #union tdSql.query('select tail(dtiny,2) from tail1 union all select tail(dtiny,2) from tail2') tdSql.checkRows(4) diff --git a/tests/develop-test/2-query/function_unique.py b/tests/develop-test/2-query/function_unique.py index f6c05413f2ff95c0221002a48ed3f59672492a50..cb6f372ffb48dcd098db0e9f21752d3dd57ba1e9 100644 --- a/tests/develop-test/2-query/function_unique.py +++ b/tests/develop-test/2-query/function_unique.py @@ -83,8 +83,8 @@ class TDTestCase: tdSql.checkData(3, 0, "2021-12-24 01:31:31") tdSql.checkData(0, 1, 1) tdSql.checkData(1, 1, 2) - tdSql.checkData(2, 1, 19) - tdSql.checkData(3, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 19) tdSql.query('select ts,unique(voltage),ts,groupid,location,tbname from unique') tdSql.checkRows(4) @@ -106,19 +106,19 @@ class TDTestCase: tdSql.checkData(2, 0, "2021-12-24 01:31:31") tdSql.checkData(2, 1, "2021-12-24 01:31:31") - tdSql.checkData(2, 2, 19) + tdSql.checkData(2, 2, 9) tdSql.checkData(2, 3, "2021-12-24 01:31:31") - tdSql.checkData(2, 4, 2) - tdSql.checkData(2, 5, "Beijing.haidian") - tdSql.checkData(2, 6, "d002") + tdSql.checkData(2, 4, 3) + tdSql.checkData(2, 5, "Beijing.Tongzhou") + tdSql.checkData(2, 6, "d003") tdSql.checkData(3, 0, "2021-12-24 01:31:31") tdSql.checkData(3, 1, "2021-12-24 01:31:31") - tdSql.checkData(3, 2, 9) + tdSql.checkData(3, 2, 19) tdSql.checkData(3, 3, "2021-12-24 01:31:31") - tdSql.checkData(3, 4, 3) - tdSql.checkData(3, 5, "Beijing.Tongzhou") - tdSql.checkData(3, 6, "d003") + tdSql.checkData(3, 4, 2) + tdSql.checkData(3, 5, "Beijing.haidian") + tdSql.checkData(3, 6, "d002") tdSql.execute('insert into D004 values("2021-10-15 00:00:01", 10, 2) ("2021-12-24 00:21:31", 5, 2) ("2021-12-25 01:31:31", 9, 4)') @@ -142,18 +142,18 @@ class TDTestCase: tdSql.query('select ts,unique(voltage) from unique group by location') tdSql.checkRows(8) tdSql.checkData(0, 2, 1) - tdSql.checkData(0, 3, "Beijing.haidian") - tdSql.checkData(3, 2, 1) - tdSql.checkData(3, 3, "Beijing.Chaoyang") - tdSql.checkData(5, 2, 1) - tdSql.checkData(5, 3, "Beijing.Tongzhou") + tdSql.checkData(5, 3, "Beijing.haidian") + tdSql.checkData(0, 2, 1) + tdSql.checkData(0, 3, "Beijing.Chaoyang") + tdSql.checkData(2, 2, 1) + tdSql.checkData(2, 3, "Beijing.Tongzhou") #group by ts tdSql.query('select ts,unique(voltage) from unique group by ts') tdSql.checkRows(9) tdSql.checkData(1, 2, 1) - tdSql.checkData(4, 2, 1) + tdSql.checkData(4, 2, 2) tdSql.checkData(8, 2, 1) - tdSql.checkData(6, 2, 9) + tdSql.checkData(6, 2, 19) tdSql.checkData(7, 2, 9) #group by tag,column tdSql.query('select ts,unique(voltage) from unique group by location,num') @@ -165,13 +165,13 @@ class TDTestCase: tdSql.query('select unique(voltage) from unique order by ts desc') tdSql.checkRows(6) tdSql.checkData(0, 0, "2021-12-24 01:31:31") - tdSql.checkData(0, 1, 9) + tdSql.checkData(0, 1, 19) tdSql.checkData(5, 0, "2021-10-15 00:00:01") tdSql.checkData(5, 1, 10) tdSql.query('select unique(voltage) from unique order by ts') tdSql.checkRows(6) tdSql.checkData(5, 0, "2021-12-24 01:31:31") - tdSql.checkData(5, 1, 9) + tdSql.checkData(5, 1, 19) tdSql.checkData(0, 0, "2021-10-15 00:00:01") tdSql.checkData(0, 1, 10) #order by column [desc] @@ -216,7 +216,7 @@ class TDTestCase: tdSql.checkData(6, 0, "2021-12-25 01:31:31") tdSql.checkData(6, 1, 9) tdSql.checkData(0, 0, "2021-12-24 01:31:31") - tdSql.checkData(0, 1, 9) + tdSql.checkData(0, 1, 19) # error tdSql.error("select unique(ts) from unique") @@ -246,7 +246,7 @@ class TDTestCase: tdSql.query('select unique(voltage) from unique where voltage > 2 limit 2 offset 1') tdSql.checkRows(2) tdSql.checkData(0, 1, 5) - tdSql.checkData(1, 1, 19) + tdSql.checkData(1, 1, 9) #having tdSql.query('select unique(voltage) from unique group by num having unique(voltage)>5') @@ -256,6 +256,20 @@ class TDTestCase: tdSql.query('select unique(num) from (select * from unique where voltage > 1)') tdSql.checkRows(2) + tdSql.query('select unique(num) from (select * from unique) order by ts') + tdSql.checkRows(2) + tdSql.checkData(0, 0, "2021-10-15 00:00:01") + tdSql.checkData(0, 1, 2) + tdSql.checkData(1, 0, "2021-12-25 01:31:31") + tdSql.checkData(1, 1, 4) + + tdSql.query('select unique(num) from (select * from unique) order by ts desc') + tdSql.checkRows(2) + tdSql.checkData(0, 0, "2021-12-25 01:31:31") + tdSql.checkData(0, 1, 4) + tdSql.checkData(1, 0, "2021-10-15 00:00:01") + tdSql.checkData(1, 1, 2) + #union tdSql.query('select unique(voltage) from d002 union all select unique(voltage) from d003') tdSql.checkRows(5) @@ -311,6 +325,14 @@ class TDTestCase: tdSql.query('select unique(unique.voltage) from unique, unique2 where unique.ts=unique2.ts and unique.groupid=unique2.groupid') tdSql.checkRows(1) + #TD-14104 + ts = 1642592221000 + sql = "insert into D004 values" + for i in range(3000): + sql += " (%d,%d,%d)"%(ts + i*1000, i, i) + tdSql.execute(sql) + tdSql.query("select unique(num) from (select * from unique)") + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/develop-test/2-query/nchar_funcs.py b/tests/develop-test/2-query/nchar_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb5aeb1d0a13277aba3996f2c34bf4746a6f44d --- /dev/null +++ b/tests/develop-test/2-query/nchar_funcs.py @@ -0,0 +1,462 @@ +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import tdDnodes +from math import inf + +class TDTestCase: + def caseDescription(self): + ''' + case1: nchar bugs on outer query, order by ts in outer query, and ucs4 mbs conversion + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def restartTaosd(self, index=1, dbname="db"): + tdDnodes.stop(index) + tdDnodes.startWithoutSleep(index) + tdSql.execute(f"use nchardb") + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists nchardb") + tdSql.execute("create database if not exists nchardb") + tdSql.execute('use nchardb') + + + + tdSql.execute('create stable stable_1 (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) tags(loc nchar(100) , t_int int , t_bigint bigint , t_smallint smallint , t_tinyint tinyint, t_bool bool , t_binary binary(100) , t_nchar nchar(100) ,t_float float , t_double double , t_ts timestamp);') + + tdSql.execute('create stable stable_2 (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) tags(loc nchar(100) , t_int int , t_bigint bigint , t_smallint smallint , t_tinyint tinyint, t_bool bool , t_binary binary(100) , t_nchar nchar(100) ,t_float float , t_double double , t_ts timestamp);') + + tdSql.execute('create stable stable_null_data (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) tags(loc nchar(100) , t_int int , t_bigint bigint , t_smallint smallint , t_tinyint tinyint, t_bool bool , t_binary binary(100) , t_nchar nchar(100) ,t_float float , t_double double , t_ts timestamp);') + + tdSql.execute('create stable stable_null_childtable (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) tags(loc nchar(100) , t_int int , t_bigint bigint , t_smallint smallint , t_tinyint tinyint, t_bool bool , t_binary binary(100) , t_nchar nchar(100) ,t_float float , t_double double , t_ts timestamp);') + + tdSql.execute("create table stable_1_1 using stable_1 tags('stable_1_1', '0' , '0' , '0' , '0' , 0 , 'binary1' , 'nchar1' , '0' , '0' ,'0') ;") + + tdSql.execute("create table stable_1_2 using stable_1 tags('stable_1_2', '2147483647' , '9223372036854775807' , '32767' , '127' , 1 , 'binary2' , 'nchar2' , '2' , '22' , '1999-09-09 09:09:09.090') ;") + + tdSql.execute("create table stable_1_3 using stable_1 tags('stable_1_3', '-2147483647' , '-9223372036854775807' , '-32767' , '-127' , false , 'binary3' , 'nchar3nchar3' , '-3.3' , '-33.33' , '2099-09-09 09:09:09.090') ;") + + tdSql.execute("create table stable_1_4 using stable_1 tags('stable_1_4', '0' , '0' , '0' , '0' , 0 , '0' , '0' , '0' , '0' ,'0') ;") + + tdSql.execute("create table stable_2_1 using stable_2 tags('stable_2_1' , '0' , '0' , '0' , '0' , 0 , 'binary21' , 'nchar21' , '0' , '0' ,'0') ;") + + tdSql.execute("create table stable_2_2 using stable_2 tags('stable_2_2' , '0' , '0' , '0' , '0' , 0 , '0' , '0' , '0' , '0' ,'0') ;") + + tdSql.execute("create table stable_null_data_1 using stable_null_data tags('stable_null_data_1', '0' , '0' , '0' , '0' , 0 , '0' , '0' , '0' , '0' ,'0') ;") + + tdSql.execute('create table regular_table_1 (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) ;') + + tdSql.execute('create table regular_table_2 (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) ;') + + tdSql.execute('create table regular_table_3 (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) ;') + + tdSql.execute('create table regular_table_null (ts timestamp , q_int int , q_bigint bigint , q_smallint smallint , q_tinyint tinyint , q_float float , q_double double , q_bool bool , q_binary binary(100) , q_nchar nchar(100) , q_ts timestamp , q_binary1 binary(100) , q_nchar1 nchar(100) ,q_binary2 binary(100) , q_nchar2 nchar(100) ,q_binary3 binary(100) , q_nchar3 nchar(100) ,q_binary4 binary(100) , q_nchar4 nchar(100) , q_binary5 binary(100) , q_nchar5 nchar(100) ,q_binary6 binary(100) , q_nchar6 nchar(100) ,q_binary7 binary(100) , q_nchar7 nchar(100) ,q_binary8 binary(100) , q_nchar8 nchar(100) , q_int_null int , q_bigint_null bigint , q_smallint_null smallint , q_tinyint_null tinyint, q_float_null float , q_double_null double , q_bool_null bool , q_binary_null binary(20) , q_nchar_null nchar(20) , q_ts_null timestamp) ;') + + tdSql.execute("insert into stable_1_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double , q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000000, -439727522, 612301787638826993, 9533, -97, 3516.375596, -63.596320, 0, 'binary.PIhHdeegEoHadxQpLAQI', 'nchar.福建省辽阳县丰都熊街u座 233621', 1630000000000, 'binary1.JgnEFSLkRtzEQOZsUibN', 'nchar1.福建省宜都县海港王街M座 713195', 'binary2.tsCyNVyBJDCnIvUdjVev', 'nchar2.宁夏回族自治区兰州市淄川香港路Y座 213761', 'binary3.AlZhLGOLRoWDRvqbsWfC', 'nchar3.海南省静市江北海口路X座 702375', 'binary4.NdciuKObKZYwDVhtIOgB', 'nchar4.四川省桂荣市滨城林街m座 503259', 'binary5.BUEJHkTvXfstJGArxcBz', 'nchar5.贵州省大冶县滨城梧州街P座 554324', 'binary6.ArgeExOkcjzjHDtyQARL', 'nchar6.山东省建华市魏都南京街o座 326153', 'binary7.QvDuzpiSJhpNBmQKHeWb', 'nchar7.湖北省桂芳市高明邯郸路q座 413345', 'binary8.WglkhUkXHcTYoWgshnnp', 'nchar8.内蒙古自治区太原县萧山王路p座 322176') ;") + + tdSql.execute("insert into regular_table_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000000, -1927728216, -6011044987062918899, 21730, 55, -379272379409.344971, 202621.613403, 0, 'binary.mgOAjgCfpIKVvJcFNMOc', 'nchar.上海市彬市丰都王路e座 634384', 1630000000000, 'binary1.cSVybMOLDLDvyNSJbRrc', 'nchar1.天津市潮州县金平胡街m座 378486', 'binary2.bdYIDYtteQeyjJkksUGK', 'nchar2.黑龙江省帅市崇文沈阳路Y座 103751', 'binary3.azSbzOjOyaUCFOTIsgHG', 'nchar3.河北省成都市东丽李街k座 303784', 'binary4.ohUNyPlQqkiMzpeTyOWS', 'nchar4.江苏省俊县西夏辛集街U座 593642', 'binary5.ENaKrNBgrArvKrFVzzlr', 'nchar5.北京市澳门县闵行杭州街L座 506999', 'binary6.VOHdDIsQoSrmQChGJvNB', 'nchar6.山西省敏县新城成都街b座 364960', 'binary7.SBvUJKRslUvmfsqGTtNO', 'nchar7.浙江省深圳市大东李路m座 882995', 'binary8.fcjjRXqwaSllnpvnvkYn', 'nchar8.云南省帅县城北香港街E座 477480') ;") + + tdSql.execute("insert into stable_1_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000000, 896032926, 6023643830222415811, 21936, 49, -3817.697182, -641551013002.837036, 1, 'binary.qjCLjIApCPmxDrPLinCu', 'nchar.安徽省洁县翔安南宁路q座 420885', 1630000000000, 'binary1.cGMsWYzwmvbENGnODINP', 'nchar1.陕西省惠州县城东郑州街a座 702479', 'binary2.FeyVxiUQWvaCkYlzlfeG', 'nchar2.上海市宁德市淄川周路n座 803882', 'binary3.UkNjWBPyCBRgkpmvtpWw', 'nchar3.北京市峰市璧山刘路G座 746867', 'binary4.xqFUKKJYHIpPlfyNuhFF', 'nchar4.湖北省齐齐哈尔市静安蒋街w座 215779', 'binary5.CCRGhhIjzzUEyhmxALRL', 'nchar5.北京市桂香市城东淮安街K座 265859', 'binary6.gvlOwjDLsDuPaCcVqiIX', 'nchar6.四川省东县静安余路Y座 617110', 'binary7.UXOSeWwjOJAoMNtgvPQE', 'nchar7.江西省玉英市海港澳门路q座 945219', 'binary8.mDiEkZDpVpDrdKUbhvcT', 'nchar8.香港特别行政区太原市黄浦黄街P座 177199') ;") + + tdSql.execute("insert into regular_table_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000000, 651177360, 1729081754117700025, 23056, 13, -6.636242, 82.921964, 1, 'binary.EoaIaneNQHMAUIbOidQe', 'nchar.广西壮族自治区天津县花溪魏街i座 376191', 1630000000000, 'binary1.HlIOKTKSbfaVAlClZuBh', 'nchar1.四川省柳县黄浦林路C座 108476', 'binary2.JLsEXPSzqGmcVHMLgAHh', 'nchar2.上海市济南市平山合山街Z座 778571', 'binary3.mxAFCDLuRGaHOqmLIJpE', 'nchar3.河南省沈阳市南溪潜江街A座 468196', 'binary4.oXDqUtayeNmHovscxiVq', 'nchar4.海南省亮市高港海门路K座 870267', 'binary5.BLksYIROpOJhmClgwqyK', 'nchar5.山东省宜都县滨城徐街N座 306711', 'binary6.CoRjxWPAzdBYFOgiZzeg', 'nchar6.广西壮族自治区霞市长寿沈阳路L座 914991', 'binary7.MLfTLPVrPGvrcJYFqfFC', 'nchar7.辽宁省合肥市高明李路l座 224862', 'binary8.IfxKkLWFTHNeNEflRfzY', 'nchar8.新疆维吾尔自治区沈阳县朝阳福州街q座 939080') ;") + + tdSql.execute("insert into stable_1_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000001, -746014185, -6611210245469344058, -27252, -77, -243654741.301468, -8.444537, 1, 'binary.EVYMoxfQftKyeUxzjhIj', 'nchar.江苏省六安县上街祁街p座 147895', 1630000000001, 'binary1.EqegqpWNNQmNarUebJgx', 'nchar1.北京市石家庄县高明太原街V座 139496', 'binary2.CgjLFXASsqDMbqpClkyo', 'nchar2.江苏省合山县涪城重庆路Q座 428968', 'binary3.wxQqnqtofXGaaQDIcVCL', 'nchar3.河南省呼和浩特市锡山兴城街O座 840658', 'binary4.zyKhpKkjeZokFeegJQDi', 'nchar4.西藏自治区潜江县魏都钟街i座 919700', 'binary5.OrEfrEsydYTamaZkNkwk', 'nchar5.重庆市兰英县沙湾嘉禾街c座 775060', 'binary6.NIpeYChLyWNMVOoSuDQY', 'nchar6.天津市杨市萧山合肥街b座 371505', 'binary7.gYzZPgKZiebmbgARfhbW', 'nchar7.河北省西安市浔阳通辽街w座 546863', 'binary8.sGpPIgZTnhPvEqbASIzz', 'nchar8.宁夏回族自治区文市朝阳昆明街O座 933200') ;") + + tdSql.execute("insert into regular_table_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000001, -1971853248, -1403199549636457306, -21922, -13, 77363611038104.703125, -458826.670338, 1, 'binary.dLopzuuaEkQyOKdwEkoF', 'nchar.浙江省深圳县涪城贵阳路L座 154418', 1630000000001, 'binary1.VsdtZMdFeVMRVgpklpmT', 'nchar1.澳门特别行政区佛山市闵行兴安盟路O座 197626', 'binary2.NDlRTlhCWMfVPcQUDEAU', 'nchar2.贵州省长沙县永川金街F座 263410', 'binary3.YySoOsWslJgqFFJLByXa', 'nchar3.辽宁省兴安盟市崇文崔街W座 740261', 'binary4.htDrNqFhPBUEgnwqUnJy', 'nchar4.上海市杨县西峰天津街A座 215633', 'binary5.PICqEmpTJMRRFMoLiAYL', 'nchar5.四川省拉萨县清浦戴路d座 807565', 'binary6.TcHUZlyIvOLzjzOLQVeY', 'nchar6.福建省玉市金平西宁路y座 216505', 'binary7.KVgSEZbApHVciiiHdmMv', 'nchar7.广东省香港市友好张路N座 530133', 'binary8.BbnDEmsmbuMsmARBrmaB', 'nchar8.陕西省淮安市西峰淮安路G座 471156') ;") + + tdSql.execute("insert into stable_2_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000000, 1290384855, 6453496169647608559, 17237, 78, -4556903756831.950195, 8558137.310094, 0, 'binary.RicjHNdlJvZXcuIUCtwp', 'nchar.辽宁省小红县安次刘路I座 783067', 1630000000000, 'binary1.PZrbgCdVlhLuYWzJfpcQ', 'nchar1.澳门特别行政区武汉市璧山孔路Y座 467679', 'binary2.CCmnLmgCmPDGsacmypKr', 'nchar2.广东省哈尔滨市朝阳巢湖路P座 520015', 'binary3.xpmnymjjdbpefsJbXiaA', 'nchar3.宁夏回族自治区齐齐哈尔市长寿海门路s座 980357', 'binary4.MQQAGeTBCbbAFmyCdNdx', 'nchar4.天津市哈尔滨县新城杨路w座 877346', 'binary5.jcGNOXcvsteCwnVwZxkv', 'nchar5.青海省哈尔滨市蓟州雷路S座 774634', 'binary6.sFIopESAmZxNtpEAXvmh', 'nchar6.上海市琳市萧山朴路I座 857895', 'binary7.GJEBncpKznEVYlBjADXc', 'nchar7.内蒙古自治区永安县南湖王路m座 128263', 'binary8.bseliCaYePtOlhjBDKlA', 'nchar8.新疆维吾尔自治区畅市清浦惠州路Y座 221741') ;") + + tdSql.execute("insert into stable_2_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000001, 1577644138, 5424290571527673071, 21765, 84, 592473004730.168945, 1461967845107.139893, 0, 'binary.REnSISlqmqqrnTVDsVuc', 'nchar.浙江省呼和浩特市丰都田街T座 149274', 1630000000000, 'binary1.QBTMVrRvMGcRSiUFpsnA', 'nchar1.甘肃省佛山县大兴石家庄街y座 699134', 'binary2.iaKGuopmHqqbANMmhQaB', 'nchar2.福建省杭州县闵行福州街e座 356019', 'binary3.pAdZtAJFuMQGiLYWCFzp', 'nchar3.天津市玲市梁平阜新路R座 699400', 'binary4.bJvTLLaAsMVnxxKragLA', 'nchar4.内蒙古自治区银川市萧山乌鲁木齐街p座 711931', 'binary5.ITFlhuZlVWIBJqLhkOey', 'nchar5.陕西省桂芳县南湖北镇路s座 173929', 'binary6.EZDRIMGNFYtddfbOlkvT', 'nchar6.四川省兴城市沙湾李街p座 370512', 'binary7.RunKOCOVDEkKXXLbQQwD', 'nchar7.河北省兴安盟市萧山张路n座 447381', 'binary8.YOTuRbbLIqBCEgLddPwI', 'nchar8.北京市文县浔阳澳门路h座 816162') ;") + + tdSql.execute("insert into stable_2_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000000010, 2090912853, 6664951181911026762, 27365, 66, -584038.233035, -934072263.917529, 0, 'binary.aqhUfBvmuNqFySsMkMdt', 'nchar.湖南省瑞县沙市王街c座 200752', 1630000000000, 'binary1.MwStUNfrTBVbvhHjfNza', 'nchar1.河北省雪市魏都杜街i座 259384', 'binary2.DGmDtcyaEObwuQVxDpUP', 'nchar2.湖北省淑兰县普陀胡路n座 716038', 'binary3.IAounswvgoPxMXtsqnwU', 'nchar3.甘肃省永安县南湖银川街C座 330264', 'binary4.wPwqkMLYqzkhmRHRpKAy', 'nchar4.上海市通辽市浔阳北镇路H座 317911', 'binary5.iQoYVJdmAoSBlyGpJpXx', 'nchar5.浙江省建华市大兴永安街K座 644305', 'binary6.MmjmFrioKDTFoegthaRD', 'nchar6.澳门特别行政区楠市龙潭太原路f座 611785', 'binary7.aHloPsebqjkwcCRXAcGc', 'nchar7.北京市桂芝市高港许街N座 542112', 'binary8.xvNxozZWlsTvtweWXQrl', 'nchar8.山东省北镇市静安巢湖路N座 751441') ;") + + tdSql.execute("insert into stable_1_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double , q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001000, 1154867532, -4617169670731049020, 21991, -24, 1168661238750.610107, -426107677972.705994, 0, 'binary.hRmglnSXuxUSvYIqDolS', 'nchar.天津市齐齐哈尔市兴山王路e座 440016', 1630000000001, 'binary1.rpZLfFIvigPxgWvEiTnf', 'nchar1.天津市欣县上街李街n座 110533', 'binary2.CWBcufneMDLIfNmMyDQD', 'nchar2.甘肃省利市房山姜路f座 539129', 'binary3.uhGROtaovBUWCsBUcRUS', 'nchar3.贵州省嘉禾县安次天津路a座 385203', 'binary4.iXwEQVdoHPejKHgtUcnp', 'nchar4.山西省乌鲁木齐县西峰王街z座 375814', 'binary5.YxaTiRVvJItsdEsMogEr', 'nchar5.陕西省金凤市静安邵街s座 349352', 'binary6.znhgdUaTGWcwjmZAsZtC', 'nchar6.澳门特别行政区宁德县朝阳苏路r座 964005', 'binary7.OaZVpQWKsvDQANUDbcVU', 'nchar7.云南省凯市淄川柳州路g座 551620', 'binary8.XKoaJcnvWGWgtmCHASlj', 'nchar8.山西省洋县吉区袁街k座 383085') ;") + + tdSql.execute("insert into regular_table_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001000, -1295218132, -2795255426441574417, -25856, -79, 31169.428912, -33.958690, 0, 'binary.qhHqAnxdwJQzpAIOnKsM', 'nchar.黑龙江省海口县上街张街B座 580665', 1630000000001, 'binary1.dFkcGdPczduswPtesnoF', 'nchar1.台湾省杰县丰都汪路j座 804255', 'binary2.pYgofQUdjJTzXLHZcNSc', 'nchar2.黑龙江省南昌市朝阳纪路i座 993767', 'binary3.UXtZpmwhjyEPOHhZyUxJ', 'nchar3.内蒙古自治区红市和平潮州路m座 803939', 'binary4.PHswTmYqZhTldHjklJYF', 'nchar4.四川省淮安市怀柔荆门路B座 969808', 'binary5.dKzVSArjPVLJXGTDWuOn', 'nchar5.台湾省璐县吉区梧州路T座 112945', 'binary6.AQrpGtxOsELOgWzfUxBo', 'nchar6.宁夏回族自治区淑兰县江北包街K座 510189', 'binary7.nYDVRmWgROIOOrVqCOse', 'nchar7.湖北省玉兰县双滦王街V座 272885', 'binary8.VCfynbYrgaMmjRiXHdUK', 'nchar8.贵州省畅县孝南宁德路z座 172562') ;") + + tdSql.execute("insert into stable_1_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001000, 1406358857, 3587109948379738474, 6769, 53, -6976945.888649, 7.677615, 1, 'binary.owVOUICouSTklPEhbivn', 'nchar.内蒙古自治区辽阳县普陀柳路a座 840131', 1630000000001, 'binary1.uJCOuTOBoHKrmxJuPjWe', 'nchar1.北京市帅市长寿王街h座 105426', 'binary2.XWXOVmhROrAgBbsXANmC', 'nchar2.澳门特别行政区金凤县海港荆门路x座 762691', 'binary3.gxCneIGHUGBNHhjKfxYi', 'nchar3.宁夏回族自治区惠州县长寿李路R座 863651', 'binary4.rRYTZlEWfyBoprvSjmrU', 'nchar4.宁夏回族自治区平县秀英马路e座 846867', 'binary5.dDdPBqkpKquoRoacZZda', 'nchar5.河南省凤兰市大兴兴城路n座 845990', 'binary6.iITctvWPvSZocnjfyaAT', 'nchar6.重庆市永安市崇文宁德路L座 343620', 'binary7.fcDNUjTjvwxhYLLCMLCL', 'nchar7.上海市淑华市安次杨街s座 495789', 'binary8.wVedqBcRAcpUPMTNhrHz', 'nchar8.陕西省军县丰都王街T座 625091') ;") + + tdSql.execute("insert into regular_table_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001000, 529011547, 5833219696463195177, 1368, 65, 88870.197516, 99120299502.128296, 1, 'binary.UxevmcLToszoUNHugtyM', 'nchar.安徽省红县安次叶路T座 440225', 1630000000001, 'binary1.sjsxFPefdlFKrTRAVouS', 'nchar1.贵州省柳州县海陵关岭街j座 890479', 'binary2.VOmSguDBtwojjcfmekbK', 'nchar2.贵州省兰州市沈北新汕尾路C座 478355', 'binary3.lJyJEMVjrqMUsmoBpWRN', 'nchar3.浙江省银川市友好黄街n座 118384', 'binary4.dgfhUSYsixNpyrERBkHr', 'nchar4.四川省琴市华龙方街J座 391129', 'binary5.hOVSTUkubHIghBwgKwEG', 'nchar5.陕西省瑜市华龙六安路x座 164875', 'binary6.SjWSOGeaMjBWIpoZSAcU', 'nchar6.河北省大冶市双滦孙路p座 902942', 'binary7.yAJcsKTMIyIhZijNsPkS', 'nchar7.台湾省银川市上街天津街U座 414513', 'binary8.BDMFDVvENIJkyoakNOvS', 'nchar8.重庆市荆门县南长银川街K座 999033') ;") + + tdSql.execute("insert into stable_1_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001001, -1866552988, -758901224671643352, -255, -64, -0.884551, -26.457607, 1, 'binary.draSVywTJWrxguXBtWEq', 'nchar.山东省上海县沙市翟街f座 172428', 1630000000002, 'binary1.nOXUZkAqDrnKxtwOxqtf', 'nchar1.辽宁省飞县牧野张路C座 379691', 'binary2.NKVuIxfhKuRiIGxqAQEh', 'nchar2.湖南省玉华市双滦王路Y座 106635', 'binary3.IWFsIUfCFJpynVEWFykw', 'nchar3.甘肃省宇县东城宜都路q座 883419', 'binary4.oYHgrkuMqsznJYiuMOGG', 'nchar4.台湾省邯郸市白云吴路H座 185871', 'binary5.DHSVcnCnLheJAOYMLLBJ', 'nchar5.新疆维吾尔自治区秀芳市怀柔巢湖路h座 193210', 'binary6.manaViLNdwzCBTxsJkdC', 'nchar6.辽宁省海门县大东马鞍山街q座 452562', 'binary7.ulrIznjySbFuIFWWjgnE', 'nchar7.新疆维吾尔自治区文市海陵刘街U座 979746', 'binary8.dAekCjvegomJekAMZOYY', 'nchar8.广西壮族自治区辽阳市城北李街c座 242662') ;") + + tdSql.execute("insert into regular_table_2 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001001, -741599443, -2779047021078882907, -2391, -17, 4299185271508.240234, 604469850161.758057, 1, 'binary.fXHBNYpwPFvxpmfkIJKq', 'nchar.河南省郑州县金平张路s座 406855', 1630000000002, 'binary1.qMsKGcIfmJmzqrLkaMZW', 'nchar1.台湾省齐齐哈尔县淄川乌路r座 947114', 'binary2.gUenDGAMpsjwAoLzuAVX', 'nchar2.江西省张家港县清浦上海街i座 960744', 'binary3.bnaWRmgZlUyMPaePUnrA', 'nchar3.香港特别行政区柳市永川张街A座 685451', 'binary4.ItKAwCgHdhBbQKJPJuWl', 'nchar4.陕西省飞县房山台北街P座 773575', 'binary5.obrRlauJBKUQjZeeDKzk', 'nchar5.澳门特别行政区丹丹市清城巢湖路D座 164790', 'binary6.EHcbDRSkpFjfYgoAhipL', 'nchar6.辽宁省小红市沈河高路R座 491125', 'binary7.zBsdfSePYONCPTFpSxtd', 'nchar7.浙江省玉英县孝南潮州街Q座 240622', 'binary8.ktVwuMPStmephdhCyXpW', 'nchar8.广西壮族自治区晨市沙湾宋路n座 375716') ;") + + tdSql.execute("insert into stable_2_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001000, 861043174, 5455100179131942803, 11627, 93, 4704891958.274140, -90663765201548.906250, 0, 'binary.mzefOJuVapGcOZRBPWSA', 'nchar.湖南省桂香市合川武汉路e座 190074', 1630000000001, 'binary1.OKSAdzYZtxmTYgUqDTUJ', 'nchar1.天津市西安市房山程路g座 201540', 'binary2.UVZXgaXnvsOFMyfQtxlk', 'nchar2.辽宁省武汉市清浦长春路C座 249816', 'binary3.cykuADWPZFQANvsqhRKX', 'nchar3.河北省刚市东城解路i座 865426', 'binary4.KJUftFRDQqQZOjPRbash', 'nchar4.辽宁省长沙县永川张路h座 794840', 'binary5.mzizxALkpwFvhsDKDZLX', 'nchar5.上海市哈尔滨市长寿阎街d座 505069', 'binary6.COpyPYrULAJYVDcSidce', 'nchar6.上海市桂英县沙湾魏街v座 727936', 'binary7.EraykZvYQkepZTyCLhrX', 'nchar7.新疆维吾尔自治区婷市兴山齐齐哈尔街T座 467826', 'binary8.qpqMrYpGgIWuzjCwqRtA', 'nchar8.辽宁省凤兰市魏都沈阳路D座 852593') ;") + + tdSql.execute("insert into stable_2_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001001, 891559292, 8826812031501648951, 25495, 17, -2673857362.484810, -992615811880.187012, 0, 'binary.sUSMJvnrtyRGAdkofSRp', 'nchar.北京市乌鲁木齐县金平郑州街K座 565319', 1630000000001, 'binary1.bkypAUrybRZdjEAQpLaD', 'nchar1.香港特别行政区通辽市清城张家港街g座 456475', 'binary2.mTeRDPIPKIqXXaCKxZZg', 'nchar2.海南省潜江市六枝特张路D座 742115', 'binary3.pXNShlLsrfFhMkZVJmvJ', 'nchar3.内蒙古自治区成市海港重庆街z座 935702', 'binary4.ePZMxraOFLRUirwjYQgz', 'nchar4.甘肃省哈尔滨县南溪兴城路B座 464192', 'binary5.EnZjhIMsFGQHTNgGwlLY', 'nchar5.山东省天津市门头沟齐齐哈尔路H座 590367', 'binary6.OwvaiZKpWMEuXNefCdSd', 'nchar6.广西壮族自治区凯县高坪葛路i座 733075', 'binary7.eZvrAHwgOSpNfkWOheQK', 'nchar7.云南省佳县大兴刘街b座 134332', 'binary8.mmASwYqspmYxzgEQMScD', 'nchar8.福建省秀英市高明广州街S座 972859') ;") + + tdSql.execute("insert into stable_2_1 (ts , q_int , q_bigint , q_smallint , q_tinyint , q_float , q_double, q_bool , q_binary , q_nchar, q_ts,q_binary1 , q_nchar1 , q_binary2 , q_nchar2 , q_binary3 , q_nchar3 , q_binary4 , q_nchar4 , q_binary5 , q_nchar5 , q_binary6 , q_nchar6 , q_binary7 , q_nchar7, q_binary8 , q_nchar8) values(1630000001010, 1406420228, 3809984898292539483, 15475, 82, -96.706822, 944989.967705, 0, 'binary.ZeTYsWJUdikuGndNhdDg', 'nchar.四川省潜江县蓟州陈街G座 347914', 1630000000001, 'binary1.xWLSLgSXgNPMCtEqeIem', 'nchar1.山东省辽阳县锡山上海路R座 816023', 'binary2.vdRFTigUtJQpwmklHmqs', 'nchar2.浙江省彬县崇文尚街v座 145248', 'binary3.DuUfOKRvTmFXKPglEJLy', 'nchar3.山西省秀荣市崇文嘉禾路b座 658257', 'binary4.XdprBDmPQensCLNylpfX', 'nchar4.青海省柳州县沈北新张家港街A座 207436', 'binary5.trUYUEAEeXecKeYDqBGX', 'nchar5.台湾省东市新城张路Q座 187531', 'binary6.gQwmTXQOFCblFwaBGoFG', 'nchar6.澳门特别行政区秀珍市萧山长春路D座 398394', 'binary7.djQZYSGDCbforCnoDkRE', 'nchar7.安徽省兴安盟市和平丰街o座 702930', 'binary8.QIuisWlGYavgxfQjfnAd', 'nchar8.黑龙江省海燕县闵行沈阳街S座 986676') ;") + + tdSql.query('select CONCAT_WS(" , , abc, 123",q_nchar2, q_nchar1, q_nchar3, q_nchar6) from stable_1;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'nchar2.宁夏回族自治区兰州市淄川香港路Y座 213761 , , abc, 123nchar1.福建省宜都县海港王街M座 713195 , , abc, 123nchar3.海南省静市江北海口路X座 702375 , , abc, 123nchar6.山东省建华市魏都南京街o座 326153') + tdSql.checkData(1, 0, 'nchar2.甘肃省利市房山姜路f座 539129 , , abc, 123nchar1.天津市欣县上街李街n座 110533 , , abc, 123nchar3.贵州省嘉禾县安次天津路a座 385203 , , abc, 123nchar6.澳门特别行政区宁德县朝阳苏路r座 964005') + tdSql.checkData(2, 0, 'nchar2.上海市宁德市淄川周路n座 803882 , , abc, 123nchar1.陕西省惠州县城东郑州街a座 702479 , , abc, 123nchar3.北京市峰市璧山刘路G座 746867 , , abc, 123nchar6.四川省东县静安余路Y座 617110') + tdSql.checkData(3, 0, 'nchar2.江苏省合山县涪城重庆路Q座 428968 , , abc, 123nchar1.北京市石家庄县高明太原街V座 139496 , , abc, 123nchar3.河南省呼和浩特市锡山兴城街O座 840658 , , abc, 123nchar6.天津市杨市萧山合肥街b座 371505') + tdSql.checkData(4, 0, 'nchar2.澳门特别行政区金凤县海港荆门路x座 762691 , , abc, 123nchar1.北京市帅市长寿王街h座 105426 , , abc, 123nchar3.宁夏回族自治区惠州县长寿李路R座 863651 , , abc, 123nchar6.重庆市永安市崇文宁德路L座 343620') + tdSql.checkData(5, 0, 'nchar2.湖南省玉华市双滦王路Y座 106635 , , abc, 123nchar1.辽宁省飞县牧野张路C座 379691 , , abc, 123nchar3.甘肃省宇县东城宜都路q座 883419 , , abc, 123nchar6.辽宁省海门县大东马鞍山街q座 452562') + + tdSql.query('select concat_ws(" , , abc, 山东省", q_nchar2, q_nchar1, q_nchar4, q_nchar6) from stable_1;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'nchar2.宁夏回族自治区兰州市淄川香港路Y座 213761 , , abc, 山东省nchar1.福建省宜都县海港王街M座 713195 , , abc, 山东省nchar4.四川省桂荣市滨城林街m座 503259 , , abc, 山东省nchar6.山东省建华市魏都南京街o座 326153') + tdSql.checkData(1, 0, 'nchar2.甘肃省利市房山姜路f座 539129 , , abc, 山东省nchar1.天津市欣县上街李街n座 110533 , , abc, 山东省nchar4.山西省乌鲁木齐县西峰王街z座 375814 , , abc, 山东省nchar6.澳门特别行政区宁德县朝阳苏路r座 964005') + tdSql.checkData(2, 0, 'nchar2.上海市宁德市淄川周路n座 803882 , , abc, 山东省nchar1.陕西省惠州县城东郑州街a座 702479 , , abc, 山东省nchar4.湖北省齐齐哈尔市静安蒋街w座 215779 , , abc, 山东省nchar6.四川省东县静安余路Y座 617110') + tdSql.checkData(3, 0, 'nchar2.江苏省合山县涪城重庆路Q座 428968 , , abc, 山东省nchar1.北京市石家庄县高明太原街V座 139496 , , abc, 山东省nchar4.西藏自治区潜江县魏都钟街i座 919700 , , abc, 山东省nchar6.天津市杨市萧山合肥街b座 371505') + tdSql.checkData(4, 0, 'nchar2.澳门特别行政区金凤县海港荆门路x座 762691 , , abc, 山东省nchar1.北京市帅市长寿王街h座 105426 , , abc, 山东省nchar4.宁夏回族自治区平县秀英马路e座 846867 , , abc, 山东省nchar6.重庆市永安市崇文宁德路L座 343620') + tdSql.checkData(5, 0, 'nchar2.湖南省玉华市双滦王路Y座 106635 , , abc, 山东省nchar1.辽宁省飞县牧野张路C座 379691 , , abc, 山东省nchar4.台湾省邯郸市白云吴路H座 185871 , , abc, 山东省nchar6.辽宁省海门县大东马鞍山街q座 452562') + + tdSql.query('select concat_ws(" , , abc, 山东省", q_nchar2, q_nchar1, q_nchar4, q_nchar6) from (select * from stable_1);') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'nchar2.宁夏回族自治区兰州市淄川香港路Y座 213761 , , abc, 山东省nchar1.福建省宜都县海港王街M座 713195 , , abc, 山东省nchar4.四川省桂荣市滨城林街m座 503259 , , abc, 山东省nchar6.山东省建华市魏都南京街o座 326153') + tdSql.checkData(1, 0, 'nchar2.甘肃省利市房山姜路f座 539129 , , abc, 山东省nchar1.天津市欣县上街李街n座 110533 , , abc, 山东省nchar4.山西省乌鲁木齐县西峰王街z座 375814 , , abc, 山东省nchar6.澳门特别行政区宁德县朝阳苏路r座 964005') + tdSql.checkData(2, 0, 'nchar2.上海市宁德市淄川周路n座 803882 , , abc, 山东省nchar1.陕西省惠州县城东郑州街a座 702479 , , abc, 山东省nchar4.湖北省齐齐哈尔市静安蒋街w座 215779 , , abc, 山东省nchar6.四川省东县静安余路Y座 617110') + tdSql.checkData(3, 0, 'nchar2.江苏省合山县涪城重庆路Q座 428968 , , abc, 山东省nchar1.北京市石家庄县高明太原街V座 139496 , , abc, 山东省nchar4.西藏自治区潜江县魏都钟街i座 919700 , , abc, 山东省nchar6.天津市杨市萧山合肥街b座 371505') + tdSql.checkData(4, 0, 'nchar2.澳门特别行政区金凤县海港荆门路x座 762691 , , abc, 山东省nchar1.北京市帅市长寿王街h座 105426 , , abc, 山东省nchar4.宁夏回族自治区平县秀英马路e座 846867 , , abc, 山东省nchar6.重庆市永安市崇文宁德路L座 343620') + tdSql.checkData(5, 0, 'nchar2.湖南省玉华市双滦王路Y座 106635 , , abc, 山东省nchar1.辽宁省飞县牧野张路C座 379691 , , abc, 山东省nchar4.台湾省邯郸市白云吴路H座 185871 , , abc, 山东省nchar6.辽宁省海门县大东马鞍山街q座 452562') + + tdSql.query('select upper(q_nchar1),upper(q_nchar2),length(q_nchar1),char_length(q_nchar1),lower(q_nchar1) from (select * from stable_1);') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR1.福建省宜都县海港王街M座 713195') + tdSql.checkData(0, 1, 'NCHAR2.宁夏回族自治区兰州市淄川香港路Y座 213761') + tdSql.checkData(0, 2, 104) + tdSql.checkData(0, 3, 26) + tdSql.checkData(0, 4, 'nchar1.福建省宜都县海港王街m座 713195') + tdSql.checkData(1, 0, 'NCHAR1.天津市欣县上街李街N座 110533') + tdSql.checkData(1, 1, 'NCHAR2.甘肃省利市房山姜路F座 539129') + tdSql.checkData(1, 2, 100) + tdSql.checkData(1, 3, 25) + tdSql.checkData(1, 4, 'nchar1.天津市欣县上街李街n座 110533') + tdSql.checkData(2, 0, 'NCHAR1.陕西省惠州县城东郑州街A座 702479') + tdSql.checkData(2, 1, 'NCHAR2.上海市宁德市淄川周路N座 803882') + tdSql.checkData(2, 2, 108) + tdSql.checkData(2, 3, 27) + tdSql.checkData(2, 4, 'nchar1.陕西省惠州县城东郑州街a座 702479') + tdSql.checkData(3, 0, 'NCHAR1.北京市石家庄县高明太原街V座 139496') + tdSql.checkData(3, 1, 'NCHAR2.江苏省合山县涪城重庆路Q座 428968') + tdSql.checkData(3, 2, 112) + tdSql.checkData(3, 3, 28) + tdSql.checkData(3, 4, 'nchar1.北京市石家庄县高明太原街v座 139496') + tdSql.checkData(4, 0, 'NCHAR1.北京市帅市长寿王街H座 105426') + tdSql.checkData(4, 1, 'NCHAR2.澳门特别行政区金凤县海港荆门路X座 762691') + tdSql.checkData(4, 2, 100) + tdSql.checkData(4, 3, 25) + tdSql.checkData(4, 4, 'nchar1.北京市帅市长寿王街h座 105426') + tdSql.checkData(5, 0, 'NCHAR1.辽宁省飞县牧野张路C座 379691') + tdSql.checkData(5, 1, 'NCHAR2.湖南省玉华市双滦王路Y座 106635') + tdSql.checkData(5, 2, 100) + tdSql.checkData(5, 3, 25) + tdSql.checkData(5, 4, 'nchar1.辽宁省飞县牧野张路c座 379691') + + tdSql.query('select upper(q_nchar1),upper(q_nchar2),length(q_nchar1),char_length(q_nchar1),lower(q_nchar1) from (select * from stable_1) order by ts;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR1.福建省宜都县海港王街M座 713195') + tdSql.checkData(0, 1, 'NCHAR2.宁夏回族自治区兰州市淄川香港路Y座 213761') + tdSql.checkData(0, 2, 104) + tdSql.checkData(0, 3, 26) + tdSql.checkData(0, 4, 'nchar1.福建省宜都县海港王街m座 713195') + tdSql.checkData(1, 0, 'NCHAR1.陕西省惠州县城东郑州街A座 702479') + tdSql.checkData(1, 1, 'NCHAR2.上海市宁德市淄川周路N座 803882') + tdSql.checkData(1, 2, 108) + tdSql.checkData(1, 3, 27) + tdSql.checkData(1, 4, 'nchar1.陕西省惠州县城东郑州街a座 702479') + tdSql.checkData(2, 0, 'NCHAR1.北京市石家庄县高明太原街V座 139496') + tdSql.checkData(2, 1, 'NCHAR2.江苏省合山县涪城重庆路Q座 428968') + tdSql.checkData(2, 2, 112) + tdSql.checkData(2, 3, 28) + tdSql.checkData(2, 4, 'nchar1.北京市石家庄县高明太原街v座 139496') + tdSql.checkData(3, 0, 'NCHAR1.天津市欣县上街李街N座 110533') + tdSql.checkData(3, 1, 'NCHAR2.甘肃省利市房山姜路F座 539129') + tdSql.checkData(3, 2, 100) + tdSql.checkData(3, 3, 25) + tdSql.checkData(3, 4, 'nchar1.天津市欣县上街李街n座 110533') + tdSql.checkData(4, 0, 'NCHAR1.北京市帅市长寿王街H座 105426') + tdSql.checkData(4, 1, 'NCHAR2.澳门特别行政区金凤县海港荆门路X座 762691') + tdSql.checkData(4, 2, 100) + tdSql.checkData(4, 3, 25) + tdSql.checkData(4, 4, 'nchar1.北京市帅市长寿王街h座 105426') + tdSql.checkData(5, 0, 'NCHAR1.辽宁省飞县牧野张路C座 379691') + tdSql.checkData(5, 1, 'NCHAR2.湖南省玉华市双滦王路Y座 106635') + tdSql.checkData(5, 2, 100) + tdSql.checkData(5, 3, 25) + tdSql.checkData(5, 4, 'nchar1.辽宁省飞县牧野张路c座 379691') + + tdSql.query('select upper(q_nchar1),upper(q_nchar2),length(q_nchar1),char_length(q_nchar1),lower(q_nchar1) from (select * from stable_1);') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR1.福建省宜都县海港王街M座 713195') + tdSql.checkData(0, 1, 'NCHAR2.宁夏回族自治区兰州市淄川香港路Y座 213761') + tdSql.checkData(0, 2, 104) + tdSql.checkData(0, 3, 26) + tdSql.checkData(0, 4, 'nchar1.福建省宜都县海港王街m座 713195') + tdSql.checkData(1, 0, 'NCHAR1.天津市欣县上街李街N座 110533') + tdSql.checkData(1, 1, 'NCHAR2.甘肃省利市房山姜路F座 539129') + tdSql.checkData(1, 2, 100) + tdSql.checkData(1, 3, 25) + tdSql.checkData(1, 4, 'nchar1.天津市欣县上街李街n座 110533') + tdSql.checkData(2, 0, 'NCHAR1.陕西省惠州县城东郑州街A座 702479') + tdSql.checkData(2, 1, 'NCHAR2.上海市宁德市淄川周路N座 803882') + tdSql.checkData(2, 2, 108) + tdSql.checkData(2, 3, 27) + tdSql.checkData(2, 4, 'nchar1.陕西省惠州县城东郑州街a座 702479') + tdSql.checkData(3, 0, 'NCHAR1.北京市石家庄县高明太原街V座 139496') + tdSql.checkData(3, 1, 'NCHAR2.江苏省合山县涪城重庆路Q座 428968') + tdSql.checkData(3, 2, 112) + tdSql.checkData(3, 3, 28) + tdSql.checkData(3, 4, 'nchar1.北京市石家庄县高明太原街v座 139496') + tdSql.checkData(4, 0, 'NCHAR1.北京市帅市长寿王街H座 105426') + tdSql.checkData(4, 1, 'NCHAR2.澳门特别行政区金凤县海港荆门路X座 762691') + tdSql.checkData(4, 2, 100) + tdSql.checkData(4, 3, 25) + tdSql.checkData(4, 4, 'nchar1.北京市帅市长寿王街h座 105426') + tdSql.checkData(5, 0, 'NCHAR1.辽宁省飞县牧野张路C座 379691') + tdSql.checkData(5, 1, 'NCHAR2.湖南省玉华市双滦王路Y座 106635') + tdSql.checkData(5, 2, 100) + tdSql.checkData(5, 3, 25) + tdSql.checkData(5, 4, 'nchar1.辽宁省飞县牧野张路c座 379691') + + tdSql.query('select CONCAT_WS("abc, taos, , <, %, $, @, |",q_binary3, q_binary7, q_binary4, q_binary8, q_binary5, q_binary6, q_binary2, q_binary1) from stable_2;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'binary3.xpmnymjjdbpefsJbXiaAabc, taos, , <, %, $, @, |binary7.GJEBncpKznEVYlBjADXcabc, taos, , <, %, $, @, |binary4.MQQAGeTBCbbAFmyCdNdxabc, taos, , <, %, $, @, |binary8.bseliCaYePtOlhjBDKlAabc, taos, , <, %, $, @, |binary5.jcGNOXcvsteCwnVwZxkvabc, taos, , <, %, $, @, |binary6.sFIopESAmZxNtpEAXvmhabc, taos, , <, %, $, @, |binary2.CCmnLmgCmPDGsacmypKrabc, taos, , <, %, $, @, |binary1.PZrbgCdVlhLuYWzJfpcQ') + tdSql.checkData(1, 0, 'binary3.pAdZtAJFuMQGiLYWCFzpabc, taos, , <, %, $, @, |binary7.RunKOCOVDEkKXXLbQQwDabc, taos, , <, %, $, @, |binary4.bJvTLLaAsMVnxxKragLAabc, taos, , <, %, $, @, |binary8.YOTuRbbLIqBCEgLddPwIabc, taos, , <, %, $, @, |binary5.ITFlhuZlVWIBJqLhkOeyabc, taos, , <, %, $, @, |binary6.EZDRIMGNFYtddfbOlkvTabc, taos, , <, %, $, @, |binary2.iaKGuopmHqqbANMmhQaBabc, taos, , <, %, $, @, |binary1.QBTMVrRvMGcRSiUFpsnA') + tdSql.checkData(2, 0, 'binary3.IAounswvgoPxMXtsqnwUabc, taos, , <, %, $, @, |binary7.aHloPsebqjkwcCRXAcGcabc, taos, , <, %, $, @, |binary4.wPwqkMLYqzkhmRHRpKAyabc, taos, , <, %, $, @, |binary8.xvNxozZWlsTvtweWXQrlabc, taos, , <, %, $, @, |binary5.iQoYVJdmAoSBlyGpJpXxabc, taos, , <, %, $, @, |binary6.MmjmFrioKDTFoegthaRDabc, taos, , <, %, $, @, |binary2.DGmDtcyaEObwuQVxDpUPabc, taos, , <, %, $, @, |binary1.MwStUNfrTBVbvhHjfNza') + tdSql.checkData(3, 0, 'binary3.cykuADWPZFQANvsqhRKXabc, taos, , <, %, $, @, |binary7.EraykZvYQkepZTyCLhrXabc, taos, , <, %, $, @, |binary4.KJUftFRDQqQZOjPRbashabc, taos, , <, %, $, @, |binary8.qpqMrYpGgIWuzjCwqRtAabc, taos, , <, %, $, @, |binary5.mzizxALkpwFvhsDKDZLXabc, taos, , <, %, $, @, |binary6.COpyPYrULAJYVDcSidceabc, taos, , <, %, $, @, |binary2.UVZXgaXnvsOFMyfQtxlkabc, taos, , <, %, $, @, |binary1.OKSAdzYZtxmTYgUqDTUJ') + tdSql.checkData(4, 0, 'binary3.pXNShlLsrfFhMkZVJmvJabc, taos, , <, %, $, @, |binary7.eZvrAHwgOSpNfkWOheQKabc, taos, , <, %, $, @, |binary4.ePZMxraOFLRUirwjYQgzabc, taos, , <, %, $, @, |binary8.mmASwYqspmYxzgEQMScDabc, taos, , <, %, $, @, |binary5.EnZjhIMsFGQHTNgGwlLYabc, taos, , <, %, $, @, |binary6.OwvaiZKpWMEuXNefCdSdabc, taos, , <, %, $, @, |binary2.mTeRDPIPKIqXXaCKxZZgabc, taos, , <, %, $, @, |binary1.bkypAUrybRZdjEAQpLaD') + tdSql.checkData(5, 0, 'binary3.DuUfOKRvTmFXKPglEJLyabc, taos, , <, %, $, @, |binary7.djQZYSGDCbforCnoDkREabc, taos, , <, %, $, @, |binary4.XdprBDmPQensCLNylpfXabc, taos, , <, %, $, @, |binary8.QIuisWlGYavgxfQjfnAdabc, taos, , <, %, $, @, |binary5.trUYUEAEeXecKeYDqBGXabc, taos, , <, %, $, @, |binary6.gQwmTXQOFCblFwaBGoFGabc, taos, , <, %, $, @, |binary2.vdRFTigUtJQpwmklHmqsabc, taos, , <, %, $, @, |binary1.xWLSLgSXgNPMCtEqeIem') + + tdSql.query('select * from (select CONCAT_WS("abc, taos, , <, %, $, @, |",q_binary3, q_binary7, q_binary4, q_binary8, q_binary5, q_binary6, q_binary2, q_binary1) from stable_2 where q_double <= 1.7E308 and q_int <= 2147483647 and t_tinyint != 128 and t_nchar is not null and q_nchar match \'nchar\' and (q_bool = true or q_bool = false));') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'binary3.xpmnymjjdbpefsJbXiaAabc, taos, , <, %, $, @, |binary7.GJEBncpKznEVYlBjADXcabc, taos, , <, %, $, @, |binary4.MQQAGeTBCbbAFmyCdNdxabc, taos, , <, %, $, @, |binary8.bseliCaYePtOlhjBDKlAabc, taos, , <, %, $, @, |binary5.jcGNOXcvsteCwnVwZxkvabc, taos, , <, %, $, @, |binary6.sFIopESAmZxNtpEAXvmhabc, taos, , <, %, $, @, |binary2.CCmnLmgCmPDGsacmypKrabc, taos, , <, %, $, @, |binary1.PZrbgCdVlhLuYWzJfpcQ') + tdSql.checkData(1, 0, 'binary3.pAdZtAJFuMQGiLYWCFzpabc, taos, , <, %, $, @, |binary7.RunKOCOVDEkKXXLbQQwDabc, taos, , <, %, $, @, |binary4.bJvTLLaAsMVnxxKragLAabc, taos, , <, %, $, @, |binary8.YOTuRbbLIqBCEgLddPwIabc, taos, , <, %, $, @, |binary5.ITFlhuZlVWIBJqLhkOeyabc, taos, , <, %, $, @, |binary6.EZDRIMGNFYtddfbOlkvTabc, taos, , <, %, $, @, |binary2.iaKGuopmHqqbANMmhQaBabc, taos, , <, %, $, @, |binary1.QBTMVrRvMGcRSiUFpsnA') + tdSql.checkData(2, 0, 'binary3.IAounswvgoPxMXtsqnwUabc, taos, , <, %, $, @, |binary7.aHloPsebqjkwcCRXAcGcabc, taos, , <, %, $, @, |binary4.wPwqkMLYqzkhmRHRpKAyabc, taos, , <, %, $, @, |binary8.xvNxozZWlsTvtweWXQrlabc, taos, , <, %, $, @, |binary5.iQoYVJdmAoSBlyGpJpXxabc, taos, , <, %, $, @, |binary6.MmjmFrioKDTFoegthaRDabc, taos, , <, %, $, @, |binary2.DGmDtcyaEObwuQVxDpUPabc, taos, , <, %, $, @, |binary1.MwStUNfrTBVbvhHjfNza') + tdSql.checkData(3, 0, 'binary3.cykuADWPZFQANvsqhRKXabc, taos, , <, %, $, @, |binary7.EraykZvYQkepZTyCLhrXabc, taos, , <, %, $, @, |binary4.KJUftFRDQqQZOjPRbashabc, taos, , <, %, $, @, |binary8.qpqMrYpGgIWuzjCwqRtAabc, taos, , <, %, $, @, |binary5.mzizxALkpwFvhsDKDZLXabc, taos, , <, %, $, @, |binary6.COpyPYrULAJYVDcSidceabc, taos, , <, %, $, @, |binary2.UVZXgaXnvsOFMyfQtxlkabc, taos, , <, %, $, @, |binary1.OKSAdzYZtxmTYgUqDTUJ') + tdSql.checkData(4, 0, 'binary3.pXNShlLsrfFhMkZVJmvJabc, taos, , <, %, $, @, |binary7.eZvrAHwgOSpNfkWOheQKabc, taos, , <, %, $, @, |binary4.ePZMxraOFLRUirwjYQgzabc, taos, , <, %, $, @, |binary8.mmASwYqspmYxzgEQMScDabc, taos, , <, %, $, @, |binary5.EnZjhIMsFGQHTNgGwlLYabc, taos, , <, %, $, @, |binary6.OwvaiZKpWMEuXNefCdSdabc, taos, , <, %, $, @, |binary2.mTeRDPIPKIqXXaCKxZZgabc, taos, , <, %, $, @, |binary1.bkypAUrybRZdjEAQpLaD') + tdSql.checkData(5, 0, 'binary3.DuUfOKRvTmFXKPglEJLyabc, taos, , <, %, $, @, |binary7.djQZYSGDCbforCnoDkREabc, taos, , <, %, $, @, |binary4.XdprBDmPQensCLNylpfXabc, taos, , <, %, $, @, |binary8.QIuisWlGYavgxfQjfnAdabc, taos, , <, %, $, @, |binary5.trUYUEAEeXecKeYDqBGXabc, taos, , <, %, $, @, |binary6.gQwmTXQOFCblFwaBGoFGabc, taos, , <, %, $, @, |binary2.vdRFTigUtJQpwmklHmqsabc, taos, , <, %, $, @, |binary1.xWLSLgSXgNPMCtEqeIem') + + tdSql.query('select CONCAT_WS("), <, ., ^, >, , |, /",q_nchar1, q_nchar6, q_nchar7, q_nchar, q_nchar5, q_nchar8, q_nchar4, q_nchar3) from stable_2;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'nchar1.澳门特别行政区武汉市璧山孔路Y座 467679), <, ., ^, >, , |, /nchar6.上海市琳市萧山朴路I座 857895), <, ., ^, >, , |, /nchar7.内蒙古自治区永安县南湖王路m座 128263), <, ., ^, >, , |, /nchar.辽宁省小红县安次刘路I座 783067), <, ., ^, >, , |, /nchar5.青海省哈尔滨市蓟州雷路S座 774634), <, ., ^, >, , |, /nchar8.新疆维吾尔自治区畅市清浦惠州路Y座 221741), <, ., ^, >, , |, /nchar4.天津市哈尔滨县新城杨路w座 877346), <, ., ^, >, , |, /nchar3.宁夏回族自治区齐齐哈尔市长寿海门路s座 980357') + tdSql.checkData(1, 0, 'nchar1.甘肃省佛山县大兴石家庄街y座 699134), <, ., ^, >, , |, /nchar6.四川省兴城市沙湾李街p座 370512), <, ., ^, >, , |, /nchar7.河北省兴安盟市萧山张路n座 447381), <, ., ^, >, , |, /nchar.浙江省呼和浩特市丰都田街T座 149274), <, ., ^, >, , |, /nchar5.陕西省桂芳县南湖北镇路s座 173929), <, ., ^, >, , |, /nchar8.北京市文县浔阳澳门路h座 816162), <, ., ^, >, , |, /nchar4.内蒙古自治区银川市萧山乌鲁木齐街p座 711931), <, ., ^, >, , |, /nchar3.天津市玲市梁平阜新路R座 699400') + tdSql.checkData(2, 0, 'nchar1.河北省雪市魏都杜街i座 259384), <, ., ^, >, , |, /nchar6.澳门特别行政区楠市龙潭太原路f座 611785), <, ., ^, >, , |, /nchar7.北京市桂芝市高港许街N座 542112), <, ., ^, >, , |, /nchar.湖南省瑞县沙市王街c座 200752), <, ., ^, >, , |, /nchar5.浙江省建华市大兴永安街K座 644305), <, ., ^, >, , |, /nchar8.山东省北镇市静安巢湖路N座 751441), <, ., ^, >, , |, /nchar4.上海市通辽市浔阳北镇路H座 317911), <, ., ^, >, , |, /nchar3.甘肃省永安县南湖银川街C座 330264') + tdSql.checkData(3, 0, 'nchar1.天津市西安市房山程路g座 201540), <, ., ^, >, , |, /nchar6.上海市桂英县沙湾魏街v座 727936), <, ., ^, >, , |, /nchar7.新疆维吾尔自治区婷市兴山齐齐哈尔街T座 467826), <, ., ^, >, , |, /nchar.湖南省桂香市合川武汉路e座 190074), <, ., ^, >, , |, /nchar5.上海市哈尔滨市长寿阎街d座 505069), <, ., ^, >, , |, /nchar8.辽宁省凤兰市魏都沈阳路D座 852593), <, ., ^, >, , |, /nchar4.辽宁省长沙县永川张路h座 794840), <, ., ^, >, , |, /nchar3.河北省刚市东城解路i座 865426') + tdSql.checkData(4, 0, 'nchar1.香港特别行政区通辽市清城张家港街g座 456475), <, ., ^, >, , |, /nchar6.广西壮族自治区凯县高坪葛路i座 733075), <, ., ^, >, , |, /nchar7.云南省佳县大兴刘街b座 134332), <, ., ^, >, , |, /nchar.北京市乌鲁木齐县金平郑州街K座 565319), <, ., ^, >, , |, /nchar5.山东省天津市门头沟齐齐哈尔路H座 590367), <, ., ^, >, , |, /nchar8.福建省秀英市高明广州街S座 972859), <, ., ^, >, , |, /nchar4.甘肃省哈尔滨县南溪兴城路B座 464192), <, ., ^, >, , |, /nchar3.内蒙古自治区成市海港重庆街z座 935702') + tdSql.checkData(5, 0, 'nchar1.山东省辽阳县锡山上海路R座 816023), <, ., ^, >, , |, /nchar6.澳门特别行政区秀珍市萧山长春路D座 398394), <, ., ^, >, , |, /nchar7.安徽省兴安盟市和平丰街o座 702930), <, ., ^, >, , |, /nchar.四川省潜江县蓟州陈街G座 347914), <, ., ^, >, , |, /nchar5.台湾省东市新城张路Q座 187531), <, ., ^, >, , |, /nchar8.黑龙江省海燕县闵行沈阳街S座 986676), <, ., ^, >, , |, /nchar4.青海省柳州县沈北新张家港街A座 207436), <, ., ^, >, , |, /nchar3.山西省秀荣市崇文嘉禾路b座 658257') + + tdSql.query('select CONCAT_WS("), <, ., ^, >, , |, /",q_nchar1, q_nchar6, q_nchar7, q_nchar, q_nchar5, q_nchar8, q_nchar4, q_nchar3) from stable_2 where q_bigint is not null and t_ts is not null and q_binary nmatch \'binarynchar\';') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'nchar1.澳门特别行政区武汉市璧山孔路Y座 467679), <, ., ^, >, , |, /nchar6.上海市琳市萧山朴路I座 857895), <, ., ^, >, , |, /nchar7.内蒙古自治区永安县南湖王路m座 128263), <, ., ^, >, , |, /nchar.辽宁省小红县安次刘路I座 783067), <, ., ^, >, , |, /nchar5.青海省哈尔滨市蓟州雷路S座 774634), <, ., ^, >, , |, /nchar8.新疆维吾尔自治区畅市清浦惠州路Y座 221741), <, ., ^, >, , |, /nchar4.天津市哈尔滨县新城杨路w座 877346), <, ., ^, >, , |, /nchar3.宁夏回族自治区齐齐哈尔市长寿海门路s座 980357') + tdSql.checkData(1, 0, 'nchar1.甘肃省佛山县大兴石家庄街y座 699134), <, ., ^, >, , |, /nchar6.四川省兴城市沙湾李街p座 370512), <, ., ^, >, , |, /nchar7.河北省兴安盟市萧山张路n座 447381), <, ., ^, >, , |, /nchar.浙江省呼和浩特市丰都田街T座 149274), <, ., ^, >, , |, /nchar5.陕西省桂芳县南湖北镇路s座 173929), <, ., ^, >, , |, /nchar8.北京市文县浔阳澳门路h座 816162), <, ., ^, >, , |, /nchar4.内蒙古自治区银川市萧山乌鲁木齐街p座 711931), <, ., ^, >, , |, /nchar3.天津市玲市梁平阜新路R座 699400') + tdSql.checkData(2, 0, 'nchar1.河北省雪市魏都杜街i座 259384), <, ., ^, >, , |, /nchar6.澳门特别行政区楠市龙潭太原路f座 611785), <, ., ^, >, , |, /nchar7.北京市桂芝市高港许街N座 542112), <, ., ^, >, , |, /nchar.湖南省瑞县沙市王街c座 200752), <, ., ^, >, , |, /nchar5.浙江省建华市大兴永安街K座 644305), <, ., ^, >, , |, /nchar8.山东省北镇市静安巢湖路N座 751441), <, ., ^, >, , |, /nchar4.上海市通辽市浔阳北镇路H座 317911), <, ., ^, >, , |, /nchar3.甘肃省永安县南湖银川街C座 330264') + tdSql.checkData(3, 0, 'nchar1.天津市西安市房山程路g座 201540), <, ., ^, >, , |, /nchar6.上海市桂英县沙湾魏街v座 727936), <, ., ^, >, , |, /nchar7.新疆维吾尔自治区婷市兴山齐齐哈尔街T座 467826), <, ., ^, >, , |, /nchar.湖南省桂香市合川武汉路e座 190074), <, ., ^, >, , |, /nchar5.上海市哈尔滨市长寿阎街d座 505069), <, ., ^, >, , |, /nchar8.辽宁省凤兰市魏都沈阳路D座 852593), <, ., ^, >, , |, /nchar4.辽宁省长沙县永川张路h座 794840), <, ., ^, >, , |, /nchar3.河北省刚市东城解路i座 865426') + tdSql.checkData(4, 0, 'nchar1.香港特别行政区通辽市清城张家港街g座 456475), <, ., ^, >, , |, /nchar6.广西壮族自治区凯县高坪葛路i座 733075), <, ., ^, >, , |, /nchar7.云南省佳县大兴刘街b座 134332), <, ., ^, >, , |, /nchar.北京市乌鲁木齐县金平郑州街K座 565319), <, ., ^, >, , |, /nchar5.山东省天津市门头沟齐齐哈尔路H座 590367), <, ., ^, >, , |, /nchar8.福建省秀英市高明广州街S座 972859), <, ., ^, >, , |, /nchar4.甘肃省哈尔滨县南溪兴城路B座 464192), <, ., ^, >, , |, /nchar3.内蒙古自治区成市海港重庆街z座 935702') + tdSql.checkData(5, 0, 'nchar1.山东省辽阳县锡山上海路R座 816023), <, ., ^, >, , |, /nchar6.澳门特别行政区秀珍市萧山长春路D座 398394), <, ., ^, >, , |, /nchar7.安徽省兴安盟市和平丰街o座 702930), <, ., ^, >, , |, /nchar.四川省潜江县蓟州陈街G座 347914), <, ., ^, >, , |, /nchar5.台湾省东市新城张路Q座 187531), <, ., ^, >, , |, /nchar8.黑龙江省海燕县闵行沈阳街S座 986676), <, ., ^, >, , |, /nchar4.青海省柳州县沈北新张家港街A座 207436), <, ., ^, >, , |, /nchar3.山西省秀荣市崇文嘉禾路b座 658257') + + tdSql.query('select CONCAT_WS("$, , ~",q_nchar7, q_nchar5, q_nchar8) from stable_1;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'nchar7.湖北省桂芳市高明邯郸路q座 413345$, , ~nchar5.贵州省大冶县滨城梧州街P座 554324$, , ~nchar8.内蒙古自治区太原县萧山王路p座 322176') + tdSql.checkData(1, 0, 'nchar7.云南省凯市淄川柳州路g座 551620$, , ~nchar5.陕西省金凤市静安邵街s座 349352$, , ~nchar8.山西省洋县吉区袁街k座 383085') + tdSql.checkData(2, 0, 'nchar7.江西省玉英市海港澳门路q座 945219$, , ~nchar5.北京市桂香市城东淮安街K座 265859$, , ~nchar8.香港特别行政区太原市黄浦黄街P座 177199') + tdSql.checkData(3, 0, 'nchar7.河北省西安市浔阳通辽街w座 546863$, , ~nchar5.重庆市兰英县沙湾嘉禾街c座 775060$, , ~nchar8.宁夏回族自治区文市朝阳昆明街O座 933200') + tdSql.checkData(4, 0, 'nchar7.上海市淑华市安次杨街s座 495789$, , ~nchar5.河南省凤兰市大兴兴城路n座 845990$, , ~nchar8.陕西省军县丰都王街T座 625091') + tdSql.checkData(5, 0, 'nchar7.新疆维吾尔自治区文市海陵刘街U座 979746$, , ~nchar5.新疆维吾尔自治区秀芳市怀柔巢湖路h座 193210$, , ~nchar8.广西壮族自治区辽阳市城北李街c座 242662') + + tdSql.query('select CONCAT_WS("taos, _, +",q_binary2, q_binary5, q_binary4) from (select * from stable_1) where q_nchar is not null;') + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'binary2.tsCyNVyBJDCnIvUdjVevtaos, _, +binary5.BUEJHkTvXfstJGArxcBztaos, _, +binary4.NdciuKObKZYwDVhtIOgB') + tdSql.checkData(1, 0, 'binary2.CWBcufneMDLIfNmMyDQDtaos, _, +binary5.YxaTiRVvJItsdEsMogErtaos, _, +binary4.iXwEQVdoHPejKHgtUcnp') + tdSql.checkData(2, 0, 'binary2.FeyVxiUQWvaCkYlzlfeGtaos, _, +binary5.CCRGhhIjzzUEyhmxALRLtaos, _, +binary4.xqFUKKJYHIpPlfyNuhFF') + tdSql.checkData(3, 0, 'binary2.CgjLFXASsqDMbqpClkyotaos, _, +binary5.OrEfrEsydYTamaZkNkwktaos, _, +binary4.zyKhpKkjeZokFeegJQDi') + tdSql.checkData(4, 0, 'binary2.XWXOVmhROrAgBbsXANmCtaos, _, +binary5.dDdPBqkpKquoRoacZZdataos, _, +binary4.rRYTZlEWfyBoprvSjmrU') + tdSql.checkData(5, 0, 'binary2.NKVuIxfhKuRiIGxqAQEhtaos, _, +binary5.DHSVcnCnLheJAOYMLLBJtaos, _, +binary4.oYHgrkuMqsznJYiuMOGG') + + tdSql.query("select UPPER(q_nchar),UPPER(q_nchar),LOWER(q_nchar),length(q_nchar),char_length(q_nchar) from stable_2 where tbname in ('stable_2_1') and q_tinyint <= 127 and t_smallint is not null and (q_binary like 'binary%' or q_nchar = '0' or q_binary = 'binary_' ) and t_bool in (0 , 1) ;") + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 1, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 2, 'nchar.辽宁省小红县安次刘路i座 783067') + tdSql.checkData(0, 3, 100) + tdSql.checkData(0, 4, 25) + tdSql.checkData(1, 0, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 1, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 2, 'nchar.浙江省呼和浩特市丰都田街t座 149274') + tdSql.checkData(1, 3, 108) + tdSql.checkData(1, 4, 27) + tdSql.checkData(2, 0, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 1, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 2, 'nchar.湖南省瑞县沙市王街c座 200752') + tdSql.checkData(2, 3, 96) + tdSql.checkData(2, 4, 24) + tdSql.checkData(3, 0, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 1, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 2, 'nchar.湖南省桂香市合川武汉路e座 190074') + tdSql.checkData(3, 3, 104) + tdSql.checkData(3, 4, 26) + tdSql.checkData(4, 0, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 1, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 2, 'nchar.北京市乌鲁木齐县金平郑州街k座 565319') + tdSql.checkData(4, 3, 112) + tdSql.checkData(4, 4, 28) + tdSql.checkData(5, 0, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 1, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 2, 'nchar.四川省潜江县蓟州陈街g座 347914') + tdSql.checkData(5, 3, 100) + tdSql.checkData(5, 4, 25) + + tdSql.query("select UPPER(q_nchar),UPPER(q_nchar),LOWER(q_nchar),length(q_nchar),char_length(q_nchar) from stable_2 where tbname in ('stable_2_1');") + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 1, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 2, 'nchar.辽宁省小红县安次刘路i座 783067') + tdSql.checkData(0, 3, 100) + tdSql.checkData(0, 4, 25) + tdSql.checkData(1, 0, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 1, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 2, 'nchar.浙江省呼和浩特市丰都田街t座 149274') + tdSql.checkData(1, 3, 108) + tdSql.checkData(1, 4, 27) + tdSql.checkData(2, 0, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 1, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 2, 'nchar.湖南省瑞县沙市王街c座 200752') + tdSql.checkData(2, 3, 96) + tdSql.checkData(2, 4, 24) + tdSql.checkData(3, 0, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 1, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 2, 'nchar.湖南省桂香市合川武汉路e座 190074') + tdSql.checkData(3, 3, 104) + tdSql.checkData(3, 4, 26) + tdSql.checkData(4, 0, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 1, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 2, 'nchar.北京市乌鲁木齐县金平郑州街k座 565319') + tdSql.checkData(4, 3, 112) + tdSql.checkData(4, 4, 28) + tdSql.checkData(5, 0, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 1, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 2, 'nchar.四川省潜江县蓟州陈街g座 347914') + tdSql.checkData(5, 3, 100) + tdSql.checkData(5, 4, 25) + + tdSql.query("select * from (select UPPER(q_nchar),UPPER(q_nchar),LOWER(q_nchar),length(q_nchar),char_length(q_nchar) from stable_2 where tbname in ('stable_2_1') and q_tinyint <= 127 and q_tinyint between -127 and 127 and (q_binary like 'binary%' or q_nchar = '0' or q_binary = 'binary_' ) and t_bool in (0 , 1) );") + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 1, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 2, 'nchar.辽宁省小红县安次刘路i座 783067') + tdSql.checkData(0, 3, 100) + tdSql.checkData(0, 4, 25) + tdSql.checkData(1, 0, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 1, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 2, 'nchar.浙江省呼和浩特市丰都田街t座 149274') + tdSql.checkData(1, 3, 108) + tdSql.checkData(1, 4, 27) + tdSql.checkData(2, 0, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 1, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 2, 'nchar.湖南省瑞县沙市王街c座 200752') + tdSql.checkData(2, 3, 96) + tdSql.checkData(2, 4, 24) + tdSql.checkData(3, 0, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 1, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 2, 'nchar.湖南省桂香市合川武汉路e座 190074') + tdSql.checkData(3, 3, 104) + tdSql.checkData(3, 4, 26) + tdSql.checkData(4, 0, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 1, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 2, 'nchar.北京市乌鲁木齐县金平郑州街k座 565319') + tdSql.checkData(4, 3, 112) + tdSql.checkData(4, 4, 28) + tdSql.checkData(5, 0, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 1, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 2, 'nchar.四川省潜江县蓟州陈街g座 347914') + tdSql.checkData(5, 3, 100) + tdSql.checkData(5, 4, 25) + + tdSql.query("select UPPER(q_nchar),LOWER(q_nchar),length(q_nchar),char_length(q_nchar) from stable_2 where tbname in ('stable_2_1');") + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(0, 1, 'nchar.辽宁省小红县安次刘路i座 783067') + tdSql.checkData(0, 2, 100) + tdSql.checkData(0, 3, 25) + tdSql.checkData(1, 0, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(1, 1, 'nchar.浙江省呼和浩特市丰都田街t座 149274') + tdSql.checkData(1, 2, 108) + tdSql.checkData(1, 3, 27) + tdSql.checkData(2, 0, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(2, 1, 'nchar.湖南省瑞县沙市王街c座 200752') + tdSql.checkData(2, 2, 96) + tdSql.checkData(2, 3, 24) + tdSql.checkData(3, 0, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(3, 1, 'nchar.湖南省桂香市合川武汉路e座 190074') + tdSql.checkData(3, 2, 104) + tdSql.checkData(3, 3, 26) + tdSql.checkData(4, 0, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(4, 1, 'nchar.北京市乌鲁木齐县金平郑州街k座 565319') + tdSql.checkData(4, 2, 112) + tdSql.checkData(4, 3, 28) + tdSql.checkData(5, 0, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + tdSql.checkData(5, 1, 'nchar.四川省潜江县蓟州陈街g座 347914') + tdSql.checkData(5, 2, 100) + tdSql.checkData(5, 3, 25) + + tdSql.query("select UPPER(q_nchar) from stable_2 where tbname in ('stable_2_1') and q_tinyint <= 127 and q_tinyint between -127 and 127 and (q_binary like 'binary%' or q_nchar = '0' or q_binary = 'binary_' ) and t_bool in (0 , 1) ;") + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'NCHAR.辽宁省小红县安次刘路I座 783067') + tdSql.checkData(1, 0, 'NCHAR.浙江省呼和浩特市丰都田街T座 149274') + tdSql.checkData(2, 0, 'NCHAR.湖南省瑞县沙市王街C座 200752') + tdSql.checkData(3, 0, 'NCHAR.湖南省桂香市合川武汉路E座 190074') + tdSql.checkData(4, 0, 'NCHAR.北京市乌鲁木齐县金平郑州街K座 565319') + tdSql.checkData(5, 0, 'NCHAR.四川省潜江县蓟州陈街G座 347914') + + tdSql.query("select * from (select UPPER(q_binary),LOWER(q_binary),CONCAT(q_binary,q_binary) from stable_2 where tbname in ('stable_2_1') and q_int is not null and t_smallint >= -32767 and q_binary nmatch 'binarynchar' and (t_bool = true or t_bool = false) order by ts desc);") + tdSql.checkRows(6) + tdSql.checkData(0, 0, 'BINARY.ZETYSWJUDIKUGNDNHDDG') + tdSql.checkData(0, 1, 'binary.zetyswjudikugndnhddg') + tdSql.checkData(0, 2, 'binary.ZeTYsWJUdikuGndNhdDgbinary.ZeTYsWJUdikuGndNhdDg') + tdSql.checkData(1, 0, 'BINARY.SUSMJVNRTYRGADKOFSRP') + tdSql.checkData(1, 1, 'binary.susmjvnrtyrgadkofsrp') + tdSql.checkData(1, 2, 'binary.sUSMJvnrtyRGAdkofSRpbinary.sUSMJvnrtyRGAdkofSRp') + tdSql.checkData(2, 0, 'BINARY.MZEFOJUVAPGCOZRBPWSA') + tdSql.checkData(2, 1, 'binary.mzefojuvapgcozrbpwsa') + tdSql.checkData(2, 2, 'binary.mzefOJuVapGcOZRBPWSAbinary.mzefOJuVapGcOZRBPWSA') + tdSql.checkData(3, 0, 'BINARY.AQHUFBVMUNQFYSSMKMDT') + tdSql.checkData(3, 1, 'binary.aqhufbvmunqfyssmkmdt') + tdSql.checkData(3, 2, 'binary.aqhUfBvmuNqFySsMkMdtbinary.aqhUfBvmuNqFySsMkMdt') + tdSql.checkData(4, 0, 'BINARY.RENSISLQMQQRNTVDSVUC') + tdSql.checkData(4, 1, 'binary.rensislqmqqrntvdsvuc') + tdSql.checkData(4, 2, 'binary.REnSISlqmqqrnTVDsVucbinary.REnSISlqmqqrnTVDsVuc') + tdSql.checkData(5, 0, 'BINARY.RICJHNDLJVZXCUIUCTWP') + tdSql.checkData(5, 1, 'binary.ricjhndljvzxcuiuctwp') + tdSql.checkData(5, 2, 'binary.RicjHNdlJvZXcuIUCtwpbinary.RicjHNdlJvZXcuIUCtwp') + + tdSql.query("select * from (select ts, UPPER(q_binary), LOWER(q_binary) from stable_2 where tbname in ('stable_2_1') and q_int is not null and t_smallint >= -32767 and q_binary nmatch 'binarynchar' and (t_bool = true or t_bool = false)) order by ts desc;") + tdSql.checkRows(6) + tdSql.checkData(0, 0, datetime.datetime(2021, 8, 27, 1, 46, 41, 10000)) + tdSql.checkData(0, 1, 'BINARY.ZETYSWJUDIKUGNDNHDDG') + tdSql.checkData(0, 2, 'binary.zetyswjudikugndnhddg') + tdSql.checkData(1, 0, datetime.datetime(2021, 8, 27, 1, 46, 41, 1000)) + tdSql.checkData(1, 1, 'BINARY.SUSMJVNRTYRGADKOFSRP') + tdSql.checkData(1, 2, 'binary.susmjvnrtyrgadkofsrp') + tdSql.checkData(2, 0, datetime.datetime(2021, 8, 27, 1, 46, 41)) + tdSql.checkData(2, 1, 'BINARY.MZEFOJUVAPGCOZRBPWSA') + tdSql.checkData(2, 2, 'binary.mzefojuvapgcozrbpwsa') + tdSql.checkData(3, 0, datetime.datetime(2021, 8, 27, 1, 46, 40, 10000)) + tdSql.checkData(3, 1, 'BINARY.AQHUFBVMUNQFYSSMKMDT') + tdSql.checkData(3, 2, 'binary.aqhufbvmunqfyssmkmdt') + tdSql.checkData(4, 0, datetime.datetime(2021, 8, 27, 1, 46, 40, 1000)) + tdSql.checkData(4, 1, 'BINARY.RENSISLQMQQRNTVDSVUC') + tdSql.checkData(4, 2, 'binary.rensislqmqqrntvdsvuc') + tdSql.checkData(5, 0, datetime.datetime(2021, 8, 27, 1, 46, 40)) + tdSql.checkData(5, 1, 'BINARY.RICJHNDLJVZXCUIUCTWP') + tdSql.checkData(5, 2, 'binary.ricjhndljvzxcuiuctwp') + + tdSql.execute('drop database nchardb') + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/query_window_keywords.py b/tests/develop-test/2-query/query_window_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..869f3697dc2fb7da45029695be9a4330036a270c --- /dev/null +++ b/tests/develop-test/2-query/query_window_keywords.py @@ -0,0 +1,1804 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-11216]: Time window related keywords + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def getBuildPath(self): + selfPath = os.path.dirname(os.path.realpath(__file__)) + + if ("community" in selfPath): + projPath = selfPath[:selfPath.find("community")] + else: + projPath = selfPath[:selfPath.find("tests")] + + for root, dirs, files in os.walk(projPath): + if ("taosd" in files): + rootRealPath = os.path.dirname(os.path.realpath(root)) + if ("packaging" not in rootRealPath): + buildPath = root[:len(root) - len("/build/bin")] + break + return buildPath + + def checkTimestampEqual(self, elm, expect_elm): + caller = inspect.getframeinfo(inspect.stack()[1][0]) + if len(elm) == len(expect_elm): + delta = abs(int(elm[-1]) - int(expect_elm[-1])) + if delta == 1: #ignore 1 second diff + new_elm = expect_elm[0:-1] + elm[-1] + else: + new_elm = expect_elm; + if elm == new_elm: + tdLog.info("sql:%s, elm:%s == expect_elm:%s" % (tdSql.sql, elm, new_elm)) + else: + args = (caller.filename, caller.lineno, tdSql.sql, elm, new_elm) + tdLog.exit("%s(%d) failed: sql:%s, elm:%s != expect_elm:%s" % args) + else: + args = (caller.filename, caller.lineno, tdSql.sql, elm, expect_elm) + tdLog.exit("%s(%d) failed: sql:%s, elm:%s != expect_elm:%s" % args) + + + def run(self): + print("running {}".format(__file__)) + + #Prepare data + #db precision "ms" + tdSql.execute("drop database if exists db_m") + tdSql.execute("create database if not exists db_m") + tdSql.execute('use db_m') + + tdSql.execute("create stable stb (ts timestamp, c0 int) tags (t0 int);") + tdSql.execute("create table ctb1 using stb tags (1);") + tdSql.execute("create table ctb2 using stb tags (2);") + tdSql.execute("create table tb (ts timestamp, c0 int);") + + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:05', 5)") + + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:00', 0)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:01', 1)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:02', 2)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:03', 3)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:04', 4)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:05', 5)") + + tdSql.execute("insert into tb values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:05', 5)") + + #db precision "us" + tdSql.execute("drop database if exists db_u") + tdSql.execute("create database if not exists db_u precision 'us'") + tdSql.execute('use db_u') + + tdSql.execute("create stable stb (ts timestamp, c0 int) tags (t0 int);") + tdSql.execute("create table ctb1 using stb tags (1);") + tdSql.execute("create table ctb2 using stb tags (2);") + tdSql.execute("create table tb (ts timestamp, c0 int);") + + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:05', 5)") + + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:00', 0)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:01', 1)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:02', 2)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:03', 3)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:04', 4)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:05', 5)") + + tdSql.execute("insert into tb values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:05', 5)") + + #db precision "ns" + tdSql.execute("drop database if exists db_n") + tdSql.execute("create database if not exists db_n precision 'ns'") + tdSql.execute('use db_n') + + tdSql.execute("create stable stb (ts timestamp, c0 int) tags (t0 int);") + tdSql.execute("create table ctb1 using stb tags (1);") + tdSql.execute("create table ctb2 using stb tags (2);") + tdSql.execute("create table tb (ts timestamp, c0 int);") + + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into ctb1 values ('2022-02-02 02:00:05', 5)") + + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:00', 0)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:01', 1)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:02', 2)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:03', 3)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:04', 4)") + tdSql.execute("insert into ctb2 values ('2022-02-02 03:00:05', 5)") + + tdSql.execute("insert into tb values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into tb values ('2022-02-02 02:00:05', 5)") + + + #execute query + print("============== STEP 1: select _qsatrt,_qstop,_qduration in projection query ================== ") + + # db precision "ms" + tdSql.execute('use db_m') + + ## _qstart + tdSql.query("select _qstart from tb;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstart from ctb1;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstart from stb;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + #res = tdSql.getData(6, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(7, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(8, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(9, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(10, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(11, 0) + + tdSql.query("select _qstart from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + #res = tdSql.getData(6, 0) + #tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + #res = tdSql.getData(7, 0) + #tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + #res = tdSql.getData(8, 0) + #tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstart from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstart from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + + tdSql.query("select _qstart,ts from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,ts from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,ts from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(9) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,_c0 from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,_c0 from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,_c0 from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(9) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,tbname from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,tbname from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,tbname from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(9) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + ##_qstop + tdSql.query("select _qstop from tb;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstop from ctb1;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstop from stb;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + #res = tdSql.getData(6, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(7, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(8, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(9, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(10, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(11, 0) + + tdSql.query("select _qstop from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + + tdSql.query("select _qstop from tb where ts >= '2022-02-02 02:00:02' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstop from ctb1 where ts >= '2022-02-02 02:00:02' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstop from stb where ts >= '2022-02-02 02:00:02' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + + tdSql.query("select _qstop,ts from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,ts from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,ts from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,_c0 from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,_c0 from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,_c0 from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,tbname from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,tbname from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,tbname from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + ##_qduration + tdSql.query("select _qduration from tb;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration from ctb1;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration from stb;") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + tdSql.checkEqual(res, None) + #res = tdSql.getData(6, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(7, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(8, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(9, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(10, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(11, 0) + + tdSql.query("select _qduration from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(3, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(4, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(5, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(6, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(7, 0) + #tdSql.checkEqual(res, None) + #res = tdSql.getData(8, 0) + #tdSql.checkEqual(res, None) + + tdSql.query("select _qduration from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(1, 0) + tdSql.checkEqual(res, None) + res = tdSql.getData(2, 0) + tdSql.checkEqual(res, None) + + + tdSql.query("select _qduration from tb where ts >= '2022-02-02 02:00:02' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qduration from ctb1 where ts >= '2022-02-02 02:00:02' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qduration from stb where ts >= '2022-02-02 02:00:02' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + + tdSql.query("select _qduration from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + + tdSql.query("select _qduration,ts from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration,ts from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration,ts from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + + tdSql.query("select _qduration,_c0 from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration,_c0 from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration,_c0 from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + + tdSql.query("select _qduration,tbname from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration,tbname from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + tdSql.query("select _qduration,tbname from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 4000) + tdSql.checkData(2, 0, 4000) + + #_qstart,_qstop,_qduration together + tdSql.query("select _qstart,_qstop,_qduration,c0 from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + tdSql.checkData(0, 2, 4000) + tdSql.checkData(1, 2, 4000) + tdSql.checkData(2, 2, 4000) + tdSql.query("select _qstart,_qstop,_qduration,c0 from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + tdSql.checkData(0, 2, 4000) + tdSql.checkData(1, 2, 4000) + tdSql.checkData(2, 2, 4000) + tdSql.query("select _qstart,_qstop,_qduration,c0 from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:07';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + tdSql.checkData(0, 2, 4000) + tdSql.checkData(1, 2, 4000) + tdSql.checkData(2, 2, 4000) + + # db precision "us" + tdSql.execute('use db_u') + + ##_qstart + tdSql.query("select _qstart from tb where ts >= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(2) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + tdSql.query("select _qstart from ctb1 where ts >= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(2) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + tdSql.query("select _qstart from stb where ts >= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(6) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + #res = tdSql.getData(6, 0) + #tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + #res = tdSql.getData(7, 0) + #tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + + ##_qstop + tdSql.query("select _qstop from tb where ts <= '2022-02-02 02:00:02.123456';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + tdSql.query("select _qstop from ctb1 where ts <= '2022-02-02 02:00:02.123456';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + tdSql.query("select _qstop from stb where ts <= '2022-02-02 02:00:02.123456';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + + ##_qduration + tdSql.query("select _qduration from tb where ts >= '2022-02-02 02:00:00.123455' and ts <= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000001) + tdSql.checkData(1, 0, 3000001) + tdSql.checkData(2, 0, 3000001) + tdSql.query("select _qduration from ctb1 where ts >= '2022-02-02 02:00:00.123455' and ts <= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000001) + tdSql.checkData(1, 0, 3000001) + tdSql.checkData(2, 0, 3000001) + tdSql.query("select _qduration from stb where ts >= '2022-02-02 02:00:00.123455' and ts <= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000001) + tdSql.checkData(1, 0, 3000001) + tdSql.checkData(2, 0, 3000001) + + + print("============== STEP 2: select _qstart,_qstop,_qduration in aggregate/selective/scalar query ================== ") + # db precision "ms" + tdSql.execute('use db_m') + + ## _qstart + tdSql.query("select _qstart,avg(c0) from tb;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstart,avg(c0) from ctb1;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstart,avg(c0) from stb;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + + tdSql.query("select _qstart,avg(c0) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,avg(c0) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,avg(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstart,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstart,avg(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + + tdSql.query("select _qstart,sum(c0) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,sum(c0) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,sum(c0) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,count(*) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,count(*) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,count(*) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,min(c0) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,min(c0) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,min(c0) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,first(c0) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,first(c0) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,first(c0) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,ceil(c0) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,ceil(c0) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,ceil(c0) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(9) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,round(1.5) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,round(1.5) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,round(1.5) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(9) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstart,abs(1.5) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,abs(1.5) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstart,abs(1.5) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(9) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + ##_qstop + tdSql.query("select _qstop,avg(c0) from tb;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstop,avg(c0) from ctb1;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qstop,avg(c0) from stb;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + + tdSql.query("select _qstop,avg(c0) from tb where ts <= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstop,avg(c0) from ctb1 where ts <= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query("select _qstop,avg(c0) from stb where ts <= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query("select _qstop,avg(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstop,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qstop,avg(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + + tdSql.query("select _qstop,sum(c0) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,sum(c0) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,sum(c0) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,count(*) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,count(*) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,count(*) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,min(c0) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,min(c0) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,min(c0) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,first(c0) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,first(c0) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,first(c0) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,ceil(c0) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,ceil(c0) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,ceil(c0) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,round(1.5) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,round(1.5) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,round(1.5) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query("select _qstop,abs(1.5) from tb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,abs(1.5) from ctb1 where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query("select _qstop,abs(1.5) from stb where ts <= '2022-02-02 02:00:02';") + tdSql.checkRows(3) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + ##_qduration + tdSql.query("select _qduration,avg(c0) from tb;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration,avg(c0) from ctb1;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration,avg(c0) from stb;") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + + tdSql.query("select _qduration,avg(c0) from tb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration,avg(c0) from stb where ts >= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + + tdSql.query("select _qduration,avg(c0) from tb where ts <= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration,avg(c0) from ctb1 where ts <= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + tdSql.query("select _qduration,avg(c0) from stb where ts <= '2022-02-02 02:00:03';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(res, None) + + tdSql.query("select _qduration,avg(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qduration,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + tdSql.query("select _qduration,avg(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:00';") + tdSql.checkRows(0) + + tdSql.query("select _qduration,sum(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,sum(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,sum(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + + tdSql.query("select _qduration,count(*) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,count(*) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,count(*) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + + tdSql.query("select _qduration,min(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,min(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,min(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + + tdSql.query("select _qduration,first(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,first(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + tdSql.query("select _qduration,first(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000) + + tdSql.query("select _qduration,ceil(c0) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query("select _qduration,ceil(c0) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query("select _qduration,ceil(c0) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + + tdSql.query("select _qduration,round(1.5) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query("select _qduration,round(1.5) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query("select _qduration,round(1.5) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + + tdSql.query("select _qduration,abs(1.5) from tb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query("select _qduration,abs(1.5) from ctb1 where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query("select _qduration,abs(1.5) from stb where ts >= '2022-02-02 02:00:03' and ts <= '2022-02-02 02:00:06';") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + + # db precision "us" + tdSql.execute('use db_u') + + ##_qstart + tdSql.query("select _qstart,avg(c0) from tb where ts >= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + tdSql.query("select _qstart,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + tdSql.query("select _qstart,avg(c0) from stb where ts >= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.123456") + + ##_qstop + tdSql.query("select _qstop,avg(c0) from tb where ts <= '2022-02-02 02:00:02.123456';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + tdSql.query("select _qstop,avg(c0) from ctb1 where ts <= '2022-02-02 02:00:02.123456';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + tdSql.query("select _qstop,avg(c0) from stb where ts <= '2022-02-02 02:00:02.123456';") + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.123456") + + ##_qduration + tdSql.query("select _qduration,avg(c0) from tb where ts >= '2022-02-02 02:00:00.123455' and ts <= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000001) + tdSql.query("select _qduration,avg(c0) from ctb1 where ts >= '2022-02-02 02:00:00.123455' and ts <= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000001) + tdSql.query("select _qduration,avg(c0) from stb where ts >= '2022-02-02 02:00:00.123455' and ts <= '2022-02-02 02:00:03.123456';") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 3000001) + + print("============== STEP 3: select _qsatrt,_qstop,_qduration in nested outer query ================== ") + tdSql.execute('use db_m') + ##_wstart + tdSql.query('select _qstart from (select _qstart,c0 from tb where ts >= "2022-02-02 02:00:03")') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query('select _qstart from (select _qstart,c0 from ctb1 where ts >= "2022-02-02 02:00:03")') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query('select _qstart from (select _qstart,c0 from stb where ts >= "2022-02-02 02:00:03")') + tdSql.checkRows(9) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(6, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(7, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(8, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + tdSql.query('select _qstart from (select _qstart,sum(c0) from tb where ts >= "2022-02-02 02:00:03")') + tdSql.checkRows(1) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query('select _qstart from (select _qstart,sum(c0) from ctb1 where ts >= "2022-02-02 02:00:03")') + tdSql.checkRows(1) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + tdSql.query('select _qstart from (select _qstart,sum(c0) from stb where ts >= "2022-02-02 02:00:03")') + tdSql.checkRows(1) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + + ##_wstop + tdSql.query('select _qstop from (select _qstop,c0 from tb where ts <= "2022-02-02 02:00:02")') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query('select _qstop from (select _qstop,c0 from ctb1 where ts <= "2022-02-02 02:00:02")') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query('select _qstop from (select _qstop,c0 from stb where ts <= "2022-02-02 02:00:02")') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + tdSql.query('select _qstop from (select _qstop,sum(c0) from tb where ts <= "2022-02-02 02:00:02")') + tdSql.checkRows(1) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query('select _qstop from (select _qstop,sum(c0) from ctb1 where ts <= "2022-02-02 02:00:02")') + tdSql.checkRows(1) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + tdSql.query('select _qstop from (select _qstop,sum(c0) from stb where ts <= "2022-02-02 02:00:02")') + tdSql.checkRows(1) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + + ##_wduration + tdSql.query('select _qduration from (select _qduration,c0 from tb where ts >= "2022-02-02 02:00:03" and ts <= "2022-02-02 02:00:06")') + tdSql.checkRows(3) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query('select _qduration from (select _qduration,c0 from ctb1 where ts >= "2022-02-02 02:00:03" and ts <= "2022-02-02 02:00:06")') + tdSql.checkRows(3) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + tdSql.query('select _qduration from (select _qduration,c0 from stb where ts >= "2022-02-02 02:00:03" and ts <= "2022-02-02 02:00:06")') + tdSql.checkRows(3) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 3000) + tdSql.checkData(1, 0, 3000) + tdSql.checkData(2, 0, 3000) + + tdSql.query('select _qduration from (select _qduration,sum(c0) from tb where ts >= "2022-02-02 02:00:03" and ts <= "2022-02-02 02:00:06")') + tdSql.checkRows(1) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 3000) + tdSql.query('select _qduration from (select _qduration,sum(c0) from ctb1 where ts >= "2022-02-02 02:00:03" and ts <= "2022-02-02 02:00:06")') + tdSql.checkRows(1) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 3000) + tdSql.query('select _qduration from (select _qduration,sum(c0) from stb where ts >= "2022-02-02 02:00:03" and ts <= "2022-02-02 02:00:06")') + tdSql.checkRows(1) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 3000) + print("============== STEP 5: select _qstart/_qstop/_qduration other cases ================== ") + + #distinct + tdSql.query("select distinct _qstart from tb") + tdSql.query("select distinct _qstart from ctb1") + tdSql.query("select distinct _qstart from stb") + + tdSql.query("select distinct _qstop from tb") + tdSql.query("select distinct _qstop from ctb1") + tdSql.query("select distinct _qstop from stb") + + tdSql.query("select distinct _qduration from tb") + tdSql.query("select distinct _qduration from ctb1") + tdSql.query("select distinct _qduration from stb") + + #_qs,col + tdSql.query("select _qstart,ts from tb") + tdSql.query("select _qstart,ts from ctb1") + tdSql.query("select _qstart,ts from stb") + tdSql.query("select _qstart,c0 from tb") + tdSql.query("select _qstart,c0 from ctb1") + tdSql.query("select _qstart,c0 from stb") + tdSql.query("select _qstart,_qstart from tb") + tdSql.query("select _qstart,_qstart from ctb1") + tdSql.query("select _qstart,_qstart from stb") + tdSql.query("select _qstart,t0 from ctb1") + tdSql.query("select _qstart,t0 from stb") + + tdSql.query("select _qstop,ts from tb") + tdSql.query("select _qstop,ts from ctb1") + tdSql.query("select _qstop,ts from stb") + tdSql.query("select _qstop,c0 from tb") + tdSql.query("select _qstop,c0 from ctb1") + tdSql.query("select _qstop,c0 from stb") + tdSql.query("select _qstop,_qstop from tb") + tdSql.query("select _qstop,_qstop from ctb1") + tdSql.query("select _qstop,_qstop from stb") + tdSql.query("select _qstop,t0 from ctb1") + tdSql.query("select _qstop,t0 from stb") + + tdSql.query("select _qduration,ts from tb") + tdSql.query("select _qduration,ts from ctb1") + tdSql.query("select _qduration,ts from stb") + tdSql.query("select _qduration,c0 from tb") + tdSql.query("select _qduration,c0 from ctb1") + tdSql.query("select _qduration,c0 from stb") + tdSql.query("select _qduration,_qduration from tb") + tdSql.query("select _qduration,_qduration from ctb1") + tdSql.query("select _qduration,_qduration from stb") + tdSql.query("select _qduration,t0 from ctb1") + tdSql.query("select _qduration,t0 from stb") + + #_qs,constant + tdSql.query("select _qstart,1 from tb") + tdSql.query("select _qstart,1 from ctb1") + tdSql.query("select _qstart,1 from stb") + tdSql.query("select _qstart,true from tb") + tdSql.query("select _qstart,true from ctb1") + tdSql.query("select _qstart,true from stb") + tdSql.query("select _qstart,'abc' from tb") + tdSql.query("select _qstart,'abc' from ctb1") + tdSql.query("select _qstart,'abc' from stb") + + tdSql.query("select _qstop,1 from tb") + tdSql.query("select _qstop,1 from ctb1") + tdSql.query("select _qstop,1 from stb") + tdSql.query("select _qstop,true from tb") + tdSql.query("select _qstop,true from ctb1") + tdSql.query("select _qstop,true from stb") + tdSql.query("select _qstop,'abc' from tb") + tdSql.query("select _qstop,'abc' from ctb1") + tdSql.query("select _qstop,'abc' from stb") + + tdSql.query("select _qduration,1 from tb") + tdSql.query("select _qduration,1 from ctb1") + tdSql.query("select _qduration,1 from stb") + tdSql.query("select _qduration,true from tb") + tdSql.query("select _qduration,true from ctb1") + tdSql.query("select _qduration,true from stb") + tdSql.query("select _qduration,'abc' from tb") + tdSql.query("select _qduration,'abc' from ctb1") + tdSql.query("select _qduration,'abc' from stb") + + #interval/sliding + tdSql.query("select _qstart from tb interval (1s)") + tdSql.query("select _qstart from ctb1 interval (1s)") + tdSql.query("select _qstart from stb interval (1s)") + + tdSql.query("select _qstop from tb interval (1s)") + tdSql.query("select _qstop from ctb1 interval (1s)") + tdSql.query("select _qstop from stb interval (1s)") + + tdSql.query("select _qduration from tb interval (1s)") + tdSql.query("select _qduration from ctb1 interval (1s)") + tdSql.query("select _qduration from stb interval (1s)") + + tdSql.query("select _qstart from tb interval (1s) sliding (1s)") + tdSql.query("select _qstart from ctb1 interval (1s) sliding (1s)") + tdSql.query("select _qstart from stb interval (1s) sliding (1s)") + + tdSql.query("select _qstop from tb interval (1s) sliding (1s)") + tdSql.query("select _qstop from ctb1 interval (1s) sliding (1s)") + tdSql.query("select _qstop from stb interval (1s) sliding (1s)") + + tdSql.query("select _qduration from tb interval (1s) sliding (1s)") + tdSql.query("select _qduration from ctb1 interval (1s) sliding (1s)") + tdSql.query("select _qduration from stb interval (1s) sliding (1s)") + + + #session_window + tdSql.query("select _qstart,avg(c0) from tb session(ts, 1s)") + tdSql.query("select _qstart,avg(c0) from ctb1 session(ts, 1s)") + + tdSql.query("select _qstop,avg(c0) from tb session(ts, 1s)") + tdSql.query("select _qstop,avg(c0) from ctb1 session(ts, 1s)") + + tdSql.query("select _qduration,avg(c0) from tb session(ts, 1s)") + tdSql.query("select _qduration,avg(c0) from ctb1 session(ts, 1s)") + + + #order by + tdSql.query("select _qstart from tb order by ts") + tdSql.query("select _qstart from ctb1 order by ts") + tdSql.query("select _qstart from stb order by ts") + #tdSql.query("select _qstart from tb order by ts desc") + #tdSql.query("select _qstart from ctb1 order by ts desc") + #tdSql.query("select _qstart from stb order by ts desc") + + tdSql.query("select _qstop from tb order by ts") + tdSql.query("select _qstop from ctb1 order by ts") + tdSql.query("select _qstop from stb order by ts") + #tdSql.query("select _qstop from tb order by ts desc") + #tdSql.query("select _qstop from ctb1 order by ts desc") + #tdSql.query("select _qstop from stb order by ts desc") + + + tdSql.query("select _qduration from tb order by ts") + tdSql.query("select _qduration from ctb1 order by ts") + tdSql.query("select _qduration from stb order by ts") + #tdSql.query("select _qduration from tb order by ts desc") + #tdSql.query("select _qduration from ctb1 order by ts desc") + #tdSql.query("select _qduration from stb order by ts desc") + + #limit + tdSql.query("select _qstart from tb limit 3") + tdSql.query("select _qstart from ctb1 limit 3") + tdSql.query("select _qstart from stb limit 3") + + tdSql.query("select _qstop from tb limit 3") + tdSql.query("select _qstop from ctb1 limit 3") + tdSql.query("select _qstop from stb limit 3") + + + tdSql.query("select _qduration from tb limit 3") + tdSql.query("select _qduration from ctb1 limit 3") + tdSql.query("select _qduration from stb limit 3") + + ############# not supported ############### + tdSql.error("select _qstart + 1 from tb interval (1s)") + tdSql.error("select _qstart + 1 from ctb1 interval (1s)") + tdSql.error("select _qstart + 1 from stb interval (1s)") + tdSql.error("select _qstart + 1.0 from tb interval (1s)") + tdSql.error("select _qstart + 1.0 from ctb1 interval (1s)") + tdSql.error("select _qstart + 1.0 from stb interval (1s)") + tdSql.error("select _qstart + true from tb interval (1s)") + tdSql.error("select _qstart + true from ctb1 interval (1s)") + tdSql.error("select _qstart + true from stb interval (1s)") + tdSql.error("select _qstart + 'abc' from tb interval (1s)") + tdSql.error("select _qstart + 'abc' from ctb1 interval (1s)") + tdSql.error("select _qstart + 'abc' from stb interval (1s)") + tdSql.error("select _qstart + 1s from tb interval (1s)") + tdSql.error("select _qstart + 1s from ctb1 interval (1s)") + tdSql.error("select _qstart + 1s from stb interval (1s)") + tdSql.error("select _qstart + ts from tb interval (1s)") + tdSql.error("select _qstart + ts from ctb1 interval (1s)") + tdSql.error("select _qstart + ts from stb interval (1s)") + tdSql.error("select _qstart + c0 from tb interval (1s)") + tdSql.error("select _qstart + c0 from ctb1 interval (1s)") + tdSql.error("select _qstart + c0 from stb interval (1s)") + tdSql.error("select _qstart + _qstop from tb interval (1s)") + tdSql.error("select _qstart + _qstop from ctb1 interval (1s)") + tdSql.error("select _qstart + _qstop from stb interval (1s)") + tdSql.error("select _qstart + _qduration from tb interval (1s)") + tdSql.error("select _qstart + _qduration from ctb1 interval (1s)") + tdSql.error("select _qstart + _qduration from stb interval (1s)") + + tdSql.error("select _qstop + 1 from tb interval (1s)") + tdSql.error("select _qstop + 1 from ctb1 interval (1s)") + tdSql.error("select _qstop + 1 from stb interval (1s)") + tdSql.error("select _qstop + 1.0 from tb interval (1s)") + tdSql.error("select _qstop + 1.0 from ctb1 interval (1s)") + tdSql.error("select _qstop + 1.0 from stb interval (1s)") + tdSql.error("select _qstop + true from tb interval (1s)") + tdSql.error("select _qstop + true from ctb1 interval (1s)") + tdSql.error("select _qstop + true from stb interval (1s)") + tdSql.error("select _qstop + 'abc' from tb interval (1s)") + tdSql.error("select _qstop + 'abc' from ctb1 interval (1s)") + tdSql.error("select _qstop + 'abc' from stb interval (1s)") + tdSql.error("select _qstop + 1s from tb interval (1s)") + tdSql.error("select _qstop + 1s from ctb1 interval (1s)") + tdSql.error("select _qstop + 1s from stb interval (1s)") + tdSql.error("select _qstop + ts from tb interval (1s)") + tdSql.error("select _qstop + ts from ctb1 interval (1s)") + tdSql.error("select _qstop + ts from stb interval (1s)") + tdSql.error("select _qstop + c0 from tb interval (1s)") + tdSql.error("select _qstop + c0 from ctb1 interval (1s)") + tdSql.error("select _qstop + c0 from stb interval (1s)") + tdSql.error("select _qstop + _qstart from tb interval (1s)") + tdSql.error("select _qstop + _qstart from ctb1 interval (1s)") + tdSql.error("select _qstop + _qstart from stb interval (1s)") + tdSql.error("select _qstop + _qduration from tb interval (1s)") + tdSql.error("select _qstop + _qduration from ctb1 interval (1s)") + tdSql.error("select _qstop + _qduration from stb interval (1s)") + + tdSql.error("select _qduration + 1 from tb interval (1s)") + tdSql.error("select _qduration + 1 from ctb1 interval (1s)") + tdSql.error("select _qduration + 1 from stb interval (1s)") + tdSql.error("select _qduration + 1.0 from tb interval (1s)") + tdSql.error("select _qduration + 1.0 from ctb1 interval (1s)") + tdSql.error("select _qduration + 1.0 from stb interval (1s)") + tdSql.error("select _qduration + true from tb interval (1s)") + tdSql.error("select _qduration + true from ctb1 interval (1s)") + tdSql.error("select _qduration + true from stb interval (1s)") + tdSql.error("select _qduration + 'abc' from tb interval (1s)") + tdSql.error("select _qduration + 'abc' from ctb1 interval (1s)") + tdSql.error("select _qduration + 'abc' from stb interval (1s)") + tdSql.error("select _qduration + 1s from tb interval (1s)") + tdSql.error("select _qduration + 1s from ctb1 interval (1s)") + tdSql.error("select _qduration + 1s from stb interval (1s)") + tdSql.error("select _qduration + ts from tb interval (1s)") + tdSql.error("select _qduration + ts from ctb1 interval (1s)") + tdSql.error("select _qduration + ts from stb interval (1s)") + tdSql.error("select _qduration + c0 from tb interval (1s)") + tdSql.error("select _qduration + c0 from ctb1 interval (1s)") + tdSql.error("select _qduration + c0 from stb interval (1s)") + tdSql.error("select _qduration + _qstart from tb interval (1s)") + tdSql.error("select _qduration + _qstart from ctb1 interval (1s)") + tdSql.error("select _qduration + _qstart from stb interval (1s)") + tdSql.error("select _qduration + _qduration from tb interval (1s)") + tdSql.error("select _qduration + _qduration from ctb1 interval (1s)") + tdSql.error("select _qduration + _qduration from stb interval (1s)") + + #state_window + tdSql.error("select _qstart,avg(c0) from tb state_window(c0)") + tdSql.error("select _qstart,avg(c0) from ctb1 state_window(c0)") + + tdSql.error("select _qstop,avg(c0) from tb state_window(c0)") + tdSql.error("select _qstop,avg(c0) from ctb1 state_window(c0)") + + tdSql.error("select _qduration,avg(c0) from tb state_window(c0)") + tdSql.error("select _qduration,avg(c0) from ctb1 state_window(c0)") + + #group by + tdSql.error("select _qstart from stb group by tbname") + tdSql.error("select _qstop from stb group by tbname") + tdSql.error("select _qduration from stb group by tbname") + + return + tdSql.execute('drop database db_m') + tdSql.execute('drop database db_u') + tdSql.execute('drop database db_n') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/scalar_expression.py b/tests/develop-test/2-query/scalar_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..5ffe9d06da7a213f382527587396293f1d8dbc76 --- /dev/null +++ b/tests/develop-test/2-query/scalar_expression.py @@ -0,0 +1,540 @@ +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import tdDnodes +from math import inf + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-14123]: fix failed test on arm64 by converting from sim tst to python test to overcome NaN value and its string representation + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def restartTaosd(self, index=1, dbname="db"): + tdDnodes.stop(index) + tdDnodes.startWithoutSleep(index) + tdSql.execute(f"use db0") + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists db0") + tdSql.execute("create database if not exists db0") + tdSql.execute('use db0') + tdSql.execute('create table st0 (ts timestamp, c1 int, c2 float, c3 bigint, c4 smallint, c5 tinyint, c6 double, c7 bool, c8 nchar(5), c9 binary(10)) TAGS (tgcol int);') + + tdSql.execute('create table ct0 using st0 tags( 0 );') + tdSql.execute('insert into ct0 values (1601481600000 , 0 , 0.25 , 0 , 0 , 0 , 0.25 , 0 , 0 , 0 );') + for i in range(1, 50): + tdSql.execute('insert into ct0 values ({}, {}, {}, {}, {}, {}, {}, {}, {}, {});'.format(1601481600000 + i * 60000, + i , i , i , i , i , i , i , i , i )) + + tdSql.execute('create table ct1 using st0 tags( 1 );') + tdSql.execute('insert into ct1 values (1601481600000 , 0 , 0.25 , 0 , 0 , 0 , 0.25 , 0 , 0 , 0 );') + for i in range(1, 50): + tdSql.execute('insert into ct1 values ({}, {}, {}, {}, {}, {}, {}, {}, {}, {});'.format(1601481600000 + i * 60000, + i , i , i , i , i , i , i , i , i )) + + + tdSql.query('select floor(3.0)+ceil(4.0) from ct0;') + tdSql.checkRows(50) + for row in range(0, 50): + tdSql.checkData(row, 0, 7.0) + + + tdSql.query('select sum(c1)+3.0+4.0 from st0;') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 2457.0) + + tdSql.query('select sin(log(avg(c1),sum(c2))+3)%4 from st0;') + tdSql.checkRows(1) + tdSql.checkData(0, 0, -0.26507428560248714) + + tdSql.query("select log(pow(length(concat('3','4')),2),c2) from st0;") + tdSql.checkRows(100) + tdSql.checkData(0, 0, -1.0) + tdSql.checkData(1, 0, inf) + tdSql.checkData(2, 0, 2.0) + tdSql.checkData(3, 0, 1.2618595071429148) + tdSql.checkData(4, 0, 1.0) + tdSql.checkData(5, 0, 0.8613531161467861) + tdSql.checkData(6, 0, 0.7737056144690831) + tdSql.checkData(7, 0, 0.7124143742160444) + tdSql.checkData(8, 0, 0.6666666666666667) + tdSql.checkData(9, 0, 0.6309297535714574) + tdSql.checkData(10, 0, 0.6020599913279623) + tdSql.checkData(11, 0, 0.5781296526357756) + tdSql.checkData(12, 0, 0.5578858913022596) + tdSql.checkData(13, 0, 0.5404763088546395) + tdSql.checkData(14, 0, 0.5252990700743871) + tdSql.checkData(15, 0, 0.511916049619631) + tdSql.checkData(16, 0, 0.5) + tdSql.checkData(17, 0, 0.489301084236452) + tdSql.checkData(18, 0, 0.4796249331362629) + tdSql.checkData(19, 0, 0.4708178267332765) + tdSql.checkData(20, 0, 0.46275642631951835) + tdSql.checkData(21, 0, 0.455340497393906) + tdSql.checkData(22, 0, 0.4484876484351508) + tdSql.checkData(23, 0, 0.4421294589150075) + tdSql.checkData(24, 0, 0.4362085839710631) + tdSql.checkData(25, 0, 0.43067655807339306) + tdSql.checkData(26, 0, 0.4254921071067263) + tdSql.checkData(27, 0, 0.42061983571430495) + tdSql.checkData(28, 0, 0.4160291953530189) + tdSql.checkData(29, 0, 0.4116936649208689) + tdSql.checkData(30, 0, 0.40759009418101233) + tdSql.checkData(31, 0, 0.4036981731641997) + tdSql.checkData(32, 0, 0.39999999999999997) + tdSql.checkData(33, 0, 0.39647972634112105) + tdSql.checkData(34, 0, 0.39312326446564516) + tdSql.checkData(35, 0, 0.3899180437875726) + tdSql.checkData(36, 0, 0.3868528072345416) + tdSql.checkData(37, 0, 0.3839174400131203) + tdSql.checkData(38, 0, 0.3811028248535468) + tdSql.checkData(39, 0, 0.37840071903374006) + tdSql.checkData(40, 0, 0.37580364941821515) + tdSql.checkData(41, 0, 0.3733048224778867) + tdSql.checkData(42, 0, 0.3708980468307378) + tdSql.checkData(43, 0, 0.36857766629741234) + tdSql.checkData(44, 0, 0.36633850182726724) + tdSql.checkData(45, 0, 0.3641758009398765) + tdSql.checkData(46, 0, 0.3620851935600804) + tdSql.checkData(47, 0, 0.3600626533133853) + tdSql.checkData(48, 0, 0.3581044635020827) + tdSql.checkData(49, 0, 0.3562071871080222) + tdSql.checkData(50, 0, -1.0) + tdSql.checkData(51, 0, inf) + tdSql.checkData(52, 0, 2.0) + tdSql.checkData(53, 0, 1.2618595071429148) + tdSql.checkData(54, 0, 1.0) + tdSql.checkData(55, 0, 0.8613531161467861) + tdSql.checkData(56, 0, 0.7737056144690831) + tdSql.checkData(57, 0, 0.7124143742160444) + tdSql.checkData(58, 0, 0.6666666666666667) + tdSql.checkData(59, 0, 0.6309297535714574) + tdSql.checkData(60, 0, 0.6020599913279623) + tdSql.checkData(61, 0, 0.5781296526357756) + tdSql.checkData(62, 0, 0.5578858913022596) + tdSql.checkData(63, 0, 0.5404763088546395) + tdSql.checkData(64, 0, 0.5252990700743871) + tdSql.checkData(65, 0, 0.511916049619631) + tdSql.checkData(66, 0, 0.5) + tdSql.checkData(67, 0, 0.489301084236452) + tdSql.checkData(68, 0, 0.4796249331362629) + tdSql.checkData(69, 0, 0.4708178267332765) + tdSql.checkData(70, 0, 0.46275642631951835) + tdSql.checkData(71, 0, 0.455340497393906) + tdSql.checkData(72, 0, 0.4484876484351508) + tdSql.checkData(73, 0, 0.4421294589150075) + tdSql.checkData(74, 0, 0.4362085839710631) + tdSql.checkData(75, 0, 0.43067655807339306) + tdSql.checkData(76, 0, 0.4254921071067263) + tdSql.checkData(77, 0, 0.42061983571430495) + tdSql.checkData(78, 0, 0.4160291953530189) + tdSql.checkData(79, 0, 0.4116936649208689) + tdSql.checkData(80, 0, 0.40759009418101233) + tdSql.checkData(81, 0, 0.4036981731641997) + tdSql.checkData(82, 0, 0.39999999999999997) + tdSql.checkData(83, 0, 0.39647972634112105) + tdSql.checkData(84, 0, 0.39312326446564516) + tdSql.checkData(85, 0, 0.3899180437875726) + tdSql.checkData(86, 0, 0.3868528072345416) + tdSql.checkData(87, 0, 0.3839174400131203) + tdSql.checkData(88, 0, 0.3811028248535468) + tdSql.checkData(89, 0, 0.37840071903374006) + tdSql.checkData(90, 0, 0.37580364941821515) + tdSql.checkData(91, 0, 0.3733048224778867) + tdSql.checkData(92, 0, 0.3708980468307378) + tdSql.checkData(93, 0, 0.36857766629741234) + tdSql.checkData(94, 0, 0.36633850182726724) + tdSql.checkData(95, 0, 0.3641758009398765) + tdSql.checkData(96, 0, 0.3620851935600804) + tdSql.checkData(97, 0, 0.3600626533133853) + tdSql.checkData(98, 0, 0.3581044635020827) + tdSql.checkData(99, 0, 0.3562071871080222) + + tdSql.query("select round(log(pow(length(concat('3','4')),2),c2)+floor(c3))+2 from st0;") + tdSql.checkRows(100) + tdSql.checkData(0, 0, 1.0) + tdSql.checkData(1, 0, inf) + tdSql.checkData(2, 0, 6.0) + tdSql.checkData(3, 0, 6.0) + tdSql.checkData(4, 0, 7.0) + tdSql.checkData(5, 0, 8.0) + tdSql.checkData(6, 0, 9.0) + tdSql.checkData(7, 0, 10.0) + tdSql.checkData(8, 0, 11.0) + tdSql.checkData(9, 0, 12.0) + tdSql.checkData(10, 0, 13.0) + tdSql.checkData(11, 0, 14.0) + tdSql.checkData(12, 0, 15.0) + tdSql.checkData(13, 0, 16.0) + tdSql.checkData(14, 0, 17.0) + tdSql.checkData(15, 0, 18.0) + tdSql.checkData(16, 0, 19.0) + tdSql.checkData(17, 0, 19.0) + tdSql.checkData(18, 0, 20.0) + tdSql.checkData(19, 0, 21.0) + tdSql.checkData(20, 0, 22.0) + tdSql.checkData(21, 0, 23.0) + tdSql.checkData(22, 0, 24.0) + tdSql.checkData(23, 0, 25.0) + tdSql.checkData(24, 0, 26.0) + tdSql.checkData(25, 0, 27.0) + tdSql.checkData(26, 0, 28.0) + tdSql.checkData(27, 0, 29.0) + tdSql.checkData(28, 0, 30.0) + tdSql.checkData(29, 0, 31.0) + tdSql.checkData(30, 0, 32.0) + tdSql.checkData(31, 0, 33.0) + tdSql.checkData(32, 0, 34.0) + tdSql.checkData(33, 0, 35.0) + tdSql.checkData(34, 0, 36.0) + tdSql.checkData(35, 0, 37.0) + tdSql.checkData(36, 0, 38.0) + tdSql.checkData(37, 0, 39.0) + tdSql.checkData(38, 0, 40.0) + tdSql.checkData(39, 0, 41.0) + tdSql.checkData(40, 0, 42.0) + tdSql.checkData(41, 0, 43.0) + tdSql.checkData(42, 0, 44.0) + tdSql.checkData(43, 0, 45.0) + tdSql.checkData(44, 0, 46.0) + tdSql.checkData(45, 0, 47.0) + tdSql.checkData(46, 0, 48.0) + tdSql.checkData(47, 0, 49.0) + tdSql.checkData(48, 0, 50.0) + tdSql.checkData(49, 0, 51.0) + tdSql.checkData(50, 0, 1.0) + tdSql.checkData(51, 0, inf) + tdSql.checkData(52, 0, 6.0) + tdSql.checkData(53, 0, 6.0) + tdSql.checkData(54, 0, 7.0) + tdSql.checkData(55, 0, 8.0) + tdSql.checkData(56, 0, 9.0) + tdSql.checkData(57, 0, 10.0) + tdSql.checkData(58, 0, 11.0) + tdSql.checkData(59, 0, 12.0) + tdSql.checkData(60, 0, 13.0) + tdSql.checkData(61, 0, 14.0) + tdSql.checkData(62, 0, 15.0) + tdSql.checkData(63, 0, 16.0) + tdSql.checkData(64, 0, 17.0) + tdSql.checkData(65, 0, 18.0) + tdSql.checkData(66, 0, 19.0) + tdSql.checkData(67, 0, 19.0) + tdSql.checkData(68, 0, 20.0) + tdSql.checkData(69, 0, 21.0) + tdSql.checkData(70, 0, 22.0) + tdSql.checkData(71, 0, 23.0) + tdSql.checkData(72, 0, 24.0) + tdSql.checkData(73, 0, 25.0) + tdSql.checkData(74, 0, 26.0) + tdSql.checkData(75, 0, 27.0) + tdSql.checkData(76, 0, 28.0) + tdSql.checkData(77, 0, 29.0) + tdSql.checkData(78, 0, 30.0) + tdSql.checkData(79, 0, 31.0) + tdSql.checkData(80, 0, 32.0) + tdSql.checkData(81, 0, 33.0) + tdSql.checkData(82, 0, 34.0) + tdSql.checkData(83, 0, 35.0) + tdSql.checkData(84, 0, 36.0) + tdSql.checkData(85, 0, 37.0) + tdSql.checkData(86, 0, 38.0) + tdSql.checkData(87, 0, 39.0) + tdSql.checkData(88, 0, 40.0) + tdSql.checkData(89, 0, 41.0) + tdSql.checkData(90, 0, 42.0) + tdSql.checkData(91, 0, 43.0) + tdSql.checkData(92, 0, 44.0) + tdSql.checkData(93, 0, 45.0) + tdSql.checkData(94, 0, 46.0) + tdSql.checkData(95, 0, 47.0) + tdSql.checkData(96, 0, 48.0) + tdSql.checkData(97, 0, 49.0) + tdSql.checkData(98, 0, 50.0) + tdSql.checkData(99, 0, 51.0) + + tdSql.query('select sin(pow(c1,log(c2,2))+pow(c2,2)) as val from ct0 union all select pow(c4,2)+tan(sin(c5)/cos(c6)) as val from ct1;') + tdSql.checkRows(100) + tdSql.checkData(0, 0, None) + tdSql.checkData(1, 0, 0.9092974268256817) + tdSql.checkData(2, 0, -0.27941549819892586) + tdSql.checkData(3, 0, 0.8433250578156978) + tdSql.checkData(4, 0, 0.5514266812416906) + tdSql.checkData(5, 0, -0.8406066116666611) + tdSql.checkData(6, 0, 0.43616107578365054) + tdSql.checkData(7, 0, 0.8974981847584117) + tdSql.checkData(8, 0, -0.8859527784925297) + tdSql.checkData(9, 0, 0.42947071474131504) + tdSql.checkData(10, 0, -0.4990148939921768) + tdSql.checkData(11, 0, -0.9668503083455382) + tdSql.checkData(12, 0, -0.37127069611623675) + tdSql.checkData(13, 0, 0.2583602129593735) + tdSql.checkData(14, 0, -0.34510090189538883) + tdSql.checkData(15, 0, 0.8660995395285155) + tdSql.checkData(16, 0, 0.6937252720798969) + tdSql.checkData(17, 0, -0.992591182028628) + tdSql.checkData(18, 0, -0.9291960033052914) + tdSql.checkData(19, 0, -0.011614784632622178) + tdSql.checkData(20, 0, -0.4106856453154767) + tdSql.checkData(21, 0, -0.36067689504566286) + tdSql.checkData(22, 0, 0.9703087105252133) + tdSql.checkData(23, 0, 0.3329834227491301) + tdSql.checkData(24, 0, -0.7486629772768763) + tdSql.checkData(25, 0, -0.971394847828127) + tdSql.checkData(26, 0, 0.5985902145855062) + tdSql.checkData(27, 0, -0.49186655944242286) + tdSql.checkData(28, 0, -0.4105290272382008) + tdSql.checkData(29, 0, -0.202908293443662) + tdSql.checkData(30, 0, -0.9672568013002486) + tdSql.checkData(31, 0, -0.9144905798912761) + tdSql.checkData(32, 0, -0.930013601079518) + tdSql.checkData(33, 0, 0.004918394988330845) + tdSql.checkData(34, 0, 0.720122562285698) + tdSql.checkData(35, 0, 0.931470218951081) + tdSql.checkData(36, 0, 0.8941486584814015) + tdSql.checkData(37, 0, 0.6498985856147372) + tdSql.checkData(38, 0, -0.9337541085366605) + tdSql.checkData(39, 0, -0.7860584458249767) + tdSql.checkData(40, 0, 0.9097616965457492) + tdSql.checkData(41, 0, 0.9262772442878136) + tdSql.checkData(42, 0, 0.9002636423705703) + tdSql.checkData(43, 0, 0.9333612649834834) + tdSql.checkData(44, 0, 0.08098252188677987) + tdSql.checkData(45, 0, -0.2669453821977269) + tdSql.checkData(46, 0, -0.9864147915539295) + tdSql.checkData(47, 0, 0.7905555341403578) + tdSql.checkData(48, 0, 0.9930380419415296) + tdSql.checkData(49, 0, -0.11973938558937497) + tdSql.checkData(50, 0, 0.0) + tdSql.checkData(51, 0, 75.68593339876413) + tdSql.checkData(52, 0, 5.417928575505387) + tdSql.checkData(53, 0, 8.85648005221507) + tdSql.checkData(54, 0, 18.282204450191365) + tdSql.checkData(55, 0, 24.756425180209273) + tdSql.checkData(56, 0, 35.7004910910186) + tdSql.checkData(57, 0, 50.188813241198766) + tdSql.checkData(58, 0, 63.43204170645191) + tdSql.checkData(59, 0, 80.51408573049088) + tdSql.checkData(60, 0, 100.75762114788726) + tdSql.checkData(61, 0, 121.24877416559158) + tdSql.checkData(62, 0, 143.26187154057212) + tdSql.checkData(63, 0, 169.49921715003558) + tdSql.checkData(64, 0, 197.43268735470073) + tdSql.checkData(65, 0, 223.84781294184071) + tdSql.checkData(66, 0, 256.31002912578884) + tdSql.checkData(67, 0, 289.36766325453783) + tdSql.checkData(68, 0, 321.83943972533865) + tdSql.checkData(69, 0, 361.1527613871425) + tdSql.checkData(70, 0, 398.72830803672844) + tdSql.checkData(71, 0, 417.9185722713414) + tdSql.checkData(72, 0, 484.00885188723004) + tdSql.checkData(73, 0, 471.3913348423639) + tdSql.checkData(74, 0, 577.5805869142416) + tdSql.checkData(75, 0, 624.8656743315343) + tdSql.checkData(76, 0, 678.4187022341146) + tdSql.checkData(77, 0, 728.8671148549121) + tdSql.checkData(78, 0, 783.7108972216736) + tdSql.checkData(79, 0, 842.2274126544997) + tdSql.checkData(80, 0, 899.877243006616) + tdSql.checkData(81, 0, 960.5271464519064) + tdSql.checkData(82, 0, 1024.7777181923664) + tdSql.checkData(83, 0, 1089.0854157079946) + tdSql.checkData(84, 0, 1155.2807954785546) + tdSql.checkData(85, 0, 1225.5127742681332) + tdSql.checkData(86, 0, 1305.6263061095037) + tdSql.checkData(87, 0, 1367.8826349729482) + tdSql.checkData(88, 0, 1444.32066897418) + tdSql.checkData(89, 0, 1521.5116974949854) + tdSql.checkData(90, 0, 1597.9486330581901) + tdSql.checkData(91, 0, 1681.1620533335488) + tdSql.checkData(92, 0, 1762.8611973159218) + tdSql.checkData(93, 0, 1835.2137045408574) + tdSql.checkData(94, 0, 1936.0177065493942) + tdSql.checkData(95, 0, 2004.599358732067) + tdSql.checkData(96, 0, 2117.763602992286) + tdSql.checkData(97, 0, 2208.874824726169) + tdSql.checkData(98, 0, 2306.5731210183926) + tdSql.checkData(99, 0, 2400.9686738603973) + + tdSql.query('select asin(c1) from st0 limit 1;') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 0.0) + + tdSql.query('select pow(c1,2) from st0 limit 1 offset 2;;') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 4.0) + + tdSql.query('select cos(c1) from db0.ct0, db0.ct1 where ct0.ts==ct1.ts;') + tdSql.checkRows(50) + tdSql.checkData(0, 0, 1.0) + tdSql.checkData(1, 0, 0.5403023058681398) + tdSql.checkData(2, 0, -0.4161468365471424) + tdSql.checkData(3, 0, -0.9899924966004454) + tdSql.checkData(4, 0, -0.6536436208636119) + tdSql.checkData(5, 0, 0.28366218546322625) + tdSql.checkData(6, 0, 0.960170286650366) + tdSql.checkData(7, 0, 0.7539022543433046) + tdSql.checkData(8, 0, -0.14550003380861354) + tdSql.checkData(9, 0, -0.9111302618846769) + tdSql.checkData(10, 0, -0.8390715290764524) + tdSql.checkData(11, 0, 0.004425697988050785) + tdSql.checkData(12, 0, 0.8438539587324921) + tdSql.checkData(13, 0, 0.9074467814501962) + tdSql.checkData(14, 0, 0.1367372182078336) + tdSql.checkData(15, 0, -0.7596879128588213) + tdSql.checkData(16, 0, -0.9576594803233847) + tdSql.checkData(17, 0, -0.27516333805159693) + tdSql.checkData(18, 0, 0.6603167082440802) + tdSql.checkData(19, 0, 0.9887046181866692) + tdSql.checkData(20, 0, 0.40808206181339196) + tdSql.checkData(21, 0, -0.5477292602242684) + tdSql.checkData(22, 0, -0.9999608263946371) + tdSql.checkData(23, 0, -0.5328330203333975) + tdSql.checkData(24, 0, 0.424179007336997) + tdSql.checkData(25, 0, 0.9912028118634736) + tdSql.checkData(26, 0, 0.6469193223286404) + tdSql.checkData(27, 0, -0.2921388087338362) + tdSql.checkData(28, 0, -0.9626058663135666) + tdSql.checkData(29, 0, -0.7480575296890003) + tdSql.checkData(30, 0, 0.15425144988758405) + tdSql.checkData(31, 0, 0.9147423578045313) + tdSql.checkData(32, 0, 0.8342233605065102) + tdSql.checkData(33, 0, -0.013276747223059479) + tdSql.checkData(34, 0, -0.8485702747846052) + tdSql.checkData(35, 0, -0.9036922050915067) + tdSql.checkData(36, 0, -0.12796368962740468) + tdSql.checkData(37, 0, 0.7654140519453434) + tdSql.checkData(38, 0, 0.9550736440472949) + tdSql.checkData(39, 0, 0.26664293235993725) + tdSql.checkData(40, 0, -0.6669380616522619) + tdSql.checkData(41, 0, -0.9873392775238264) + tdSql.checkData(42, 0, -0.39998531498835127) + tdSql.checkData(43, 0, 0.5551133015206257) + tdSql.checkData(44, 0, 0.9998433086476912) + tdSql.checkData(45, 0, 0.5253219888177297) + tdSql.checkData(46, 0, -0.4321779448847783) + tdSql.checkData(47, 0, -0.9923354691509287) + tdSql.checkData(48, 0, -0.6401443394691997) + tdSql.checkData(49, 0, 0.3005925437436371) + + tdSql.query('select sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(c1)))))))))))))))) from st0;') + tdSql.checkRows(100) + tdSql.checkData(0, 0, 0.0) + tdSql.checkData(1, 0, 0.38515571309652635) + tdSql.checkData(2, 0, 0.3902026038089464) + tdSql.checkData(3, 0, 0.13455542224130787) + tdSql.checkData(4, 0, -0.3769735598744493) + tdSql.checkData(5, 0, -0.39322796903554574) + tdSql.checkData(6, 0, -0.23651996268319414) + tdSql.checkData(7, 0, 0.3636586143033131) + tdSql.checkData(8, 0, 0.3948481297132482) + tdSql.checkData(9, 0, 0.3013035615379907) + tdSql.checkData(10, 0, -0.3415979020470687) + tdSql.checkData(11, 0, -0.3953760693679444) + tdSql.checkData(12, 0, -0.33980128729652753) + tdSql.checkData(13, 0, 0.30435222656468974) + tdSql.checkData(14, 0, 0.39491114169715646) + tdSql.checkData(15, 0, 0.3625854118079003) + tdSql.checkData(16, 0, -0.24157669718552427) + tdSql.checkData(17, 0, -0.3933659195685728) + tdSql.checkData(18, 0, -0.37631897787570007) + tdSql.checkData(19, 0, 0.14207823704465328) + tdSql.checkData(20, 0, 0.39044261434523814) + tdSql.checkData(21, 0, 0.3847512959295267) + tdSql.checkData(22, 0, -0.008849576117906611) + tdSql.checkData(23, 0, -0.3855481500830306) + tdSql.checkData(24, 0, -0.38995484687725573) + tdSql.checkData(25, 0, -0.126893408273143) + tdSql.checkData(26, 0, 0.37760858396391034) + tdSql.checkData(27, 0, 0.39308462128198374) + tdSql.checkData(28, 0, 0.23131327316607625) + tdSql.checkData(29, 0, -0.3646985418138878) + tdSql.checkData(30, 0, -0.3947809161937072) + tdSql.checkData(31, 0, -0.29815291606002575) + tdSql.checkData(32, 0, 0.3433365642562851) + tdSql.checkData(33, 0, 0.39537224788827796) + tdSql.checkData(34, 0, 0.3379446735775925) + tdSql.checkData(35, 0, -0.3073019994396687) + tdSql.checkData(36, 0, -0.3949699977540669) + tdSql.checkData(37, 0, -0.3614777744074771) + tdSql.checkData(38, 0, 0.24648579565525397) + tdSql.checkData(39, 0, 0.39349857640819885) + tdSql.checkData(40, 0, 0.37564419916566116) + tdSql.checkData(41, 0, -0.14945748476886428) + tdSql.checkData(42, 0, -0.3906750702498718) + tdSql.checkData(43, 0, -0.3843345435654991) + tdSql.checkData(44, 0, 0.017688072907053588) + tdSql.checkData(45, 0, 0.3859289492584567) + tdSql.checkData(46, 0, 0.38969914464525074) + tdSql.checkData(47, 0, 0.11909715912089874) + tdSql.checkData(48, 0, -0.3782246656581614) + tdSql.checkData(49, 0, -0.392935768393244) + tdSql.checkData(50, 0, 0.0) + tdSql.checkData(51, 0, 0.38515571309652635) + tdSql.checkData(52, 0, 0.3902026038089464) + tdSql.checkData(53, 0, 0.13455542224130787) + tdSql.checkData(54, 0, -0.3769735598744493) + tdSql.checkData(55, 0, -0.39322796903554574) + tdSql.checkData(56, 0, -0.23651996268319414) + tdSql.checkData(57, 0, 0.3636586143033131) + tdSql.checkData(58, 0, 0.3948481297132482) + tdSql.checkData(59, 0, 0.3013035615379907) + tdSql.checkData(60, 0, -0.3415979020470687) + tdSql.checkData(61, 0, -0.3953760693679444) + tdSql.checkData(62, 0, -0.33980128729652753) + tdSql.checkData(63, 0, 0.30435222656468974) + tdSql.checkData(64, 0, 0.39491114169715646) + tdSql.checkData(65, 0, 0.3625854118079003) + tdSql.checkData(66, 0, -0.24157669718552427) + tdSql.checkData(67, 0, -0.3933659195685728) + tdSql.checkData(68, 0, -0.37631897787570007) + tdSql.checkData(69, 0, 0.14207823704465328) + tdSql.checkData(70, 0, 0.39044261434523814) + tdSql.checkData(71, 0, 0.3847512959295267) + tdSql.checkData(72, 0, -0.008849576117906611) + tdSql.checkData(73, 0, -0.3855481500830306) + tdSql.checkData(74, 0, -0.38995484687725573) + tdSql.checkData(75, 0, -0.126893408273143) + tdSql.checkData(76, 0, 0.37760858396391034) + tdSql.checkData(77, 0, 0.39308462128198374) + tdSql.checkData(78, 0, 0.23131327316607625) + tdSql.checkData(79, 0, -0.3646985418138878) + tdSql.checkData(80, 0, -0.3947809161937072) + tdSql.checkData(81, 0, -0.29815291606002575) + tdSql.checkData(82, 0, 0.3433365642562851) + tdSql.checkData(83, 0, 0.39537224788827796) + tdSql.checkData(84, 0, 0.3379446735775925) + tdSql.checkData(85, 0, -0.3073019994396687) + tdSql.checkData(86, 0, -0.3949699977540669) + tdSql.checkData(87, 0, -0.3614777744074771) + tdSql.checkData(88, 0, 0.24648579565525397) + tdSql.checkData(89, 0, 0.39349857640819885) + tdSql.checkData(90, 0, 0.37564419916566116) + tdSql.checkData(91, 0, -0.14945748476886428) + tdSql.checkData(92, 0, -0.3906750702498718) + tdSql.checkData(93, 0, -0.3843345435654991) + tdSql.checkData(94, 0, 0.017688072907053588) + tdSql.checkData(95, 0, 0.3859289492584567) + tdSql.checkData(96, 0, 0.38969914464525074) + tdSql.checkData(97, 0, 0.11909715912089874) + tdSql.checkData(98, 0, -0.3782246656581614) + tdSql.checkData(99, 0, -0.392935768393244) + + tdSql.execute('drop database db0;') + + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/scalar_triangle.py b/tests/develop-test/2-query/scalar_triangle.py new file mode 100644 index 0000000000000000000000000000000000000000..0dbb55bc556c06afcfb243ada698b4eaca2a64f3 --- /dev/null +++ b/tests/develop-test/2-query/scalar_triangle.py @@ -0,0 +1,4167 @@ +import sys +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import tdDnodes +from math import inf + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-14122]: fix failed test on arm64 by converting from sim tst to python test to overcome NaN value and its string representation + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def restartTaosd(self, index=1, dbname="db"): + tdDnodes.stop(index) + tdDnodes.startWithoutSleep(index) + tdSql.execute(f"use db0") + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists db0") + tdSql.execute("create database if not exists db0") + tdSql.execute('use db0') + tdSql.execute('create table st0 (ts timestamp, c1 int, c2 float, c3 bigint, c4 smallint, c5 tinyint, c6 double, c7 bool, c8 nchar(5), c9 binary(10)) TAGS (tgcol int);') + + tdSql.execute('create table ct0 using st0 tags( 0 );') + tdSql.execute('insert into ct0 values (1601481600000 , 0 , 0.25 , 0 , 0 , 0 , 0.25 , 0 , 0 , 0 );') + for i in range(1, 50): + tdSql.execute('insert into ct0 values ({}, {}, {}, {}, {}, {}, {}, {}, {}, {});'.format(1601481600000 + i * 60000, + i , i , i , i , i , i , i , i , i )) + + tdSql.execute('create table ct1 using st0 tags( 1 );') + tdSql.execute('insert into ct1 values (1601481600000 , 0 , 0.25 , 0 , 0 , 0 , 0.25 , 0 , 0 , 0 );') + for i in range(1, 50): + tdSql.execute('insert into ct1 values ({}, {}, {}, {}, {}, {}, {}, {}, {}, {});'.format(1601481600000 + i * 60000, + i , i , i , i , i , i , i , i , i )) + + + tdSql.query('select c1, sin(c1), cos(c1), tan(c1), asin(c1), acos(c1), atan(c1) from ct1;') + tdSql.checkRows(50) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.0) + tdSql.checkData(0, 2, 1.0) + tdSql.checkData(0, 3, 0.0) + tdSql.checkData(0, 4, 0.0) + tdSql.checkData(0, 5, 1.5707963267948966) + tdSql.checkData(0, 6, 0.0) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.8414709848078965) + tdSql.checkData(1, 2, 0.5403023058681398) + tdSql.checkData(1, 3, 1.5574077246549023) + tdSql.checkData(1, 4, 1.5707963267948966) + tdSql.checkData(1, 5, 0.0) + tdSql.checkData(1, 6, 0.7853981633974483) + tdSql.checkData(2, 0, 2) + tdSql.checkData(2, 1, 0.9092974268256817) + tdSql.checkData(2, 2, -0.4161468365471424) + tdSql.checkData(2, 3, -2.185039863261519) + tdSql.checkData(2, 4, None) + tdSql.checkData(2, 5, None) + tdSql.checkData(2, 6, 1.1071487177940904) + tdSql.checkData(3, 0, 3) + tdSql.checkData(3, 1, 0.1411200080598672) + tdSql.checkData(3, 2, -0.9899924966004454) + tdSql.checkData(3, 3, -0.1425465430742778) + tdSql.checkData(3, 4, None) + tdSql.checkData(3, 5, None) + tdSql.checkData(3, 6, 1.2490457723982544) + tdSql.checkData(4, 0, 4) + tdSql.checkData(4, 1, -0.7568024953079282) + tdSql.checkData(4, 2, -0.6536436208636119) + tdSql.checkData(4, 3, 1.1578212823495775) + tdSql.checkData(4, 4, None) + tdSql.checkData(4, 5, None) + tdSql.checkData(4, 6, 1.3258176636680326) + tdSql.checkData(5, 0, 5) + tdSql.checkData(5, 1, -0.9589242746631385) + tdSql.checkData(5, 2, 0.28366218546322625) + tdSql.checkData(5, 3, -3.380515006246586) + tdSql.checkData(5, 4, None) + tdSql.checkData(5, 5, None) + tdSql.checkData(5, 6, 1.373400766945016) + tdSql.checkData(6, 0, 6) + tdSql.checkData(6, 1, -0.27941549819892586) + tdSql.checkData(6, 2, 0.960170286650366) + tdSql.checkData(6, 3, -0.29100619138474915) + tdSql.checkData(6, 4, None) + tdSql.checkData(6, 5, None) + tdSql.checkData(6, 6, 1.4056476493802699) + tdSql.checkData(7, 0, 7) + tdSql.checkData(7, 1, 0.6569865987187891) + tdSql.checkData(7, 2, 0.7539022543433046) + tdSql.checkData(7, 3, 0.8714479827243188) + tdSql.checkData(7, 4, None) + tdSql.checkData(7, 5, None) + tdSql.checkData(7, 6, 1.4288992721907328) + tdSql.checkData(8, 0, 8) + tdSql.checkData(8, 1, 0.9893582466233818) + tdSql.checkData(8, 2, -0.14550003380861354) + tdSql.checkData(8, 3, -6.799711455220379) + tdSql.checkData(8, 4, None) + tdSql.checkData(8, 5, None) + tdSql.checkData(8, 6, 1.446441332248135) + tdSql.checkData(9, 0, 9) + tdSql.checkData(9, 1, 0.4121184852417566) + tdSql.checkData(9, 2, -0.9111302618846769) + tdSql.checkData(9, 3, -0.45231565944180985) + tdSql.checkData(9, 4, None) + tdSql.checkData(9, 5, None) + tdSql.checkData(9, 6, 1.460139105621001) + tdSql.checkData(10, 0, 10) + tdSql.checkData(10, 1, -0.5440211108893698) + tdSql.checkData(10, 2, -0.8390715290764524) + tdSql.checkData(10, 3, 0.6483608274590866) + tdSql.checkData(10, 4, None) + tdSql.checkData(10, 5, None) + tdSql.checkData(10, 6, 1.4711276743037347) + tdSql.checkData(11, 0, 11) + tdSql.checkData(11, 1, -0.9999902065507035) + tdSql.checkData(11, 2, 0.004425697988050785) + tdSql.checkData(11, 3, -225.95084645419513) + tdSql.checkData(11, 4, None) + tdSql.checkData(11, 5, None) + tdSql.checkData(11, 6, 1.4801364395941514) + tdSql.checkData(12, 0, 12) + tdSql.checkData(12, 1, -0.5365729180004349) + tdSql.checkData(12, 2, 0.8438539587324921) + tdSql.checkData(12, 3, -0.6358599286615808) + tdSql.checkData(12, 4, None) + tdSql.checkData(12, 5, None) + tdSql.checkData(12, 6, 1.4876550949064553) + tdSql.checkData(13, 0, 13) + tdSql.checkData(13, 1, 0.4201670368266409) + tdSql.checkData(13, 2, 0.9074467814501962) + tdSql.checkData(13, 3, 0.4630211329364896) + tdSql.checkData(13, 4, None) + tdSql.checkData(13, 5, None) + tdSql.checkData(13, 6, 1.4940244355251187) + tdSql.checkData(14, 0, 14) + tdSql.checkData(14, 1, 0.9906073556948704) + tdSql.checkData(14, 2, 0.1367372182078336) + tdSql.checkData(14, 3, 7.2446066160948055) + tdSql.checkData(14, 4, None) + tdSql.checkData(14, 5, None) + tdSql.checkData(14, 6, 1.4994888620096063) + tdSql.checkData(15, 0, 15) + tdSql.checkData(15, 1, 0.6502878401571168) + tdSql.checkData(15, 2, -0.7596879128588213) + tdSql.checkData(15, 3, -0.8559934009085187) + tdSql.checkData(15, 4, None) + tdSql.checkData(15, 5, None) + tdSql.checkData(15, 6, 1.5042281630190728) + tdSql.checkData(16, 0, 16) + tdSql.checkData(16, 1, -0.2879033166650653) + tdSql.checkData(16, 2, -0.9576594803233847) + tdSql.checkData(16, 3, 0.3006322420239034) + tdSql.checkData(16, 4, None) + tdSql.checkData(16, 5, None) + tdSql.checkData(16, 6, 1.5083775167989393) + tdSql.checkData(17, 0, 17) + tdSql.checkData(17, 1, -0.9613974918795568) + tdSql.checkData(17, 2, -0.27516333805159693) + tdSql.checkData(17, 3, 3.49391564547484) + tdSql.checkData(17, 4, None) + tdSql.checkData(17, 5, None) + tdSql.checkData(17, 6, 1.512040504079174) + tdSql.checkData(18, 0, 18) + tdSql.checkData(18, 1, -0.750987246771676) + tdSql.checkData(18, 2, 0.6603167082440802) + tdSql.checkData(18, 3, -1.1373137123376869) + tdSql.checkData(18, 4, None) + tdSql.checkData(18, 5, None) + tdSql.checkData(18, 6, 1.5152978215491797) + tdSql.checkData(19, 0, 19) + tdSql.checkData(19, 1, 0.14987720966295234) + tdSql.checkData(19, 2, 0.9887046181866692) + tdSql.checkData(19, 3, 0.15158947061240008) + tdSql.checkData(19, 4, None) + tdSql.checkData(19, 5, None) + tdSql.checkData(19, 6, 1.5182132651839548) + tdSql.checkData(20, 0, 20) + tdSql.checkData(20, 1, 0.9129452507276277) + tdSql.checkData(20, 2, 0.40808206181339196) + tdSql.checkData(20, 3, 2.237160944224742) + tdSql.checkData(20, 4, None) + tdSql.checkData(20, 5, None) + tdSql.checkData(20, 6, 1.5208379310729538) + tdSql.checkData(21, 0, 21) + tdSql.checkData(21, 1, 0.8366556385360561) + tdSql.checkData(21, 2, -0.5477292602242684) + tdSql.checkData(21, 3, -1.5274985276366035) + tdSql.checkData(21, 4, None) + tdSql.checkData(21, 5, None) + tdSql.checkData(21, 6, 1.5232132235179132) + tdSql.checkData(22, 0, 22) + tdSql.checkData(22, 1, -0.008851309290403876) + tdSql.checkData(22, 2, -0.9999608263946371) + tdSql.checkData(22, 3, 0.00885165604168446) + tdSql.checkData(22, 4, None) + tdSql.checkData(22, 5, None) + tdSql.checkData(22, 6, 1.5253730473733196) + tdSql.checkData(23, 0, 23) + tdSql.checkData(23, 1, -0.8462204041751706) + tdSql.checkData(23, 2, -0.5328330203333975) + tdSql.checkData(23, 3, 1.5881530833912738) + tdSql.checkData(23, 4, None) + tdSql.checkData(23, 5, None) + tdSql.checkData(23, 6, 1.5273454314033659) + tdSql.checkData(24, 0, 24) + tdSql.checkData(24, 1, -0.9055783620066239) + tdSql.checkData(24, 2, 0.424179007336997) + tdSql.checkData(24, 3, -2.1348966977217008) + tdSql.checkData(24, 4, None) + tdSql.checkData(24, 5, None) + tdSql.checkData(24, 6, 1.5291537476963082) + tdSql.checkData(25, 0, 25) + tdSql.checkData(25, 1, -0.13235175009777303) + tdSql.checkData(25, 2, 0.9912028118634736) + tdSql.checkData(25, 3, -0.13352640702153587) + tdSql.checkData(25, 4, None) + tdSql.checkData(25, 5, None) + tdSql.checkData(25, 6, 1.5308176396716067) + tdSql.checkData(26, 0, 26) + tdSql.checkData(26, 1, 0.7625584504796027) + tdSql.checkData(26, 2, 0.6469193223286404) + tdSql.checkData(26, 3, 1.1787535542062797) + tdSql.checkData(26, 4, None) + tdSql.checkData(26, 5, None) + tdSql.checkData(26, 6, 1.5323537367737086) + tdSql.checkData(27, 0, 27) + tdSql.checkData(27, 1, 0.956375928404503) + tdSql.checkData(27, 2, -0.2921388087338362) + tdSql.checkData(27, 3, -3.273703800428119) + tdSql.checkData(27, 4, None) + tdSql.checkData(27, 5, None) + tdSql.checkData(27, 6, 1.5337762109209665) + tdSql.checkData(28, 0, 28) + tdSql.checkData(28, 1, 0.27090578830786904) + tdSql.checkData(28, 2, -0.9626058663135666) + tdSql.checkData(28, 3, -0.28142960456426525) + tdSql.checkData(28, 4, None) + tdSql.checkData(28, 5, None) + tdSql.checkData(28, 6, 1.5350972141155725) + tdSql.checkData(29, 0, 29) + tdSql.checkData(29, 1, -0.6636338842129675) + tdSql.checkData(29, 2, -0.7480575296890003) + tdSql.checkData(29, 3, 0.8871428437982151) + tdSql.checkData(29, 4, None) + tdSql.checkData(29, 5, None) + tdSql.checkData(29, 6, 1.5363272257953886) + tdSql.checkData(30, 0, 30) + tdSql.checkData(30, 1, -0.9880316240928618) + tdSql.checkData(30, 2, 0.15425144988758405) + tdSql.checkData(30, 3, -6.405331196646276) + tdSql.checkData(30, 4, None) + tdSql.checkData(30, 5, None) + tdSql.checkData(30, 6, 1.5374753309166493) + tdSql.checkData(31, 0, 31) + tdSql.checkData(31, 1, -0.404037645323065) + tdSql.checkData(31, 2, 0.9147423578045313) + tdSql.checkData(31, 3, -0.441695568020698) + tdSql.checkData(31, 4, None) + tdSql.checkData(31, 5, None) + tdSql.checkData(31, 6, 1.5385494443596428) + tdSql.checkData(32, 0, 32) + tdSql.checkData(32, 1, 0.5514266812416906) + tdSql.checkData(32, 2, 0.8342233605065102) + tdSql.checkData(32, 3, 0.6610060414837631) + tdSql.checkData(32, 4, None) + tdSql.checkData(32, 5, None) + tdSql.checkData(32, 6, 1.5395564933646284) + tdSql.checkData(33, 0, 33) + tdSql.checkData(33, 1, 0.9999118601072672) + tdSql.checkData(33, 2, -0.013276747223059479) + tdSql.checkData(33, 3, -75.31301480008509) + tdSql.checkData(33, 4, None) + tdSql.checkData(33, 5, None) + tdSql.checkData(33, 6, 1.5405025668761214) + tdSql.checkData(34, 0, 34) + tdSql.checkData(34, 1, 0.5290826861200238) + tdSql.checkData(34, 2, -0.8485702747846052) + tdSql.checkData(34, 3, -0.6234989627162255) + tdSql.checkData(34, 4, None) + tdSql.checkData(34, 5, None) + tdSql.checkData(34, 6, 1.5413930385908916) + tdSql.checkData(35, 0, 35) + tdSql.checkData(35, 1, -0.428182669496151) + tdSql.checkData(35, 2, -0.9036922050915067) + tdSql.checkData(35, 3, 0.473814720414451) + tdSql.checkData(35, 4, None) + tdSql.checkData(35, 5, None) + tdSql.checkData(35, 6, 1.5422326689561365) + tdSql.checkData(36, 0, 36) + tdSql.checkData(36, 1, -0.9917788534431158) + tdSql.checkData(36, 2, -0.12796368962740468) + tdSql.checkData(36, 3, 7.750470905699148) + tdSql.checkData(36, 4, None) + tdSql.checkData(36, 5, None) + tdSql.checkData(36, 6, 1.5430256902014756) + tdSql.checkData(37, 0, 37) + tdSql.checkData(37, 1, -0.6435381333569995) + tdSql.checkData(37, 2, 0.7654140519453434) + tdSql.checkData(37, 3, -0.8407712554027597) + tdSql.checkData(37, 4, None) + tdSql.checkData(37, 5, None) + tdSql.checkData(37, 6, 1.5437758776076318) + tdSql.checkData(38, 0, 38) + tdSql.checkData(38, 1, 0.2963685787093853) + tdSql.checkData(38, 2, 0.9550736440472949) + tdSql.checkData(38, 3, 0.310309660994801) + tdSql.checkData(38, 4, None) + tdSql.checkData(38, 5, None) + tdSql.checkData(38, 6, 1.5444866095419745) + tdSql.checkData(39, 0, 39) + tdSql.checkData(39, 1, 0.9637953862840878) + tdSql.checkData(39, 2, 0.26664293235993725) + tdSql.checkData(39, 3, 3.614554407101535) + tdSql.checkData(39, 4, None) + tdSql.checkData(39, 5, None) + tdSql.checkData(39, 6, 1.545160918273219) + tdSql.checkData(40, 0, 40) + tdSql.checkData(40, 1, 0.7451131604793488) + tdSql.checkData(40, 2, -0.6669380616522619) + tdSql.checkData(40, 3, -1.117214930923896) + tdSql.checkData(40, 4, None) + tdSql.checkData(40, 5, None) + tdSql.checkData(40, 6, 1.5458015331759765) + tdSql.checkData(41, 0, 41) + tdSql.checkData(41, 1, -0.158622668804709) + tdSql.checkData(41, 2, -0.9873392775238264) + tdSql.checkData(41, 3, 0.16065669868064283) + tdSql.checkData(41, 4, None) + tdSql.checkData(41, 5, None) + tdSql.checkData(41, 6, 1.546410917622178) + tdSql.checkData(42, 0, 42) + tdSql.checkData(42, 1, -0.9165215479156338) + tdSql.checkData(42, 2, -0.39998531498835127) + tdSql.checkData(42, 3, 2.2913879924374863) + tdSql.checkData(42, 4, None) + tdSql.checkData(42, 5, None) + tdSql.checkData(42, 6, 1.5469913006098266) + tdSql.checkData(43, 0, 43) + tdSql.checkData(43, 1, -0.8317747426285983) + tdSql.checkData(43, 2, 0.5551133015206257) + tdSql.checkData(43, 3, -1.4983873388551707) + tdSql.checkData(43, 4, None) + tdSql.checkData(43, 5, None) + tdSql.checkData(43, 6, 1.5475447039844337) + tdSql.checkData(44, 0, 44) + tdSql.checkData(44, 1, 0.017701925105413577) + tdSql.checkData(44, 2, 0.9998433086476912) + tdSql.checkData(44, 3, 0.017704699278685777) + tdSql.checkData(44, 4, None) + tdSql.checkData(44, 5, None) + tdSql.checkData(44, 6, 1.5480729659532555) + tdSql.checkData(45, 0, 45) + tdSql.checkData(45, 1, 0.8509035245341184) + tdSql.checkData(45, 2, 0.5253219888177297) + tdSql.checkData(45, 3, 1.6197751905438615) + tdSql.checkData(45, 4, None) + tdSql.checkData(45, 5, None) + tdSql.checkData(45, 6, 1.5485777614681775) + tdSql.checkData(46, 0, 46) + tdSql.checkData(46, 1, 0.9017883476488092) + tdSql.checkData(46, 2, -0.4321779448847783) + tdSql.checkData(46, 3, -2.086613531121382) + tdSql.checkData(46, 4, None) + tdSql.checkData(46, 5, None) + tdSql.checkData(46, 6, 1.5490606199531038) + tdSql.checkData(47, 0, 47) + tdSql.checkData(47, 1, 0.123573122745224) + tdSql.checkData(47, 2, -0.9923354691509287) + tdSql.checkData(47, 3, -0.12452756813273719) + tdSql.checkData(47, 4, None) + tdSql.checkData(47, 5, None) + tdSql.checkData(47, 6, 1.5495229407708355) + tdSql.checkData(48, 0, 48) + tdSql.checkData(48, 1, -0.7682546613236668) + tdSql.checkData(48, 2, -0.6401443394691997) + tdSql.checkData(48, 3, 1.2001272431162864) + tdSql.checkData(48, 4, None) + tdSql.checkData(48, 5, None) + tdSql.checkData(48, 6, 1.5499660067586796) + tdSql.checkData(49, 0, 49) + tdSql.checkData(49, 1, -0.9537526527594719) + tdSql.checkData(49, 2, 0.3005925437436371) + tdSql.checkData(49, 3, -3.172908552159191) + tdSql.checkData(49, 4, None) + tdSql.checkData(49, 5, None) + tdSql.checkData(49, 6, 1.5503909961083586) + + tdSql.query('select c1, sin(c2)+2, cos(c2)+2, cos(pow(c2,2)+2), tan(pow(c2,3)+log(c3, 2)+pow(c5,2)) as v4, asin(pow(c4, 4.5)+pow(c3, 2)), acos(log(c1,2)+log(c3,4)+pow(c6,2.8)+2) as v6 from ct1 where ts == 1601481600000;') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 2.2474039592545227) + tdSql.checkData(0, 2, 2.9689124217106446) + tdSql.checkData(0, 3, -0.4721284112969602) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.0) + tdSql.checkData(0, 6, None) + + tdSql.query('select c1, sin(c2), cos(c1+2), tan(c2+2)+2, sin(c2+3)+cos(c3+2)+tan(c5+2) as v4, sin(c4+4.5)+tan(c3+2), sin(c1+2)+cos(c3+4)+acos(c6+2.8)+2 as v6 from st0 where ts == 1601481600000;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.24740395925452294) + tdSql.checkData(0, 2, -0.4161468365471424) + tdSql.checkData(0, 3, 0.7613723837759034) + tdSql.checkData(0, 4, -2.7093818343387697) + tdSql.checkData(0, 5, -3.162569980926616) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 0) + tdSql.checkData(1, 1, 0.24740395925452294) + tdSql.checkData(1, 2, -0.4161468365471424) + tdSql.checkData(1, 3, 0.7613723837759034) + tdSql.checkData(1, 4, -2.7093818343387697) + tdSql.checkData(1, 5, -3.162569980926616) + tdSql.checkData(1, 6, None) + + tdSql.query('select c1, tan(c2+ 2), sin(pow(c1,2)), cos(pow(c2,2)+2), tan(pow(c2,3)+log(c3, 2)+pow(c5,2)) as v4, asin(pow(c4, 4.5)+pow(c3, 2)), acos(log(c1,2)+log(c3,4)+pow(c6,2.8)+2) as v6 from st0 where c1 == 0;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, -1.2386276162240966) + tdSql.checkData(0, 2, 0.0) + tdSql.checkData(0, 3, -0.4721284112969602) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.0) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 0) + tdSql.checkData(1, 1, -1.2386276162240966) + tdSql.checkData(1, 2, 0.0) + tdSql.checkData(1, 3, -0.4721284112969602) + tdSql.checkData(1, 4, None) + tdSql.checkData(1, 5, 0.0) + tdSql.checkData(1, 6, None) + + tdSql.query('select c1, atan(c2+2), asin(c1+2), acos(c2+c1)+2, acos(c2+c3)+asin(c3+c2)+pow(c5,2) as v4, acos(c4/4.5)+asin(c3-2), asin(c1/2)+log(c3,c4)+pow(c6, 2.8)+2 as v6 from st0 where c1 == 0;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 1.1525719972156676) + tdSql.checkData(0, 2, None) + tdSql.checkData(0, 3, 3.3181160716528177) + tdSql.checkData(0, 4, 1.5707963267948966) + tdSql.checkData(0, 5, None) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 0) + tdSql.checkData(1, 1, 1.1525719972156676) + tdSql.checkData(1, 2, None) + tdSql.checkData(1, 3, 3.3181160716528177) + tdSql.checkData(1, 4, 1.5707963267948966) + tdSql.checkData(1, 5, None) + tdSql.checkData(1, 6, None) + + tdSql.query('select c1, cos(c2+2), cos(ceil(pow(c1,2))), sin(floor(pow(c2,2)+2)), sin(ceil(c2)+floor(c3+c2)+round(c5+c2)) as v4, atan(pow(c4, 4.5)+pow(c3, 2)), tan(log(c1,2)+cos(c3+4)+pow(c6,2.8)+2) as v6 from st0 order by ts desc;') + tdSql.checkRows(100) + tdSql.checkData(0, 0, 49) + tdSql.checkData(0, 1, 0.7421541968137826) + tdSql.checkData(0, 2, 0.6798687696126814) + tdSql.checkData(0, 3, 0.3130283835205022) + tdSql.checkData(0, 4, -0.04421256322855966) + tdSql.checkData(0, 5, 1.5707963020154387) + tdSql.checkData(0, 6, 0.03652568194248612) + tdSql.checkData(1, 0, 49) + tdSql.checkData(1, 1, 0.7421541968137826) + tdSql.checkData(1, 2, 0.6798687696126814) + tdSql.checkData(1, 3, 0.3130283835205022) + tdSql.checkData(1, 4, -0.04421256322855966) + tdSql.checkData(1, 5, 1.5707963020154387) + tdSql.checkData(1, 6, 0.03652568194248612) + tdSql.checkData(2, 0, 48) + tdSql.checkData(2, 1, 0.9649660284921133) + tdSql.checkData(2, 2, -0.3505997332287945) + tdSql.checkData(2, 3, 0.07093264777739541) + tdSql.checkData(2, 4, 0.9454451549211168) + tdSql.checkData(2, 5, 1.5707962996062728) + tdSql.checkData(2, 6, -2.3765070948049045) + tdSql.checkData(3, 0, 48) + tdSql.checkData(3, 1, 0.9649660284921133) + tdSql.checkData(3, 2, -0.3505997332287945) + tdSql.checkData(3, 3, 0.07093264777739541) + tdSql.checkData(3, 4, 0.9454451549211168) + tdSql.checkData(3, 5, 1.5707962996062728) + tdSql.checkData(3, 6, -2.3765070948049045) + tdSql.checkData(4, 0, 47) + tdSql.checkData(4, 1, 0.3005925437436371) + tdSql.checkData(4, 2, -0.8958906072013385) + tdSql.checkData(4, 3, -0.6297475077924276) + tdSql.checkData(4, 4, 0.5805866409896447) + tdSql.checkData(4, 5, 1.5707962969045492) + tdSql.checkData(4, 6, -0.7609930344795104) + tdSql.checkData(5, 0, 47) + tdSql.checkData(5, 1, 0.3005925437436371) + tdSql.checkData(5, 2, -0.8958906072013385) + tdSql.checkData(5, 3, -0.6297475077924276) + tdSql.checkData(5, 4, 0.5805866409896447) + tdSql.checkData(5, 5, 1.5707962969045492) + tdSql.checkData(5, 6, -0.7609930344795104) + tdSql.checkData(6, 0, 46) + tdSql.checkData(6, 1, -0.6401443394691997) + tdSql.checkData(6, 2, 0.13691638327939556) + tdSql.checkData(6, 3, 0.5367255338147858) + tdSql.checkData(6, 4, -0.6160642040533645) + tdSql.checkData(6, 5, 1.5707962938673405) + tdSql.checkData(6, 6, -1.9292699714079746) + tdSql.checkData(7, 0, 46) + tdSql.checkData(7, 1, -0.6401443394691997) + tdSql.checkData(7, 2, 0.13691638327939556) + tdSql.checkData(7, 3, 0.5367255338147858) + tdSql.checkData(7, 4, -0.6160642040533645) + tdSql.checkData(7, 5, 1.5707962938673405) + tdSql.checkData(7, 6, -1.9292699714079746) + tdSql.checkData(8, 0, 45) + tdSql.checkData(8, 1, -0.9923354691509287) + tdSql.checkData(8, 2, -0.24113458224528692) + tdSql.checkData(8, 3, -0.6231301003179452) + tdSql.checkData(8, 4, -0.9300948780045254) + tdSql.checkData(8, 5, 1.5707962904442854) + tdSql.checkData(8, 6, -7.205947408999204) + tdSql.checkData(9, 0, 45) + tdSql.checkData(9, 1, -0.9923354691509287) + tdSql.checkData(9, 2, -0.24113458224528692) + tdSql.checkData(9, 3, -0.6231301003179452) + tdSql.checkData(9, 4, -0.9300948780045254) + tdSql.checkData(9, 5, 1.5707962904442854) + tdSql.checkData(9, 6, -7.205947408999204) + tdSql.checkData(10, 0, 44) + tdSql.checkData(10, 1, -0.4321779448847783) + tdSql.checkData(10, 2, 0.7116688794089422) + tdSql.checkData(10, 3, 0.3547692619733851) + tdSql.checkData(10, 4, 0.08839871248753149) + tdSql.checkData(10, 5, 1.5707962865760938) + tdSql.checkData(10, 6, 0.20475275676724466) + tdSql.checkData(11, 0, 44) + tdSql.checkData(11, 1, -0.4321779448847783) + tdSql.checkData(11, 2, 0.7116688794089422) + tdSql.checkData(11, 3, 0.3547692619733851) + tdSql.checkData(11, 4, 0.08839871248753149) + tdSql.checkData(11, 5, 1.5707962865760938) + tdSql.checkData(11, 6, 0.20475275676724466) + tdSql.checkData(12, 0, 43) + tdSql.checkData(12, 1, 0.5253219888177297) + tdSql.checkData(12, 2, -0.17186582286471372) + tdSql.checkData(12, 3, -0.5662318751422317) + tdSql.checkData(12, 4, 0.9802456219572225) + tdSql.checkData(12, 5, 1.570796282192712) + tdSql.checkData(12, 6, -0.367384536387167) + tdSql.checkData(13, 0, 43) + tdSql.checkData(13, 1, 0.5253219888177297) + tdSql.checkData(13, 2, -0.17186582286471372) + tdSql.checkData(13, 3, -0.5662318751422317) + tdSql.checkData(13, 4, 0.9802456219572225) + tdSql.checkData(13, 5, 1.570796282192712) + tdSql.checkData(13, 6, -0.367384536387167) + tdSql.checkData(14, 0, 42) + tdSql.checkData(14, 1, 0.9998433086476912) + tdSql.checkData(14, 2, -0.004274977647617749) + tdSql.checkData(14, 3, 0.412255807723053) + tdSql.checkData(14, 4, 0.46771851834275896) + tdSql.checkData(14, 5, 1.570796277211051) + tdSql.checkData(14, 6, -22.120550530872286) + tdSql.checkData(15, 0, 42) + tdSql.checkData(15, 1, 0.9998433086476912) + tdSql.checkData(15, 2, -0.004274977647617749) + tdSql.checkData(15, 3, 0.412255807723053) + tdSql.checkData(15, 4, 0.46771851834275896) + tdSql.checkData(15, 5, 1.570796277211051) + tdSql.checkData(15, 6, -22.120550530872286) + tdSql.checkData(16, 0, 41) + tdSql.checkData(16, 1, 0.5551133015206257) + tdSql.checkData(16, 2, -0.9694223908459327) + tdSql.checkData(16, 3, -0.7793716419485732) + tdSql.checkData(16, 4, -0.7148975077677643) + tdSql.checkData(16, 5, 1.5707962715321713) + tdSql.checkData(16, 6, 0.6057979864116589) + tdSql.checkData(17, 0, 41) + tdSql.checkData(17, 1, 0.5551133015206257) + tdSql.checkData(17, 2, -0.9694223908459327) + tdSql.checkData(17, 3, -0.7793716419485732) + tdSql.checkData(17, 4, -0.7148975077677643) + tdSql.checkData(17, 5, 1.5707962715321713) + tdSql.checkData(17, 6, 0.6057979864116589) + tdSql.checkData(18, 0, 40) + tdSql.checkData(18, 1, -0.39998531498835127) + tdSql.checkData(18, 2, -0.5983634637950125) + tdSql.checkData(18, 3, -0.21066319593197044) + tdSql.checkData(18, 4, -0.8732972972139946) + tdSql.checkData(18, 5, 1.570796265037764) + tdSql.checkData(18, 6, -0.0772047427955866) + tdSql.checkData(19, 0, 40) + tdSql.checkData(19, 1, -0.39998531498835127) + tdSql.checkData(19, 2, -0.5983634637950125) + tdSql.checkData(19, 3, -0.21066319593197044) + tdSql.checkData(19, 4, -0.8732972972139946) + tdSql.checkData(19, 5, 1.570796265037764) + tdSql.checkData(19, 6, -0.0772047427955866) + tdSql.checkData(20, 0, 39) + tdSql.checkData(20, 1, -0.9873392775238264) + tdSql.checkData(20, 2, 0.8919503592036683) + tdSql.checkData(20, 3, 0.6228943075363607) + tdSql.checkData(20, 4, 0.21945466799406363) + tdSql.checkData(20, 5, 1.5707962575857413) + tdSql.checkData(20, 6, 0.5897115109610915) + tdSql.checkData(21, 0, 39) + tdSql.checkData(21, 1, -0.9873392775238264) + tdSql.checkData(21, 2, 0.8919503592036683) + tdSql.checkData(21, 3, 0.6228943075363607) + tdSql.checkData(21, 4, 0.21945466799406363) + tdSql.checkData(21, 5, 1.5707962575857413) + tdSql.checkData(21, 6, 0.5897115109610915) + tdSql.checkData(22, 0, 38) + tdSql.checkData(22, 1, -0.6669380616522619) + tdSql.checkData(22, 2, 0.4242881965497543) + tdSql.checkData(22, 3, 0.7626364487946297) + tdSql.checkData(22, 4, 0.9977992786806003) + tdSql.checkData(22, 5, 1.5707962490046714) + tdSql.checkData(22, 6, 1.138845506389765) + tdSql.checkData(23, 0, 38) + tdSql.checkData(23, 1, -0.6669380616522619) + tdSql.checkData(23, 2, 0.4242881965497543) + tdSql.checkData(23, 3, 0.7626364487946297) + tdSql.checkData(23, 4, 0.9977992786806003) + tdSql.checkData(23, 5, 1.5707962490046714) + tdSql.checkData(23, 6, 1.138845506389765) + tdSql.checkData(24, 0, 37) + tdSql.checkData(24, 1, 0.26664293235993725) + tdSql.checkData(24, 2, 0.7422350059189753) + tdSql.checkData(24, 3, 0.9537888904975496) + tdSql.checkData(24, 4, 0.346621180094276) + tdSql.checkData(24, 5, 1.570796239086718) + tdSql.checkData(24, 6, -0.1919260039444686) + tdSql.checkData(25, 0, 37) + tdSql.checkData(25, 1, 0.26664293235993725) + tdSql.checkData(25, 2, 0.7422350059189753) + tdSql.checkData(25, 3, 0.9537888904975496) + tdSql.checkData(25, 4, 0.346621180094276) + tdSql.checkData(25, 5, 1.570796239086718) + tdSql.checkData(25, 6, -0.1919260039444686) + tdSql.checkData(26, 0, 36) + tdSql.checkData(26, 1, 0.9550736440472949) + tdSql.checkData(26, 2, -0.0928962612844285) + tdSql.checkData(26, 3, -0.4988176628046754) + tdSql.checkData(26, 4, -0.8011526357338304) + tdSql.checkData(26, 5, 1.5707962275786258) + tdSql.checkData(26, 6, -1.1574711833500264) + tdSql.checkData(27, 0, 36) + tdSql.checkData(27, 1, 0.9550736440472949) + tdSql.checkData(27, 2, -0.0928962612844285) + tdSql.checkData(27, 3, -0.4988176628046754) + tdSql.checkData(27, 4, -0.8011526357338304) + tdSql.checkData(27, 5, 1.5707962275786258) + tdSql.checkData(27, 6, -1.1574711833500264) + tdSql.checkData(28, 0, 35) + tdSql.checkData(28, 1, 0.7654140519453434) + tdSql.checkData(28, 2, 0.9756491521033712) + tdSql.checkData(28, 3, 0.9784316739726002) + tdSql.checkData(28, 4, -0.8011345951780408) + tdSql.checkData(28, 5, 1.5707962141701366) + tdSql.checkData(28, 6, -0.2793610475623728) + tdSql.checkData(29, 0, 35) + tdSql.checkData(29, 1, 0.7654140519453434) + tdSql.checkData(29, 2, 0.9756491521033712) + tdSql.checkData(29, 3, 0.9784316739726002) + tdSql.checkData(29, 4, -0.8011345951780408) + tdSql.checkData(29, 5, 1.5707962141701366) + tdSql.checkData(29, 6, -0.2793610475623728) + tdSql.checkData(30, 0, 34) + tdSql.checkData(30, 1, -0.12796368962740468) + tdSql.checkData(30, 2, 0.9943770416371703) + tdSql.checkData(30, 3, 0.9482534313435556) + tdSql.checkData(30, 4, 0.3466494554970303) + tdSql.checkData(30, 5, 1.5707961984790044) + tdSql.checkData(30, 6, -3.168873759467214) + tdSql.checkData(31, 0, 34) + tdSql.checkData(31, 1, -0.12796368962740468) + tdSql.checkData(31, 2, 0.9943770416371703) + tdSql.checkData(31, 3, 0.9482534313435556) + tdSql.checkData(31, 4, 0.3466494554970303) + tdSql.checkData(31, 5, 1.5707961984790044) + tdSql.checkData(31, 6, -3.168873759467214) + tdSql.checkData(32, 0, 33) + tdSql.checkData(32, 1, -0.9036922050915067) + tdSql.checkData(32, 2, -0.42426089982481757) + tdSql.checkData(32, 3, -0.7626169502553196) + tdSql.checkData(32, 4, 0.9977972794498907) + tdSql.checkData(32, 5, 1.5707961800314665) + tdSql.checkData(32, 6, -0.1738544089832513) + tdSql.checkData(33, 0, 33) + tdSql.checkData(33, 1, -0.9036922050915067) + tdSql.checkData(33, 2, -0.42426089982481757) + tdSql.checkData(33, 3, -0.7626169502553196) + tdSql.checkData(33, 4, 0.9977972794498907) + tdSql.checkData(33, 5, 1.5707961800314665) + tdSql.checkData(33, 6, -0.1738544089832513) + tdSql.checkData(34, 0, 32) + tdSql.checkData(34, 1, -0.8485702747846052) + tdSql.checkData(34, 2, 0.9873536182198484) + tdSql.checkData(34, 3, 0.9637712690067693) + tdSql.checkData(34, 4, 0.21942525837900473) + tdSql.checkData(34, 5, 1.5707961582366015) + tdSql.checkData(34, 6, 2.449230012275883) + tdSql.checkData(35, 0, 32) + tdSql.checkData(35, 1, -0.8485702747846052) + tdSql.checkData(35, 2, 0.9873536182198484) + tdSql.checkData(35, 3, 0.9637712690067693) + tdSql.checkData(35, 4, 0.21942525837900473) + tdSql.checkData(35, 5, 1.5707961582366015) + tdSql.checkData(35, 6, 2.449230012275883) + tdSql.checkData(36, 0, 31) + tdSql.checkData(36, 1, -0.013276747223059479) + tdSql.checkData(36, 2, 0.9468970921774763) + tdSql.checkData(36, 3, 0.9948176005844565) + tdSql.checkData(36, 4, -0.8733119827746476) + tdSql.checkData(36, 5, 1.5707961323523867) + tdSql.checkData(36, 6, -24.115588387874705) + tdSql.checkData(37, 0, 31) + tdSql.checkData(37, 1, -0.013276747223059479) + tdSql.checkData(37, 2, 0.9468970921774763) + tdSql.checkData(37, 3, 0.9948176005844565) + tdSql.checkData(37, 4, -0.8733119827746476) + tdSql.checkData(37, 5, 1.5707961323523867) + tdSql.checkData(37, 6, -24.115588387874705) + tdSql.checkData(38, 0, 30) + tdSql.checkData(38, 1, 0.8342233605065102) + tdSql.checkData(38, 2, 0.06624670220315812) + tdSql.checkData(38, 3, -0.3549947202980643) + tdSql.checkData(38, 4, -0.7148764296291646) + tdSql.checkData(38, 5, 1.5707961014403826) + tdSql.checkData(38, 6, -0.1966943463168791) + tdSql.checkData(39, 0, 30) + tdSql.checkData(39, 1, 0.8342233605065102) + tdSql.checkData(39, 2, 0.06624670220315812) + tdSql.checkData(39, 3, -0.3549947202980643) + tdSql.checkData(39, 4, -0.7148764296291646) + tdSql.checkData(39, 5, 1.5707961014403826) + tdSql.checkData(39, 6, -0.1966943463168791) + tdSql.checkData(40, 0, 29) + tdSql.checkData(40, 1, 0.9147423578045313) + tdSql.checkData(40, 2, 0.5842577465661262) + tdSql.checkData(40, 3, 0.8689955898411542) + tdSql.checkData(40, 4, 0.4677451620451334) + tdSql.checkData(40, 5, 1.5707960643046768) + tdSql.checkData(40, 6, -0.039333072296354944) + tdSql.checkData(41, 0, 29) + tdSql.checkData(41, 1, 0.9147423578045313) + tdSql.checkData(41, 2, 0.5842577465661262) + tdSql.checkData(41, 3, 0.8689955898411542) + tdSql.checkData(41, 4, 0.4677451620451334) + tdSql.checkData(41, 5, 1.5707960643046768) + tdSql.checkData(41, 6, -0.039333072296354944) + tdSql.checkData(42, 0, 28) + tdSql.checkData(42, 1, 0.15425144988758405) + tdSql.checkData(42, 2, 0.17177673471265031) + tdSql.checkData(42, 3, 0.5661573337391944) + tdSql.checkData(42, 4, 0.9802396594403116) + tdSql.checkData(42, 5, 1.5707960194088244) + tdSql.checkData(42, 6, -0.9135826820615496) + tdSql.checkData(43, 0, 28) + tdSql.checkData(43, 1, 0.15425144988758405) + tdSql.checkData(43, 2, 0.17177673471265031) + tdSql.checkData(43, 3, 0.5661573337391944) + tdSql.checkData(43, 4, 0.9802396594403116) + tdSql.checkData(43, 5, 1.5707960194088244) + tdSql.checkData(43, 6, -0.9135826820615496) + tdSql.checkData(44, 0, 27) + tdSql.checkData(44, 1, -0.7480575296890003) + tdSql.checkData(44, 2, 0.9886955804866999) + tdSql.checkData(44, 3, 0.8366226151268321) + tdSql.checkData(44, 4, 0.08836868610400143) + tdSql.checkData(44, 5, 1.570795964761674) + tdSql.checkData(44, 6, 2.19589437576056) + tdSql.checkData(45, 0, 27) + tdSql.checkData(45, 1, -0.7480575296890003) + tdSql.checkData(45, 2, 0.9886955804866999) + tdSql.checkData(45, 3, 0.8366226151268321) + tdSql.checkData(45, 4, 0.08836868610400143) + tdSql.checkData(45, 5, 1.570795964761674) + tdSql.checkData(45, 6, 2.19589437576056) + tdSql.checkData(46, 0, 26) + tdSql.checkData(46, 1, -0.9626058663135666) + tdSql.checkData(46, 2, -0.848538375531565) + tdSql.checkData(46, 3, -0.5513763859920506) + tdSql.checkData(46, 4, -0.9301059501867618) + tdSql.checkData(46, 5, 1.5707958977586762) + tdSql.checkData(46, 6, 0.32917637498880103) + tdSql.checkData(47, 0, 26) + tdSql.checkData(47, 1, -0.9626058663135666) + tdSql.checkData(47, 2, -0.848538375531565) + tdSql.checkData(47, 3, -0.5513763859920506) + tdSql.checkData(47, 4, -0.9301059501867618) + tdSql.checkData(47, 5, 1.5707958977586762) + tdSql.checkData(47, 6, 0.32917637498880103) + tdSql.checkData(48, 0, 25) + tdSql.checkData(48, 1, -0.2921388087338362) + tdSql.checkData(48, 2, -0.9843872569764778) + tdSql.checkData(48, 3, -0.9683494148893343) + tdSql.checkData(48, 4, -0.6160404591886565) + tdSql.checkData(48, 5, 1.5707958149586843) + tdSql.checkData(48, 6, -9.848194527671561) + tdSql.checkData(49, 0, 25) + tdSql.checkData(49, 1, -0.2921388087338362) + tdSql.checkData(49, 2, -0.9843872569764778) + tdSql.checkData(49, 3, -0.9683494148893343) + tdSql.checkData(49, 4, -0.6160404591886565) + tdSql.checkData(49, 5, 1.5707958149586843) + tdSql.checkData(49, 6, -9.848194527671561) + tdSql.checkData(50, 0, 24) + tdSql.checkData(50, 1, 0.6469193223286404) + tdSql.checkData(50, 2, -0.4637754567475154) + tdSql.checkData(50, 3, -0.053023383345603574) + tdSql.checkData(50, 4, 0.5806111842123143) + tdSql.checkData(50, 5, 1.5707957117659828) + tdSql.checkData(50, 6, 0.9961666148069158) + tdSql.checkData(51, 0, 24) + tdSql.checkData(51, 1, 0.6469193223286404) + tdSql.checkData(51, 2, -0.4637754567475154) + tdSql.checkData(51, 3, -0.053023383345603574) + tdSql.checkData(51, 4, 0.5806111842123143) + tdSql.checkData(51, 5, 1.5707957117659828) + tdSql.checkData(51, 6, 0.9961666148069158) + tdSql.checkData(52, 0, 23) + tdSql.checkData(52, 1, 0.9912028118634736) + tdSql.checkData(52, 2, 0.3507408840091023) + tdSql.checkData(52, 3, -0.07078230485740782) + tdSql.checkData(52, 4, 0.9454353340247703) + tdSql.checkData(52, 5, 1.5707955819710255) + tdSql.checkData(52, 6, -2.150870213297903) + tdSql.checkData(53, 0, 23) + tdSql.checkData(53, 1, 0.9912028118634736) + tdSql.checkData(53, 2, 0.3507408840091023) + tdSql.checkData(53, 3, -0.07078230485740782) + tdSql.checkData(53, 4, 0.9454353340247703) + tdSql.checkData(53, 5, 1.5707955819710255) + tdSql.checkData(53, 6, -2.150870213297903) + tdSql.checkData(54, 0, 22) + tdSql.checkData(54, 1, 0.424179007336997) + tdSql.checkData(54, 2, 0.9810996900733364) + tdSql.checkData(54, 3, 0.8115857761709371) + tdSql.checkData(54, 4, -0.044242678085070965) + tdSql.checkData(54, 5, 1.5707954170771377) + tdSql.checkData(54, 6, -0.6314442572652602) + tdSql.checkData(55, 0, 22) + tdSql.checkData(55, 1, 0.424179007336997) + tdSql.checkData(55, 2, 0.9810996900733364) + tdSql.checkData(55, 3, 0.8115857761709371) + tdSql.checkData(55, 4, -0.044242678085070965) + tdSql.checkData(55, 5, 1.5707954170771377) + tdSql.checkData(55, 6, -0.6314442572652602) + tdSql.checkData(56, 0, 21) + tdSql.checkData(56, 1, -0.5328330203333975) + tdSql.checkData(56, 2, 0.3836706077176726) + tdSql.checkData(56, 3, -0.035428428178979524) + tdSql.checkData(56, 4, -0.9705352835374847) + tdSql.checkData(56, 5, 1.5707952052973522) + tdSql.checkData(56, 6, -0.5809225429871196) + tdSql.checkData(57, 0, 21) + tdSql.checkData(57, 1, -0.5328330203333975) + tdSql.checkData(57, 2, 0.3836706077176726) + tdSql.checkData(57, 3, -0.035428428178979524) + tdSql.checkData(57, 4, -0.9705352835374847) + tdSql.checkData(57, 5, 1.5707952052973522) + tdSql.checkData(57, 6, -0.5809225429871196) + tdSql.checkData(58, 0, 20) + tdSql.checkData(58, 1, -0.9999608263946371) + tdSql.checkData(58, 2, -0.525296338642536) + tdSql.checkData(58, 3, -0.12354320937804643) + tdSql.checkData(58, 4, -0.5063656411097588) + tdSql.checkData(58, 5, 1.5707949300332242) + tdSql.checkData(58, 6, -0.4029272896258388) + tdSql.checkData(59, 0, 20) + tdSql.checkData(59, 1, -0.9999608263946371) + tdSql.checkData(59, 2, -0.525296338642536) + tdSql.checkData(59, 3, -0.12354320937804643) + tdSql.checkData(59, 4, -0.5063656411097588) + tdSql.checkData(59, 5, 1.5707949300332242) + tdSql.checkData(59, 6, -0.4029272896258388) + tdSql.checkData(60, 0, 19) + tdSql.checkData(60, 1, -0.5477292602242684) + tdSql.checkData(60, 2, -0.9601787090136331) + tdSql.checkData(60, 3, -0.9893538601694428) + tdSql.checkData(60, 4, 0.683261714736121) + tdSql.checkData(60, 5, 1.5707945675233086) + tdSql.checkData(60, 6, 3.988678905790852) + tdSql.checkData(61, 0, 19) + tdSql.checkData(61, 1, -0.5477292602242684) + tdSql.checkData(61, 2, -0.9601787090136331) + tdSql.checkData(61, 3, -0.9893538601694428) + tdSql.checkData(61, 4, 0.683261714736121) + tdSql.checkData(61, 5, 1.5707945675233086) + tdSql.checkData(61, 6, 3.988678905790852) + tdSql.checkData(62, 0, 18) + tdSql.checkData(62, 1, 0.40808206181339196) + tdSql.checkData(62, 2, -0.9147301779353751) + tdSql.checkData(62, 3, -0.6636113342009432) + tdSql.checkData(62, 4, 0.8939966636005579) + tdSql.checkData(62, 5, 1.5707940831304659) + tdSql.checkData(62, 6, 0.11047679998824196) + tdSql.checkData(63, 0, 18) + tdSql.checkData(63, 1, 0.40808206181339196) + tdSql.checkData(63, 2, -0.9147301779353751) + tdSql.checkData(63, 3, -0.6636113342009432) + tdSql.checkData(63, 4, 0.8939966636005579) + tdSql.checkData(63, 5, 1.5707940831304659) + tdSql.checkData(63, 6, 0.11047679998824196) + tdSql.checkData(64, 0, 17) + tdSql.checkData(64, 1, 0.9887046181866692) + tdSql.checkData(64, 2, 0.9996482558795381) + tdSql.checkData(64, 3, 0.9200142254959646) + tdSql.checkData(64, 4, -0.1760756199485871) + tdSql.checkData(64, 5, 1.5707934253419198) + tdSql.checkData(64, 6, 0.46361590355468435) + tdSql.checkData(65, 0, 17) + tdSql.checkData(65, 1, 0.9887046181866692) + tdSql.checkData(65, 2, 0.9996482558795381) + tdSql.checkData(65, 3, 0.9200142254959646) + tdSql.checkData(65, 4, -0.1760756199485871) + tdSql.checkData(65, 5, 1.5707934253419198) + tdSql.checkData(65, 6, 0.46361590355468435) + tdSql.checkData(66, 0, 16) + tdSql.checkData(66, 1, 0.6603167082440802) + tdSql.checkData(66, 2, -0.03979075993115771) + tdSql.checkData(66, 3, 0.37963562682930313) + tdSql.checkData(66, 4, -0.9938886539233752) + tdSql.checkData(66, 5, 1.5707925158192868) + tdSql.checkData(66, 6, -0.4154684855612854) + tdSql.checkData(67, 0, 16) + tdSql.checkData(67, 1, 0.6603167082440802) + tdSql.checkData(67, 2, -0.03979075993115771) + tdSql.checkData(67, 3, 0.37963562682930313) + tdSql.checkData(67, 4, -0.9938886539233752) + tdSql.checkData(67, 5, 1.5707925158192868) + tdSql.checkData(67, 6, -0.4154684855612854) + tdSql.checkData(68, 0, 15) + tdSql.checkData(68, 1, -0.27516333805159693) + tdSql.checkData(68, 2, 0.36731936773024515) + tdSql.checkData(68, 3, 0.7210585970706318) + tdSql.checkData(68, 4, -0.38778163540943045) + tdSql.checkData(68, 5, 1.5707912324159716) + tdSql.checkData(68, 6, 0.8918850194348307) + tdSql.checkData(69, 0, 15) + tdSql.checkData(69, 1, -0.27516333805159693) + tdSql.checkData(69, 2, 0.36731936773024515) + tdSql.checkData(69, 3, 0.7210585970706318) + tdSql.checkData(69, 4, -0.38778163540943045) + tdSql.checkData(69, 5, 1.5707912324159716) + tdSql.checkData(69, 6, 0.8918850194348307) + tdSql.checkData(70, 0, 14) + tdSql.checkData(70, 1, -0.9576594803233847) + tdSql.checkData(70, 2, 0.3424664577455166) + tdSql.checkData(70, 3, -0.07957859166428352) + tdSql.checkData(70, 4, 0.7738906815578891) + tdSql.checkData(70, 5, 1.5707893792390168) + tdSql.checkData(70, 6, 1.3548129828192632) + tdSql.checkData(71, 0, 14) + tdSql.checkData(71, 1, -0.9576594803233847) + tdSql.checkData(71, 2, 0.3424664577455166) + tdSql.checkData(71, 3, -0.07957859166428352) + tdSql.checkData(71, 4, 0.7738906815578891) + tdSql.checkData(71, 5, 1.5707893792390168) + tdSql.checkData(71, 6, 1.3548129828192632) + tdSql.checkData(72, 0, 13) + tdSql.checkData(72, 1, -0.7596879128588213) + tdSql.checkData(72, 2, 0.7984961861625556) + tdSql.checkData(72, 3, 0.9765908679435658) + tdSql.checkData(72, 4, 0.8268286794901034) + tdSql.checkData(72, 5, 1.5707866319075423) + tdSql.checkData(72, 6, 3.695640303509019) + tdSql.checkData(73, 0, 13) + tdSql.checkData(73, 1, -0.7596879128588213) + tdSql.checkData(73, 2, 0.7984961861625556) + tdSql.checkData(73, 3, 0.9765908679435658) + tdSql.checkData(73, 4, 0.8268286794901034) + tdSql.checkData(73, 5, 1.5707866319075423) + tdSql.checkData(73, 6, 3.695640303509019) + tdSql.checkData(74, 0, 12) + tdSql.checkData(74, 1, 0.1367372182078336) + tdSql.checkData(74, 2, 0.8711474010323434) + tdSql.checkData(74, 3, 0.9964691731217737) + tdSql.checkData(74, 4, -0.3048106211022167) + tdSql.checkData(74, 5, 1.570782433199764) + tdSql.checkData(74, 6, 0.31565238132361734) + tdSql.checkData(75, 0, 12) + tdSql.checkData(75, 1, 0.1367372182078336) + tdSql.checkData(75, 2, 0.8711474010323434) + tdSql.checkData(75, 3, 0.9964691731217737) + tdSql.checkData(75, 4, -0.3048106211022167) + tdSql.checkData(75, 5, 1.570782433199764) + tdSql.checkData(75, 6, 0.31565238132361734) + tdSql.checkData(76, 0, 11) + tdSql.checkData(76, 1, 0.9074467814501962) + tdSql.checkData(76, 2, -0.04866360920015389) + tdSql.checkData(76, 3, -0.45990349068959124) + tdSql.checkData(76, 4, -0.9997551733586199) + tdSql.checkData(76, 5, 1.5707757843526298) + tdSql.checkData(76, 6, -0.9008027113130536) + tdSql.checkData(77, 0, 11) + tdSql.checkData(77, 1, 0.9074467814501962) + tdSql.checkData(77, 2, -0.04866360920015389) + tdSql.checkData(77, 3, -0.45990349068959124) + tdSql.checkData(77, 4, -0.9997551733586199) + tdSql.checkData(77, 5, 1.5707757843526298) + tdSql.checkData(77, 6, -0.9008027113130536) + tdSql.checkData(78, 0, 10) + tdSql.checkData(78, 1, 0.8438539587324921) + tdSql.checkData(78, 2, 0.8623188722876839) + tdSql.checkData(78, 3, 0.9948267913584063) + tdSql.checkData(78, 4, -0.26237485370392877) + tdSql.checkData(78, 5, 1.5707648037030744) + tdSql.checkData(78, 6, -4.025330871196722) + tdSql.checkData(79, 0, 10) + tdSql.checkData(79, 1, 0.8438539587324921) + tdSql.checkData(79, 2, 0.8623188722876839) + tdSql.checkData(79, 3, 0.9948267913584063) + tdSql.checkData(79, 4, -0.26237485370392877) + tdSql.checkData(79, 5, 1.5707648037030744) + tdSql.checkData(79, 6, -4.025330871196722) + tdSql.checkData(80, 0, 9) + tdSql.checkData(80, 1, 0.004425697988050785) + tdSql.checkData(80, 2, 0.7766859820216312) + tdSql.checkData(80, 3, 0.9683644611001854) + tdSql.checkData(80, 4, 0.8509035245341184) + tdSql.checkData(80, 5, 1.5707457297498073) + tdSql.checkData(80, 6, 8.99827042612123) + tdSql.checkData(81, 0, 9) + tdSql.checkData(81, 1, 0.004425697988050785) + tdSql.checkData(81, 2, 0.7766859820216312) + tdSql.checkData(81, 3, 0.9683644611001854) + tdSql.checkData(81, 4, 0.8509035245341184) + tdSql.checkData(81, 5, 1.5707457297498073) + tdSql.checkData(81, 6, 8.99827042612123) + tdSql.checkData(82, 0, 8) + tdSql.checkData(82, 1, -0.8390715290764524) + tdSql.checkData(82, 2, 0.39185723042955) + tdSql.checkData(82, 3, -0.026551154023966794) + tdSql.checkData(82, 4, 0.7451131604793488) + tdSql.checkData(82, 5, 1.5707104842668094) + tdSql.checkData(82, 6, 2.605110021628947) + tdSql.checkData(83, 0, 8) + tdSql.checkData(83, 1, -0.8390715290764524) + tdSql.checkData(83, 2, 0.39185723042955) + tdSql.checkData(83, 3, -0.026551154023966794) + tdSql.checkData(83, 4, 0.7451131604793488) + tdSql.checkData(83, 5, 1.5707104842668094) + tdSql.checkData(83, 6, 2.605110021628947) + tdSql.checkData(84, 0, 7) + tdSql.checkData(84, 1, -0.9111302618846769) + tdSql.checkData(84, 2, 0.3005925437436371) + tdSql.checkData(84, 3, 0.6702291758433747) + tdSql.checkData(84, 4, -0.428182669496151) + tdSql.checkData(84, 5, 1.570640112161644) + tdSql.checkData(84, 6, -23.751038099429206) + tdSql.checkData(85, 0, 7) + tdSql.checkData(85, 1, -0.9111302618846769) + tdSql.checkData(85, 2, 0.3005925437436371) + tdSql.checkData(85, 3, 0.6702291758433747) + tdSql.checkData(85, 4, -0.428182669496151) + tdSql.checkData(85, 5, 1.570640112161644) + tdSql.checkData(85, 6, -23.751038099429206) + tdSql.checkData(86, 0, 6) + tdSql.checkData(86, 1, -0.14550003380861354) + tdSql.checkData(86, 2, -0.12796368962740468) + tdSql.checkData(86, 3, 0.2963685787093853) + tdSql.checkData(86, 4, -0.9880316240928618) + tdSql.checkData(86, 5, 1.5704848525972515) + tdSql.checkData(86, 6, 0.9400535268838884) + tdSql.checkData(87, 0, 6) + tdSql.checkData(87, 1, -0.14550003380861354) + tdSql.checkData(87, 2, -0.12796368962740468) + tdSql.checkData(87, 3, 0.2963685787093853) + tdSql.checkData(87, 4, -0.9880316240928618) + tdSql.checkData(87, 5, 1.5704848525972515) + tdSql.checkData(87, 6, 0.9400535268838884) + tdSql.checkData(88, 0, 5) + tdSql.checkData(88, 1, 0.7539022543433046) + tdSql.checkData(88, 2, 0.9912028118634736) + tdSql.checkData(88, 3, 0.956375928404503) + tdSql.checkData(88, 4, -0.13235175009777303) + tdSql.checkData(88, 5, 1.5700933602085452) + tdSql.checkData(88, 6, -0.24421205951965097) + tdSql.checkData(89, 0, 5) + tdSql.checkData(89, 1, 0.7539022543433046) + tdSql.checkData(89, 2, 0.9912028118634736) + tdSql.checkData(89, 3, 0.956375928404503) + tdSql.checkData(89, 4, -0.13235175009777303) + tdSql.checkData(89, 5, 1.5700933602085452) + tdSql.checkData(89, 6, -0.24421205951965097) + tdSql.checkData(90, 0, 4) + tdSql.checkData(90, 1, 0.960170286650366) + tdSql.checkData(90, 2, -0.9576594803233847) + tdSql.checkData(90, 3, -0.750987246771676) + tdSql.checkData(90, 4, 0.9129452507276277) + tdSql.checkData(90, 5, 1.5689023896654766) + tdSql.checkData(90, 6, -1.741882365717585) + tdSql.checkData(91, 0, 4) + tdSql.checkData(91, 1, 0.960170286650366) + tdSql.checkData(91, 2, -0.9576594803233847) + tdSql.checkData(91, 3, -0.750987246771676) + tdSql.checkData(91, 4, 0.9129452507276277) + tdSql.checkData(91, 5, 1.5689023896654766) + tdSql.checkData(91, 6, -1.741882365717585) + tdSql.checkData(92, 0, 3) + tdSql.checkData(92, 1, 0.28366218546322625) + tdSql.checkData(92, 2, -0.9111302618846769) + tdSql.checkData(92, 3, -0.9999902065507035) + tdSql.checkData(92, 4, 0.6502878401571168) + tdSql.checkData(92, 5, 1.5640983290419266) + tdSql.checkData(92, 6, 1.2100230702966224) + tdSql.checkData(93, 0, 3) + tdSql.checkData(93, 1, 0.28366218546322625) + tdSql.checkData(93, 2, -0.9111302618846769) + tdSql.checkData(93, 3, -0.9999902065507035) + tdSql.checkData(93, 4, 0.6502878401571168) + tdSql.checkData(93, 5, 1.5640983290419266) + tdSql.checkData(93, 6, 1.2100230702966224) + tdSql.checkData(94, 0, 2) + tdSql.checkData(94, 1, -0.6536436208636119) + tdSql.checkData(94, 2, -0.6536436208636119) + tdSql.checkData(94, 3, -0.27941549819892586) + tdSql.checkData(94, 4, -0.5440211108893698) + tdSql.checkData(94, 5, 1.5332586916349722) + tdSql.checkData(94, 6, 14.060932856369687) + tdSql.checkData(95, 0, 2) + tdSql.checkData(95, 1, -0.6536436208636119) + tdSql.checkData(95, 2, -0.6536436208636119) + tdSql.checkData(95, 3, -0.27941549819892586) + tdSql.checkData(95, 4, -0.5440211108893698) + tdSql.checkData(95, 5, 1.5332586916349722) + tdSql.checkData(95, 6, 14.060932856369687) + tdSql.checkData(96, 0, 1) + tdSql.checkData(96, 1, -0.9899924966004454) + tdSql.checkData(96, 2, 0.5403023058681398) + tdSql.checkData(96, 3, 0.1411200080598672) + tdSql.checkData(96, 4, -0.9589242746631385) + tdSql.checkData(96, 5, 1.1071487177940904) + tdSql.checkData(96, 6, 0.14303314440903753) + tdSql.checkData(97, 0, 1) + tdSql.checkData(97, 1, -0.9899924966004454) + tdSql.checkData(97, 2, 0.5403023058681398) + tdSql.checkData(97, 3, 0.1411200080598672) + tdSql.checkData(97, 4, -0.9589242746631385) + tdSql.checkData(97, 5, 1.1071487177940904) + tdSql.checkData(97, 6, 0.14303314440903753) + tdSql.checkData(98, 0, 0) + tdSql.checkData(98, 1, -0.6281736227227391) + tdSql.checkData(98, 2, 1.0) + tdSql.checkData(98, 3, 0.9092974268256817) + tdSql.checkData(98, 4, 0.8414709848078965) + tdSql.checkData(98, 5, 0.0) + tdSql.checkData(98, 6, None) + tdSql.checkData(99, 0, 0) + tdSql.checkData(99, 1, -0.6281736227227391) + tdSql.checkData(99, 2, 1.0) + tdSql.checkData(99, 3, 0.9092974268256817) + tdSql.checkData(99, 4, 0.8414709848078965) + tdSql.checkData(99, 5, 0.0) + tdSql.checkData(99, 6, None) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5+c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from ct1 order by ts limit 2;;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.7780731968879212) + tdSql.checkData(0, 2, 0.6143002821164822) + tdSql.checkData(0, 3, 3.2037266279837113) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.02246988233490299) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.1411200080598672) + tdSql.checkData(1, 2, 0.6663667453928805) + tdSql.checkData(1, 3, 1.558041126155035) + tdSql.checkData(1, 4, 2.1543462689906883) + tdSql.checkData(1, 5, 0.17204223631998083) + tdSql.checkData(1, 6, None) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 order by ts desc);') + tdSql.checkRows(100) + tdSql.checkData(0, 0, 49) + tdSql.checkData(0, 1, 0.6702291758433747) + tdSql.checkData(0, 2, 0.9923745526637894) + tdSql.checkData(0, 3, 0.9298143670243166) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.7136182821549459) + tdSql.checkData(0, 6, -0.7462904241496138) + tdSql.checkData(1, 0, 49) + tdSql.checkData(1, 1, 0.6702291758433747) + tdSql.checkData(1, 2, 0.9923745526637894) + tdSql.checkData(1, 3, 0.9298143670243166) + tdSql.checkData(1, 4, None) + tdSql.checkData(1, 5, 0.7136182821549459) + tdSql.checkData(1, 6, -0.7462904241496138) + tdSql.checkData(2, 0, 48) + tdSql.checkData(2, 1, -0.26237485370392877) + tdSql.checkData(2, 2, 0.6202081141679935) + tdSql.checkData(2, 3, 1.8175857333771335) + tdSql.checkData(2, 4, None) + tdSql.checkData(2, 5, 1.211884234321115) + tdSql.checkData(2, 6, 5.183714988550632) + tdSql.checkData(3, 0, 48) + tdSql.checkData(3, 1, -0.26237485370392877) + tdSql.checkData(3, 2, 0.6202081141679935) + tdSql.checkData(3, 3, 1.8175857333771335) + tdSql.checkData(3, 4, None) + tdSql.checkData(3, 5, 1.211884234321115) + tdSql.checkData(3, 6, 5.183714988550632) + tdSql.checkData(4, 0, 47) + tdSql.checkData(4, 1, -0.9537526527594719) + tdSql.checkData(4, 2, 0.6593040763085178) + tdSql.checkData(4, 3, 3.4575106745458637) + tdSql.checkData(4, 4, None) + tdSql.checkData(4, 5, 0.8820838187306987) + tdSql.checkData(4, 6, 2.6302204463996084) + tdSql.checkData(5, 0, 47) + tdSql.checkData(5, 1, -0.9537526527594719) + tdSql.checkData(5, 2, 0.6593040763085178) + tdSql.checkData(5, 3, 3.4575106745458637) + tdSql.checkData(5, 4, None) + tdSql.checkData(5, 5, 0.8820838187306987) + tdSql.checkData(5, 6, 2.6302204463996084) + tdSql.checkData(6, 0, 46) + tdSql.checkData(6, 1, -0.7682546613236668) + tdSql.checkData(6, 2, 0.9998433250151273) + tdSql.checkData(6, 3, 1.2763169256468458) + tdSql.checkData(6, 4, None) + tdSql.checkData(6, 5, -0.300459258677913) + tdSql.checkData(6, 6, 0.13392039926281352) + tdSql.checkData(7, 0, 46) + tdSql.checkData(7, 1, -0.7682546613236668) + tdSql.checkData(7, 2, 0.9998433250151273) + tdSql.checkData(7, 3, 1.2763169256468458) + tdSql.checkData(7, 4, None) + tdSql.checkData(7, 5, -0.300459258677913) + tdSql.checkData(7, 6, 0.13392039926281352) + tdSql.checkData(8, 0, 45) + tdSql.checkData(8, 1, 0.123573122745224) + tdSql.checkData(8, 2, 0.6735650596658175) + tdSql.checkData(8, 3, 1.5193186190030223) + tdSql.checkData(8, 4, None) + tdSql.checkData(8, 5, -1.5661895943272113) + tdSql.checkData(8, 6, 5.513771854144419) + tdSql.checkData(9, 0, 45) + tdSql.checkData(9, 1, 0.123573122745224) + tdSql.checkData(9, 2, 0.6735650596658175) + tdSql.checkData(9, 3, 1.5193186190030223) + tdSql.checkData(9, 4, None) + tdSql.checkData(9, 5, -1.5661895943272113) + tdSql.checkData(9, 6, 5.513771854144419) + tdSql.checkData(10, 0, 44) + tdSql.checkData(10, 1, 0.9017883476488092) + tdSql.checkData(10, 2, 0.6085839480802863) + tdSql.checkData(10, 3, 3.5552629892514687) + tdSql.checkData(10, 4, None) + tdSql.checkData(10, 5, -1.9810692649977342) + tdSql.checkData(10, 6, 3.0531030020123464) + tdSql.checkData(11, 0, 44) + tdSql.checkData(11, 1, 0.9017883476488092) + tdSql.checkData(11, 2, 0.6085839480802863) + tdSql.checkData(11, 3, 3.5552629892514687) + tdSql.checkData(11, 4, None) + tdSql.checkData(11, 5, -1.9810692649977342) + tdSql.checkData(11, 6, 3.0531030020123464) + tdSql.checkData(12, 0, 43) + tdSql.checkData(12, 1, 0.8509035245341184) + tdSql.checkData(12, 2, 0.9874457808369176) + tdSql.checkData(12, 3, 1.5962924548219202) + tdSql.checkData(12, 4, None) + tdSql.checkData(12, 5, -1.2490970766755156) + tdSql.checkData(12, 6, 0.5781542141407696) + tdSql.checkData(13, 0, 43) + tdSql.checkData(13, 1, 0.8509035245341184) + tdSql.checkData(13, 2, 0.9874457808369176) + tdSql.checkData(13, 3, 1.5962924548219202) + tdSql.checkData(13, 4, None) + tdSql.checkData(13, 5, -1.2490970766755156) + tdSql.checkData(13, 6, 0.5781542141407696) + tdSql.checkData(14, 0, 42) + tdSql.checkData(14, 1, 0.017701925105413577) + tdSql.checkData(14, 2, 0.7350111780599404) + tdSql.checkData(14, 3, 1.1912997639866574) + tdSql.checkData(14, 4, None) + tdSql.checkData(14, 5, 0.036467324189017214) + tdSql.checkData(14, 6, 6.024578312510778) + tdSql.checkData(15, 0, 42) + tdSql.checkData(15, 1, 0.017701925105413577) + tdSql.checkData(15, 2, 0.7350111780599404) + tdSql.checkData(15, 3, 1.1912997639866574) + tdSql.checkData(15, 4, None) + tdSql.checkData(15, 5, 0.036467324189017214) + tdSql.checkData(15, 6, 6.024578312510778) + tdSql.checkData(16, 0, 41) + tdSql.checkData(16, 1, -0.8317747426285983) + tdSql.checkData(16, 2, 0.5704067143341829) + tdSql.checkData(16, 3, 3.397430462894578) + tdSql.checkData(16, 4, None) + tdSql.checkData(16, 5, 0.9190273051332304) + tdSql.checkData(16, 6, 3.473885481113728) + tdSql.checkData(17, 0, 41) + tdSql.checkData(17, 1, -0.8317747426285983) + tdSql.checkData(17, 2, 0.5704067143341829) + tdSql.checkData(17, 3, 3.397430462894578) + tdSql.checkData(17, 4, None) + tdSql.checkData(17, 5, 0.9190273051332304) + tdSql.checkData(17, 6, 3.473885481113728) + tdSql.checkData(18, 0, 40) + tdSql.checkData(18, 1, -0.9165215479156338) + tdSql.checkData(18, 2, 0.9564033460276342) + tdSql.checkData(18, 3, 1.889162191085516) + tdSql.checkData(18, 4, None) + tdSql.checkData(18, 5, 0.90296737936602) + tdSql.checkData(18, 6, 0.888896415152729) + tdSql.checkData(19, 0, 40) + tdSql.checkData(19, 1, -0.9165215479156338) + tdSql.checkData(19, 2, 0.9564033460276342) + tdSql.checkData(19, 3, 1.889162191085516) + tdSql.checkData(19, 4, None) + tdSql.checkData(19, 5, 0.90296737936602) + tdSql.checkData(19, 6, 0.888896415152729) + tdSql.checkData(20, 0, 39) + tdSql.checkData(20, 1, -0.158622668804709) + tdSql.checkData(20, 2, 0.7999777847134487) + tdSql.checkData(20, 3, 0.8435920138756074) + tdSql.checkData(20, 4, None) + tdSql.checkData(20, 5, 0.3319994538301167) + tdSql.checkData(20, 6, 7.12853286308907) + tdSql.checkData(21, 0, 39) + tdSql.checkData(21, 1, -0.158622668804709) + tdSql.checkData(21, 2, 0.7999777847134487) + tdSql.checkData(21, 3, 0.8435920138756074) + tdSql.checkData(21, 4, None) + tdSql.checkData(21, 5, 0.3319994538301167) + tdSql.checkData(21, 6, 7.12853286308907) + tdSql.checkData(22, 0, 38) + tdSql.checkData(22, 1, 0.7451131604793488) + tdSql.checkData(22, 2, 0.5472018255605284) + tdSql.checkData(22, 3, 3.081063350979351) + tdSql.checkData(22, 4, None) + tdSql.checkData(22, 5, -0.007381884932924798) + tdSql.checkData(22, 6, 3.8764172978929814) + tdSql.checkData(23, 0, 38) + tdSql.checkData(23, 1, 0.7451131604793488) + tdSql.checkData(23, 2, 0.5472018255605284) + tdSql.checkData(23, 3, 3.081063350979351) + tdSql.checkData(23, 4, None) + tdSql.checkData(23, 5, -0.007381884932924798) + tdSql.checkData(23, 6, 3.8764172978929814) + tdSql.checkData(24, 0, 37) + tdSql.checkData(24, 1, 0.9637953862840878) + tdSql.checkData(24, 2, 0.909721840267583) + tdSql.checkData(24, 3, 2.1734252903776303) + tdSql.checkData(24, 4, None) + tdSql.checkData(24, 5, 0.32696474077278626) + tdSql.checkData(24, 6, 1.174082484128993) + tdSql.checkData(25, 0, 37) + tdSql.checkData(25, 1, 0.9637953862840878) + tdSql.checkData(25, 2, 0.909721840267583) + tdSql.checkData(25, 3, 2.1734252903776303) + tdSql.checkData(25, 4, None) + tdSql.checkData(25, 5, 0.32696474077278626) + tdSql.checkData(25, 6, 1.174082484128993) + tdSql.checkData(26, 0, 36) + tdSql.checkData(26, 1, 0.2963685787093853) + tdSql.checkData(26, 2, 0.8632704401895588) + tdSql.checkData(26, 3, 0.5493681603601657) + tdSql.checkData(26, 4, None) + tdSql.checkData(26, 5, 0.9944678850925007) + tdSql.checkData(26, 6, 11.004294268461184) + tdSql.checkData(27, 0, 36) + tdSql.checkData(27, 1, 0.2963685787093853) + tdSql.checkData(27, 2, 0.8632704401895588) + tdSql.checkData(27, 3, 0.5493681603601657) + tdSql.checkData(27, 4, None) + tdSql.checkData(27, 5, 0.9944678850925007) + tdSql.checkData(27, 6, 11.004294268461184) + tdSql.checkData(28, 0, 35) + tdSql.checkData(28, 1, -0.6435381333569995) + tdSql.checkData(28, 2, 0.5403764709316752) + tdSql.checkData(28, 3, 2.734210799811235) + tdSql.checkData(28, 4, None) + tdSql.checkData(28, 5, 1.1930854189064375) + tdSql.checkData(28, 6, 4.24770540197234) + tdSql.checkData(29, 0, 35) + tdSql.checkData(29, 1, -0.6435381333569995) + tdSql.checkData(29, 2, 0.5403764709316752) + tdSql.checkData(29, 3, 2.734210799811235) + tdSql.checkData(29, 4, None) + tdSql.checkData(29, 5, 1.1930854189064375) + tdSql.checkData(29, 6, 4.24770540197234) + tdSql.checkData(30, 0, 34) + tdSql.checkData(30, 1, -0.9917788534431158) + tdSql.checkData(30, 2, 0.8517779466253769) + tdSql.checkData(30, 3, 2.470955260231499) + tdSql.checkData(30, 4, None) + tdSql.checkData(30, 5, 0.4428112547200472) + tdSql.checkData(30, 6, 1.4785733565944832) + tdSql.checkData(31, 0, 34) + tdSql.checkData(31, 1, -0.9917788534431158) + tdSql.checkData(31, 2, 0.8517779466253769) + tdSql.checkData(31, 3, 2.470955260231499) + tdSql.checkData(31, 4, None) + tdSql.checkData(31, 5, 0.4428112547200472) + tdSql.checkData(31, 6, 1.4785733565944832) + tdSql.checkData(32, 0, 33) + tdSql.checkData(32, 1, -0.428182669496151) + tdSql.checkData(32, 2, 0.9194811573015673) + tdSql.checkData(32, 3, 0.4437992589174107) + tdSql.checkData(32, 4, None) + tdSql.checkData(32, 5, -0.9001958571391758) + tdSql.checkData(32, 6, -72.33956595410905) + tdSql.checkData(33, 0, 33) + tdSql.checkData(33, 1, -0.428182669496151) + tdSql.checkData(33, 2, 0.9194811573015673) + tdSql.checkData(33, 3, 0.4437992589174107) + tdSql.checkData(33, 4, None) + tdSql.checkData(33, 5, -0.9001958571391758) + tdSql.checkData(33, 6, -72.33956595410905) + tdSql.checkData(34, 0, 32) + tdSql.checkData(34, 1, 0.5290826861200238) + tdSql.checkData(34, 2, 0.5503344099628432) + tdSql.checkData(34, 3, 2.413227615833899) + tdSql.checkData(34, 4, None) + tdSql.checkData(34, 5, -1.8893763681780902) + tdSql.checkData(34, 6, 4.581032079680554) + tdSql.checkData(35, 0, 32) + tdSql.checkData(35, 1, 0.5290826861200238) + tdSql.checkData(35, 2, 0.5503344099628432) + tdSql.checkData(35, 3, 2.413227615833899) + tdSql.checkData(35, 4, None) + tdSql.checkData(35, 5, -1.8893763681780902) + tdSql.checkData(35, 6, 4.581032079680554) + tdSql.checkData(36, 0, 31) + tdSql.checkData(36, 1, 0.9999118601072672) + tdSql.checkData(36, 2, 0.7877590247885756) + tdSql.checkData(36, 3, 2.7979785951133604) + tdSql.checkData(36, 4, None) + tdSql.checkData(36, 5, -1.7874722290307907) + tdSql.checkData(36, 6, 1.8191237353300793) + tdSql.checkData(37, 0, 31) + tdSql.checkData(37, 1, 0.9999118601072672) + tdSql.checkData(37, 2, 0.7877590247885756) + tdSql.checkData(37, 3, 2.7979785951133604) + tdSql.checkData(37, 4, None) + tdSql.checkData(37, 5, -1.7874722290307907) + tdSql.checkData(37, 6, 1.8191237353300793) + tdSql.checkData(38, 0, 30) + tdSql.checkData(38, 1, 0.5514266812416906) + tdSql.checkData(38, 2, 0.9635288988181601) + tdSql.checkData(38, 3, 0.5944617511422015) + tdSql.checkData(38, 4, None) + tdSql.checkData(38, 5, -0.7022004347538967) + tdSql.checkData(38, 6, -3.710141817748492) + tdSql.checkData(39, 0, 30) + tdSql.checkData(39, 1, 0.5514266812416906) + tdSql.checkData(39, 2, 0.9635288988181601) + tdSql.checkData(39, 3, 0.5944617511422015) + tdSql.checkData(39, 4, None) + tdSql.checkData(39, 5, -0.7022004347538967) + tdSql.checkData(39, 6, -3.710141817748492) + tdSql.checkData(40, 0, 29) + tdSql.checkData(40, 1, -0.404037645323065) + tdSql.checkData(40, 2, 0.5764850221962442) + tdSql.checkData(40, 3, 2.1197476343754156) + tdSql.checkData(40, 4, None) + tdSql.checkData(40, 5, 0.5162157333804713) + tdSql.checkData(40, 6, 4.8800154918827525) + tdSql.checkData(41, 0, 29) + tdSql.checkData(41, 1, -0.404037645323065) + tdSql.checkData(41, 2, 0.5764850221962442) + tdSql.checkData(41, 3, 2.1197476343754156) + tdSql.checkData(41, 4, None) + tdSql.checkData(41, 5, 0.5162157333804713) + tdSql.checkData(41, 6, 4.8800154918827525) + tdSql.checkData(42, 0, 28) + tdSql.checkData(42, 1, -0.9880316240928618) + tdSql.checkData(42, 2, 0.7230710689951642) + tdSql.checkData(42, 3, 3.1457526648156393) + tdSql.checkData(42, 4, None) + tdSql.checkData(42, 5, 1.0206076417536643) + tdSql.checkData(42, 6, 2.197019393348823) + tdSql.checkData(43, 0, 28) + tdSql.checkData(43, 1, -0.9880316240928618) + tdSql.checkData(43, 2, 0.7230710689951642) + tdSql.checkData(43, 3, 3.1457526648156393) + tdSql.checkData(43, 4, None) + tdSql.checkData(43, 5, 1.0206076417536643) + tdSql.checkData(43, 6, 2.197019393348823) + tdSql.checkData(44, 0, 27) + tdSql.checkData(44, 1, -0.6636338842129675) + tdSql.checkData(44, 2, 0.9912542848596704) + tdSql.checkData(44, 3, 0.9080812682077812) + tdSql.checkData(44, 4, None) + tdSql.checkData(44, 5, 0.6788951190016388) + tdSql.checkData(44, 6, -0.8324928492797357) + tdSql.checkData(45, 0, 27) + tdSql.checkData(45, 1, -0.6636338842129675) + tdSql.checkData(45, 2, 0.9912542848596704) + tdSql.checkData(45, 3, 0.9080812682077812) + tdSql.checkData(45, 4, None) + tdSql.checkData(45, 5, 0.6788951190016388) + tdSql.checkData(45, 6, -0.8324928492797357) + tdSql.checkData(46, 0, 26) + tdSql.checkData(46, 1, 0.27090578830786904) + tdSql.checkData(46, 2, 0.6172306382193644) + tdSql.checkData(46, 3, 1.835550377607515) + tdSql.checkData(46, 4, None) + tdSql.checkData(46, 5, 0.11431954199291106) + tdSql.checkData(46, 6, 5.165381146246765) + tdSql.checkData(47, 0, 26) + tdSql.checkData(47, 1, 0.27090578830786904) + tdSql.checkData(47, 2, 0.6172306382193644) + tdSql.checkData(47, 3, 1.835550377607515) + tdSql.checkData(47, 4, None) + tdSql.checkData(47, 5, 0.11431954199291106) + tdSql.checkData(47, 6, 5.165381146246765) + tdSql.checkData(48, 0, 25) + tdSql.checkData(48, 1, 0.956375928404503) + tdSql.checkData(48, 2, 0.6628179613691831) + tdSql.checkData(48, 3, 3.4435632194258416) + tdSql.checkData(48, 4, None) + tdSql.checkData(48, 5, 0.05676687083562715) + tdSql.checkData(48, 6, 2.6040987392745354) + tdSql.checkData(49, 0, 25) + tdSql.checkData(49, 1, 0.956375928404503) + tdSql.checkData(49, 2, 0.6628179613691831) + tdSql.checkData(49, 3, 3.4435632194258416) + tdSql.checkData(49, 4, None) + tdSql.checkData(49, 5, 0.05676687083562715) + tdSql.checkData(49, 6, 2.6040987392745354) + tdSql.checkData(50, 0, 24) + tdSql.checkData(50, 1, 0.7625584504796027) + tdSql.checkData(50, 2, 0.999960827417674) + tdSql.checkData(50, 3, 1.2552318002593996) + tdSql.checkData(50, 4, None) + tdSql.checkData(50, 5, 0.6200983185456957) + tdSql.checkData(50, 6, 0.09684864095463253) + tdSql.checkData(51, 0, 24) + tdSql.checkData(51, 1, 0.7625584504796027) + tdSql.checkData(51, 2, 0.999960827417674) + tdSql.checkData(51, 3, 1.2552318002593996) + tdSql.checkData(51, 4, None) + tdSql.checkData(51, 5, 0.6200983185456957) + tdSql.checkData(51, 6, 0.09684864095463253) + tdSql.checkData(52, 0, 23) + tdSql.checkData(52, 1, -0.13235175009777303) + tdSql.checkData(52, 2, 0.6699494442536529) + tdSql.checkData(52, 3, 1.5387402975985367) + tdSql.checkData(52, 4, None) + tdSql.checkData(52, 5, 1.1825447904081037) + tdSql.checkData(52, 6, 5.489941431040083) + tdSql.checkData(53, 0, 23) + tdSql.checkData(53, 1, -0.13235175009777303) + tdSql.checkData(53, 2, 0.6699494442536529) + tdSql.checkData(53, 3, 1.5387402975985367) + tdSql.checkData(53, 4, None) + tdSql.checkData(53, 5, 1.1825447904081037) + tdSql.checkData(53, 6, 5.489941431040083) + tdSql.checkData(54, 0, 22) + tdSql.checkData(54, 1, -0.9055783620066239) + tdSql.checkData(54, 2, 0.6114178044194122) + tdSql.checkData(54, 3, 3.5568711064263105) + tdSql.checkData(54, 4, None) + tdSql.checkData(54, 5, 0.9837833410919679) + tdSql.checkData(54, 6, 3.0265535811470983) + tdSql.checkData(55, 0, 22) + tdSql.checkData(55, 1, -0.9055783620066239) + tdSql.checkData(55, 2, 0.6114178044194122) + tdSql.checkData(55, 3, 3.5568711064263105) + tdSql.checkData(55, 4, None) + tdSql.checkData(55, 5, 0.9837833410919679) + tdSql.checkData(55, 6, 3.0265535811470983) + tdSql.checkData(56, 0, 21) + tdSql.checkData(56, 1, -0.8462204041751706) + tdSql.checkData(56, 2, 0.9887894200405688) + tdSql.checkData(56, 3, 1.5772240911721418) + tdSql.checkData(56, 4, None) + tdSql.checkData(56, 5, -0.11647857397382422) + tdSql.checkData(56, 6, 0.5559799244477626) + tdSql.checkData(57, 0, 21) + tdSql.checkData(57, 1, -0.8462204041751706) + tdSql.checkData(57, 2, 0.9887894200405688) + tdSql.checkData(57, 3, 1.5772240911721418) + tdSql.checkData(57, 4, None) + tdSql.checkData(57, 5, -0.11647857397382422) + tdSql.checkData(57, 6, 0.5559799244477626) + tdSql.checkData(58, 0, 20) + tdSql.checkData(58, 1, -0.008851309290403876) + tdSql.checkData(58, 2, 0.7310155667453407) + tdSql.checkData(58, 3, 1.2127175951404974) + tdSql.checkData(58, 4, None) + tdSql.checkData(58, 5, -1.4304290589415767) + tdSql.checkData(58, 6, 5.982274104704091) + tdSql.checkData(59, 0, 20) + tdSql.checkData(59, 1, -0.008851309290403876) + tdSql.checkData(59, 2, 0.7310155667453407) + tdSql.checkData(59, 3, 1.2127175951404974) + tdSql.checkData(59, 4, None) + tdSql.checkData(59, 5, -1.4304290589415767) + tdSql.checkData(59, 6, 5.982274104704091) + tdSql.checkData(60, 0, 19) + tdSql.checkData(60, 1, 0.8366556385360561) + tdSql.checkData(60, 2, 0.5723746128431292) + tdSql.checkData(60, 3, 3.413484890511323) + tdSql.checkData(60, 4, None) + tdSql.checkData(60, 5, -1.9952541841757747) + tdSql.checkData(60, 6, 3.4479580493217856) + tdSql.checkData(61, 0, 19) + tdSql.checkData(61, 1, 0.8366556385360561) + tdSql.checkData(61, 2, 0.5723746128431292) + tdSql.checkData(61, 3, 3.413484890511323) + tdSql.checkData(61, 4, None) + tdSql.checkData(61, 5, -1.9952541841757747) + tdSql.checkData(61, 6, 3.4479580493217856) + tdSql.checkData(62, 0, 18) + tdSql.checkData(62, 1, 0.9129452507276277) + tdSql.checkData(62, 2, 0.9588413200803038) + tdSql.checkData(62, 3, 1.8713332491184997) + tdSql.checkData(62, 4, None) + tdSql.checkData(62, 5, -1.3983047743451864) + tdSql.checkData(62, 6, 0.8709074342191974) + tdSql.checkData(63, 0, 18) + tdSql.checkData(63, 1, 0.9129452507276277) + tdSql.checkData(63, 2, 0.9588413200803038) + tdSql.checkData(63, 3, 1.8713332491184997) + tdSql.checkData(63, 4, None) + tdSql.checkData(63, 5, -1.3983047743451864) + tdSql.checkData(63, 6, 0.8709074342191974) + tdSql.checkData(64, 0, 17) + tdSql.checkData(64, 1, 0.14987720966295234) + tdSql.checkData(64, 2, 0.7959095686227995) + tdSql.checkData(64, 3, 0.864944320724419) + tdSql.checkData(64, 4, None) + tdSql.checkData(64, 5, -0.13037289959062748) + tdSql.checkData(64, 6, 7.022998331594864) + tdSql.checkData(65, 0, 17) + tdSql.checkData(65, 1, 0.14987720966295234) + tdSql.checkData(65, 2, 0.7959095686227995) + tdSql.checkData(65, 3, 0.864944320724419) + tdSql.checkData(65, 4, None) + tdSql.checkData(65, 5, -0.13037289959062748) + tdSql.checkData(65, 6, 7.022998331594864) + tdSql.checkData(66, 0, 16) + tdSql.checkData(66, 1, -0.750987246771676) + tdSql.checkData(66, 2, 0.5481819942730298) + tdSql.checkData(66, 3, 3.102748784455539) + tdSql.checkData(66, 4, None) + tdSql.checkData(66, 5, 0.8513297604701857) + tdSql.checkData(66, 6, 3.852058923265594) + tdSql.checkData(67, 0, 16) + tdSql.checkData(67, 1, -0.750987246771676) + tdSql.checkData(67, 2, 0.5481819942730298) + tdSql.checkData(67, 3, 3.102748784455539) + tdSql.checkData(67, 4, None) + tdSql.checkData(67, 5, 0.8513297604701857) + tdSql.checkData(67, 6, 3.852058923265594) + tdSql.checkData(68, 0, 15) + tdSql.checkData(68, 1, -0.9613974918795568) + tdSql.checkData(68, 2, 0.9130208165623314) + tdSql.checkData(68, 3, 2.1554866011151765) + tdSql.checkData(68, 4, None) + tdSql.checkData(68, 5, 0.9521751875546269) + tdSql.checkData(68, 6, 1.1559749749986195) + tdSql.checkData(69, 0, 15) + tdSql.checkData(69, 1, -0.9613974918795568) + tdSql.checkData(69, 2, 0.9130208165623314) + tdSql.checkData(69, 3, 2.1554866011151765) + tdSql.checkData(69, 4, None) + tdSql.checkData(69, 5, 0.9521751875546269) + tdSql.checkData(69, 6, 1.1559749749986195) + tdSql.checkData(70, 0, 14) + tdSql.checkData(70, 1, -0.2879033166650653) + tdSql.checkData(70, 2, 0.859465627274523) + tdSql.checkData(70, 3, 0.5636905248139659) + tdSql.checkData(70, 4, None) + tdSql.checkData(70, 5, 0.41142163587369207) + tdSql.checkData(70, 6, 10.515512404402676) + tdSql.checkData(71, 0, 14) + tdSql.checkData(71, 1, -0.2879033166650653) + tdSql.checkData(71, 2, 0.859465627274523) + tdSql.checkData(71, 3, 0.5636905248139659) + tdSql.checkData(71, 4, None) + tdSql.checkData(71, 5, 0.41142163587369207) + tdSql.checkData(71, 6, 10.515512404402676) + tdSql.checkData(72, 0, 13) + tdSql.checkData(72, 1, 0.6502878401571168) + tdSql.checkData(72, 2, 0.5403105467456532) + tdSql.checkData(72, 3, 2.75535470715349) + tdSql.checkData(72, 4, None) + tdSql.checkData(72, 5, 0.0009616202598659029) + tdSql.checkData(72, 6, 4.225579583416092) + tdSql.checkData(73, 0, 13) + tdSql.checkData(73, 1, 0.6502878401571168) + tdSql.checkData(73, 2, 0.5403105467456532) + tdSql.checkData(73, 3, 2.75535470715349) + tdSql.checkData(73, 4, None) + tdSql.checkData(73, 5, 0.0009616202598659029) + tdSql.checkData(73, 6, 4.225579583416092) + tdSql.checkData(74, 0, 12) + tdSql.checkData(74, 1, 0.9906073556948704) + tdSql.checkData(74, 2, 0.8556343548213666) + tdSql.checkData(74, 3, 2.451594361777497) + tdSql.checkData(74, 4, None) + tdSql.checkData(74, 5, 0.24838494428124291) + tdSql.checkData(74, 6, 1.4585617093317953) + tdSql.checkData(75, 0, 12) + tdSql.checkData(75, 1, 0.9906073556948704) + tdSql.checkData(75, 2, 0.8556343548213666) + tdSql.checkData(75, 3, 2.451594361777497) + tdSql.checkData(75, 4, None) + tdSql.checkData(75, 5, 0.24838494428124291) + tdSql.checkData(75, 6, 1.4585617093317953) + tdSql.checkData(76, 0, 11) + tdSql.checkData(76, 1, 0.4201670368266409) + tdSql.checkData(76, 2, 0.9162743174606308) + tdSql.checkData(76, 3, 0.44272645708128566) + tdSql.checkData(76, 4, None) + tdSql.checkData(76, 5, 0.9151372562290566) + tdSql.checkData(76, 6, -222.95969776348554) + tdSql.checkData(77, 0, 11) + tdSql.checkData(77, 1, 0.4201670368266409) + tdSql.checkData(77, 2, 0.9162743174606308) + tdSql.checkData(77, 3, 0.44272645708128566) + tdSql.checkData(77, 4, None) + tdSql.checkData(77, 5, 0.9151372562290566) + tdSql.checkData(77, 6, -222.95969776348554) + tdSql.checkData(78, 0, 10) + tdSql.checkData(78, 1, -0.5365729180004349) + tdSql.checkData(78, 2, 0.549226270051226) + tdSql.checkData(78, 3, 2.432352856101439) + tdSql.checkData(78, 4, None) + tdSql.checkData(78, 5, 1.2185572409879093) + tdSql.checkData(78, 6, 4.561306078186714) + tdSql.checkData(79, 0, 10) + tdSql.checkData(79, 1, -0.5365729180004349) + tdSql.checkData(79, 2, 0.549226270051226) + tdSql.checkData(79, 3, 2.432352856101439) + tdSql.checkData(79, 4, None) + tdSql.checkData(79, 5, 1.2185572409879093) + tdSql.checkData(79, 6, 4.561306078186714) + tdSql.checkData(80, 0, 9) + tdSql.checkData(80, 1, -0.9999902065507035) + tdSql.checkData(80, 2, 0.7918362090144786) + tdSql.checkData(80, 3, 2.776612511546888) + tdSql.checkData(80, 4, None) + tdSql.checkData(80, 5, 0.5929886271208413) + tdSql.checkData(80, 6, 1.796697093786514) + tdSql.checkData(81, 0, 9) + tdSql.checkData(81, 1, -0.9999902065507035) + tdSql.checkData(81, 2, 0.7918362090144786) + tdSql.checkData(81, 3, 2.776612511546888) + tdSql.checkData(81, 4, None) + tdSql.checkData(81, 5, 0.5929886271208413) + tdSql.checkData(81, 6, 1.796697093786514) + tdSql.checkData(82, 0, 8) + tdSql.checkData(82, 1, -0.5440211108893698) + tdSql.checkData(82, 2, 0.9612168045072789) + tdSql.checkData(82, 3, 0.5787344727995947) + tdSql.checkData(82, 4, None) + tdSql.checkData(82, 5, -0.7199655182148126) + tdSql.checkData(82, 6, -4.087614771885445) + tdSql.checkData(83, 0, 8) + tdSql.checkData(83, 1, -0.5440211108893698) + tdSql.checkData(83, 2, 0.9612168045072789) + tdSql.checkData(83, 3, 0.5787344727995947) + tdSql.checkData(83, 4, None) + tdSql.checkData(83, 5, -0.7199655182148126) + tdSql.checkData(83, 6, -4.087614771885445) + tdSql.checkData(84, 0, 7) + tdSql.checkData(84, 1, 0.4121184852417566) + tdSql.checkData(84, 2, 0.574400879193934) + tdSql.checkData(84, 3, 2.137595835197328) + tdSql.checkData(84, 4, None) + tdSql.checkData(84, 5, -1.8119088619792247) + tdSql.checkData(84, 6, 4.862055338419189) + tdSql.checkData(85, 0, 7) + tdSql.checkData(85, 1, 0.4121184852417566) + tdSql.checkData(85, 2, 0.574400879193934) + tdSql.checkData(85, 3, 2.137595835197328) + tdSql.checkData(85, 4, None) + tdSql.checkData(85, 5, -1.8119088619792247) + tdSql.checkData(85, 6, 4.862055338419189) + tdSql.checkData(86, 0, 6) + tdSql.checkData(86, 1, 0.9893582466233818) + tdSql.checkData(86, 2, 0.7270351311688125) + tdSql.checkData(86, 3, 3.1243204798042576) + tdSql.checkData(86, 4, None) + tdSql.checkData(86, 5, -1.8696882565721156) + tdSql.checkData(86, 6, 2.172420890614816) + tdSql.checkData(87, 0, 6) + tdSql.checkData(87, 1, 0.9893582466233818) + tdSql.checkData(87, 2, 0.7270351311688125) + tdSql.checkData(87, 3, 3.1243204798042576) + tdSql.checkData(87, 4, None) + tdSql.checkData(87, 5, -1.8696882565721156) + tdSql.checkData(87, 6, 2.172420890614816) + tdSql.checkData(88, 0, 5) + tdSql.checkData(88, 1, 0.6569865987187891) + tdSql.checkData(88, 2, 0.9900590857598653) + tdSql.checkData(88, 3, 0.8864495743441427) + tdSql.checkData(88, 4, None) + tdSql.checkData(88, 5, -0.876294736008743) + tdSql.checkData(88, 6, -0.9245361171359558) + tdSql.checkData(89, 0, 5) + tdSql.checkData(89, 1, 0.6569865987187891) + tdSql.checkData(89, 2, 0.9900590857598653) + tdSql.checkData(89, 3, 0.8864495743441427) + tdSql.checkData(89, 4, None) + tdSql.checkData(89, 5, -0.876294736008743) + tdSql.checkData(89, 6, -0.9245361171359558) + tdSql.checkData(90, 0, 4) + tdSql.checkData(90, 1, -0.27941549819892586) + tdSql.checkData(90, 2, 0.6143002821164822) + tdSql.checkData(90, 3, 1.853464438509776) + tdSql.checkData(90, 4, None) + tdSql.checkData(90, 5, 0.38234027607634785) + tdSql.checkData(90, 6, 5.147179528972959) + tdSql.checkData(91, 0, 4) + tdSql.checkData(91, 1, -0.27941549819892586) + tdSql.checkData(91, 2, 0.6143002821164822) + tdSql.checkData(91, 3, 1.853464438509776) + tdSql.checkData(91, 4, None) + tdSql.checkData(91, 5, 0.38234027607634785) + tdSql.checkData(91, 6, 5.147179528972959) + tdSql.checkData(92, 0, 3) + tdSql.checkData(92, 1, -0.9589242746631385) + tdSql.checkData(92, 2, 0.6663667453928805) + tdSql.checkData(92, 3, 3.4288753232277074) + tdSql.checkData(92, 4, None) + tdSql.checkData(92, 5, 1.0087371784424417) + tdSql.checkData(92, 6, 2.5780379587267963) + tdSql.checkData(93, 0, 3) + tdSql.checkData(93, 1, -0.9589242746631385) + tdSql.checkData(93, 2, 0.6663667453928805) + tdSql.checkData(93, 3, 3.4288753232277074) + tdSql.checkData(93, 4, None) + tdSql.checkData(93, 5, 1.0087371784424417) + tdSql.checkData(93, 6, 2.5780379587267963) + tdSql.checkData(94, 0, 2) + tdSql.checkData(94, 1, -0.7568024953079282) + tdSql.checkData(94, 2, 1.0) + tdSql.checkData(94, 3, 1.2340302976078754) + tdSql.checkData(94, 4, None) + tdSql.checkData(94, 5, 0.7554222939559553) + tdSql.checkData(94, 6, 0.05815764143055291) + tdSql.checkData(95, 0, 2) + tdSql.checkData(95, 1, -0.7568024953079282) + tdSql.checkData(95, 2, 1.0) + tdSql.checkData(95, 3, 1.2340302976078754) + tdSql.checkData(95, 4, None) + tdSql.checkData(95, 5, 0.7554222939559553) + tdSql.checkData(95, 6, 0.05815764143055291) + tdSql.checkData(96, 0, 1) + tdSql.checkData(96, 1, 0.1411200080598672) + tdSql.checkData(96, 2, 0.6663667453928805) + tdSql.checkData(96, 3, 1.558041126155035) + tdSql.checkData(96, 4, 1.8325957145940461) + tdSql.checkData(96, 5, 0.17204223631998083) + tdSql.checkData(96, 6, None) + tdSql.checkData(97, 0, 1) + tdSql.checkData(97, 1, 0.1411200080598672) + tdSql.checkData(97, 2, 0.6663667453928805) + tdSql.checkData(97, 3, 1.558041126155035) + tdSql.checkData(97, 4, 1.8325957145940461) + tdSql.checkData(97, 5, 0.17204223631998083) + tdSql.checkData(97, 6, None) + tdSql.checkData(98, 0, 0) + tdSql.checkData(98, 1, 0.7780731968879212) + tdSql.checkData(98, 2, 0.6143002821164822) + tdSql.checkData(98, 3, 3.2037266279837113) + tdSql.checkData(98, 4, None) + tdSql.checkData(98, 5, 0.02246988233490299) + tdSql.checkData(98, 6, None) + tdSql.checkData(99, 0, 0) + tdSql.checkData(99, 1, 0.7780731968879212) + tdSql.checkData(99, 2, 0.6143002821164822) + tdSql.checkData(99, 3, 3.2037266279837113) + tdSql.checkData(99, 4, None) + tdSql.checkData(99, 5, 0.02246988233490299) + tdSql.checkData(99, 6, None) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 order by ts limit 2);;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.7780731968879212) + tdSql.checkData(0, 2, 0.6143002821164822) + tdSql.checkData(0, 3, 3.2037266279837113) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.02246988233490299) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.1411200080598672) + tdSql.checkData(1, 2, 0.6663667453928805) + tdSql.checkData(1, 3, 1.558041126155035) + tdSql.checkData(1, 4, 1.8325957145940461) + tdSql.checkData(1, 5, 0.17204223631998083) + tdSql.checkData(1, 6, None) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 ) order by ts desc;') + tdSql.checkRows(100) + tdSql.checkData(0, 0, 49) + tdSql.checkData(0, 1, 0.6702291758433747) + tdSql.checkData(0, 2, 0.9923745526637894) + tdSql.checkData(0, 3, 0.9298143670243166) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.7136182821549459) + tdSql.checkData(0, 6, -0.7462904241496138) + tdSql.checkData(1, 0, 49) + tdSql.checkData(1, 1, 0.6702291758433747) + tdSql.checkData(1, 2, 0.9923745526637894) + tdSql.checkData(1, 3, 0.9298143670243166) + tdSql.checkData(1, 4, None) + tdSql.checkData(1, 5, 0.7136182821549459) + tdSql.checkData(1, 6, -0.7462904241496138) + tdSql.checkData(2, 0, 48) + tdSql.checkData(2, 1, -0.26237485370392877) + tdSql.checkData(2, 2, 0.6202081141679935) + tdSql.checkData(2, 3, 1.8175857333771335) + tdSql.checkData(2, 4, None) + tdSql.checkData(2, 5, 1.211884234321115) + tdSql.checkData(2, 6, 5.183714988550632) + tdSql.checkData(3, 0, 48) + tdSql.checkData(3, 1, -0.26237485370392877) + tdSql.checkData(3, 2, 0.6202081141679935) + tdSql.checkData(3, 3, 1.8175857333771335) + tdSql.checkData(3, 4, None) + tdSql.checkData(3, 5, 1.211884234321115) + tdSql.checkData(3, 6, 5.183714988550632) + tdSql.checkData(4, 0, 47) + tdSql.checkData(4, 1, -0.9537526527594719) + tdSql.checkData(4, 2, 0.6593040763085178) + tdSql.checkData(4, 3, 3.4575106745458637) + tdSql.checkData(4, 4, None) + tdSql.checkData(4, 5, 0.8820838187306987) + tdSql.checkData(4, 6, 2.6302204463996084) + tdSql.checkData(5, 0, 47) + tdSql.checkData(5, 1, -0.9537526527594719) + tdSql.checkData(5, 2, 0.6593040763085178) + tdSql.checkData(5, 3, 3.4575106745458637) + tdSql.checkData(5, 4, None) + tdSql.checkData(5, 5, 0.8820838187306987) + tdSql.checkData(5, 6, 2.6302204463996084) + tdSql.checkData(6, 0, 46) + tdSql.checkData(6, 1, -0.7682546613236668) + tdSql.checkData(6, 2, 0.9998433250151273) + tdSql.checkData(6, 3, 1.2763169256468458) + tdSql.checkData(6, 4, None) + tdSql.checkData(6, 5, -0.300459258677913) + tdSql.checkData(6, 6, 0.13392039926281352) + tdSql.checkData(7, 0, 46) + tdSql.checkData(7, 1, -0.7682546613236668) + tdSql.checkData(7, 2, 0.9998433250151273) + tdSql.checkData(7, 3, 1.2763169256468458) + tdSql.checkData(7, 4, None) + tdSql.checkData(7, 5, -0.300459258677913) + tdSql.checkData(7, 6, 0.13392039926281352) + tdSql.checkData(8, 0, 45) + tdSql.checkData(8, 1, 0.123573122745224) + tdSql.checkData(8, 2, 0.6735650596658175) + tdSql.checkData(8, 3, 1.5193186190030223) + tdSql.checkData(8, 4, None) + tdSql.checkData(8, 5, -1.5661895943272113) + tdSql.checkData(8, 6, 5.513771854144419) + tdSql.checkData(9, 0, 45) + tdSql.checkData(9, 1, 0.123573122745224) + tdSql.checkData(9, 2, 0.6735650596658175) + tdSql.checkData(9, 3, 1.5193186190030223) + tdSql.checkData(9, 4, None) + tdSql.checkData(9, 5, -1.5661895943272113) + tdSql.checkData(9, 6, 5.513771854144419) + tdSql.checkData(10, 0, 44) + tdSql.checkData(10, 1, 0.9017883476488092) + tdSql.checkData(10, 2, 0.6085839480802863) + tdSql.checkData(10, 3, 3.5552629892514687) + tdSql.checkData(10, 4, None) + tdSql.checkData(10, 5, -1.9810692649977342) + tdSql.checkData(10, 6, 3.0531030020123464) + tdSql.checkData(11, 0, 44) + tdSql.checkData(11, 1, 0.9017883476488092) + tdSql.checkData(11, 2, 0.6085839480802863) + tdSql.checkData(11, 3, 3.5552629892514687) + tdSql.checkData(11, 4, None) + tdSql.checkData(11, 5, -1.9810692649977342) + tdSql.checkData(11, 6, 3.0531030020123464) + tdSql.checkData(12, 0, 43) + tdSql.checkData(12, 1, 0.8509035245341184) + tdSql.checkData(12, 2, 0.9874457808369176) + tdSql.checkData(12, 3, 1.5962924548219202) + tdSql.checkData(12, 4, None) + tdSql.checkData(12, 5, -1.2490970766755156) + tdSql.checkData(12, 6, 0.5781542141407696) + tdSql.checkData(13, 0, 43) + tdSql.checkData(13, 1, 0.8509035245341184) + tdSql.checkData(13, 2, 0.9874457808369176) + tdSql.checkData(13, 3, 1.5962924548219202) + tdSql.checkData(13, 4, None) + tdSql.checkData(13, 5, -1.2490970766755156) + tdSql.checkData(13, 6, 0.5781542141407696) + tdSql.checkData(14, 0, 42) + tdSql.checkData(14, 1, 0.017701925105413577) + tdSql.checkData(14, 2, 0.7350111780599404) + tdSql.checkData(14, 3, 1.1912997639866574) + tdSql.checkData(14, 4, None) + tdSql.checkData(14, 5, 0.036467324189017214) + tdSql.checkData(14, 6, 6.024578312510778) + tdSql.checkData(15, 0, 42) + tdSql.checkData(15, 1, 0.017701925105413577) + tdSql.checkData(15, 2, 0.7350111780599404) + tdSql.checkData(15, 3, 1.1912997639866574) + tdSql.checkData(15, 4, None) + tdSql.checkData(15, 5, 0.036467324189017214) + tdSql.checkData(15, 6, 6.024578312510778) + tdSql.checkData(16, 0, 41) + tdSql.checkData(16, 1, -0.8317747426285983) + tdSql.checkData(16, 2, 0.5704067143341829) + tdSql.checkData(16, 3, 3.397430462894578) + tdSql.checkData(16, 4, None) + tdSql.checkData(16, 5, 0.9190273051332304) + tdSql.checkData(16, 6, 3.473885481113728) + tdSql.checkData(17, 0, 41) + tdSql.checkData(17, 1, -0.8317747426285983) + tdSql.checkData(17, 2, 0.5704067143341829) + tdSql.checkData(17, 3, 3.397430462894578) + tdSql.checkData(17, 4, None) + tdSql.checkData(17, 5, 0.9190273051332304) + tdSql.checkData(17, 6, 3.473885481113728) + tdSql.checkData(18, 0, 40) + tdSql.checkData(18, 1, -0.9165215479156338) + tdSql.checkData(18, 2, 0.9564033460276342) + tdSql.checkData(18, 3, 1.889162191085516) + tdSql.checkData(18, 4, None) + tdSql.checkData(18, 5, 0.90296737936602) + tdSql.checkData(18, 6, 0.888896415152729) + tdSql.checkData(19, 0, 40) + tdSql.checkData(19, 1, -0.9165215479156338) + tdSql.checkData(19, 2, 0.9564033460276342) + tdSql.checkData(19, 3, 1.889162191085516) + tdSql.checkData(19, 4, None) + tdSql.checkData(19, 5, 0.90296737936602) + tdSql.checkData(19, 6, 0.888896415152729) + tdSql.checkData(20, 0, 39) + tdSql.checkData(20, 1, -0.158622668804709) + tdSql.checkData(20, 2, 0.7999777847134487) + tdSql.checkData(20, 3, 0.8435920138756074) + tdSql.checkData(20, 4, None) + tdSql.checkData(20, 5, 0.3319994538301167) + tdSql.checkData(20, 6, 7.12853286308907) + tdSql.checkData(21, 0, 39) + tdSql.checkData(21, 1, -0.158622668804709) + tdSql.checkData(21, 2, 0.7999777847134487) + tdSql.checkData(21, 3, 0.8435920138756074) + tdSql.checkData(21, 4, None) + tdSql.checkData(21, 5, 0.3319994538301167) + tdSql.checkData(21, 6, 7.12853286308907) + tdSql.checkData(22, 0, 38) + tdSql.checkData(22, 1, 0.7451131604793488) + tdSql.checkData(22, 2, 0.5472018255605284) + tdSql.checkData(22, 3, 3.081063350979351) + tdSql.checkData(22, 4, None) + tdSql.checkData(22, 5, -0.007381884932924798) + tdSql.checkData(22, 6, 3.8764172978929814) + tdSql.checkData(23, 0, 38) + tdSql.checkData(23, 1, 0.7451131604793488) + tdSql.checkData(23, 2, 0.5472018255605284) + tdSql.checkData(23, 3, 3.081063350979351) + tdSql.checkData(23, 4, None) + tdSql.checkData(23, 5, -0.007381884932924798) + tdSql.checkData(23, 6, 3.8764172978929814) + tdSql.checkData(24, 0, 37) + tdSql.checkData(24, 1, 0.9637953862840878) + tdSql.checkData(24, 2, 0.909721840267583) + tdSql.checkData(24, 3, 2.1734252903776303) + tdSql.checkData(24, 4, None) + tdSql.checkData(24, 5, 0.32696474077278626) + tdSql.checkData(24, 6, 1.174082484128993) + tdSql.checkData(25, 0, 37) + tdSql.checkData(25, 1, 0.9637953862840878) + tdSql.checkData(25, 2, 0.909721840267583) + tdSql.checkData(25, 3, 2.1734252903776303) + tdSql.checkData(25, 4, None) + tdSql.checkData(25, 5, 0.32696474077278626) + tdSql.checkData(25, 6, 1.174082484128993) + tdSql.checkData(26, 0, 36) + tdSql.checkData(26, 1, 0.2963685787093853) + tdSql.checkData(26, 2, 0.8632704401895588) + tdSql.checkData(26, 3, 0.5493681603601657) + tdSql.checkData(26, 4, None) + tdSql.checkData(26, 5, 0.9944678850925007) + tdSql.checkData(26, 6, 11.004294268461184) + tdSql.checkData(27, 0, 36) + tdSql.checkData(27, 1, 0.2963685787093853) + tdSql.checkData(27, 2, 0.8632704401895588) + tdSql.checkData(27, 3, 0.5493681603601657) + tdSql.checkData(27, 4, None) + tdSql.checkData(27, 5, 0.9944678850925007) + tdSql.checkData(27, 6, 11.004294268461184) + tdSql.checkData(28, 0, 35) + tdSql.checkData(28, 1, -0.6435381333569995) + tdSql.checkData(28, 2, 0.5403764709316752) + tdSql.checkData(28, 3, 2.734210799811235) + tdSql.checkData(28, 4, None) + tdSql.checkData(28, 5, 1.1930854189064375) + tdSql.checkData(28, 6, 4.24770540197234) + tdSql.checkData(29, 0, 35) + tdSql.checkData(29, 1, -0.6435381333569995) + tdSql.checkData(29, 2, 0.5403764709316752) + tdSql.checkData(29, 3, 2.734210799811235) + tdSql.checkData(29, 4, None) + tdSql.checkData(29, 5, 1.1930854189064375) + tdSql.checkData(29, 6, 4.24770540197234) + tdSql.checkData(30, 0, 34) + tdSql.checkData(30, 1, -0.9917788534431158) + tdSql.checkData(30, 2, 0.8517779466253769) + tdSql.checkData(30, 3, 2.470955260231499) + tdSql.checkData(30, 4, None) + tdSql.checkData(30, 5, 0.4428112547200472) + tdSql.checkData(30, 6, 1.4785733565944832) + tdSql.checkData(31, 0, 34) + tdSql.checkData(31, 1, -0.9917788534431158) + tdSql.checkData(31, 2, 0.8517779466253769) + tdSql.checkData(31, 3, 2.470955260231499) + tdSql.checkData(31, 4, None) + tdSql.checkData(31, 5, 0.4428112547200472) + tdSql.checkData(31, 6, 1.4785733565944832) + tdSql.checkData(32, 0, 33) + tdSql.checkData(32, 1, -0.428182669496151) + tdSql.checkData(32, 2, 0.9194811573015673) + tdSql.checkData(32, 3, 0.4437992589174107) + tdSql.checkData(32, 4, None) + tdSql.checkData(32, 5, -0.9001958571391758) + tdSql.checkData(32, 6, -72.33956595410905) + tdSql.checkData(33, 0, 33) + tdSql.checkData(33, 1, -0.428182669496151) + tdSql.checkData(33, 2, 0.9194811573015673) + tdSql.checkData(33, 3, 0.4437992589174107) + tdSql.checkData(33, 4, None) + tdSql.checkData(33, 5, -0.9001958571391758) + tdSql.checkData(33, 6, -72.33956595410905) + tdSql.checkData(34, 0, 32) + tdSql.checkData(34, 1, 0.5290826861200238) + tdSql.checkData(34, 2, 0.5503344099628432) + tdSql.checkData(34, 3, 2.413227615833899) + tdSql.checkData(34, 4, None) + tdSql.checkData(34, 5, -1.8893763681780902) + tdSql.checkData(34, 6, 4.581032079680554) + tdSql.checkData(35, 0, 32) + tdSql.checkData(35, 1, 0.5290826861200238) + tdSql.checkData(35, 2, 0.5503344099628432) + tdSql.checkData(35, 3, 2.413227615833899) + tdSql.checkData(35, 4, None) + tdSql.checkData(35, 5, -1.8893763681780902) + tdSql.checkData(35, 6, 4.581032079680554) + tdSql.checkData(36, 0, 31) + tdSql.checkData(36, 1, 0.9999118601072672) + tdSql.checkData(36, 2, 0.7877590247885756) + tdSql.checkData(36, 3, 2.7979785951133604) + tdSql.checkData(36, 4, None) + tdSql.checkData(36, 5, -1.7874722290307907) + tdSql.checkData(36, 6, 1.8191237353300793) + tdSql.checkData(37, 0, 31) + tdSql.checkData(37, 1, 0.9999118601072672) + tdSql.checkData(37, 2, 0.7877590247885756) + tdSql.checkData(37, 3, 2.7979785951133604) + tdSql.checkData(37, 4, None) + tdSql.checkData(37, 5, -1.7874722290307907) + tdSql.checkData(37, 6, 1.8191237353300793) + tdSql.checkData(38, 0, 30) + tdSql.checkData(38, 1, 0.5514266812416906) + tdSql.checkData(38, 2, 0.9635288988181601) + tdSql.checkData(38, 3, 0.5944617511422015) + tdSql.checkData(38, 4, None) + tdSql.checkData(38, 5, -0.7022004347538967) + tdSql.checkData(38, 6, -3.710141817748492) + tdSql.checkData(39, 0, 30) + tdSql.checkData(39, 1, 0.5514266812416906) + tdSql.checkData(39, 2, 0.9635288988181601) + tdSql.checkData(39, 3, 0.5944617511422015) + tdSql.checkData(39, 4, None) + tdSql.checkData(39, 5, -0.7022004347538967) + tdSql.checkData(39, 6, -3.710141817748492) + tdSql.checkData(40, 0, 29) + tdSql.checkData(40, 1, -0.404037645323065) + tdSql.checkData(40, 2, 0.5764850221962442) + tdSql.checkData(40, 3, 2.1197476343754156) + tdSql.checkData(40, 4, None) + tdSql.checkData(40, 5, 0.5162157333804713) + tdSql.checkData(40, 6, 4.8800154918827525) + tdSql.checkData(41, 0, 29) + tdSql.checkData(41, 1, -0.404037645323065) + tdSql.checkData(41, 2, 0.5764850221962442) + tdSql.checkData(41, 3, 2.1197476343754156) + tdSql.checkData(41, 4, None) + tdSql.checkData(41, 5, 0.5162157333804713) + tdSql.checkData(41, 6, 4.8800154918827525) + tdSql.checkData(42, 0, 28) + tdSql.checkData(42, 1, -0.9880316240928618) + tdSql.checkData(42, 2, 0.7230710689951642) + tdSql.checkData(42, 3, 3.1457526648156393) + tdSql.checkData(42, 4, None) + tdSql.checkData(42, 5, 1.0206076417536643) + tdSql.checkData(42, 6, 2.197019393348823) + tdSql.checkData(43, 0, 28) + tdSql.checkData(43, 1, -0.9880316240928618) + tdSql.checkData(43, 2, 0.7230710689951642) + tdSql.checkData(43, 3, 3.1457526648156393) + tdSql.checkData(43, 4, None) + tdSql.checkData(43, 5, 1.0206076417536643) + tdSql.checkData(43, 6, 2.197019393348823) + tdSql.checkData(44, 0, 27) + tdSql.checkData(44, 1, -0.6636338842129675) + tdSql.checkData(44, 2, 0.9912542848596704) + tdSql.checkData(44, 3, 0.9080812682077812) + tdSql.checkData(44, 4, None) + tdSql.checkData(44, 5, 0.6788951190016388) + tdSql.checkData(44, 6, -0.8324928492797357) + tdSql.checkData(45, 0, 27) + tdSql.checkData(45, 1, -0.6636338842129675) + tdSql.checkData(45, 2, 0.9912542848596704) + tdSql.checkData(45, 3, 0.9080812682077812) + tdSql.checkData(45, 4, None) + tdSql.checkData(45, 5, 0.6788951190016388) + tdSql.checkData(45, 6, -0.8324928492797357) + tdSql.checkData(46, 0, 26) + tdSql.checkData(46, 1, 0.27090578830786904) + tdSql.checkData(46, 2, 0.6172306382193644) + tdSql.checkData(46, 3, 1.835550377607515) + tdSql.checkData(46, 4, None) + tdSql.checkData(46, 5, 0.11431954199291106) + tdSql.checkData(46, 6, 5.165381146246765) + tdSql.checkData(47, 0, 26) + tdSql.checkData(47, 1, 0.27090578830786904) + tdSql.checkData(47, 2, 0.6172306382193644) + tdSql.checkData(47, 3, 1.835550377607515) + tdSql.checkData(47, 4, None) + tdSql.checkData(47, 5, 0.11431954199291106) + tdSql.checkData(47, 6, 5.165381146246765) + tdSql.checkData(48, 0, 25) + tdSql.checkData(48, 1, 0.956375928404503) + tdSql.checkData(48, 2, 0.6628179613691831) + tdSql.checkData(48, 3, 3.4435632194258416) + tdSql.checkData(48, 4, None) + tdSql.checkData(48, 5, 0.05676687083562715) + tdSql.checkData(48, 6, 2.6040987392745354) + tdSql.checkData(49, 0, 25) + tdSql.checkData(49, 1, 0.956375928404503) + tdSql.checkData(49, 2, 0.6628179613691831) + tdSql.checkData(49, 3, 3.4435632194258416) + tdSql.checkData(49, 4, None) + tdSql.checkData(49, 5, 0.05676687083562715) + tdSql.checkData(49, 6, 2.6040987392745354) + tdSql.checkData(50, 0, 24) + tdSql.checkData(50, 1, 0.7625584504796027) + tdSql.checkData(50, 2, 0.999960827417674) + tdSql.checkData(50, 3, 1.2552318002593996) + tdSql.checkData(50, 4, None) + tdSql.checkData(50, 5, 0.6200983185456957) + tdSql.checkData(50, 6, 0.09684864095463253) + tdSql.checkData(51, 0, 24) + tdSql.checkData(51, 1, 0.7625584504796027) + tdSql.checkData(51, 2, 0.999960827417674) + tdSql.checkData(51, 3, 1.2552318002593996) + tdSql.checkData(51, 4, None) + tdSql.checkData(51, 5, 0.6200983185456957) + tdSql.checkData(51, 6, 0.09684864095463253) + tdSql.checkData(52, 0, 23) + tdSql.checkData(52, 1, -0.13235175009777303) + tdSql.checkData(52, 2, 0.6699494442536529) + tdSql.checkData(52, 3, 1.5387402975985367) + tdSql.checkData(52, 4, None) + tdSql.checkData(52, 5, 1.1825447904081037) + tdSql.checkData(52, 6, 5.489941431040083) + tdSql.checkData(53, 0, 23) + tdSql.checkData(53, 1, -0.13235175009777303) + tdSql.checkData(53, 2, 0.6699494442536529) + tdSql.checkData(53, 3, 1.5387402975985367) + tdSql.checkData(53, 4, None) + tdSql.checkData(53, 5, 1.1825447904081037) + tdSql.checkData(53, 6, 5.489941431040083) + tdSql.checkData(54, 0, 22) + tdSql.checkData(54, 1, -0.9055783620066239) + tdSql.checkData(54, 2, 0.6114178044194122) + tdSql.checkData(54, 3, 3.5568711064263105) + tdSql.checkData(54, 4, None) + tdSql.checkData(54, 5, 0.9837833410919679) + tdSql.checkData(54, 6, 3.0265535811470983) + tdSql.checkData(55, 0, 22) + tdSql.checkData(55, 1, -0.9055783620066239) + tdSql.checkData(55, 2, 0.6114178044194122) + tdSql.checkData(55, 3, 3.5568711064263105) + tdSql.checkData(55, 4, None) + tdSql.checkData(55, 5, 0.9837833410919679) + tdSql.checkData(55, 6, 3.0265535811470983) + tdSql.checkData(56, 0, 21) + tdSql.checkData(56, 1, -0.8462204041751706) + tdSql.checkData(56, 2, 0.9887894200405688) + tdSql.checkData(56, 3, 1.5772240911721418) + tdSql.checkData(56, 4, None) + tdSql.checkData(56, 5, -0.11647857397382422) + tdSql.checkData(56, 6, 0.5559799244477626) + tdSql.checkData(57, 0, 21) + tdSql.checkData(57, 1, -0.8462204041751706) + tdSql.checkData(57, 2, 0.9887894200405688) + tdSql.checkData(57, 3, 1.5772240911721418) + tdSql.checkData(57, 4, None) + tdSql.checkData(57, 5, -0.11647857397382422) + tdSql.checkData(57, 6, 0.5559799244477626) + tdSql.checkData(58, 0, 20) + tdSql.checkData(58, 1, -0.008851309290403876) + tdSql.checkData(58, 2, 0.7310155667453407) + tdSql.checkData(58, 3, 1.2127175951404974) + tdSql.checkData(58, 4, None) + tdSql.checkData(58, 5, -1.4304290589415767) + tdSql.checkData(58, 6, 5.982274104704091) + tdSql.checkData(59, 0, 20) + tdSql.checkData(59, 1, -0.008851309290403876) + tdSql.checkData(59, 2, 0.7310155667453407) + tdSql.checkData(59, 3, 1.2127175951404974) + tdSql.checkData(59, 4, None) + tdSql.checkData(59, 5, -1.4304290589415767) + tdSql.checkData(59, 6, 5.982274104704091) + tdSql.checkData(60, 0, 19) + tdSql.checkData(60, 1, 0.8366556385360561) + tdSql.checkData(60, 2, 0.5723746128431292) + tdSql.checkData(60, 3, 3.413484890511323) + tdSql.checkData(60, 4, None) + tdSql.checkData(60, 5, -1.9952541841757747) + tdSql.checkData(60, 6, 3.4479580493217856) + tdSql.checkData(61, 0, 19) + tdSql.checkData(61, 1, 0.8366556385360561) + tdSql.checkData(61, 2, 0.5723746128431292) + tdSql.checkData(61, 3, 3.413484890511323) + tdSql.checkData(61, 4, None) + tdSql.checkData(61, 5, -1.9952541841757747) + tdSql.checkData(61, 6, 3.4479580493217856) + tdSql.checkData(62, 0, 18) + tdSql.checkData(62, 1, 0.9129452507276277) + tdSql.checkData(62, 2, 0.9588413200803038) + tdSql.checkData(62, 3, 1.8713332491184997) + tdSql.checkData(62, 4, None) + tdSql.checkData(62, 5, -1.3983047743451864) + tdSql.checkData(62, 6, 0.8709074342191974) + tdSql.checkData(63, 0, 18) + tdSql.checkData(63, 1, 0.9129452507276277) + tdSql.checkData(63, 2, 0.9588413200803038) + tdSql.checkData(63, 3, 1.8713332491184997) + tdSql.checkData(63, 4, None) + tdSql.checkData(63, 5, -1.3983047743451864) + tdSql.checkData(63, 6, 0.8709074342191974) + tdSql.checkData(64, 0, 17) + tdSql.checkData(64, 1, 0.14987720966295234) + tdSql.checkData(64, 2, 0.7959095686227995) + tdSql.checkData(64, 3, 0.864944320724419) + tdSql.checkData(64, 4, None) + tdSql.checkData(64, 5, -0.13037289959062748) + tdSql.checkData(64, 6, 7.022998331594864) + tdSql.checkData(65, 0, 17) + tdSql.checkData(65, 1, 0.14987720966295234) + tdSql.checkData(65, 2, 0.7959095686227995) + tdSql.checkData(65, 3, 0.864944320724419) + tdSql.checkData(65, 4, None) + tdSql.checkData(65, 5, -0.13037289959062748) + tdSql.checkData(65, 6, 7.022998331594864) + tdSql.checkData(66, 0, 16) + tdSql.checkData(66, 1, -0.750987246771676) + tdSql.checkData(66, 2, 0.5481819942730298) + tdSql.checkData(66, 3, 3.102748784455539) + tdSql.checkData(66, 4, None) + tdSql.checkData(66, 5, 0.8513297604701857) + tdSql.checkData(66, 6, 3.852058923265594) + tdSql.checkData(67, 0, 16) + tdSql.checkData(67, 1, -0.750987246771676) + tdSql.checkData(67, 2, 0.5481819942730298) + tdSql.checkData(67, 3, 3.102748784455539) + tdSql.checkData(67, 4, None) + tdSql.checkData(67, 5, 0.8513297604701857) + tdSql.checkData(67, 6, 3.852058923265594) + tdSql.checkData(68, 0, 15) + tdSql.checkData(68, 1, -0.9613974918795568) + tdSql.checkData(68, 2, 0.9130208165623314) + tdSql.checkData(68, 3, 2.1554866011151765) + tdSql.checkData(68, 4, None) + tdSql.checkData(68, 5, 0.9521751875546269) + tdSql.checkData(68, 6, 1.1559749749986195) + tdSql.checkData(69, 0, 15) + tdSql.checkData(69, 1, -0.9613974918795568) + tdSql.checkData(69, 2, 0.9130208165623314) + tdSql.checkData(69, 3, 2.1554866011151765) + tdSql.checkData(69, 4, None) + tdSql.checkData(69, 5, 0.9521751875546269) + tdSql.checkData(69, 6, 1.1559749749986195) + tdSql.checkData(70, 0, 14) + tdSql.checkData(70, 1, -0.2879033166650653) + tdSql.checkData(70, 2, 0.859465627274523) + tdSql.checkData(70, 3, 0.5636905248139659) + tdSql.checkData(70, 4, None) + tdSql.checkData(70, 5, 0.41142163587369207) + tdSql.checkData(70, 6, 10.515512404402676) + tdSql.checkData(71, 0, 14) + tdSql.checkData(71, 1, -0.2879033166650653) + tdSql.checkData(71, 2, 0.859465627274523) + tdSql.checkData(71, 3, 0.5636905248139659) + tdSql.checkData(71, 4, None) + tdSql.checkData(71, 5, 0.41142163587369207) + tdSql.checkData(71, 6, 10.515512404402676) + tdSql.checkData(72, 0, 13) + tdSql.checkData(72, 1, 0.6502878401571168) + tdSql.checkData(72, 2, 0.5403105467456532) + tdSql.checkData(72, 3, 2.75535470715349) + tdSql.checkData(72, 4, None) + tdSql.checkData(72, 5, 0.0009616202598659029) + tdSql.checkData(72, 6, 4.225579583416092) + tdSql.checkData(73, 0, 13) + tdSql.checkData(73, 1, 0.6502878401571168) + tdSql.checkData(73, 2, 0.5403105467456532) + tdSql.checkData(73, 3, 2.75535470715349) + tdSql.checkData(73, 4, None) + tdSql.checkData(73, 5, 0.0009616202598659029) + tdSql.checkData(73, 6, 4.225579583416092) + tdSql.checkData(74, 0, 12) + tdSql.checkData(74, 1, 0.9906073556948704) + tdSql.checkData(74, 2, 0.8556343548213666) + tdSql.checkData(74, 3, 2.451594361777497) + tdSql.checkData(74, 4, None) + tdSql.checkData(74, 5, 0.24838494428124291) + tdSql.checkData(74, 6, 1.4585617093317953) + tdSql.checkData(75, 0, 12) + tdSql.checkData(75, 1, 0.9906073556948704) + tdSql.checkData(75, 2, 0.8556343548213666) + tdSql.checkData(75, 3, 2.451594361777497) + tdSql.checkData(75, 4, None) + tdSql.checkData(75, 5, 0.24838494428124291) + tdSql.checkData(75, 6, 1.4585617093317953) + tdSql.checkData(76, 0, 11) + tdSql.checkData(76, 1, 0.4201670368266409) + tdSql.checkData(76, 2, 0.9162743174606308) + tdSql.checkData(76, 3, 0.44272645708128566) + tdSql.checkData(76, 4, None) + tdSql.checkData(76, 5, 0.9151372562290566) + tdSql.checkData(76, 6, -222.95969776348554) + tdSql.checkData(77, 0, 11) + tdSql.checkData(77, 1, 0.4201670368266409) + tdSql.checkData(77, 2, 0.9162743174606308) + tdSql.checkData(77, 3, 0.44272645708128566) + tdSql.checkData(77, 4, None) + tdSql.checkData(77, 5, 0.9151372562290566) + tdSql.checkData(77, 6, -222.95969776348554) + tdSql.checkData(78, 0, 10) + tdSql.checkData(78, 1, -0.5365729180004349) + tdSql.checkData(78, 2, 0.549226270051226) + tdSql.checkData(78, 3, 2.432352856101439) + tdSql.checkData(78, 4, None) + tdSql.checkData(78, 5, 1.2185572409879093) + tdSql.checkData(78, 6, 4.561306078186714) + tdSql.checkData(79, 0, 10) + tdSql.checkData(79, 1, -0.5365729180004349) + tdSql.checkData(79, 2, 0.549226270051226) + tdSql.checkData(79, 3, 2.432352856101439) + tdSql.checkData(79, 4, None) + tdSql.checkData(79, 5, 1.2185572409879093) + tdSql.checkData(79, 6, 4.561306078186714) + tdSql.checkData(80, 0, 9) + tdSql.checkData(80, 1, -0.9999902065507035) + tdSql.checkData(80, 2, 0.7918362090144786) + tdSql.checkData(80, 3, 2.776612511546888) + tdSql.checkData(80, 4, None) + tdSql.checkData(80, 5, 0.5929886271208413) + tdSql.checkData(80, 6, 1.796697093786514) + tdSql.checkData(81, 0, 9) + tdSql.checkData(81, 1, -0.9999902065507035) + tdSql.checkData(81, 2, 0.7918362090144786) + tdSql.checkData(81, 3, 2.776612511546888) + tdSql.checkData(81, 4, None) + tdSql.checkData(81, 5, 0.5929886271208413) + tdSql.checkData(81, 6, 1.796697093786514) + tdSql.checkData(82, 0, 8) + tdSql.checkData(82, 1, -0.5440211108893698) + tdSql.checkData(82, 2, 0.9612168045072789) + tdSql.checkData(82, 3, 0.5787344727995947) + tdSql.checkData(82, 4, None) + tdSql.checkData(82, 5, -0.7199655182148126) + tdSql.checkData(82, 6, -4.087614771885445) + tdSql.checkData(83, 0, 8) + tdSql.checkData(83, 1, -0.5440211108893698) + tdSql.checkData(83, 2, 0.9612168045072789) + tdSql.checkData(83, 3, 0.5787344727995947) + tdSql.checkData(83, 4, None) + tdSql.checkData(83, 5, -0.7199655182148126) + tdSql.checkData(83, 6, -4.087614771885445) + tdSql.checkData(84, 0, 7) + tdSql.checkData(84, 1, 0.4121184852417566) + tdSql.checkData(84, 2, 0.574400879193934) + tdSql.checkData(84, 3, 2.137595835197328) + tdSql.checkData(84, 4, None) + tdSql.checkData(84, 5, -1.8119088619792247) + tdSql.checkData(84, 6, 4.862055338419189) + tdSql.checkData(85, 0, 7) + tdSql.checkData(85, 1, 0.4121184852417566) + tdSql.checkData(85, 2, 0.574400879193934) + tdSql.checkData(85, 3, 2.137595835197328) + tdSql.checkData(85, 4, None) + tdSql.checkData(85, 5, -1.8119088619792247) + tdSql.checkData(85, 6, 4.862055338419189) + tdSql.checkData(86, 0, 6) + tdSql.checkData(86, 1, 0.9893582466233818) + tdSql.checkData(86, 2, 0.7270351311688125) + tdSql.checkData(86, 3, 3.1243204798042576) + tdSql.checkData(86, 4, None) + tdSql.checkData(86, 5, -1.8696882565721156) + tdSql.checkData(86, 6, 2.172420890614816) + tdSql.checkData(87, 0, 6) + tdSql.checkData(87, 1, 0.9893582466233818) + tdSql.checkData(87, 2, 0.7270351311688125) + tdSql.checkData(87, 3, 3.1243204798042576) + tdSql.checkData(87, 4, None) + tdSql.checkData(87, 5, -1.8696882565721156) + tdSql.checkData(87, 6, 2.172420890614816) + tdSql.checkData(88, 0, 5) + tdSql.checkData(88, 1, 0.6569865987187891) + tdSql.checkData(88, 2, 0.9900590857598653) + tdSql.checkData(88, 3, 0.8864495743441427) + tdSql.checkData(88, 4, None) + tdSql.checkData(88, 5, -0.876294736008743) + tdSql.checkData(88, 6, -0.9245361171359558) + tdSql.checkData(89, 0, 5) + tdSql.checkData(89, 1, 0.6569865987187891) + tdSql.checkData(89, 2, 0.9900590857598653) + tdSql.checkData(89, 3, 0.8864495743441427) + tdSql.checkData(89, 4, None) + tdSql.checkData(89, 5, -0.876294736008743) + tdSql.checkData(89, 6, -0.9245361171359558) + tdSql.checkData(90, 0, 4) + tdSql.checkData(90, 1, -0.27941549819892586) + tdSql.checkData(90, 2, 0.6143002821164822) + tdSql.checkData(90, 3, 1.853464438509776) + tdSql.checkData(90, 4, None) + tdSql.checkData(90, 5, 0.38234027607634785) + tdSql.checkData(90, 6, 5.147179528972959) + tdSql.checkData(91, 0, 4) + tdSql.checkData(91, 1, -0.27941549819892586) + tdSql.checkData(91, 2, 0.6143002821164822) + tdSql.checkData(91, 3, 1.853464438509776) + tdSql.checkData(91, 4, None) + tdSql.checkData(91, 5, 0.38234027607634785) + tdSql.checkData(91, 6, 5.147179528972959) + tdSql.checkData(92, 0, 3) + tdSql.checkData(92, 1, -0.9589242746631385) + tdSql.checkData(92, 2, 0.6663667453928805) + tdSql.checkData(92, 3, 3.4288753232277074) + tdSql.checkData(92, 4, None) + tdSql.checkData(92, 5, 1.0087371784424417) + tdSql.checkData(92, 6, 2.5780379587267963) + tdSql.checkData(93, 0, 3) + tdSql.checkData(93, 1, -0.9589242746631385) + tdSql.checkData(93, 2, 0.6663667453928805) + tdSql.checkData(93, 3, 3.4288753232277074) + tdSql.checkData(93, 4, None) + tdSql.checkData(93, 5, 1.0087371784424417) + tdSql.checkData(93, 6, 2.5780379587267963) + tdSql.checkData(94, 0, 2) + tdSql.checkData(94, 1, -0.7568024953079282) + tdSql.checkData(94, 2, 1.0) + tdSql.checkData(94, 3, 1.2340302976078754) + tdSql.checkData(94, 4, None) + tdSql.checkData(94, 5, 0.7554222939559553) + tdSql.checkData(94, 6, 0.05815764143055291) + tdSql.checkData(95, 0, 2) + tdSql.checkData(95, 1, -0.7568024953079282) + tdSql.checkData(95, 2, 1.0) + tdSql.checkData(95, 3, 1.2340302976078754) + tdSql.checkData(95, 4, None) + tdSql.checkData(95, 5, 0.7554222939559553) + tdSql.checkData(95, 6, 0.05815764143055291) + tdSql.checkData(96, 0, 1) + tdSql.checkData(96, 1, 0.1411200080598672) + tdSql.checkData(96, 2, 0.6663667453928805) + tdSql.checkData(96, 3, 1.558041126155035) + tdSql.checkData(96, 4, 1.8325957145940461) + tdSql.checkData(96, 5, 0.17204223631998083) + tdSql.checkData(96, 6, None) + tdSql.checkData(97, 0, 1) + tdSql.checkData(97, 1, 0.1411200080598672) + tdSql.checkData(97, 2, 0.6663667453928805) + tdSql.checkData(97, 3, 1.558041126155035) + tdSql.checkData(97, 4, 1.8325957145940461) + tdSql.checkData(97, 5, 0.17204223631998083) + tdSql.checkData(97, 6, None) + tdSql.checkData(98, 0, 0) + tdSql.checkData(98, 1, 0.7780731968879212) + tdSql.checkData(98, 2, 0.6143002821164822) + tdSql.checkData(98, 3, 3.2037266279837113) + tdSql.checkData(98, 4, None) + tdSql.checkData(98, 5, 0.02246988233490299) + tdSql.checkData(98, 6, None) + tdSql.checkData(99, 0, 0) + tdSql.checkData(99, 1, 0.7780731968879212) + tdSql.checkData(99, 2, 0.6143002821164822) + tdSql.checkData(99, 3, 3.2037266279837113) + tdSql.checkData(99, 4, None) + tdSql.checkData(99, 5, 0.02246988233490299) + tdSql.checkData(99, 6, None) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 );') + tdSql.checkRows(100) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.7780731968879212) + tdSql.checkData(0, 2, 0.6143002821164822) + tdSql.checkData(0, 3, 3.2037266279837113) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.02246988233490299) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.1411200080598672) + tdSql.checkData(1, 2, 0.6663667453928805) + tdSql.checkData(1, 3, 1.558041126155035) + tdSql.checkData(1, 4, 1.8325957145940461) + tdSql.checkData(1, 5, 0.17204223631998083) + tdSql.checkData(1, 6, None) + tdSql.checkData(2, 0, 2) + tdSql.checkData(2, 1, -0.7568024953079282) + tdSql.checkData(2, 2, 1.0) + tdSql.checkData(2, 3, 1.2340302976078754) + tdSql.checkData(2, 4, None) + tdSql.checkData(2, 5, 0.7554222939559553) + tdSql.checkData(2, 6, 0.05815764143055291) + tdSql.checkData(3, 0, 3) + tdSql.checkData(3, 1, -0.9589242746631385) + tdSql.checkData(3, 2, 0.6663667453928805) + tdSql.checkData(3, 3, 3.4288753232277074) + tdSql.checkData(3, 4, None) + tdSql.checkData(3, 5, 1.0087371784424417) + tdSql.checkData(3, 6, 2.5780379587267963) + tdSql.checkData(4, 0, 4) + tdSql.checkData(4, 1, -0.27941549819892586) + tdSql.checkData(4, 2, 0.6143002821164822) + tdSql.checkData(4, 3, 1.853464438509776) + tdSql.checkData(4, 4, None) + tdSql.checkData(4, 5, 0.38234027607634785) + tdSql.checkData(4, 6, 5.147179528972959) + tdSql.checkData(5, 0, 5) + tdSql.checkData(5, 1, 0.6569865987187891) + tdSql.checkData(5, 2, 0.9900590857598653) + tdSql.checkData(5, 3, 0.8864495743441427) + tdSql.checkData(5, 4, None) + tdSql.checkData(5, 5, -0.876294736008743) + tdSql.checkData(5, 6, -0.9245361171359558) + tdSql.checkData(6, 0, 6) + tdSql.checkData(6, 1, 0.9893582466233818) + tdSql.checkData(6, 2, 0.7270351311688125) + tdSql.checkData(6, 3, 3.1243204798042576) + tdSql.checkData(6, 4, None) + tdSql.checkData(6, 5, -1.8696882565721156) + tdSql.checkData(6, 6, 2.172420890614816) + tdSql.checkData(7, 0, 7) + tdSql.checkData(7, 1, 0.4121184852417566) + tdSql.checkData(7, 2, 0.574400879193934) + tdSql.checkData(7, 3, 2.137595835197328) + tdSql.checkData(7, 4, None) + tdSql.checkData(7, 5, -1.8119088619792247) + tdSql.checkData(7, 6, 4.862055338419189) + tdSql.checkData(8, 0, 8) + tdSql.checkData(8, 1, -0.5440211108893698) + tdSql.checkData(8, 2, 0.9612168045072789) + tdSql.checkData(8, 3, 0.5787344727995947) + tdSql.checkData(8, 4, None) + tdSql.checkData(8, 5, -0.7199655182148126) + tdSql.checkData(8, 6, -4.087614771885445) + tdSql.checkData(9, 0, 9) + tdSql.checkData(9, 1, -0.9999902065507035) + tdSql.checkData(9, 2, 0.7918362090144786) + tdSql.checkData(9, 3, 2.776612511546888) + tdSql.checkData(9, 4, None) + tdSql.checkData(9, 5, 0.5929886271208413) + tdSql.checkData(9, 6, 1.796697093786514) + tdSql.checkData(10, 0, 10) + tdSql.checkData(10, 1, -0.5365729180004349) + tdSql.checkData(10, 2, 0.549226270051226) + tdSql.checkData(10, 3, 2.432352856101439) + tdSql.checkData(10, 4, None) + tdSql.checkData(10, 5, 1.2185572409879093) + tdSql.checkData(10, 6, 4.561306078186714) + tdSql.checkData(11, 0, 11) + tdSql.checkData(11, 1, 0.4201670368266409) + tdSql.checkData(11, 2, 0.9162743174606308) + tdSql.checkData(11, 3, 0.44272645708128566) + tdSql.checkData(11, 4, None) + tdSql.checkData(11, 5, 0.9151372562290566) + tdSql.checkData(11, 6, -222.95969776348554) + tdSql.checkData(12, 0, 12) + tdSql.checkData(12, 1, 0.9906073556948704) + tdSql.checkData(12, 2, 0.8556343548213666) + tdSql.checkData(12, 3, 2.451594361777497) + tdSql.checkData(12, 4, None) + tdSql.checkData(12, 5, 0.24838494428124291) + tdSql.checkData(12, 6, 1.4585617093317953) + tdSql.checkData(13, 0, 13) + tdSql.checkData(13, 1, 0.6502878401571168) + tdSql.checkData(13, 2, 0.5403105467456532) + tdSql.checkData(13, 3, 2.75535470715349) + tdSql.checkData(13, 4, None) + tdSql.checkData(13, 5, 0.0009616202598659029) + tdSql.checkData(13, 6, 4.225579583416092) + tdSql.checkData(14, 0, 14) + tdSql.checkData(14, 1, -0.2879033166650653) + tdSql.checkData(14, 2, 0.859465627274523) + tdSql.checkData(14, 3, 0.5636905248139659) + tdSql.checkData(14, 4, None) + tdSql.checkData(14, 5, 0.41142163587369207) + tdSql.checkData(14, 6, 10.515512404402676) + tdSql.checkData(15, 0, 15) + tdSql.checkData(15, 1, -0.9613974918795568) + tdSql.checkData(15, 2, 0.9130208165623314) + tdSql.checkData(15, 3, 2.1554866011151765) + tdSql.checkData(15, 4, None) + tdSql.checkData(15, 5, 0.9521751875546269) + tdSql.checkData(15, 6, 1.1559749749986195) + tdSql.checkData(16, 0, 16) + tdSql.checkData(16, 1, -0.750987246771676) + tdSql.checkData(16, 2, 0.5481819942730298) + tdSql.checkData(16, 3, 3.102748784455539) + tdSql.checkData(16, 4, None) + tdSql.checkData(16, 5, 0.8513297604701857) + tdSql.checkData(16, 6, 3.852058923265594) + tdSql.checkData(17, 0, 17) + tdSql.checkData(17, 1, 0.14987720966295234) + tdSql.checkData(17, 2, 0.7959095686227995) + tdSql.checkData(17, 3, 0.864944320724419) + tdSql.checkData(17, 4, None) + tdSql.checkData(17, 5, -0.13037289959062748) + tdSql.checkData(17, 6, 7.022998331594864) + tdSql.checkData(18, 0, 18) + tdSql.checkData(18, 1, 0.9129452507276277) + tdSql.checkData(18, 2, 0.9588413200803038) + tdSql.checkData(18, 3, 1.8713332491184997) + tdSql.checkData(18, 4, None) + tdSql.checkData(18, 5, -1.3983047743451864) + tdSql.checkData(18, 6, 0.8709074342191974) + tdSql.checkData(19, 0, 19) + tdSql.checkData(19, 1, 0.8366556385360561) + tdSql.checkData(19, 2, 0.5723746128431292) + tdSql.checkData(19, 3, 3.413484890511323) + tdSql.checkData(19, 4, None) + tdSql.checkData(19, 5, -1.9952541841757747) + tdSql.checkData(19, 6, 3.4479580493217856) + tdSql.checkData(20, 0, 20) + tdSql.checkData(20, 1, -0.008851309290403876) + tdSql.checkData(20, 2, 0.7310155667453407) + tdSql.checkData(20, 3, 1.2127175951404974) + tdSql.checkData(20, 4, None) + tdSql.checkData(20, 5, -1.4304290589415767) + tdSql.checkData(20, 6, 5.982274104704091) + tdSql.checkData(21, 0, 21) + tdSql.checkData(21, 1, -0.8462204041751706) + tdSql.checkData(21, 2, 0.9887894200405688) + tdSql.checkData(21, 3, 1.5772240911721418) + tdSql.checkData(21, 4, None) + tdSql.checkData(21, 5, -0.11647857397382422) + tdSql.checkData(21, 6, 0.5559799244477626) + tdSql.checkData(22, 0, 22) + tdSql.checkData(22, 1, -0.9055783620066239) + tdSql.checkData(22, 2, 0.6114178044194122) + tdSql.checkData(22, 3, 3.5568711064263105) + tdSql.checkData(22, 4, None) + tdSql.checkData(22, 5, 0.9837833410919679) + tdSql.checkData(22, 6, 3.0265535811470983) + tdSql.checkData(23, 0, 23) + tdSql.checkData(23, 1, -0.13235175009777303) + tdSql.checkData(23, 2, 0.6699494442536529) + tdSql.checkData(23, 3, 1.5387402975985367) + tdSql.checkData(23, 4, None) + tdSql.checkData(23, 5, 1.1825447904081037) + tdSql.checkData(23, 6, 5.489941431040083) + tdSql.checkData(24, 0, 24) + tdSql.checkData(24, 1, 0.7625584504796027) + tdSql.checkData(24, 2, 0.999960827417674) + tdSql.checkData(24, 3, 1.2552318002593996) + tdSql.checkData(24, 4, None) + tdSql.checkData(24, 5, 0.6200983185456957) + tdSql.checkData(24, 6, 0.09684864095463253) + tdSql.checkData(25, 0, 25) + tdSql.checkData(25, 1, 0.956375928404503) + tdSql.checkData(25, 2, 0.6628179613691831) + tdSql.checkData(25, 3, 3.4435632194258416) + tdSql.checkData(25, 4, None) + tdSql.checkData(25, 5, 0.05676687083562715) + tdSql.checkData(25, 6, 2.6040987392745354) + tdSql.checkData(26, 0, 26) + tdSql.checkData(26, 1, 0.27090578830786904) + tdSql.checkData(26, 2, 0.6172306382193644) + tdSql.checkData(26, 3, 1.835550377607515) + tdSql.checkData(26, 4, None) + tdSql.checkData(26, 5, 0.11431954199291106) + tdSql.checkData(26, 6, 5.165381146246765) + tdSql.checkData(27, 0, 27) + tdSql.checkData(27, 1, -0.6636338842129675) + tdSql.checkData(27, 2, 0.9912542848596704) + tdSql.checkData(27, 3, 0.9080812682077812) + tdSql.checkData(27, 4, None) + tdSql.checkData(27, 5, 0.6788951190016388) + tdSql.checkData(27, 6, -0.8324928492797357) + tdSql.checkData(28, 0, 28) + tdSql.checkData(28, 1, -0.9880316240928618) + tdSql.checkData(28, 2, 0.7230710689951642) + tdSql.checkData(28, 3, 3.1457526648156393) + tdSql.checkData(28, 4, None) + tdSql.checkData(28, 5, 1.0206076417536643) + tdSql.checkData(28, 6, 2.197019393348823) + tdSql.checkData(29, 0, 29) + tdSql.checkData(29, 1, -0.404037645323065) + tdSql.checkData(29, 2, 0.5764850221962442) + tdSql.checkData(29, 3, 2.1197476343754156) + tdSql.checkData(29, 4, None) + tdSql.checkData(29, 5, 0.5162157333804713) + tdSql.checkData(29, 6, 4.8800154918827525) + tdSql.checkData(30, 0, 30) + tdSql.checkData(30, 1, 0.5514266812416906) + tdSql.checkData(30, 2, 0.9635288988181601) + tdSql.checkData(30, 3, 0.5944617511422015) + tdSql.checkData(30, 4, None) + tdSql.checkData(30, 5, -0.7022004347538967) + tdSql.checkData(30, 6, -3.710141817748492) + tdSql.checkData(31, 0, 31) + tdSql.checkData(31, 1, 0.9999118601072672) + tdSql.checkData(31, 2, 0.7877590247885756) + tdSql.checkData(31, 3, 2.7979785951133604) + tdSql.checkData(31, 4, None) + tdSql.checkData(31, 5, -1.7874722290307907) + tdSql.checkData(31, 6, 1.8191237353300793) + tdSql.checkData(32, 0, 32) + tdSql.checkData(32, 1, 0.5290826861200238) + tdSql.checkData(32, 2, 0.5503344099628432) + tdSql.checkData(32, 3, 2.413227615833899) + tdSql.checkData(32, 4, None) + tdSql.checkData(32, 5, -1.8893763681780902) + tdSql.checkData(32, 6, 4.581032079680554) + tdSql.checkData(33, 0, 33) + tdSql.checkData(33, 1, -0.428182669496151) + tdSql.checkData(33, 2, 0.9194811573015673) + tdSql.checkData(33, 3, 0.4437992589174107) + tdSql.checkData(33, 4, None) + tdSql.checkData(33, 5, -0.9001958571391758) + tdSql.checkData(33, 6, -72.33956595410905) + tdSql.checkData(34, 0, 34) + tdSql.checkData(34, 1, -0.9917788534431158) + tdSql.checkData(34, 2, 0.8517779466253769) + tdSql.checkData(34, 3, 2.470955260231499) + tdSql.checkData(34, 4, None) + tdSql.checkData(34, 5, 0.4428112547200472) + tdSql.checkData(34, 6, 1.4785733565944832) + tdSql.checkData(35, 0, 35) + tdSql.checkData(35, 1, -0.6435381333569995) + tdSql.checkData(35, 2, 0.5403764709316752) + tdSql.checkData(35, 3, 2.734210799811235) + tdSql.checkData(35, 4, None) + tdSql.checkData(35, 5, 1.1930854189064375) + tdSql.checkData(35, 6, 4.24770540197234) + tdSql.checkData(36, 0, 36) + tdSql.checkData(36, 1, 0.2963685787093853) + tdSql.checkData(36, 2, 0.8632704401895588) + tdSql.checkData(36, 3, 0.5493681603601657) + tdSql.checkData(36, 4, None) + tdSql.checkData(36, 5, 0.9944678850925007) + tdSql.checkData(36, 6, 11.004294268461184) + tdSql.checkData(37, 0, 37) + tdSql.checkData(37, 1, 0.9637953862840878) + tdSql.checkData(37, 2, 0.909721840267583) + tdSql.checkData(37, 3, 2.1734252903776303) + tdSql.checkData(37, 4, None) + tdSql.checkData(37, 5, 0.32696474077278626) + tdSql.checkData(37, 6, 1.174082484128993) + tdSql.checkData(38, 0, 38) + tdSql.checkData(38, 1, 0.7451131604793488) + tdSql.checkData(38, 2, 0.5472018255605284) + tdSql.checkData(38, 3, 3.081063350979351) + tdSql.checkData(38, 4, None) + tdSql.checkData(38, 5, -0.007381884932924798) + tdSql.checkData(38, 6, 3.8764172978929814) + tdSql.checkData(39, 0, 39) + tdSql.checkData(39, 1, -0.158622668804709) + tdSql.checkData(39, 2, 0.7999777847134487) + tdSql.checkData(39, 3, 0.8435920138756074) + tdSql.checkData(39, 4, None) + tdSql.checkData(39, 5, 0.3319994538301167) + tdSql.checkData(39, 6, 7.12853286308907) + tdSql.checkData(40, 0, 40) + tdSql.checkData(40, 1, -0.9165215479156338) + tdSql.checkData(40, 2, 0.9564033460276342) + tdSql.checkData(40, 3, 1.889162191085516) + tdSql.checkData(40, 4, None) + tdSql.checkData(40, 5, 0.90296737936602) + tdSql.checkData(40, 6, 0.888896415152729) + tdSql.checkData(41, 0, 41) + tdSql.checkData(41, 1, -0.8317747426285983) + tdSql.checkData(41, 2, 0.5704067143341829) + tdSql.checkData(41, 3, 3.397430462894578) + tdSql.checkData(41, 4, None) + tdSql.checkData(41, 5, 0.9190273051332304) + tdSql.checkData(41, 6, 3.473885481113728) + tdSql.checkData(42, 0, 42) + tdSql.checkData(42, 1, 0.017701925105413577) + tdSql.checkData(42, 2, 0.7350111780599404) + tdSql.checkData(42, 3, 1.1912997639866574) + tdSql.checkData(42, 4, None) + tdSql.checkData(42, 5, 0.036467324189017214) + tdSql.checkData(42, 6, 6.024578312510778) + tdSql.checkData(43, 0, 43) + tdSql.checkData(43, 1, 0.8509035245341184) + tdSql.checkData(43, 2, 0.9874457808369176) + tdSql.checkData(43, 3, 1.5962924548219202) + tdSql.checkData(43, 4, None) + tdSql.checkData(43, 5, -1.2490970766755156) + tdSql.checkData(43, 6, 0.5781542141407696) + tdSql.checkData(44, 0, 44) + tdSql.checkData(44, 1, 0.9017883476488092) + tdSql.checkData(44, 2, 0.6085839480802863) + tdSql.checkData(44, 3, 3.5552629892514687) + tdSql.checkData(44, 4, None) + tdSql.checkData(44, 5, -1.9810692649977342) + tdSql.checkData(44, 6, 3.0531030020123464) + tdSql.checkData(45, 0, 45) + tdSql.checkData(45, 1, 0.123573122745224) + tdSql.checkData(45, 2, 0.6735650596658175) + tdSql.checkData(45, 3, 1.5193186190030223) + tdSql.checkData(45, 4, None) + tdSql.checkData(45, 5, -1.5661895943272113) + tdSql.checkData(45, 6, 5.513771854144419) + tdSql.checkData(46, 0, 46) + tdSql.checkData(46, 1, -0.7682546613236668) + tdSql.checkData(46, 2, 0.9998433250151273) + tdSql.checkData(46, 3, 1.2763169256468458) + tdSql.checkData(46, 4, None) + tdSql.checkData(46, 5, -0.300459258677913) + tdSql.checkData(46, 6, 0.13392039926281352) + tdSql.checkData(47, 0, 47) + tdSql.checkData(47, 1, -0.9537526527594719) + tdSql.checkData(47, 2, 0.6593040763085178) + tdSql.checkData(47, 3, 3.4575106745458637) + tdSql.checkData(47, 4, None) + tdSql.checkData(47, 5, 0.8820838187306987) + tdSql.checkData(47, 6, 2.6302204463996084) + tdSql.checkData(48, 0, 48) + tdSql.checkData(48, 1, -0.26237485370392877) + tdSql.checkData(48, 2, 0.6202081141679935) + tdSql.checkData(48, 3, 1.8175857333771335) + tdSql.checkData(48, 4, None) + tdSql.checkData(48, 5, 1.211884234321115) + tdSql.checkData(48, 6, 5.183714988550632) + tdSql.checkData(49, 0, 49) + tdSql.checkData(49, 1, 0.6702291758433747) + tdSql.checkData(49, 2, 0.9923745526637894) + tdSql.checkData(49, 3, 0.9298143670243166) + tdSql.checkData(49, 4, None) + tdSql.checkData(49, 5, 0.7136182821549459) + tdSql.checkData(49, 6, -0.7462904241496138) + tdSql.checkData(50, 0, 0) + tdSql.checkData(50, 1, 0.7780731968879212) + tdSql.checkData(50, 2, 0.6143002821164822) + tdSql.checkData(50, 3, 3.2037266279837113) + tdSql.checkData(50, 4, None) + tdSql.checkData(50, 5, 0.02246988233490299) + tdSql.checkData(50, 6, None) + tdSql.checkData(51, 0, 1) + tdSql.checkData(51, 1, 0.1411200080598672) + tdSql.checkData(51, 2, 0.6663667453928805) + tdSql.checkData(51, 3, 1.558041126155035) + tdSql.checkData(51, 4, 1.8325957145940461) + tdSql.checkData(51, 5, 0.17204223631998083) + tdSql.checkData(51, 6, None) + tdSql.checkData(52, 0, 2) + tdSql.checkData(52, 1, -0.7568024953079282) + tdSql.checkData(52, 2, 1.0) + tdSql.checkData(52, 3, 1.2340302976078754) + tdSql.checkData(52, 4, None) + tdSql.checkData(52, 5, 0.7554222939559553) + tdSql.checkData(52, 6, 0.05815764143055291) + tdSql.checkData(53, 0, 3) + tdSql.checkData(53, 1, -0.9589242746631385) + tdSql.checkData(53, 2, 0.6663667453928805) + tdSql.checkData(53, 3, 3.4288753232277074) + tdSql.checkData(53, 4, None) + tdSql.checkData(53, 5, 1.0087371784424417) + tdSql.checkData(53, 6, 2.5780379587267963) + tdSql.checkData(54, 0, 4) + tdSql.checkData(54, 1, -0.27941549819892586) + tdSql.checkData(54, 2, 0.6143002821164822) + tdSql.checkData(54, 3, 1.853464438509776) + tdSql.checkData(54, 4, None) + tdSql.checkData(54, 5, 0.38234027607634785) + tdSql.checkData(54, 6, 5.147179528972959) + tdSql.checkData(55, 0, 5) + tdSql.checkData(55, 1, 0.6569865987187891) + tdSql.checkData(55, 2, 0.9900590857598653) + tdSql.checkData(55, 3, 0.8864495743441427) + tdSql.checkData(55, 4, None) + tdSql.checkData(55, 5, -0.876294736008743) + tdSql.checkData(55, 6, -0.9245361171359558) + tdSql.checkData(56, 0, 6) + tdSql.checkData(56, 1, 0.9893582466233818) + tdSql.checkData(56, 2, 0.7270351311688125) + tdSql.checkData(56, 3, 3.1243204798042576) + tdSql.checkData(56, 4, None) + tdSql.checkData(56, 5, -1.8696882565721156) + tdSql.checkData(56, 6, 2.172420890614816) + tdSql.checkData(57, 0, 7) + tdSql.checkData(57, 1, 0.4121184852417566) + tdSql.checkData(57, 2, 0.574400879193934) + tdSql.checkData(57, 3, 2.137595835197328) + tdSql.checkData(57, 4, None) + tdSql.checkData(57, 5, -1.8119088619792247) + tdSql.checkData(57, 6, 4.862055338419189) + tdSql.checkData(58, 0, 8) + tdSql.checkData(58, 1, -0.5440211108893698) + tdSql.checkData(58, 2, 0.9612168045072789) + tdSql.checkData(58, 3, 0.5787344727995947) + tdSql.checkData(58, 4, None) + tdSql.checkData(58, 5, -0.7199655182148126) + tdSql.checkData(58, 6, -4.087614771885445) + tdSql.checkData(59, 0, 9) + tdSql.checkData(59, 1, -0.9999902065507035) + tdSql.checkData(59, 2, 0.7918362090144786) + tdSql.checkData(59, 3, 2.776612511546888) + tdSql.checkData(59, 4, None) + tdSql.checkData(59, 5, 0.5929886271208413) + tdSql.checkData(59, 6, 1.796697093786514) + tdSql.checkData(60, 0, 10) + tdSql.checkData(60, 1, -0.5365729180004349) + tdSql.checkData(60, 2, 0.549226270051226) + tdSql.checkData(60, 3, 2.432352856101439) + tdSql.checkData(60, 4, None) + tdSql.checkData(60, 5, 1.2185572409879093) + tdSql.checkData(60, 6, 4.561306078186714) + tdSql.checkData(61, 0, 11) + tdSql.checkData(61, 1, 0.4201670368266409) + tdSql.checkData(61, 2, 0.9162743174606308) + tdSql.checkData(61, 3, 0.44272645708128566) + tdSql.checkData(61, 4, None) + tdSql.checkData(61, 5, 0.9151372562290566) + tdSql.checkData(61, 6, -222.95969776348554) + tdSql.checkData(62, 0, 12) + tdSql.checkData(62, 1, 0.9906073556948704) + tdSql.checkData(62, 2, 0.8556343548213666) + tdSql.checkData(62, 3, 2.451594361777497) + tdSql.checkData(62, 4, None) + tdSql.checkData(62, 5, 0.24838494428124291) + tdSql.checkData(62, 6, 1.4585617093317953) + tdSql.checkData(63, 0, 13) + tdSql.checkData(63, 1, 0.6502878401571168) + tdSql.checkData(63, 2, 0.5403105467456532) + tdSql.checkData(63, 3, 2.75535470715349) + tdSql.checkData(63, 4, None) + tdSql.checkData(63, 5, 0.0009616202598659029) + tdSql.checkData(63, 6, 4.225579583416092) + tdSql.checkData(64, 0, 14) + tdSql.checkData(64, 1, -0.2879033166650653) + tdSql.checkData(64, 2, 0.859465627274523) + tdSql.checkData(64, 3, 0.5636905248139659) + tdSql.checkData(64, 4, None) + tdSql.checkData(64, 5, 0.41142163587369207) + tdSql.checkData(64, 6, 10.515512404402676) + tdSql.checkData(65, 0, 15) + tdSql.checkData(65, 1, -0.9613974918795568) + tdSql.checkData(65, 2, 0.9130208165623314) + tdSql.checkData(65, 3, 2.1554866011151765) + tdSql.checkData(65, 4, None) + tdSql.checkData(65, 5, 0.9521751875546269) + tdSql.checkData(65, 6, 1.1559749749986195) + tdSql.checkData(66, 0, 16) + tdSql.checkData(66, 1, -0.750987246771676) + tdSql.checkData(66, 2, 0.5481819942730298) + tdSql.checkData(66, 3, 3.102748784455539) + tdSql.checkData(66, 4, None) + tdSql.checkData(66, 5, 0.8513297604701857) + tdSql.checkData(66, 6, 3.852058923265594) + tdSql.checkData(67, 0, 17) + tdSql.checkData(67, 1, 0.14987720966295234) + tdSql.checkData(67, 2, 0.7959095686227995) + tdSql.checkData(67, 3, 0.864944320724419) + tdSql.checkData(67, 4, None) + tdSql.checkData(67, 5, -0.13037289959062748) + tdSql.checkData(67, 6, 7.022998331594864) + tdSql.checkData(68, 0, 18) + tdSql.checkData(68, 1, 0.9129452507276277) + tdSql.checkData(68, 2, 0.9588413200803038) + tdSql.checkData(68, 3, 1.8713332491184997) + tdSql.checkData(68, 4, None) + tdSql.checkData(68, 5, -1.3983047743451864) + tdSql.checkData(68, 6, 0.8709074342191974) + tdSql.checkData(69, 0, 19) + tdSql.checkData(69, 1, 0.8366556385360561) + tdSql.checkData(69, 2, 0.5723746128431292) + tdSql.checkData(69, 3, 3.413484890511323) + tdSql.checkData(69, 4, None) + tdSql.checkData(69, 5, -1.9952541841757747) + tdSql.checkData(69, 6, 3.4479580493217856) + tdSql.checkData(70, 0, 20) + tdSql.checkData(70, 1, -0.008851309290403876) + tdSql.checkData(70, 2, 0.7310155667453407) + tdSql.checkData(70, 3, 1.2127175951404974) + tdSql.checkData(70, 4, None) + tdSql.checkData(70, 5, -1.4304290589415767) + tdSql.checkData(70, 6, 5.982274104704091) + tdSql.checkData(71, 0, 21) + tdSql.checkData(71, 1, -0.8462204041751706) + tdSql.checkData(71, 2, 0.9887894200405688) + tdSql.checkData(71, 3, 1.5772240911721418) + tdSql.checkData(71, 4, None) + tdSql.checkData(71, 5, -0.11647857397382422) + tdSql.checkData(71, 6, 0.5559799244477626) + tdSql.checkData(72, 0, 22) + tdSql.checkData(72, 1, -0.9055783620066239) + tdSql.checkData(72, 2, 0.6114178044194122) + tdSql.checkData(72, 3, 3.5568711064263105) + tdSql.checkData(72, 4, None) + tdSql.checkData(72, 5, 0.9837833410919679) + tdSql.checkData(72, 6, 3.0265535811470983) + tdSql.checkData(73, 0, 23) + tdSql.checkData(73, 1, -0.13235175009777303) + tdSql.checkData(73, 2, 0.6699494442536529) + tdSql.checkData(73, 3, 1.5387402975985367) + tdSql.checkData(73, 4, None) + tdSql.checkData(73, 5, 1.1825447904081037) + tdSql.checkData(73, 6, 5.489941431040083) + tdSql.checkData(74, 0, 24) + tdSql.checkData(74, 1, 0.7625584504796027) + tdSql.checkData(74, 2, 0.999960827417674) + tdSql.checkData(74, 3, 1.2552318002593996) + tdSql.checkData(74, 4, None) + tdSql.checkData(74, 5, 0.6200983185456957) + tdSql.checkData(74, 6, 0.09684864095463253) + tdSql.checkData(75, 0, 25) + tdSql.checkData(75, 1, 0.956375928404503) + tdSql.checkData(75, 2, 0.6628179613691831) + tdSql.checkData(75, 3, 3.4435632194258416) + tdSql.checkData(75, 4, None) + tdSql.checkData(75, 5, 0.05676687083562715) + tdSql.checkData(75, 6, 2.6040987392745354) + tdSql.checkData(76, 0, 26) + tdSql.checkData(76, 1, 0.27090578830786904) + tdSql.checkData(76, 2, 0.6172306382193644) + tdSql.checkData(76, 3, 1.835550377607515) + tdSql.checkData(76, 4, None) + tdSql.checkData(76, 5, 0.11431954199291106) + tdSql.checkData(76, 6, 5.165381146246765) + tdSql.checkData(77, 0, 27) + tdSql.checkData(77, 1, -0.6636338842129675) + tdSql.checkData(77, 2, 0.9912542848596704) + tdSql.checkData(77, 3, 0.9080812682077812) + tdSql.checkData(77, 4, None) + tdSql.checkData(77, 5, 0.6788951190016388) + tdSql.checkData(77, 6, -0.8324928492797357) + tdSql.checkData(78, 0, 28) + tdSql.checkData(78, 1, -0.9880316240928618) + tdSql.checkData(78, 2, 0.7230710689951642) + tdSql.checkData(78, 3, 3.1457526648156393) + tdSql.checkData(78, 4, None) + tdSql.checkData(78, 5, 1.0206076417536643) + tdSql.checkData(78, 6, 2.197019393348823) + tdSql.checkData(79, 0, 29) + tdSql.checkData(79, 1, -0.404037645323065) + tdSql.checkData(79, 2, 0.5764850221962442) + tdSql.checkData(79, 3, 2.1197476343754156) + tdSql.checkData(79, 4, None) + tdSql.checkData(79, 5, 0.5162157333804713) + tdSql.checkData(79, 6, 4.8800154918827525) + tdSql.checkData(80, 0, 30) + tdSql.checkData(80, 1, 0.5514266812416906) + tdSql.checkData(80, 2, 0.9635288988181601) + tdSql.checkData(80, 3, 0.5944617511422015) + tdSql.checkData(80, 4, None) + tdSql.checkData(80, 5, -0.7022004347538967) + tdSql.checkData(80, 6, -3.710141817748492) + tdSql.checkData(81, 0, 31) + tdSql.checkData(81, 1, 0.9999118601072672) + tdSql.checkData(81, 2, 0.7877590247885756) + tdSql.checkData(81, 3, 2.7979785951133604) + tdSql.checkData(81, 4, None) + tdSql.checkData(81, 5, -1.7874722290307907) + tdSql.checkData(81, 6, 1.8191237353300793) + tdSql.checkData(82, 0, 32) + tdSql.checkData(82, 1, 0.5290826861200238) + tdSql.checkData(82, 2, 0.5503344099628432) + tdSql.checkData(82, 3, 2.413227615833899) + tdSql.checkData(82, 4, None) + tdSql.checkData(82, 5, -1.8893763681780902) + tdSql.checkData(82, 6, 4.581032079680554) + tdSql.checkData(83, 0, 33) + tdSql.checkData(83, 1, -0.428182669496151) + tdSql.checkData(83, 2, 0.9194811573015673) + tdSql.checkData(83, 3, 0.4437992589174107) + tdSql.checkData(83, 4, None) + tdSql.checkData(83, 5, -0.9001958571391758) + tdSql.checkData(83, 6, -72.33956595410905) + tdSql.checkData(84, 0, 34) + tdSql.checkData(84, 1, -0.9917788534431158) + tdSql.checkData(84, 2, 0.8517779466253769) + tdSql.checkData(84, 3, 2.470955260231499) + tdSql.checkData(84, 4, None) + tdSql.checkData(84, 5, 0.4428112547200472) + tdSql.checkData(84, 6, 1.4785733565944832) + tdSql.checkData(85, 0, 35) + tdSql.checkData(85, 1, -0.6435381333569995) + tdSql.checkData(85, 2, 0.5403764709316752) + tdSql.checkData(85, 3, 2.734210799811235) + tdSql.checkData(85, 4, None) + tdSql.checkData(85, 5, 1.1930854189064375) + tdSql.checkData(85, 6, 4.24770540197234) + tdSql.checkData(86, 0, 36) + tdSql.checkData(86, 1, 0.2963685787093853) + tdSql.checkData(86, 2, 0.8632704401895588) + tdSql.checkData(86, 3, 0.5493681603601657) + tdSql.checkData(86, 4, None) + tdSql.checkData(86, 5, 0.9944678850925007) + tdSql.checkData(86, 6, 11.004294268461184) + tdSql.checkData(87, 0, 37) + tdSql.checkData(87, 1, 0.9637953862840878) + tdSql.checkData(87, 2, 0.909721840267583) + tdSql.checkData(87, 3, 2.1734252903776303) + tdSql.checkData(87, 4, None) + tdSql.checkData(87, 5, 0.32696474077278626) + tdSql.checkData(87, 6, 1.174082484128993) + tdSql.checkData(88, 0, 38) + tdSql.checkData(88, 1, 0.7451131604793488) + tdSql.checkData(88, 2, 0.5472018255605284) + tdSql.checkData(88, 3, 3.081063350979351) + tdSql.checkData(88, 4, None) + tdSql.checkData(88, 5, -0.007381884932924798) + tdSql.checkData(88, 6, 3.8764172978929814) + tdSql.checkData(89, 0, 39) + tdSql.checkData(89, 1, -0.158622668804709) + tdSql.checkData(89, 2, 0.7999777847134487) + tdSql.checkData(89, 3, 0.8435920138756074) + tdSql.checkData(89, 4, None) + tdSql.checkData(89, 5, 0.3319994538301167) + tdSql.checkData(89, 6, 7.12853286308907) + tdSql.checkData(90, 0, 40) + tdSql.checkData(90, 1, -0.9165215479156338) + tdSql.checkData(90, 2, 0.9564033460276342) + tdSql.checkData(90, 3, 1.889162191085516) + tdSql.checkData(90, 4, None) + tdSql.checkData(90, 5, 0.90296737936602) + tdSql.checkData(90, 6, 0.888896415152729) + tdSql.checkData(91, 0, 41) + tdSql.checkData(91, 1, -0.8317747426285983) + tdSql.checkData(91, 2, 0.5704067143341829) + tdSql.checkData(91, 3, 3.397430462894578) + tdSql.checkData(91, 4, None) + tdSql.checkData(91, 5, 0.9190273051332304) + tdSql.checkData(91, 6, 3.473885481113728) + tdSql.checkData(92, 0, 42) + tdSql.checkData(92, 1, 0.017701925105413577) + tdSql.checkData(92, 2, 0.7350111780599404) + tdSql.checkData(92, 3, 1.1912997639866574) + tdSql.checkData(92, 4, None) + tdSql.checkData(92, 5, 0.036467324189017214) + tdSql.checkData(92, 6, 6.024578312510778) + tdSql.checkData(93, 0, 43) + tdSql.checkData(93, 1, 0.8509035245341184) + tdSql.checkData(93, 2, 0.9874457808369176) + tdSql.checkData(93, 3, 1.5962924548219202) + tdSql.checkData(93, 4, None) + tdSql.checkData(93, 5, -1.2490970766755156) + tdSql.checkData(93, 6, 0.5781542141407696) + tdSql.checkData(94, 0, 44) + tdSql.checkData(94, 1, 0.9017883476488092) + tdSql.checkData(94, 2, 0.6085839480802863) + tdSql.checkData(94, 3, 3.5552629892514687) + tdSql.checkData(94, 4, None) + tdSql.checkData(94, 5, -1.9810692649977342) + tdSql.checkData(94, 6, 3.0531030020123464) + tdSql.checkData(95, 0, 45) + tdSql.checkData(95, 1, 0.123573122745224) + tdSql.checkData(95, 2, 0.6735650596658175) + tdSql.checkData(95, 3, 1.5193186190030223) + tdSql.checkData(95, 4, None) + tdSql.checkData(95, 5, -1.5661895943272113) + tdSql.checkData(95, 6, 5.513771854144419) + tdSql.checkData(96, 0, 46) + tdSql.checkData(96, 1, -0.7682546613236668) + tdSql.checkData(96, 2, 0.9998433250151273) + tdSql.checkData(96, 3, 1.2763169256468458) + tdSql.checkData(96, 4, None) + tdSql.checkData(96, 5, -0.300459258677913) + tdSql.checkData(96, 6, 0.13392039926281352) + tdSql.checkData(97, 0, 47) + tdSql.checkData(97, 1, -0.9537526527594719) + tdSql.checkData(97, 2, 0.6593040763085178) + tdSql.checkData(97, 3, 3.4575106745458637) + tdSql.checkData(97, 4, None) + tdSql.checkData(97, 5, 0.8820838187306987) + tdSql.checkData(97, 6, 2.6302204463996084) + tdSql.checkData(98, 0, 48) + tdSql.checkData(98, 1, -0.26237485370392877) + tdSql.checkData(98, 2, 0.6202081141679935) + tdSql.checkData(98, 3, 1.8175857333771335) + tdSql.checkData(98, 4, None) + tdSql.checkData(98, 5, 1.211884234321115) + tdSql.checkData(98, 6, 5.183714988550632) + tdSql.checkData(99, 0, 49) + tdSql.checkData(99, 1, 0.6702291758433747) + tdSql.checkData(99, 2, 0.9923745526637894) + tdSql.checkData(99, 3, 0.9298143670243166) + tdSql.checkData(99, 4, None) + tdSql.checkData(99, 5, 0.7136182821549459) + tdSql.checkData(99, 6, -0.7462904241496138) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 ) order by ts limit 2;;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.7780731968879212) + tdSql.checkData(0, 2, 0.6143002821164822) + tdSql.checkData(0, 3, 3.2037266279837113) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.02246988233490299) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.1411200080598672) + tdSql.checkData(1, 2, 0.6663667453928805) + tdSql.checkData(1, 3, 1.558041126155035) + tdSql.checkData(1, 4, 1.8325957145940461) + tdSql.checkData(1, 5, 0.17204223631998083) + tdSql.checkData(1, 6, None) + + tdSql.query('select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 ) limit 2;;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.7780731968879212) + tdSql.checkData(0, 2, 0.6143002821164822) + tdSql.checkData(0, 3, 3.2037266279837113) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.02246988233490299) + tdSql.checkData(0, 6, None) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.1411200080598672) + tdSql.checkData(1, 2, 0.6663667453928805) + tdSql.checkData(1, 3, 1.558041126155035) + tdSql.checkData(1, 4, 1.8325957145940461) + tdSql.checkData(1, 5, 0.17204223631998083) + tdSql.checkData(1, 6, None) + + tdSql.query('select * from (select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6, ts from st0 order by ts desc);') + tdSql.checkRows(100) + tdSql.checkData(0, 0, 49) + tdSql.checkData(0, 1, 0.6702291758433747) + tdSql.checkData(0, 2, 0.9923745526637894) + tdSql.checkData(0, 3, 0.9298143670243166) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.7136182821549459) + tdSql.checkData(0, 6, -0.7462904241496138) + tdSql.checkData(0, 7, datetime.datetime(2020, 10, 1, 0, 49)) + tdSql.checkData(1, 0, 49) + tdSql.checkData(1, 1, 0.6702291758433747) + tdSql.checkData(1, 2, 0.9923745526637894) + tdSql.checkData(1, 3, 0.9298143670243166) + tdSql.checkData(1, 4, None) + tdSql.checkData(1, 5, 0.7136182821549459) + tdSql.checkData(1, 6, -0.7462904241496138) + tdSql.checkData(1, 7, datetime.datetime(2020, 10, 1, 0, 49)) + tdSql.checkData(2, 0, 48) + tdSql.checkData(2, 1, -0.26237485370392877) + tdSql.checkData(2, 2, 0.6202081141679935) + tdSql.checkData(2, 3, 1.8175857333771335) + tdSql.checkData(2, 4, None) + tdSql.checkData(2, 5, 1.211884234321115) + tdSql.checkData(2, 6, 5.183714988550632) + tdSql.checkData(2, 7, datetime.datetime(2020, 10, 1, 0, 48)) + tdSql.checkData(3, 0, 48) + tdSql.checkData(3, 1, -0.26237485370392877) + tdSql.checkData(3, 2, 0.6202081141679935) + tdSql.checkData(3, 3, 1.8175857333771335) + tdSql.checkData(3, 4, None) + tdSql.checkData(3, 5, 1.211884234321115) + tdSql.checkData(3, 6, 5.183714988550632) + tdSql.checkData(3, 7, datetime.datetime(2020, 10, 1, 0, 48)) + tdSql.checkData(4, 0, 47) + tdSql.checkData(4, 1, -0.9537526527594719) + tdSql.checkData(4, 2, 0.6593040763085178) + tdSql.checkData(4, 3, 3.4575106745458637) + tdSql.checkData(4, 4, None) + tdSql.checkData(4, 5, 0.8820838187306987) + tdSql.checkData(4, 6, 2.6302204463996084) + tdSql.checkData(4, 7, datetime.datetime(2020, 10, 1, 0, 47)) + tdSql.checkData(5, 0, 47) + tdSql.checkData(5, 1, -0.9537526527594719) + tdSql.checkData(5, 2, 0.6593040763085178) + tdSql.checkData(5, 3, 3.4575106745458637) + tdSql.checkData(5, 4, None) + tdSql.checkData(5, 5, 0.8820838187306987) + tdSql.checkData(5, 6, 2.6302204463996084) + tdSql.checkData(5, 7, datetime.datetime(2020, 10, 1, 0, 47)) + tdSql.checkData(6, 0, 46) + tdSql.checkData(6, 1, -0.7682546613236668) + tdSql.checkData(6, 2, 0.9998433250151273) + tdSql.checkData(6, 3, 1.2763169256468458) + tdSql.checkData(6, 4, None) + tdSql.checkData(6, 5, -0.300459258677913) + tdSql.checkData(6, 6, 0.13392039926281352) + tdSql.checkData(6, 7, datetime.datetime(2020, 10, 1, 0, 46)) + tdSql.checkData(7, 0, 46) + tdSql.checkData(7, 1, -0.7682546613236668) + tdSql.checkData(7, 2, 0.9998433250151273) + tdSql.checkData(7, 3, 1.2763169256468458) + tdSql.checkData(7, 4, None) + tdSql.checkData(7, 5, -0.300459258677913) + tdSql.checkData(7, 6, 0.13392039926281352) + tdSql.checkData(7, 7, datetime.datetime(2020, 10, 1, 0, 46)) + tdSql.checkData(8, 0, 45) + tdSql.checkData(8, 1, 0.123573122745224) + tdSql.checkData(8, 2, 0.6735650596658175) + tdSql.checkData(8, 3, 1.5193186190030223) + tdSql.checkData(8, 4, None) + tdSql.checkData(8, 5, -1.5661895943272113) + tdSql.checkData(8, 6, 5.513771854144419) + tdSql.checkData(8, 7, datetime.datetime(2020, 10, 1, 0, 45)) + tdSql.checkData(9, 0, 45) + tdSql.checkData(9, 1, 0.123573122745224) + tdSql.checkData(9, 2, 0.6735650596658175) + tdSql.checkData(9, 3, 1.5193186190030223) + tdSql.checkData(9, 4, None) + tdSql.checkData(9, 5, -1.5661895943272113) + tdSql.checkData(9, 6, 5.513771854144419) + tdSql.checkData(9, 7, datetime.datetime(2020, 10, 1, 0, 45)) + tdSql.checkData(10, 0, 44) + tdSql.checkData(10, 1, 0.9017883476488092) + tdSql.checkData(10, 2, 0.6085839480802863) + tdSql.checkData(10, 3, 3.5552629892514687) + tdSql.checkData(10, 4, None) + tdSql.checkData(10, 5, -1.9810692649977342) + tdSql.checkData(10, 6, 3.0531030020123464) + tdSql.checkData(10, 7, datetime.datetime(2020, 10, 1, 0, 44)) + tdSql.checkData(11, 0, 44) + tdSql.checkData(11, 1, 0.9017883476488092) + tdSql.checkData(11, 2, 0.6085839480802863) + tdSql.checkData(11, 3, 3.5552629892514687) + tdSql.checkData(11, 4, None) + tdSql.checkData(11, 5, -1.9810692649977342) + tdSql.checkData(11, 6, 3.0531030020123464) + tdSql.checkData(11, 7, datetime.datetime(2020, 10, 1, 0, 44)) + tdSql.checkData(12, 0, 43) + tdSql.checkData(12, 1, 0.8509035245341184) + tdSql.checkData(12, 2, 0.9874457808369176) + tdSql.checkData(12, 3, 1.5962924548219202) + tdSql.checkData(12, 4, None) + tdSql.checkData(12, 5, -1.2490970766755156) + tdSql.checkData(12, 6, 0.5781542141407696) + tdSql.checkData(12, 7, datetime.datetime(2020, 10, 1, 0, 43)) + tdSql.checkData(13, 0, 43) + tdSql.checkData(13, 1, 0.8509035245341184) + tdSql.checkData(13, 2, 0.9874457808369176) + tdSql.checkData(13, 3, 1.5962924548219202) + tdSql.checkData(13, 4, None) + tdSql.checkData(13, 5, -1.2490970766755156) + tdSql.checkData(13, 6, 0.5781542141407696) + tdSql.checkData(13, 7, datetime.datetime(2020, 10, 1, 0, 43)) + tdSql.checkData(14, 0, 42) + tdSql.checkData(14, 1, 0.017701925105413577) + tdSql.checkData(14, 2, 0.7350111780599404) + tdSql.checkData(14, 3, 1.1912997639866574) + tdSql.checkData(14, 4, None) + tdSql.checkData(14, 5, 0.036467324189017214) + tdSql.checkData(14, 6, 6.024578312510778) + tdSql.checkData(14, 7, datetime.datetime(2020, 10, 1, 0, 42)) + tdSql.checkData(15, 0, 42) + tdSql.checkData(15, 1, 0.017701925105413577) + tdSql.checkData(15, 2, 0.7350111780599404) + tdSql.checkData(15, 3, 1.1912997639866574) + tdSql.checkData(15, 4, None) + tdSql.checkData(15, 5, 0.036467324189017214) + tdSql.checkData(15, 6, 6.024578312510778) + tdSql.checkData(15, 7, datetime.datetime(2020, 10, 1, 0, 42)) + tdSql.checkData(16, 0, 41) + tdSql.checkData(16, 1, -0.8317747426285983) + tdSql.checkData(16, 2, 0.5704067143341829) + tdSql.checkData(16, 3, 3.397430462894578) + tdSql.checkData(16, 4, None) + tdSql.checkData(16, 5, 0.9190273051332304) + tdSql.checkData(16, 6, 3.473885481113728) + tdSql.checkData(16, 7, datetime.datetime(2020, 10, 1, 0, 41)) + tdSql.checkData(17, 0, 41) + tdSql.checkData(17, 1, -0.8317747426285983) + tdSql.checkData(17, 2, 0.5704067143341829) + tdSql.checkData(17, 3, 3.397430462894578) + tdSql.checkData(17, 4, None) + tdSql.checkData(17, 5, 0.9190273051332304) + tdSql.checkData(17, 6, 3.473885481113728) + tdSql.checkData(17, 7, datetime.datetime(2020, 10, 1, 0, 41)) + tdSql.checkData(18, 0, 40) + tdSql.checkData(18, 1, -0.9165215479156338) + tdSql.checkData(18, 2, 0.9564033460276342) + tdSql.checkData(18, 3, 1.889162191085516) + tdSql.checkData(18, 4, None) + tdSql.checkData(18, 5, 0.90296737936602) + tdSql.checkData(18, 6, 0.888896415152729) + tdSql.checkData(18, 7, datetime.datetime(2020, 10, 1, 0, 40)) + tdSql.checkData(19, 0, 40) + tdSql.checkData(19, 1, -0.9165215479156338) + tdSql.checkData(19, 2, 0.9564033460276342) + tdSql.checkData(19, 3, 1.889162191085516) + tdSql.checkData(19, 4, None) + tdSql.checkData(19, 5, 0.90296737936602) + tdSql.checkData(19, 6, 0.888896415152729) + tdSql.checkData(19, 7, datetime.datetime(2020, 10, 1, 0, 40)) + tdSql.checkData(20, 0, 39) + tdSql.checkData(20, 1, -0.158622668804709) + tdSql.checkData(20, 2, 0.7999777847134487) + tdSql.checkData(20, 3, 0.8435920138756074) + tdSql.checkData(20, 4, None) + tdSql.checkData(20, 5, 0.3319994538301167) + tdSql.checkData(20, 6, 7.12853286308907) + tdSql.checkData(20, 7, datetime.datetime(2020, 10, 1, 0, 39)) + tdSql.checkData(21, 0, 39) + tdSql.checkData(21, 1, -0.158622668804709) + tdSql.checkData(21, 2, 0.7999777847134487) + tdSql.checkData(21, 3, 0.8435920138756074) + tdSql.checkData(21, 4, None) + tdSql.checkData(21, 5, 0.3319994538301167) + tdSql.checkData(21, 6, 7.12853286308907) + tdSql.checkData(21, 7, datetime.datetime(2020, 10, 1, 0, 39)) + tdSql.checkData(22, 0, 38) + tdSql.checkData(22, 1, 0.7451131604793488) + tdSql.checkData(22, 2, 0.5472018255605284) + tdSql.checkData(22, 3, 3.081063350979351) + tdSql.checkData(22, 4, None) + tdSql.checkData(22, 5, -0.007381884932924798) + tdSql.checkData(22, 6, 3.8764172978929814) + tdSql.checkData(22, 7, datetime.datetime(2020, 10, 1, 0, 38)) + tdSql.checkData(23, 0, 38) + tdSql.checkData(23, 1, 0.7451131604793488) + tdSql.checkData(23, 2, 0.5472018255605284) + tdSql.checkData(23, 3, 3.081063350979351) + tdSql.checkData(23, 4, None) + tdSql.checkData(23, 5, -0.007381884932924798) + tdSql.checkData(23, 6, 3.8764172978929814) + tdSql.checkData(23, 7, datetime.datetime(2020, 10, 1, 0, 38)) + tdSql.checkData(24, 0, 37) + tdSql.checkData(24, 1, 0.9637953862840878) + tdSql.checkData(24, 2, 0.909721840267583) + tdSql.checkData(24, 3, 2.1734252903776303) + tdSql.checkData(24, 4, None) + tdSql.checkData(24, 5, 0.32696474077278626) + tdSql.checkData(24, 6, 1.174082484128993) + tdSql.checkData(24, 7, datetime.datetime(2020, 10, 1, 0, 37)) + tdSql.checkData(25, 0, 37) + tdSql.checkData(25, 1, 0.9637953862840878) + tdSql.checkData(25, 2, 0.909721840267583) + tdSql.checkData(25, 3, 2.1734252903776303) + tdSql.checkData(25, 4, None) + tdSql.checkData(25, 5, 0.32696474077278626) + tdSql.checkData(25, 6, 1.174082484128993) + tdSql.checkData(25, 7, datetime.datetime(2020, 10, 1, 0, 37)) + tdSql.checkData(26, 0, 36) + tdSql.checkData(26, 1, 0.2963685787093853) + tdSql.checkData(26, 2, 0.8632704401895588) + tdSql.checkData(26, 3, 0.5493681603601657) + tdSql.checkData(26, 4, None) + tdSql.checkData(26, 5, 0.9944678850925007) + tdSql.checkData(26, 6, 11.004294268461184) + tdSql.checkData(26, 7, datetime.datetime(2020, 10, 1, 0, 36)) + tdSql.checkData(27, 0, 36) + tdSql.checkData(27, 1, 0.2963685787093853) + tdSql.checkData(27, 2, 0.8632704401895588) + tdSql.checkData(27, 3, 0.5493681603601657) + tdSql.checkData(27, 4, None) + tdSql.checkData(27, 5, 0.9944678850925007) + tdSql.checkData(27, 6, 11.004294268461184) + tdSql.checkData(27, 7, datetime.datetime(2020, 10, 1, 0, 36)) + tdSql.checkData(28, 0, 35) + tdSql.checkData(28, 1, -0.6435381333569995) + tdSql.checkData(28, 2, 0.5403764709316752) + tdSql.checkData(28, 3, 2.734210799811235) + tdSql.checkData(28, 4, None) + tdSql.checkData(28, 5, 1.1930854189064375) + tdSql.checkData(28, 6, 4.24770540197234) + tdSql.checkData(28, 7, datetime.datetime(2020, 10, 1, 0, 35)) + tdSql.checkData(29, 0, 35) + tdSql.checkData(29, 1, -0.6435381333569995) + tdSql.checkData(29, 2, 0.5403764709316752) + tdSql.checkData(29, 3, 2.734210799811235) + tdSql.checkData(29, 4, None) + tdSql.checkData(29, 5, 1.1930854189064375) + tdSql.checkData(29, 6, 4.24770540197234) + tdSql.checkData(29, 7, datetime.datetime(2020, 10, 1, 0, 35)) + tdSql.checkData(30, 0, 34) + tdSql.checkData(30, 1, -0.9917788534431158) + tdSql.checkData(30, 2, 0.8517779466253769) + tdSql.checkData(30, 3, 2.470955260231499) + tdSql.checkData(30, 4, None) + tdSql.checkData(30, 5, 0.4428112547200472) + tdSql.checkData(30, 6, 1.4785733565944832) + tdSql.checkData(30, 7, datetime.datetime(2020, 10, 1, 0, 34)) + tdSql.checkData(31, 0, 34) + tdSql.checkData(31, 1, -0.9917788534431158) + tdSql.checkData(31, 2, 0.8517779466253769) + tdSql.checkData(31, 3, 2.470955260231499) + tdSql.checkData(31, 4, None) + tdSql.checkData(31, 5, 0.4428112547200472) + tdSql.checkData(31, 6, 1.4785733565944832) + tdSql.checkData(31, 7, datetime.datetime(2020, 10, 1, 0, 34)) + tdSql.checkData(32, 0, 33) + tdSql.checkData(32, 1, -0.428182669496151) + tdSql.checkData(32, 2, 0.9194811573015673) + tdSql.checkData(32, 3, 0.4437992589174107) + tdSql.checkData(32, 4, None) + tdSql.checkData(32, 5, -0.9001958571391758) + tdSql.checkData(32, 6, -72.33956595410905) + tdSql.checkData(32, 7, datetime.datetime(2020, 10, 1, 0, 33)) + tdSql.checkData(33, 0, 33) + tdSql.checkData(33, 1, -0.428182669496151) + tdSql.checkData(33, 2, 0.9194811573015673) + tdSql.checkData(33, 3, 0.4437992589174107) + tdSql.checkData(33, 4, None) + tdSql.checkData(33, 5, -0.9001958571391758) + tdSql.checkData(33, 6, -72.33956595410905) + tdSql.checkData(33, 7, datetime.datetime(2020, 10, 1, 0, 33)) + tdSql.checkData(34, 0, 32) + tdSql.checkData(34, 1, 0.5290826861200238) + tdSql.checkData(34, 2, 0.5503344099628432) + tdSql.checkData(34, 3, 2.413227615833899) + tdSql.checkData(34, 4, None) + tdSql.checkData(34, 5, -1.8893763681780902) + tdSql.checkData(34, 6, 4.581032079680554) + tdSql.checkData(34, 7, datetime.datetime(2020, 10, 1, 0, 32)) + tdSql.checkData(35, 0, 32) + tdSql.checkData(35, 1, 0.5290826861200238) + tdSql.checkData(35, 2, 0.5503344099628432) + tdSql.checkData(35, 3, 2.413227615833899) + tdSql.checkData(35, 4, None) + tdSql.checkData(35, 5, -1.8893763681780902) + tdSql.checkData(35, 6, 4.581032079680554) + tdSql.checkData(35, 7, datetime.datetime(2020, 10, 1, 0, 32)) + tdSql.checkData(36, 0, 31) + tdSql.checkData(36, 1, 0.9999118601072672) + tdSql.checkData(36, 2, 0.7877590247885756) + tdSql.checkData(36, 3, 2.7979785951133604) + tdSql.checkData(36, 4, None) + tdSql.checkData(36, 5, -1.7874722290307907) + tdSql.checkData(36, 6, 1.8191237353300793) + tdSql.checkData(36, 7, datetime.datetime(2020, 10, 1, 0, 31)) + tdSql.checkData(37, 0, 31) + tdSql.checkData(37, 1, 0.9999118601072672) + tdSql.checkData(37, 2, 0.7877590247885756) + tdSql.checkData(37, 3, 2.7979785951133604) + tdSql.checkData(37, 4, None) + tdSql.checkData(37, 5, -1.7874722290307907) + tdSql.checkData(37, 6, 1.8191237353300793) + tdSql.checkData(37, 7, datetime.datetime(2020, 10, 1, 0, 31)) + tdSql.checkData(38, 0, 30) + tdSql.checkData(38, 1, 0.5514266812416906) + tdSql.checkData(38, 2, 0.9635288988181601) + tdSql.checkData(38, 3, 0.5944617511422015) + tdSql.checkData(38, 4, None) + tdSql.checkData(38, 5, -0.7022004347538967) + tdSql.checkData(38, 6, -3.710141817748492) + tdSql.checkData(38, 7, datetime.datetime(2020, 10, 1, 0, 30)) + tdSql.checkData(39, 0, 30) + tdSql.checkData(39, 1, 0.5514266812416906) + tdSql.checkData(39, 2, 0.9635288988181601) + tdSql.checkData(39, 3, 0.5944617511422015) + tdSql.checkData(39, 4, None) + tdSql.checkData(39, 5, -0.7022004347538967) + tdSql.checkData(39, 6, -3.710141817748492) + tdSql.checkData(39, 7, datetime.datetime(2020, 10, 1, 0, 30)) + tdSql.checkData(40, 0, 29) + tdSql.checkData(40, 1, -0.404037645323065) + tdSql.checkData(40, 2, 0.5764850221962442) + tdSql.checkData(40, 3, 2.1197476343754156) + tdSql.checkData(40, 4, None) + tdSql.checkData(40, 5, 0.5162157333804713) + tdSql.checkData(40, 6, 4.8800154918827525) + tdSql.checkData(40, 7, datetime.datetime(2020, 10, 1, 0, 29)) + tdSql.checkData(41, 0, 29) + tdSql.checkData(41, 1, -0.404037645323065) + tdSql.checkData(41, 2, 0.5764850221962442) + tdSql.checkData(41, 3, 2.1197476343754156) + tdSql.checkData(41, 4, None) + tdSql.checkData(41, 5, 0.5162157333804713) + tdSql.checkData(41, 6, 4.8800154918827525) + tdSql.checkData(41, 7, datetime.datetime(2020, 10, 1, 0, 29)) + tdSql.checkData(42, 0, 28) + tdSql.checkData(42, 1, -0.9880316240928618) + tdSql.checkData(42, 2, 0.7230710689951642) + tdSql.checkData(42, 3, 3.1457526648156393) + tdSql.checkData(42, 4, None) + tdSql.checkData(42, 5, 1.0206076417536643) + tdSql.checkData(42, 6, 2.197019393348823) + tdSql.checkData(42, 7, datetime.datetime(2020, 10, 1, 0, 28)) + tdSql.checkData(43, 0, 28) + tdSql.checkData(43, 1, -0.9880316240928618) + tdSql.checkData(43, 2, 0.7230710689951642) + tdSql.checkData(43, 3, 3.1457526648156393) + tdSql.checkData(43, 4, None) + tdSql.checkData(43, 5, 1.0206076417536643) + tdSql.checkData(43, 6, 2.197019393348823) + tdSql.checkData(43, 7, datetime.datetime(2020, 10, 1, 0, 28)) + tdSql.checkData(44, 0, 27) + tdSql.checkData(44, 1, -0.6636338842129675) + tdSql.checkData(44, 2, 0.9912542848596704) + tdSql.checkData(44, 3, 0.9080812682077812) + tdSql.checkData(44, 4, None) + tdSql.checkData(44, 5, 0.6788951190016388) + tdSql.checkData(44, 6, -0.8324928492797357) + tdSql.checkData(44, 7, datetime.datetime(2020, 10, 1, 0, 27)) + tdSql.checkData(45, 0, 27) + tdSql.checkData(45, 1, -0.6636338842129675) + tdSql.checkData(45, 2, 0.9912542848596704) + tdSql.checkData(45, 3, 0.9080812682077812) + tdSql.checkData(45, 4, None) + tdSql.checkData(45, 5, 0.6788951190016388) + tdSql.checkData(45, 6, -0.8324928492797357) + tdSql.checkData(45, 7, datetime.datetime(2020, 10, 1, 0, 27)) + tdSql.checkData(46, 0, 26) + tdSql.checkData(46, 1, 0.27090578830786904) + tdSql.checkData(46, 2, 0.6172306382193644) + tdSql.checkData(46, 3, 1.835550377607515) + tdSql.checkData(46, 4, None) + tdSql.checkData(46, 5, 0.11431954199291106) + tdSql.checkData(46, 6, 5.165381146246765) + tdSql.checkData(46, 7, datetime.datetime(2020, 10, 1, 0, 26)) + tdSql.checkData(47, 0, 26) + tdSql.checkData(47, 1, 0.27090578830786904) + tdSql.checkData(47, 2, 0.6172306382193644) + tdSql.checkData(47, 3, 1.835550377607515) + tdSql.checkData(47, 4, None) + tdSql.checkData(47, 5, 0.11431954199291106) + tdSql.checkData(47, 6, 5.165381146246765) + tdSql.checkData(47, 7, datetime.datetime(2020, 10, 1, 0, 26)) + tdSql.checkData(48, 0, 25) + tdSql.checkData(48, 1, 0.956375928404503) + tdSql.checkData(48, 2, 0.6628179613691831) + tdSql.checkData(48, 3, 3.4435632194258416) + tdSql.checkData(48, 4, None) + tdSql.checkData(48, 5, 0.05676687083562715) + tdSql.checkData(48, 6, 2.6040987392745354) + tdSql.checkData(48, 7, datetime.datetime(2020, 10, 1, 0, 25)) + tdSql.checkData(49, 0, 25) + tdSql.checkData(49, 1, 0.956375928404503) + tdSql.checkData(49, 2, 0.6628179613691831) + tdSql.checkData(49, 3, 3.4435632194258416) + tdSql.checkData(49, 4, None) + tdSql.checkData(49, 5, 0.05676687083562715) + tdSql.checkData(49, 6, 2.6040987392745354) + tdSql.checkData(49, 7, datetime.datetime(2020, 10, 1, 0, 25)) + tdSql.checkData(50, 0, 24) + tdSql.checkData(50, 1, 0.7625584504796027) + tdSql.checkData(50, 2, 0.999960827417674) + tdSql.checkData(50, 3, 1.2552318002593996) + tdSql.checkData(50, 4, None) + tdSql.checkData(50, 5, 0.6200983185456957) + tdSql.checkData(50, 6, 0.09684864095463253) + tdSql.checkData(50, 7, datetime.datetime(2020, 10, 1, 0, 24)) + tdSql.checkData(51, 0, 24) + tdSql.checkData(51, 1, 0.7625584504796027) + tdSql.checkData(51, 2, 0.999960827417674) + tdSql.checkData(51, 3, 1.2552318002593996) + tdSql.checkData(51, 4, None) + tdSql.checkData(51, 5, 0.6200983185456957) + tdSql.checkData(51, 6, 0.09684864095463253) + tdSql.checkData(51, 7, datetime.datetime(2020, 10, 1, 0, 24)) + tdSql.checkData(52, 0, 23) + tdSql.checkData(52, 1, -0.13235175009777303) + tdSql.checkData(52, 2, 0.6699494442536529) + tdSql.checkData(52, 3, 1.5387402975985367) + tdSql.checkData(52, 4, None) + tdSql.checkData(52, 5, 1.1825447904081037) + tdSql.checkData(52, 6, 5.489941431040083) + tdSql.checkData(52, 7, datetime.datetime(2020, 10, 1, 0, 23)) + tdSql.checkData(53, 0, 23) + tdSql.checkData(53, 1, -0.13235175009777303) + tdSql.checkData(53, 2, 0.6699494442536529) + tdSql.checkData(53, 3, 1.5387402975985367) + tdSql.checkData(53, 4, None) + tdSql.checkData(53, 5, 1.1825447904081037) + tdSql.checkData(53, 6, 5.489941431040083) + tdSql.checkData(53, 7, datetime.datetime(2020, 10, 1, 0, 23)) + tdSql.checkData(54, 0, 22) + tdSql.checkData(54, 1, -0.9055783620066239) + tdSql.checkData(54, 2, 0.6114178044194122) + tdSql.checkData(54, 3, 3.5568711064263105) + tdSql.checkData(54, 4, None) + tdSql.checkData(54, 5, 0.9837833410919679) + tdSql.checkData(54, 6, 3.0265535811470983) + tdSql.checkData(54, 7, datetime.datetime(2020, 10, 1, 0, 22)) + tdSql.checkData(55, 0, 22) + tdSql.checkData(55, 1, -0.9055783620066239) + tdSql.checkData(55, 2, 0.6114178044194122) + tdSql.checkData(55, 3, 3.5568711064263105) + tdSql.checkData(55, 4, None) + tdSql.checkData(55, 5, 0.9837833410919679) + tdSql.checkData(55, 6, 3.0265535811470983) + tdSql.checkData(55, 7, datetime.datetime(2020, 10, 1, 0, 22)) + tdSql.checkData(56, 0, 21) + tdSql.checkData(56, 1, -0.8462204041751706) + tdSql.checkData(56, 2, 0.9887894200405688) + tdSql.checkData(56, 3, 1.5772240911721418) + tdSql.checkData(56, 4, None) + tdSql.checkData(56, 5, -0.11647857397382422) + tdSql.checkData(56, 6, 0.5559799244477626) + tdSql.checkData(56, 7, datetime.datetime(2020, 10, 1, 0, 21)) + tdSql.checkData(57, 0, 21) + tdSql.checkData(57, 1, -0.8462204041751706) + tdSql.checkData(57, 2, 0.9887894200405688) + tdSql.checkData(57, 3, 1.5772240911721418) + tdSql.checkData(57, 4, None) + tdSql.checkData(57, 5, -0.11647857397382422) + tdSql.checkData(57, 6, 0.5559799244477626) + tdSql.checkData(57, 7, datetime.datetime(2020, 10, 1, 0, 21)) + tdSql.checkData(58, 0, 20) + tdSql.checkData(58, 1, -0.008851309290403876) + tdSql.checkData(58, 2, 0.7310155667453407) + tdSql.checkData(58, 3, 1.2127175951404974) + tdSql.checkData(58, 4, None) + tdSql.checkData(58, 5, -1.4304290589415767) + tdSql.checkData(58, 6, 5.982274104704091) + tdSql.checkData(58, 7, datetime.datetime(2020, 10, 1, 0, 20)) + tdSql.checkData(59, 0, 20) + tdSql.checkData(59, 1, -0.008851309290403876) + tdSql.checkData(59, 2, 0.7310155667453407) + tdSql.checkData(59, 3, 1.2127175951404974) + tdSql.checkData(59, 4, None) + tdSql.checkData(59, 5, -1.4304290589415767) + tdSql.checkData(59, 6, 5.982274104704091) + tdSql.checkData(59, 7, datetime.datetime(2020, 10, 1, 0, 20)) + tdSql.checkData(60, 0, 19) + tdSql.checkData(60, 1, 0.8366556385360561) + tdSql.checkData(60, 2, 0.5723746128431292) + tdSql.checkData(60, 3, 3.413484890511323) + tdSql.checkData(60, 4, None) + tdSql.checkData(60, 5, -1.9952541841757747) + tdSql.checkData(60, 6, 3.4479580493217856) + tdSql.checkData(60, 7, datetime.datetime(2020, 10, 1, 0, 19)) + tdSql.checkData(61, 0, 19) + tdSql.checkData(61, 1, 0.8366556385360561) + tdSql.checkData(61, 2, 0.5723746128431292) + tdSql.checkData(61, 3, 3.413484890511323) + tdSql.checkData(61, 4, None) + tdSql.checkData(61, 5, -1.9952541841757747) + tdSql.checkData(61, 6, 3.4479580493217856) + tdSql.checkData(61, 7, datetime.datetime(2020, 10, 1, 0, 19)) + tdSql.checkData(62, 0, 18) + tdSql.checkData(62, 1, 0.9129452507276277) + tdSql.checkData(62, 2, 0.9588413200803038) + tdSql.checkData(62, 3, 1.8713332491184997) + tdSql.checkData(62, 4, None) + tdSql.checkData(62, 5, -1.3983047743451864) + tdSql.checkData(62, 6, 0.8709074342191974) + tdSql.checkData(62, 7, datetime.datetime(2020, 10, 1, 0, 18)) + tdSql.checkData(63, 0, 18) + tdSql.checkData(63, 1, 0.9129452507276277) + tdSql.checkData(63, 2, 0.9588413200803038) + tdSql.checkData(63, 3, 1.8713332491184997) + tdSql.checkData(63, 4, None) + tdSql.checkData(63, 5, -1.3983047743451864) + tdSql.checkData(63, 6, 0.8709074342191974) + tdSql.checkData(63, 7, datetime.datetime(2020, 10, 1, 0, 18)) + tdSql.checkData(64, 0, 17) + tdSql.checkData(64, 1, 0.14987720966295234) + tdSql.checkData(64, 2, 0.7959095686227995) + tdSql.checkData(64, 3, 0.864944320724419) + tdSql.checkData(64, 4, None) + tdSql.checkData(64, 5, -0.13037289959062748) + tdSql.checkData(64, 6, 7.022998331594864) + tdSql.checkData(64, 7, datetime.datetime(2020, 10, 1, 0, 17)) + tdSql.checkData(65, 0, 17) + tdSql.checkData(65, 1, 0.14987720966295234) + tdSql.checkData(65, 2, 0.7959095686227995) + tdSql.checkData(65, 3, 0.864944320724419) + tdSql.checkData(65, 4, None) + tdSql.checkData(65, 5, -0.13037289959062748) + tdSql.checkData(65, 6, 7.022998331594864) + tdSql.checkData(65, 7, datetime.datetime(2020, 10, 1, 0, 17)) + tdSql.checkData(66, 0, 16) + tdSql.checkData(66, 1, -0.750987246771676) + tdSql.checkData(66, 2, 0.5481819942730298) + tdSql.checkData(66, 3, 3.102748784455539) + tdSql.checkData(66, 4, None) + tdSql.checkData(66, 5, 0.8513297604701857) + tdSql.checkData(66, 6, 3.852058923265594) + tdSql.checkData(66, 7, datetime.datetime(2020, 10, 1, 0, 16)) + tdSql.checkData(67, 0, 16) + tdSql.checkData(67, 1, -0.750987246771676) + tdSql.checkData(67, 2, 0.5481819942730298) + tdSql.checkData(67, 3, 3.102748784455539) + tdSql.checkData(67, 4, None) + tdSql.checkData(67, 5, 0.8513297604701857) + tdSql.checkData(67, 6, 3.852058923265594) + tdSql.checkData(67, 7, datetime.datetime(2020, 10, 1, 0, 16)) + tdSql.checkData(68, 0, 15) + tdSql.checkData(68, 1, -0.9613974918795568) + tdSql.checkData(68, 2, 0.9130208165623314) + tdSql.checkData(68, 3, 2.1554866011151765) + tdSql.checkData(68, 4, None) + tdSql.checkData(68, 5, 0.9521751875546269) + tdSql.checkData(68, 6, 1.1559749749986195) + tdSql.checkData(68, 7, datetime.datetime(2020, 10, 1, 0, 15)) + tdSql.checkData(69, 0, 15) + tdSql.checkData(69, 1, -0.9613974918795568) + tdSql.checkData(69, 2, 0.9130208165623314) + tdSql.checkData(69, 3, 2.1554866011151765) + tdSql.checkData(69, 4, None) + tdSql.checkData(69, 5, 0.9521751875546269) + tdSql.checkData(69, 6, 1.1559749749986195) + tdSql.checkData(69, 7, datetime.datetime(2020, 10, 1, 0, 15)) + tdSql.checkData(70, 0, 14) + tdSql.checkData(70, 1, -0.2879033166650653) + tdSql.checkData(70, 2, 0.859465627274523) + tdSql.checkData(70, 3, 0.5636905248139659) + tdSql.checkData(70, 4, None) + tdSql.checkData(70, 5, 0.41142163587369207) + tdSql.checkData(70, 6, 10.515512404402676) + tdSql.checkData(70, 7, datetime.datetime(2020, 10, 1, 0, 14)) + tdSql.checkData(71, 0, 14) + tdSql.checkData(71, 1, -0.2879033166650653) + tdSql.checkData(71, 2, 0.859465627274523) + tdSql.checkData(71, 3, 0.5636905248139659) + tdSql.checkData(71, 4, None) + tdSql.checkData(71, 5, 0.41142163587369207) + tdSql.checkData(71, 6, 10.515512404402676) + tdSql.checkData(71, 7, datetime.datetime(2020, 10, 1, 0, 14)) + tdSql.checkData(72, 0, 13) + tdSql.checkData(72, 1, 0.6502878401571168) + tdSql.checkData(72, 2, 0.5403105467456532) + tdSql.checkData(72, 3, 2.75535470715349) + tdSql.checkData(72, 4, None) + tdSql.checkData(72, 5, 0.0009616202598659029) + tdSql.checkData(72, 6, 4.225579583416092) + tdSql.checkData(72, 7, datetime.datetime(2020, 10, 1, 0, 13)) + tdSql.checkData(73, 0, 13) + tdSql.checkData(73, 1, 0.6502878401571168) + tdSql.checkData(73, 2, 0.5403105467456532) + tdSql.checkData(73, 3, 2.75535470715349) + tdSql.checkData(73, 4, None) + tdSql.checkData(73, 5, 0.0009616202598659029) + tdSql.checkData(73, 6, 4.225579583416092) + tdSql.checkData(73, 7, datetime.datetime(2020, 10, 1, 0, 13)) + tdSql.checkData(74, 0, 12) + tdSql.checkData(74, 1, 0.9906073556948704) + tdSql.checkData(74, 2, 0.8556343548213666) + tdSql.checkData(74, 3, 2.451594361777497) + tdSql.checkData(74, 4, None) + tdSql.checkData(74, 5, 0.24838494428124291) + tdSql.checkData(74, 6, 1.4585617093317953) + tdSql.checkData(74, 7, datetime.datetime(2020, 10, 1, 0, 12)) + tdSql.checkData(75, 0, 12) + tdSql.checkData(75, 1, 0.9906073556948704) + tdSql.checkData(75, 2, 0.8556343548213666) + tdSql.checkData(75, 3, 2.451594361777497) + tdSql.checkData(75, 4, None) + tdSql.checkData(75, 5, 0.24838494428124291) + tdSql.checkData(75, 6, 1.4585617093317953) + tdSql.checkData(75, 7, datetime.datetime(2020, 10, 1, 0, 12)) + tdSql.checkData(76, 0, 11) + tdSql.checkData(76, 1, 0.4201670368266409) + tdSql.checkData(76, 2, 0.9162743174606308) + tdSql.checkData(76, 3, 0.44272645708128566) + tdSql.checkData(76, 4, None) + tdSql.checkData(76, 5, 0.9151372562290566) + tdSql.checkData(76, 6, -222.95969776348554) + tdSql.checkData(76, 7, datetime.datetime(2020, 10, 1, 0, 11)) + tdSql.checkData(77, 0, 11) + tdSql.checkData(77, 1, 0.4201670368266409) + tdSql.checkData(77, 2, 0.9162743174606308) + tdSql.checkData(77, 3, 0.44272645708128566) + tdSql.checkData(77, 4, None) + tdSql.checkData(77, 5, 0.9151372562290566) + tdSql.checkData(77, 6, -222.95969776348554) + tdSql.checkData(77, 7, datetime.datetime(2020, 10, 1, 0, 11)) + tdSql.checkData(78, 0, 10) + tdSql.checkData(78, 1, -0.5365729180004349) + tdSql.checkData(78, 2, 0.549226270051226) + tdSql.checkData(78, 3, 2.432352856101439) + tdSql.checkData(78, 4, None) + tdSql.checkData(78, 5, 1.2185572409879093) + tdSql.checkData(78, 6, 4.561306078186714) + tdSql.checkData(78, 7, datetime.datetime(2020, 10, 1, 0, 10)) + tdSql.checkData(79, 0, 10) + tdSql.checkData(79, 1, -0.5365729180004349) + tdSql.checkData(79, 2, 0.549226270051226) + tdSql.checkData(79, 3, 2.432352856101439) + tdSql.checkData(79, 4, None) + tdSql.checkData(79, 5, 1.2185572409879093) + tdSql.checkData(79, 6, 4.561306078186714) + tdSql.checkData(79, 7, datetime.datetime(2020, 10, 1, 0, 10)) + tdSql.checkData(80, 0, 9) + tdSql.checkData(80, 1, -0.9999902065507035) + tdSql.checkData(80, 2, 0.7918362090144786) + tdSql.checkData(80, 3, 2.776612511546888) + tdSql.checkData(80, 4, None) + tdSql.checkData(80, 5, 0.5929886271208413) + tdSql.checkData(80, 6, 1.796697093786514) + tdSql.checkData(80, 7, datetime.datetime(2020, 10, 1, 0, 9)) + tdSql.checkData(81, 0, 9) + tdSql.checkData(81, 1, -0.9999902065507035) + tdSql.checkData(81, 2, 0.7918362090144786) + tdSql.checkData(81, 3, 2.776612511546888) + tdSql.checkData(81, 4, None) + tdSql.checkData(81, 5, 0.5929886271208413) + tdSql.checkData(81, 6, 1.796697093786514) + tdSql.checkData(81, 7, datetime.datetime(2020, 10, 1, 0, 9)) + tdSql.checkData(82, 0, 8) + tdSql.checkData(82, 1, -0.5440211108893698) + tdSql.checkData(82, 2, 0.9612168045072789) + tdSql.checkData(82, 3, 0.5787344727995947) + tdSql.checkData(82, 4, None) + tdSql.checkData(82, 5, -0.7199655182148126) + tdSql.checkData(82, 6, -4.087614771885445) + tdSql.checkData(82, 7, datetime.datetime(2020, 10, 1, 0, 8)) + tdSql.checkData(83, 0, 8) + tdSql.checkData(83, 1, -0.5440211108893698) + tdSql.checkData(83, 2, 0.9612168045072789) + tdSql.checkData(83, 3, 0.5787344727995947) + tdSql.checkData(83, 4, None) + tdSql.checkData(83, 5, -0.7199655182148126) + tdSql.checkData(83, 6, -4.087614771885445) + tdSql.checkData(83, 7, datetime.datetime(2020, 10, 1, 0, 8)) + tdSql.checkData(84, 0, 7) + tdSql.checkData(84, 1, 0.4121184852417566) + tdSql.checkData(84, 2, 0.574400879193934) + tdSql.checkData(84, 3, 2.137595835197328) + tdSql.checkData(84, 4, None) + tdSql.checkData(84, 5, -1.8119088619792247) + tdSql.checkData(84, 6, 4.862055338419189) + tdSql.checkData(84, 7, datetime.datetime(2020, 10, 1, 0, 7)) + tdSql.checkData(85, 0, 7) + tdSql.checkData(85, 1, 0.4121184852417566) + tdSql.checkData(85, 2, 0.574400879193934) + tdSql.checkData(85, 3, 2.137595835197328) + tdSql.checkData(85, 4, None) + tdSql.checkData(85, 5, -1.8119088619792247) + tdSql.checkData(85, 6, 4.862055338419189) + tdSql.checkData(85, 7, datetime.datetime(2020, 10, 1, 0, 7)) + tdSql.checkData(86, 0, 6) + tdSql.checkData(86, 1, 0.9893582466233818) + tdSql.checkData(86, 2, 0.7270351311688125) + tdSql.checkData(86, 3, 3.1243204798042576) + tdSql.checkData(86, 4, None) + tdSql.checkData(86, 5, -1.8696882565721156) + tdSql.checkData(86, 6, 2.172420890614816) + tdSql.checkData(86, 7, datetime.datetime(2020, 10, 1, 0, 6)) + tdSql.checkData(87, 0, 6) + tdSql.checkData(87, 1, 0.9893582466233818) + tdSql.checkData(87, 2, 0.7270351311688125) + tdSql.checkData(87, 3, 3.1243204798042576) + tdSql.checkData(87, 4, None) + tdSql.checkData(87, 5, -1.8696882565721156) + tdSql.checkData(87, 6, 2.172420890614816) + tdSql.checkData(87, 7, datetime.datetime(2020, 10, 1, 0, 6)) + tdSql.checkData(88, 0, 5) + tdSql.checkData(88, 1, 0.6569865987187891) + tdSql.checkData(88, 2, 0.9900590857598653) + tdSql.checkData(88, 3, 0.8864495743441427) + tdSql.checkData(88, 4, None) + tdSql.checkData(88, 5, -0.876294736008743) + tdSql.checkData(88, 6, -0.9245361171359558) + tdSql.checkData(88, 7, datetime.datetime(2020, 10, 1, 0, 5)) + tdSql.checkData(89, 0, 5) + tdSql.checkData(89, 1, 0.6569865987187891) + tdSql.checkData(89, 2, 0.9900590857598653) + tdSql.checkData(89, 3, 0.8864495743441427) + tdSql.checkData(89, 4, None) + tdSql.checkData(89, 5, -0.876294736008743) + tdSql.checkData(89, 6, -0.9245361171359558) + tdSql.checkData(89, 7, datetime.datetime(2020, 10, 1, 0, 5)) + tdSql.checkData(90, 0, 4) + tdSql.checkData(90, 1, -0.27941549819892586) + tdSql.checkData(90, 2, 0.6143002821164822) + tdSql.checkData(90, 3, 1.853464438509776) + tdSql.checkData(90, 4, None) + tdSql.checkData(90, 5, 0.38234027607634785) + tdSql.checkData(90, 6, 5.147179528972959) + tdSql.checkData(90, 7, datetime.datetime(2020, 10, 1, 0, 4)) + tdSql.checkData(91, 0, 4) + tdSql.checkData(91, 1, -0.27941549819892586) + tdSql.checkData(91, 2, 0.6143002821164822) + tdSql.checkData(91, 3, 1.853464438509776) + tdSql.checkData(91, 4, None) + tdSql.checkData(91, 5, 0.38234027607634785) + tdSql.checkData(91, 6, 5.147179528972959) + tdSql.checkData(91, 7, datetime.datetime(2020, 10, 1, 0, 4)) + tdSql.checkData(92, 0, 3) + tdSql.checkData(92, 1, -0.9589242746631385) + tdSql.checkData(92, 2, 0.6663667453928805) + tdSql.checkData(92, 3, 3.4288753232277074) + tdSql.checkData(92, 4, None) + tdSql.checkData(92, 5, 1.0087371784424417) + tdSql.checkData(92, 6, 2.5780379587267963) + tdSql.checkData(92, 7, datetime.datetime(2020, 10, 1, 0, 3)) + tdSql.checkData(93, 0, 3) + tdSql.checkData(93, 1, -0.9589242746631385) + tdSql.checkData(93, 2, 0.6663667453928805) + tdSql.checkData(93, 3, 3.4288753232277074) + tdSql.checkData(93, 4, None) + tdSql.checkData(93, 5, 1.0087371784424417) + tdSql.checkData(93, 6, 2.5780379587267963) + tdSql.checkData(93, 7, datetime.datetime(2020, 10, 1, 0, 3)) + tdSql.checkData(94, 0, 2) + tdSql.checkData(94, 1, -0.7568024953079282) + tdSql.checkData(94, 2, 1.0) + tdSql.checkData(94, 3, 1.2340302976078754) + tdSql.checkData(94, 4, None) + tdSql.checkData(94, 5, 0.7554222939559553) + tdSql.checkData(94, 6, 0.05815764143055291) + tdSql.checkData(94, 7, datetime.datetime(2020, 10, 1, 0, 2)) + tdSql.checkData(95, 0, 2) + tdSql.checkData(95, 1, -0.7568024953079282) + tdSql.checkData(95, 2, 1.0) + tdSql.checkData(95, 3, 1.2340302976078754) + tdSql.checkData(95, 4, None) + tdSql.checkData(95, 5, 0.7554222939559553) + tdSql.checkData(95, 6, 0.05815764143055291) + tdSql.checkData(95, 7, datetime.datetime(2020, 10, 1, 0, 2)) + tdSql.checkData(96, 0, 1) + tdSql.checkData(96, 1, 0.1411200080598672) + tdSql.checkData(96, 2, 0.6663667453928805) + tdSql.checkData(96, 3, 1.558041126155035) + tdSql.checkData(96, 4, 1.8325957145940461) + tdSql.checkData(96, 5, 0.17204223631998083) + tdSql.checkData(96, 6, None) + tdSql.checkData(96, 7, datetime.datetime(2020, 10, 1, 0, 1)) + tdSql.checkData(97, 0, 1) + tdSql.checkData(97, 1, 0.1411200080598672) + tdSql.checkData(97, 2, 0.6663667453928805) + tdSql.checkData(97, 3, 1.558041126155035) + tdSql.checkData(97, 4, 1.8325957145940461) + tdSql.checkData(97, 5, 0.17204223631998083) + tdSql.checkData(97, 6, None) + tdSql.checkData(97, 7, datetime.datetime(2020, 10, 1, 0, 1)) + tdSql.checkData(98, 0, 0) + tdSql.checkData(98, 1, 0.7780731968879212) + tdSql.checkData(98, 2, 0.6143002821164822) + tdSql.checkData(98, 3, 3.2037266279837113) + tdSql.checkData(98, 4, None) + tdSql.checkData(98, 5, 0.02246988233490299) + tdSql.checkData(98, 6, None) + tdSql.checkData(98, 7, datetime.datetime(2020, 10, 1, 0, 0)) + tdSql.checkData(99, 0, 0) + tdSql.checkData(99, 1, 0.7780731968879212) + tdSql.checkData(99, 2, 0.6143002821164822) + tdSql.checkData(99, 3, 3.2037266279837113) + tdSql.checkData(99, 4, None) + tdSql.checkData(99, 5, 0.02246988233490299) + tdSql.checkData(99, 6, None) + tdSql.checkData(99, 7, datetime.datetime(2020, 10, 1, 0, 0)) + + tdSql.query('select * from (select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6, ts from ct1 order by ts limit 2);;') + tdSql.checkRows(2) + tdSql.checkData(0, 0, 0) + tdSql.checkData(0, 1, 0.7780731968879212) + tdSql.checkData(0, 2, 0.6143002821164822) + tdSql.checkData(0, 3, 3.2037266279837113) + tdSql.checkData(0, 4, None) + tdSql.checkData(0, 5, 0.02246988233490299) + tdSql.checkData(0, 6, None) + tdSql.checkData(0, 7, datetime.datetime(2020, 10, 1, 0, 0)) + tdSql.checkData(1, 0, 1) + tdSql.checkData(1, 1, 0.1411200080598672) + tdSql.checkData(1, 2, 0.6663667453928805) + tdSql.checkData(1, 3, 1.558041126155035) + tdSql.checkData(1, 4, 1.8325957145940461) + tdSql.checkData(1, 5, 0.17204223631998083) + tdSql.checkData(1, 6, None) + tdSql.checkData(1, 7, datetime.datetime(2020, 10, 1, 0, 1)) + + tdSql.execute('drop database db0') + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/time_window_keywords.py b/tests/develop-test/2-query/time_window_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..48c0973aa7e8fc24294304053170ab3ed56fde6c --- /dev/null +++ b/tests/develop-test/2-query/time_window_keywords.py @@ -0,0 +1,4123 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-11216]: Time window related keywords + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def getBuildPath(self): + selfPath = os.path.dirname(os.path.realpath(__file__)) + + if ("community" in selfPath): + projPath = selfPath[:selfPath.find("community")] + else: + projPath = selfPath[:selfPath.find("tests")] + + for root, dirs, files in os.walk(projPath): + if ("taosd" in files): + rootRealPath = os.path.dirname(os.path.realpath(root)) + if ("packaging" not in rootRealPath): + buildPath = root[:len(root) - len("/build/bin")] + break + return buildPath + + def checkTimestampEqual(self, elm, expect_elm): + caller = inspect.getframeinfo(inspect.stack()[1][0]) + if len(elm) == len(expect_elm): + delta = abs(int(elm[-1]) - int(expect_elm[-1])) + if delta == 1: #ignore 1 second diff + new_elm = expect_elm[0:-1] + elm[-1] + else: + new_elm = expect_elm; + if elm == new_elm: + tdLog.info("sql:%s, elm:%s == expect_elm:%s" % (tdSql.sql, elm, new_elm)) + else: + args = (caller.filename, caller.lineno, tdSql.sql, elm, new_elm) + tdLog.exit("%s(%d) failed: sql:%s, elm:%s != expect_elm:%s" % args) + else: + args = (caller.filename, caller.lineno, tdSql.sql, elm, expect_elm) + tdLog.exit("%s(%d) failed: sql:%s, elm:%s != expect_elm:%s" % args) + + + def run(self): + print("running {}".format(__file__)) + + #Prepare data + #db precision "ms" + tdSql.execute("drop database if exists db_m") + tdSql.execute("create database if not exists db_m") + tdSql.execute('use db_m') + + #for interval query + tdSql.execute("create stable stb_i (ts timestamp, c0 int) tags (t0 int);") + tdSql.execute("create table ctb1_i using stb_i tags (1);") + tdSql.execute("create table ctb2_i using stb_i tags (2);") + tdSql.execute("create table tb_i (ts timestamp, c0 int);") + + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:05', 5)") + + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:00', 0)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:01', 1)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:02', 2)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:03', 3)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:04', 4)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:05', 5)") + + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:05', 5)") + + #for state_window query + tdSql.execute("create table tb_w (ts timestamp, c0 int);") + + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:01', 0)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:02', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:03', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:04', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:05', 2)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:06', 5)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:07', 5)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:08', 0)") + + #for session query + tdSql.execute("create table tb_s (ts timestamp, c0 int);") + + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:00', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:02', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:04', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:07', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:10', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:14', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:18', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:23', 1)") + + #db precision "us" + tdSql.execute("drop database if exists db_u") + tdSql.execute("create database if not exists db_u precision 'us'") + tdSql.execute('use db_u') + + #for interval query + tdSql.execute("create stable stb_i (ts timestamp, c0 int) tags (t0 int);") + tdSql.execute("create table ctb1_i using stb_i tags (1);") + tdSql.execute("create table ctb2_i using stb_i tags (2);") + tdSql.execute("create table tb_i (ts timestamp, c0 int);") + + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:05', 5)") + + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:00', 0)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:01', 1)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:02', 2)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:03', 3)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:04', 4)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:05', 5)") + + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:05', 5)") + + #for state_window query + tdSql.execute("create table tb_w (ts timestamp, c0 int);") + + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:01', 0)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:02', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:03', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:04', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:05', 2)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:06', 5)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:07', 5)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:08', 0)") + + #for session query + tdSql.execute("create table tb_s (ts timestamp, c0 int);") + + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:00', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:02', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:04', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:07', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:10', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:14', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:18', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:23', 1)") + + #db precision "ns" + tdSql.execute("drop database if exists db_n") + tdSql.execute("create database if not exists db_n precision 'ns'") + tdSql.execute('use db_n') + + #for interval query + tdSql.execute("create stable stb_i (ts timestamp, c0 int) tags (t0 int);") + tdSql.execute("create table ctb1_i using stb_i tags (1);") + tdSql.execute("create table ctb2_i using stb_i tags (2);") + tdSql.execute("create table tb_i (ts timestamp, c0 int);") + + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into ctb1_i values ('2022-02-02 02:00:05', 5)") + + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:00', 0)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:01', 1)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:02', 2)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:03', 3)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:04', 4)") + tdSql.execute("insert into ctb2_i values ('2022-02-02 03:00:05', 5)") + + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:01', 1)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:02', 2)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:03', 3)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:04', 4)") + tdSql.execute("insert into tb_i values ('2022-02-02 02:00:05', 5)") + + #for state_window query + tdSql.execute("create table tb_w (ts timestamp, c0 int);") + + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:00', 0)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:01', 0)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:02', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:03', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:04', 1)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:05', 2)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:06', 5)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:07', 5)") + tdSql.execute("insert into tb_w values ('2022-02-02 02:00:08', 0)") + + #for session query + tdSql.execute("create table tb_s (ts timestamp, c0 int);") + + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:00', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:02', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:04', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:07', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:10', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:14', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:18', 1)") + tdSql.execute("insert into tb_s values ('2022-02-02 02:00:23', 1)") + + #execute query + print("============== STEP 1: select _wsatrt,_wstop,_wduration in interval query ================== ") + + # db precision "ms" + tdSql.execute('use db_m') + + ## _wstart + tdSql.query("select _wstart from tb_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from ctb1_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from stb_i interval (1a);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05") + + tdSql.query("select _wstart from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + + tdSql.query("select _wstart from tb_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + tdSql.query("select _wstart from ctb1_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + tdSql.query("select _wstart from stb_i interval (2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + + tdSql.query("select _wstart from tb_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + tdSql.query("select _wstart from ctb1_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + tdSql.query("select _wstart from stb_i interval (1m);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + + tdSql.query("select _wstart,avg(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart,avg(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart,avg(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + + tdSql.query("select avg(c0),_wstart from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 2) + + tdSql.query("select avg(c0),_wstart,sum(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart,sum(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart,sum(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 2) + + ##_wstop + tdSql.query("select _wstop from tb_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstop from ctb1_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstop from stb_i interval (1a);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05") + + tdSql.query("select _wstop from tb_i interval (10a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.009000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.009000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.009000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.009000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.009000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.009000") + tdSql.query("select _wstop from ctb1_i interval (10a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.009000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.009000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.009000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.009000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.009000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.009000") + tdSql.query("select _wstop from stb_i interval (10a);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.009000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.009000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.009000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.009000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.009000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.009000") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.009000") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.009000") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.009000") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.009000") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.009000") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.009000") + + tdSql.query("select _wstop from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wstop from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wstop from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999000") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999000") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999000") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + tdSql.query("select _wstop from tb_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wstop from ctb1_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wstop from stb_i interval (2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + tdSql.query("select _wstop from tb_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:59.999000") + tdSql.query("select _wstop from ctb1_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:59.999000") + tdSql.query("select _wstop from stb_i interval (1m);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:59.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:59.999000") + + tdSql.query("select _wstop,avg(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wstop,avg(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wstop,avg(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999000") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999000") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999000") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + tdSql.query("select avg(c0),_wstop from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select avg(c0),_wstop from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select avg(c0),_wstop from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999000") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999000") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999000") + res = tdSql.getData(11, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + tdSql.query("select avg(c0),_wstop,sum(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select avg(c0),_wstop,sum(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select avg(c0),_wstop,sum(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999000") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999000") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999000") + res = tdSql.getData(11, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + ##_wduration + tdSql.query("select _wduration from tb_i interval (1a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.query("select _wduration from ctb1_i interval (1a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.query("select _wduration from stb_i interval (1a);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.checkData(6, 1, 0) + tdSql.checkData(7, 1, 0) + tdSql.checkData(8, 1, 0) + tdSql.checkData(9, 1, 0) + tdSql.checkData(10, 1, 0) + tdSql.checkData(11, 1, 0) + + tdSql.query("select _wduration from tb_i interval (10a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 9) + tdSql.checkData(1, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 9) + tdSql.checkData(4, 1, 9) + tdSql.checkData(5, 1, 9) + tdSql.query("select _wduration from ctb1_i interval (10a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 9) + tdSql.checkData(1, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 9) + tdSql.checkData(4, 1, 9) + tdSql.checkData(5, 1, 9) + tdSql.query("select _wduration from stb_i interval (10a);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 9) + tdSql.checkData(1, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 9) + tdSql.checkData(4, 1, 9) + tdSql.checkData(5, 1, 9) + tdSql.checkData(6, 1, 9) + tdSql.checkData(7, 1, 9) + tdSql.checkData(8, 1, 9) + tdSql.checkData(9, 1, 9) + tdSql.checkData(10, 1, 9) + tdSql.checkData(11, 1, 9) + + tdSql.query("select _wduration from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.query("select _wduration from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.query("select _wduration from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.checkData(6, 1, 999) + tdSql.checkData(7, 1, 999) + tdSql.checkData(8, 1, 999) + tdSql.checkData(9, 1, 999) + tdSql.checkData(10, 1, 999) + tdSql.checkData(11, 1, 999) + + tdSql.query("select _wduration from tb_i interval (2s);") + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999) + tdSql.checkData(1, 1, 1999) + tdSql.checkData(2, 1, 1999) + tdSql.query("select _wduration from ctb1_i interval (2s);") + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999) + tdSql.checkData(1, 1, 1999) + tdSql.checkData(2, 1, 1999) + tdSql.query("select _wduration from stb_i interval (2s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 1999) + tdSql.checkData(1, 1, 1999) + tdSql.checkData(2, 1, 1999) + tdSql.checkData(3, 1, 1999) + tdSql.checkData(4, 1, 1999) + tdSql.checkData(5, 1, 1999) + + tdSql.query("select _wduration from tb_i interval (1m);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 59999) + tdSql.query("select _wduration from ctb1_i interval (1m);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 59999) + tdSql.query("select _wduration from stb_i interval (1m);") + tdSql.checkRows(2) + tdSql.checkData(0, 1, 59999) + tdSql.checkData(1, 1, 59999) + + tdSql.query("select _wduration,avg(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.query("select _wduration,avg(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.query("select _wduration,avg(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.checkData(6, 1, 999) + tdSql.checkData(7, 1, 999) + tdSql.checkData(8, 1, 999) + tdSql.checkData(9, 1, 999) + tdSql.checkData(10, 1, 999) + tdSql.checkData(11, 1, 999) + + tdSql.query("select avg(c0),_wduration from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999) + tdSql.checkData(1, 2, 999) + tdSql.checkData(2, 2, 999) + tdSql.checkData(3, 2, 999) + tdSql.checkData(4, 2, 999) + tdSql.checkData(5, 2, 999) + tdSql.query("select avg(c0),_wduration from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999) + tdSql.checkData(1, 2, 999) + tdSql.checkData(2, 2, 999) + tdSql.checkData(3, 2, 999) + tdSql.checkData(4, 2, 999) + tdSql.checkData(5, 2, 999) + tdSql.query("select avg(c0),_wduration from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 2, 999) + tdSql.checkData(1, 2, 999) + tdSql.checkData(2, 2, 999) + tdSql.checkData(3, 2, 999) + tdSql.checkData(4, 2, 999) + tdSql.checkData(5, 2, 999) + tdSql.checkData(6, 2, 999) + tdSql.checkData(7, 2, 999) + tdSql.checkData(8, 2, 999) + tdSql.checkData(9, 2, 999) + tdSql.checkData(10, 2, 999) + tdSql.checkData(11, 2, 999) + + tdSql.query("select avg(c0),_wduration,sum(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999) + tdSql.checkData(1, 2, 999) + tdSql.checkData(2, 2, 999) + tdSql.checkData(3, 2, 999) + tdSql.checkData(4, 2, 999) + tdSql.checkData(5, 2, 999) + tdSql.query("select avg(c0),_wduration,sum(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999) + tdSql.checkData(1, 2, 999) + tdSql.checkData(2, 2, 999) + tdSql.checkData(3, 2, 999) + tdSql.checkData(4, 2, 999) + tdSql.checkData(5, 2, 999) + tdSql.query("select avg(c0),_wduration,sum(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 2, 999) + tdSql.checkData(1, 2, 999) + tdSql.checkData(2, 2, 999) + tdSql.checkData(3, 2, 999) + tdSql.checkData(4, 2, 999) + tdSql.checkData(5, 2, 999) + tdSql.checkData(6, 2, 999) + tdSql.checkData(7, 2, 999) + tdSql.checkData(8, 2, 999) + tdSql.checkData(9, 2, 999) + tdSql.checkData(10, 2, 999) + tdSql.checkData(11, 2, 999) + + #_wstart,_wstop,_wduration together + tdSql.query("select _wstart,_wstop,_wduration from tb_i interval (2s);") + tdSql.checkCols(4) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.checkData(0, 3, 1999) + tdSql.checkData(1, 3, 1999) + tdSql.checkData(2, 3, 1999) + tdSql.query("select _wstart,_wstop,_wduration from ctb1_i interval (2s);") + tdSql.checkCols(4) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.checkData(0, 3, 1999) + tdSql.checkData(1, 3, 1999) + tdSql.checkData(2, 3, 1999) + tdSql.query("select _wstart,_wstop,_wduration from stb_i interval (2s);") + tdSql.checkCols(4) + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + tdSql.checkData(0, 3, 1999) + tdSql.checkData(1, 3, 1999) + tdSql.checkData(2, 3, 1999) + tdSql.checkData(3, 3, 1999) + tdSql.checkData(4, 3, 1999) + tdSql.checkData(5, 3, 1999) + + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from tb_i interval (2s);") + tdSql.checkCols(5) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.checkData(0, 3, 1999) + tdSql.checkData(1, 3, 1999) + tdSql.checkData(2, 3, 1999) + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from ctb1_i interval (2s);") + tdSql.checkCols(5) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.checkData(0, 3, 1999) + tdSql.checkData(1, 3, 1999) + tdSql.checkData(2, 3, 1999) + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from stb_i interval (2s);") + tdSql.checkCols(5) + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + tdSql.checkData(0, 3, 1999) + tdSql.checkData(1, 3, 1999) + tdSql.checkData(2, 3, 1999) + tdSql.checkData(3, 3, 1999) + tdSql.checkData(4, 3, 1999) + tdSql.checkData(5, 3, 1999) + + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from tb_i interval (2s);") + tdSql.checkCols(7) + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999) + tdSql.checkData(1, 1, 1999) + tdSql.checkData(2, 1, 1999) + res = tdSql.getData(0, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from ctb1_i interval (2s);") + tdSql.checkCols(7) + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999) + tdSql.checkData(1, 1, 1999) + tdSql.checkData(2, 1, 1999) + res = tdSql.getData(0, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from stb_i interval (2s);") + tdSql.checkCols(7) + tdSql.checkRows(6) + tdSql.checkData(0, 1, 1999) + tdSql.checkData(1, 1, 1999) + tdSql.checkData(2, 1, 1999) + tdSql.checkData(3, 1, 1999) + tdSql.checkData(4, 1, 1999) + tdSql.checkData(5, 1, 1999) + res = tdSql.getData(0, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 3) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 3) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 3) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(0, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(3, 5) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(4, 5) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(5, 5) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + # db precision "us" + tdSql.execute('use db_u') + + ## _wstart + tdSql.query("select _wstart from tb_i interval (1u);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from ctb1_i interval (1u);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from stb_i interval (1u);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05") + + tdSql.query("select _wstart from tb_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from ctb1_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from stb_i interval (1a);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05") + + tdSql.query("select _wstart from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + + tdSql.query("select _wstart from tb_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + tdSql.query("select _wstart from ctb1_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + tdSql.query("select _wstart from stb_i interval (2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + + tdSql.query("select _wstart from tb_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + tdSql.query("select _wstart from ctb1_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + tdSql.query("select _wstart from stb_i interval (1m);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + + tdSql.query("select _wstart,avg(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart,avg(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstart,avg(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + + tdSql.query("select avg(c0),_wstart from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 2) + + tdSql.query("select avg(c0),_wstart,sum(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart,sum(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select avg(c0),_wstart,sum(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 2) + + ##_wstop + tdSql.query("select _wstop from tb_i interval (1u);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstop from ctb1_i interval (1u);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + tdSql.query("select _wstop from stb_i interval (1u);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05") + + tdSql.query("select _wstop from tb_i interval (10u);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.000009") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.000009") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.000009") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.000009") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.000009") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.000009") + tdSql.query("select _wstop from ctb1_i interval (10u);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.000009") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.000009") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.000009") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.000009") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.000009") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.000009") + tdSql.query("select _wstop from stb_i interval (10u);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.000009") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.000009") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.000009") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.000009") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.000009") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.000009") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.000009") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.000009") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.000009") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.000009") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.000009") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.000009") + + tdSql.query("select _wstop from tb_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.000999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.000999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.000999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.000999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.000999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.000999") + tdSql.query("select _wstop from ctb1_i interval (1a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.000999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.000999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.000999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.000999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.000999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.000999") + tdSql.query("select _wstop from stb_i interval (1a);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.000999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.000999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.000999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.000999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.000999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.000999") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.000999") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.000999") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.000999") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.000999") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.000999") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.000999") + + tdSql.query("select _wstop from tb_i interval (10a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.009999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.009999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.009999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.009999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.009999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.009999") + tdSql.query("select _wstop from ctb1_i interval (10a);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.009999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.009999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.009999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.009999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.009999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.009999") + tdSql.query("select _wstop from stb_i interval (10a);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.009999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.009999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.009999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.009999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.009999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.009999") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.009999") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.009999") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.009999") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.009999") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.009999") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.009999") + + tdSql.query("select _wstop from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wstop from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wstop from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999999") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999999") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999999") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + + tdSql.query("select _wstop from tb_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wstop from ctb1_i interval (2s);") + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wstop from stb_i interval (2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + + tdSql.query("select _wstop from tb_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:59.999999") + tdSql.query("select _wstop from ctb1_i interval (1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:59.999999") + tdSql.query("select _wstop from stb_i interval (1m);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:59.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:59.999999") + + tdSql.query("select _wstop,avg(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wstop,avg(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wstop,avg(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999999") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(8, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999999") + res = tdSql.getData(9, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(10, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999999") + res = tdSql.getData(11, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + + tdSql.query("select avg(c0),_wstop from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select avg(c0),_wstop from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select avg(c0),_wstop from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999999") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999999") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999999") + res = tdSql.getData(11, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + + tdSql.query("select avg(c0),_wstop,sum(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select avg(c0),_wstop,sum(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select avg(c0),_wstop,sum(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00.999999") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(8, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02.999999") + res = tdSql.getData(9, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(10, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04.999999") + res = tdSql.getData(11, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + + ##_wduration + tdSql.query("select _wduration from tb_i interval (1u);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.query("select _wduration from ctb1_i interval (1u);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.query("select _wduration from stb_i interval (1u);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.checkData(6, 1, 0) + tdSql.checkData(7, 1, 0) + tdSql.checkData(8, 1, 0) + tdSql.checkData(9, 1, 0) + tdSql.checkData(10, 1, 0) + tdSql.checkData(11, 1, 0) + + tdSql.query("select _wduration from tb_i interval (10u);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 9) + tdSql.checkData(1, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 9) + tdSql.checkData(4, 1, 9) + tdSql.checkData(5, 1, 9) + tdSql.query("select _wduration from ctb1_i interval (10u);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 9) + tdSql.checkData(1, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 9) + tdSql.checkData(4, 1, 9) + tdSql.checkData(5, 1, 9) + tdSql.query("select _wduration from stb_i interval (10u);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 9) + tdSql.checkData(1, 1, 9) + tdSql.checkData(2, 1, 9) + tdSql.checkData(3, 1, 9) + tdSql.checkData(4, 1, 9) + tdSql.checkData(5, 1, 9) + tdSql.checkData(6, 1, 9) + tdSql.checkData(7, 1, 9) + tdSql.checkData(8, 1, 9) + tdSql.checkData(9, 1, 9) + tdSql.checkData(10, 1, 9) + tdSql.checkData(11, 1, 9) + + tdSql.query("select _wduration from tb_i interval (1a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.query("select _wduration from ctb1_i interval (1a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.query("select _wduration from stb_i interval (1a);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 999) + tdSql.checkData(1, 1, 999) + tdSql.checkData(2, 1, 999) + tdSql.checkData(3, 1, 999) + tdSql.checkData(4, 1, 999) + tdSql.checkData(5, 1, 999) + tdSql.checkData(6, 1, 999) + tdSql.checkData(7, 1, 999) + tdSql.checkData(8, 1, 999) + tdSql.checkData(9, 1, 999) + tdSql.checkData(10, 1, 999) + tdSql.checkData(11, 1, 999) + + tdSql.query("select _wduration from tb_i interval (10a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 9999) + tdSql.checkData(1, 1, 9999) + tdSql.checkData(2, 1, 9999) + tdSql.checkData(3, 1, 9999) + tdSql.checkData(4, 1, 9999) + tdSql.checkData(5, 1, 9999) + tdSql.query("select _wduration from ctb1_i interval (10a);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 9999) + tdSql.checkData(1, 1, 9999) + tdSql.checkData(2, 1, 9999) + tdSql.checkData(3, 1, 9999) + tdSql.checkData(4, 1, 9999) + tdSql.checkData(5, 1, 9999) + tdSql.query("select _wduration from stb_i interval (10a);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 9999) + tdSql.checkData(1, 1, 9999) + tdSql.checkData(2, 1, 9999) + tdSql.checkData(3, 1, 9999) + tdSql.checkData(4, 1, 9999) + tdSql.checkData(5, 1, 9999) + tdSql.checkData(6, 1, 9999) + tdSql.checkData(7, 1, 9999) + tdSql.checkData(8, 1, 9999) + tdSql.checkData(9, 1, 9999) + tdSql.checkData(10, 1, 9999) + tdSql.checkData(11, 1, 9999) + + tdSql.query("select _wduration from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999999) + tdSql.checkData(1, 1, 999999) + tdSql.checkData(2, 1, 999999) + tdSql.checkData(3, 1, 999999) + tdSql.checkData(4, 1, 999999) + tdSql.checkData(5, 1, 999999) + tdSql.query("select _wduration from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999999) + tdSql.checkData(1, 1, 999999) + tdSql.checkData(2, 1, 999999) + tdSql.checkData(3, 1, 999999) + tdSql.checkData(4, 1, 999999) + tdSql.checkData(5, 1, 999999) + tdSql.query("select _wduration from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 999999) + tdSql.checkData(1, 1, 999999) + tdSql.checkData(2, 1, 999999) + tdSql.checkData(3, 1, 999999) + tdSql.checkData(4, 1, 999999) + tdSql.checkData(5, 1, 999999) + tdSql.checkData(6, 1, 999999) + tdSql.checkData(7, 1, 999999) + tdSql.checkData(8, 1, 999999) + tdSql.checkData(9, 1, 999999) + tdSql.checkData(10, 1, 999999) + tdSql.checkData(11, 1, 999999) + + tdSql.query("select _wduration from tb_i interval (2s);") + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999999) + tdSql.checkData(1, 1, 1999999) + tdSql.checkData(2, 1, 1999999) + tdSql.query("select _wduration from ctb1_i interval (2s);") + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999999) + tdSql.checkData(1, 1, 1999999) + tdSql.checkData(2, 1, 1999999) + tdSql.query("select _wduration from stb_i interval (2s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 1999999) + tdSql.checkData(1, 1, 1999999) + tdSql.checkData(2, 1, 1999999) + tdSql.checkData(3, 1, 1999999) + tdSql.checkData(4, 1, 1999999) + tdSql.checkData(5, 1, 1999999) + + tdSql.query("select _wduration from tb_i interval (1m);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 59999999) + tdSql.query("select _wduration from ctb1_i interval (1m);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 59999999) + tdSql.query("select _wduration from stb_i interval (1m);") + tdSql.checkRows(2) + tdSql.checkData(0, 1, 59999999) + tdSql.checkData(1, 1, 59999999) + + tdSql.query("select _wduration,avg(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999999) + tdSql.checkData(1, 1, 999999) + tdSql.checkData(2, 1, 999999) + tdSql.checkData(3, 1, 999999) + tdSql.checkData(4, 1, 999999) + tdSql.checkData(5, 1, 999999) + tdSql.query("select _wduration,avg(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 999999) + tdSql.checkData(1, 1, 999999) + tdSql.checkData(2, 1, 999999) + tdSql.checkData(3, 1, 999999) + tdSql.checkData(4, 1, 999999) + tdSql.checkData(5, 1, 999999) + tdSql.query("select _wduration,avg(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 1, 999999) + tdSql.checkData(1, 1, 999999) + tdSql.checkData(2, 1, 999999) + tdSql.checkData(3, 1, 999999) + tdSql.checkData(4, 1, 999999) + tdSql.checkData(5, 1, 999999) + tdSql.checkData(6, 1, 999999) + tdSql.checkData(7, 1, 999999) + tdSql.checkData(8, 1, 999999) + tdSql.checkData(9, 1, 999999) + tdSql.checkData(10, 1, 999999) + tdSql.checkData(11, 1, 999999) + + tdSql.query("select avg(c0),_wduration from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999999) + tdSql.checkData(1, 2, 999999) + tdSql.checkData(2, 2, 999999) + tdSql.checkData(3, 2, 999999) + tdSql.checkData(4, 2, 999999) + tdSql.checkData(5, 2, 999999) + tdSql.query("select avg(c0),_wduration from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999999) + tdSql.checkData(1, 2, 999999) + tdSql.checkData(2, 2, 999999) + tdSql.checkData(3, 2, 999999) + tdSql.checkData(4, 2, 999999) + tdSql.checkData(5, 2, 999999) + tdSql.query("select avg(c0),_wduration from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 2, 999999) + tdSql.checkData(1, 2, 999999) + tdSql.checkData(2, 2, 999999) + tdSql.checkData(3, 2, 999999) + tdSql.checkData(4, 2, 999999) + tdSql.checkData(5, 2, 999999) + tdSql.checkData(6, 2, 999999) + tdSql.checkData(7, 2, 999999) + tdSql.checkData(8, 2, 999999) + tdSql.checkData(9, 2, 999999) + tdSql.checkData(10, 2, 999999) + tdSql.checkData(11, 2, 999999) + + tdSql.query("select avg(c0),_wduration,sum(c0) from tb_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999999) + tdSql.checkData(1, 2, 999999) + tdSql.checkData(2, 2, 999999) + tdSql.checkData(3, 2, 999999) + tdSql.checkData(4, 2, 999999) + tdSql.checkData(5, 2, 999999) + tdSql.query("select avg(c0),_wduration,sum(c0) from ctb1_i interval (1s);") + tdSql.checkRows(6) + tdSql.checkData(0, 2, 999999) + tdSql.checkData(1, 2, 999999) + tdSql.checkData(2, 2, 999999) + tdSql.checkData(3, 2, 999999) + tdSql.checkData(4, 2, 999999) + tdSql.checkData(5, 2, 999999) + tdSql.query("select avg(c0),_wduration,sum(c0) from stb_i interval (1s);") + tdSql.checkRows(12) + tdSql.checkData(0, 2, 999999) + tdSql.checkData(1, 2, 999999) + tdSql.checkData(2, 2, 999999) + tdSql.checkData(3, 2, 999999) + tdSql.checkData(4, 2, 999999) + tdSql.checkData(5, 2, 999999) + tdSql.checkData(6, 2, 999999) + tdSql.checkData(7, 2, 999999) + tdSql.checkData(8, 2, 999999) + tdSql.checkData(9, 2, 999999) + tdSql.checkData(10, 2, 999999) + tdSql.checkData(11, 2, 999999) + + #_wstart,_wstop,_wduration together + tdSql.query("select _wstart,_wstop,_wduration from tb_i interval (2s);") + tdSql.checkCols(4) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.checkData(0, 3, 1999999) + tdSql.checkData(1, 3, 1999999) + tdSql.checkData(2, 3, 1999999) + tdSql.query("select _wstart,_wstop,_wduration from ctb1_i interval (2s);") + tdSql.checkCols(4) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.checkData(0, 3, 1999999) + tdSql.checkData(1, 3, 1999999) + tdSql.checkData(2, 3, 1999999) + tdSql.query("select _wstart,_wstop,_wduration from stb_i interval (2s);") + tdSql.checkCols(4) + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + tdSql.checkData(0, 3, 1999999) + tdSql.checkData(1, 3, 1999999) + tdSql.checkData(2, 3, 1999999) + tdSql.checkData(3, 3, 1999999) + tdSql.checkData(4, 3, 1999999) + tdSql.checkData(5, 3, 1999999) + + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from tb_i interval (2s);") + tdSql.checkCols(5) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.checkData(0, 3, 1999999) + tdSql.checkData(1, 3, 1999999) + tdSql.checkData(2, 3, 1999999) + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from ctb1_i interval (2s);") + tdSql.checkCols(5) + tdSql.checkRows(3) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.checkData(0, 3, 1999999) + tdSql.checkData(1, 3, 1999999) + tdSql.checkData(2, 3, 1999999) + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from stb_i interval (2s);") + tdSql.checkCols(5) + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + tdSql.checkData(0, 3, 1999999) + tdSql.checkData(1, 3, 1999999) + tdSql.checkData(2, 3, 1999999) + tdSql.checkData(3, 3, 1999999) + tdSql.checkData(4, 3, 1999999) + tdSql.checkData(5, 3, 1999999) + + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from tb_i interval (2s);") + tdSql.checkCols(7) + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999999) + tdSql.checkData(1, 1, 1999999) + tdSql.checkData(2, 1, 1999999) + res = tdSql.getData(0, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from ctb1_i interval (2s);") + tdSql.checkCols(7) + tdSql.checkRows(3) + tdSql.checkData(0, 1, 1999999) + tdSql.checkData(1, 1, 1999999) + tdSql.checkData(2, 1, 1999999) + res = tdSql.getData(0, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(0, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from stb_i interval (2s);") + tdSql.checkCols(7) + tdSql.checkRows(6) + tdSql.checkData(0, 1, 1999999) + tdSql.checkData(1, 1, 1999999) + tdSql.checkData(2, 1, 1999999) + tdSql.checkData(3, 1, 1999999) + tdSql.checkData(4, 1, 1999999) + tdSql.checkData(5, 1, 1999999) + res = tdSql.getData(0, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 3) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 3) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 3) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 3) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + res = tdSql.getData(0, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999999") + res = tdSql.getData(1, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999999") + res = tdSql.getData(2, 5) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999999") + res = tdSql.getData(3, 5) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999999") + res = tdSql.getData(4, 5) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999999") + res = tdSql.getData(5, 5) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999999") + + + print("============== STEP 2: select _wsatrt,_wstop,_wduration in state_window query ================== ") + + # db precision "ms" + tdSql.execute('use db_m') + + ## _wstart + tdSql.query("select _wstart from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select _wstart,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select sum(c0),_wstart,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + ##_wstop + tdSql.query("select _wstop from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select _wstop,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select sum(c0),_wstop,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + ##_wduration + tdSql.query("select _wduration from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 0, 1000) + tdSql.checkData(1, 0, 2000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000) + tdSql.checkData(4, 0, 0) + + tdSql.query("select _wduration,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 0, 1000) + tdSql.checkData(1, 0, 2000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000) + tdSql.checkData(4, 0, 0) + + tdSql.query("select sum(c0),_wduration,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 1, 1000) + tdSql.checkData(1, 1, 2000) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 1000) + tdSql.checkData(4, 1, 0) + + #_wstart,_wstop,_wduration together + tdSql.query("select _wstart,_wstop,_wduration from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + tdSql.checkData(0, 2, 1000) + tdSql.checkData(1, 2, 2000) + tdSql.checkData(2, 2, 0) + tdSql.checkData(3, 2, 1000) + tdSql.checkData(4, 2, 0) + + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + tdSql.checkData(0, 2, 1000) + tdSql.checkData(1, 2, 2000) + tdSql.checkData(2, 2, 0) + tdSql.checkData(3, 2, 1000) + tdSql.checkData(4, 2, 0) + + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 0, 1000) + tdSql.checkData(1, 0, 2000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000) + tdSql.checkData(4, 0, 0) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + res = tdSql.getData(0, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + # db precision "us" + tdSql.execute('use db_u') + + ## _wstart + tdSql.query("select _wstart from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select _wstart,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select sum(c0),_wstart,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + ##_wstop + tdSql.query("select _wstop from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select _wstop,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query("select sum(c0),_wstop,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + ##_wduration + tdSql.query("select _wduration from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 0, 1000000) + tdSql.checkData(1, 0, 2000000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000000) + tdSql.checkData(4, 0, 0) + + tdSql.query("select _wduration,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 0, 1000000) + tdSql.checkData(1, 0, 2000000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000000) + tdSql.checkData(4, 0, 0) + + tdSql.query("select sum(c0),_wduration,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 1, 1000000) + tdSql.checkData(1, 1, 2000000) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 1000000) + tdSql.checkData(4, 1, 0) + + #_wstart,_wstop,_wduration together + tdSql.query("select _wstart,_wstop,_wduration from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + tdSql.checkData(0, 0, 1000000) + tdSql.checkData(1, 0, 2000000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000000) + tdSql.checkData(4, 0, 0) + + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + tdSql.checkData(0, 0, 1000000) + tdSql.checkData(1, 0, 2000000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000000) + tdSql.checkData(4, 0, 0) + + tdSql.query("select _wduration,avg(c0),_wstart,sum(c0),_wstop,stddev(c0) from tb_w state_window(c0);") + tdSql.checkRows(5) + tdSql.checkData(0, 0, 1000000) + tdSql.checkData(1, 0, 2000000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000000) + tdSql.checkData(4, 0, 0) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + res = tdSql.getData(0, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 4) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + print("============== STEP 3: select _wsatrt,_wstop,_wduration in session query ================== ") + + # db precision "ms" + tdSql.execute('use db_m') + + ## _wstart + tdSql.query("select _wstart from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 3s);") + tdSql.checkRows(4) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 5s);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + + tdSql.query("select _wstart from tb_s session(ts, 1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + + tdSql.query("select _wstart,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select sum(c0),_wstart,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + ##_wstop + tdSql.query("select _wstop from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 3s);") + tdSql.checkRows(4) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 5s);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select sum(c0),_wstop,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + ##_wduration + tdSql.query("select _wduration from tb_s session(ts, 1s);") + tdSql.checkRows(8) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.checkData(6, 1, 0) + tdSql.checkData(7, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 2s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 4000) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 3s);") + tdSql.checkRows(4) + tdSql.checkData(0, 1, 10000) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 4s);") + tdSql.checkRows(2) + tdSql.checkData(0, 1, 18000) + tdSql.checkData(1, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 5s);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 23000) + + tdSql.query("select _wduration from tb_s session(ts, 1m);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 23000) + + tdSql.query("select _wduration,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + tdSql.checkData(0, 1, 18000) + tdSql.checkData(1, 1, 0) + + tdSql.query("select sum(c0),_wduration,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + tdSql.checkData(0, 2, 18000) + tdSql.checkData(1, 2, 0) + + #_wstart,_wstop,_wduration together + tdSql.query("select _wstart,_wstop,_wduration from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + tdSql.checkData(0, 3, 0) + tdSql.checkData(1, 3, 0) + tdSql.checkData(2, 3, 0) + tdSql.checkData(3, 3, 0) + tdSql.checkData(4, 3, 0) + tdSql.checkData(5, 3, 0) + tdSql.checkData(6, 3, 0) + tdSql.checkData(7, 3, 0) + + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + tdSql.checkData(0, 3, 0) + tdSql.checkData(1, 3, 0) + tdSql.checkData(2, 3, 0) + tdSql.checkData(3, 3, 0) + tdSql.checkData(4, 3, 0) + tdSql.checkData(5, 3, 0) + tdSql.checkData(6, 3, 0) + tdSql.checkData(7, 3, 0) + + + # db precision "us" + tdSql.execute('use db_u') + + ## _wstart + tdSql.query("select _wstart from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 3s);") + tdSql.checkRows(4) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstart from tb_s session(ts, 5s);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + + tdSql.query("select _wstart from tb_s session(ts, 1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + + tdSql.query("select _wstart,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select sum(c0),_wstart,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + ##_wstop + tdSql.query("select _wstop from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 2s);") + tdSql.checkRows(6) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 3s);") + tdSql.checkRows(4) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 5s);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop from tb_s session(ts, 1m);") + tdSql.checkRows(1) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select _wstop,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + tdSql.query("select sum(c0),_wstop,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + ##_wduration + tdSql.query("select _wduration from tb_s session(ts, 1s);") + tdSql.checkRows(8) + tdSql.checkData(0, 1, 0) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + tdSql.checkData(6, 1, 0) + tdSql.checkData(7, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 2s);") + tdSql.checkRows(6) + tdSql.checkData(0, 1, 4000000) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + tdSql.checkData(4, 1, 0) + tdSql.checkData(5, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 3s);") + tdSql.checkRows(4) + tdSql.checkData(0, 1, 10000000) + tdSql.checkData(1, 1, 0) + tdSql.checkData(2, 1, 0) + tdSql.checkData(3, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 4s);") + tdSql.checkRows(2) + tdSql.checkData(0, 1, 18000000) + tdSql.checkData(1, 1, 0) + + tdSql.query("select _wduration from tb_s session(ts, 5s);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 23000000) + + tdSql.query("select _wduration from tb_s session(ts, 1m);") + tdSql.checkRows(1) + tdSql.checkData(0, 1, 23000000) + + tdSql.query("select _wduration,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + tdSql.checkData(0, 1, 18000000) + tdSql.checkData(1, 1, 0) + + tdSql.query("select sum(c0),_wduration,avg(c0) from tb_s session(ts, 4s);") + tdSql.checkRows(2) + tdSql.checkData(0, 2, 18000000) + tdSql.checkData(1, 2, 0) + + #_wstart,_wstop,_wduration together + tdSql.query("select _wstart,_wstop,_wduration from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + tdSql.checkData(0, 3, 0) + tdSql.checkData(1, 3, 0) + tdSql.checkData(2, 3, 0) + tdSql.checkData(3, 3, 0) + tdSql.checkData(4, 3, 0) + tdSql.checkData(5, 3, 0) + tdSql.checkData(6, 3, 0) + tdSql.checkData(7, 3, 0) + + tdSql.query("select _wstart,_wstop,_wduration,avg(c0) from tb_s session(ts, 1s);") + tdSql.checkRows(8) + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 1) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + res = tdSql.getData(0, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(5, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(6, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(7, 2) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + tdSql.checkData(0, 3, 0) + tdSql.checkData(1, 3, 0) + tdSql.checkData(2, 3, 0) + tdSql.checkData(3, 3, 0) + tdSql.checkData(4, 3, 0) + tdSql.checkData(5, 3, 0) + tdSql.checkData(6, 3, 0) + tdSql.checkData(7, 3, 0) + + print("============== STEP 4: select _wsatrt,_wstop,_wduration in nested outer query ================== ") + tdSql.execute('use db_m') + ##_wstart + tdSql.query('select _wstart from (select _wstart from tb_i interval (2s))') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + tdSql.query('select _wstart from (select _wstart from ctb1_i interval (2s))') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + tdSql.query('select _wstart from (select _wstart from stb_i interval (2s))') + tdSql.checkRows(6) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 03:00:00") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 03:00:02") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 03:00:04") + + tdSql.query('select _wstart from (select _wstart from tb_w state_window(c0))') + tdSql.checkRows(5) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:02") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:06") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query('select _wstart from (select _wstart from tb_s session(ts, 2s))') + tdSql.checkRows(6) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:00") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + ##_wstop + tdSql.query('select _wstop from (select _wstop from tb_i interval (2s))') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query('select _wstop from (select _wstop from ctb1_i interval (2s))') + tdSql.checkRows(3) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + tdSql.query('select _wstop from (select _wstop from stb_i interval (2s))') + tdSql.checkRows(6) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01.999000") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:03.999000") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05.999000") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 03:00:01.999000") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 03:00:03.999000") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 03:00:05.999000") + + tdSql.query('select _wstop from (select _wstop from tb_w state_window(c0))') + tdSql.checkRows(5) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:01") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:05") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:08") + + tdSql.query('select _wstop from (select _wstop from tb_s session(ts, 2s))') + tdSql.checkRows(6) + tdSql.checkCols(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:04") + res = tdSql.getData(1, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:07") + res = tdSql.getData(2, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:10") + res = tdSql.getData(3, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:14") + res = tdSql.getData(4, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:18") + res = tdSql.getData(5, 0) + tdSql.checkEqual(str(res), "2022-02-02 02:00:23") + + ##_wduration + tdSql.query('select _wduration from (select _wduration from tb_i interval (2s))') + tdSql.checkRows(3) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 1999) + tdSql.checkData(1, 0, 1999) + tdSql.checkData(2, 0, 1999) + tdSql.query('select _wduration from (select _wduration from ctb1_i interval (2s))') + tdSql.checkRows(3) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 1999) + tdSql.checkData(1, 0, 1999) + tdSql.checkData(2, 0, 1999) + tdSql.query('select _wduration from (select _wduration from stb_i interval (2s))') + tdSql.checkRows(6) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 1999) + tdSql.checkData(1, 0, 1999) + tdSql.checkData(2, 0, 1999) + tdSql.checkData(3, 0, 1999) + tdSql.checkData(4, 0, 1999) + tdSql.checkData(5, 0, 1999) + + tdSql.query('select _wduration from (select _wduration from tb_w state_window(c0))') + tdSql.checkRows(5) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 1000) + tdSql.checkData(1, 0, 2000) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 1000) + tdSql.checkData(4, 0, 0) + + tdSql.query('select _wduration from (select _wduration from tb_s session(ts, 2s))') + tdSql.checkRows(6) + tdSql.checkCols(1) + tdSql.checkData(0, 0, 4000) + tdSql.checkData(1, 0, 0) + tdSql.checkData(2, 0, 0) + tdSql.checkData(3, 0, 0) + tdSql.checkData(4, 0, 0) + tdSql.checkData(5, 0, 0) + + print("============== STEP 5: select _wstart/_wstop/_wduration other cases ================== ") + + #distinct + tdSql.query("select distinct _wstart from tb_i interval (1s)") + tdSql.query("select distinct _wstart from ctb1_i interval (1s)") + tdSql.query("select distinct _wstart from stb_i interval (1s)") + + tdSql.query("select distinct _wstop from tb_i interval (1s)") + tdSql.query("select distinct _wstop from ctb1_i interval (1s)") + tdSql.query("select distinct _wstop from stb_i interval (1s)") + + tdSql.query("select distinct _wduration from tb_i interval (1s)") + tdSql.query("select distinct _wduration from ctb1_i interval (1s)") + tdSql.query("select distinct _wduration from stb_i interval (1s)") + + #_ws,col + tdSql.query("select _wstart,ts from tb_i interval (1s)") + tdSql.query("select _wstart,ts from ctb1_i interval (1s)") + tdSql.query("select _wstart,ts from stb_i interval (1s)") + #tdSql.query("select _wstart,c0 from tb_i interval (1s)") + #tdSql.query("select _wstart,c0 from ctb1_i interval (1s)") + #tdSql.query("select _wstart,c0 from stb_i interval (1s)") + tdSql.query("select _wstart,_wstart from tb_i interval (1s)") + tdSql.query("select _wstart,_wstart from ctb1_i interval (1s)") + tdSql.query("select _wstart,_wstart from stb_i interval (1s)") + tdSql.query("select _wstart,t0 from ctb1_i interval (1s)") + tdSql.query("select _wstart,t0 from stb_i interval (1s)") + + tdSql.query("select _wstop,ts from tb_i interval (1s)") + tdSql.query("select _wstop,ts from ctb1_i interval (1s)") + tdSql.query("select _wstop,ts from stb_i interval (1s)") + #tdSql.query("select _wstop,c0 from tb_i interval (1s)") + #tdSql.query("select _wstop,c0 from ctb1_i interval (1s)") + #tdSql.query("select _wstop,c0 from stb_i interval (1s)") + tdSql.query("select _wstop,_wstop from tb_i interval (1s)") + tdSql.query("select _wstop,_wstop from ctb1_i interval (1s)") + tdSql.query("select _wstop,_wstop from stb_i interval (1s)") + tdSql.query("select _wstop,t0 from ctb1_i interval (1s)") + tdSql.query("select _wstop,t0 from stb_i interval (1s)") + + tdSql.query("select _wduration,ts from tb_i interval (1s)") + tdSql.query("select _wduration,ts from ctb1_i interval (1s)") + tdSql.query("select _wduration,ts from stb_i interval (1s)") + #tdSql.query("select _wduration,c0 from tb_i interval (1s)") + #tdSql.query("select _wduration,c0 from ctb1_i interval (1s)") + #tdSql.query("select _wduration,c0 from stb_i interval (1s)") + tdSql.query("select _wduration,_wduration from tb_i interval (1s)") + tdSql.query("select _wduration,_wduration from ctb1_i interval (1s)") + tdSql.query("select _wduration,_wduration from stb_i interval (1s)") + tdSql.query("select _wduration,t0 from ctb1_i interval (1s)") + tdSql.query("select _wduration,t0 from stb_i interval (1s)") + + #_ws,constant + tdSql.query("select _wstart,1 from tb_i interval (1s)") + tdSql.query("select _wstart,1 from ctb1_i interval (1s)") + tdSql.query("select _wstart,1 from stb_i interval (1s)") + tdSql.query("select _wstart,true from tb_i interval (1s)") + tdSql.query("select _wstart,true from ctb1_i interval (1s)") + tdSql.query("select _wstart,true from stb_i interval (1s)") + tdSql.query("select _wstart,'abc' from tb_i interval (1s)") + tdSql.query("select _wstart,'abc' from ctb1_i interval (1s)") + tdSql.query("select _wstart,'abc' from stb_i interval (1s)") + + tdSql.query("select _wstop,1 from tb_i interval (1s)") + tdSql.query("select _wstop,1 from ctb1_i interval (1s)") + tdSql.query("select _wstop,1 from stb_i interval (1s)") + tdSql.query("select _wstop,true from tb_i interval (1s)") + tdSql.query("select _wstop,true from ctb1_i interval (1s)") + tdSql.query("select _wstop,true from stb_i interval (1s)") + tdSql.query("select _wstop,'abc' from tb_i interval (1s)") + tdSql.query("select _wstop,'abc' from ctb1_i interval (1s)") + tdSql.query("select _wstop,'abc' from stb_i interval (1s)") + + tdSql.query("select _wduration,1 from tb_i interval (1s)") + tdSql.query("select _wduration,1 from ctb1_i interval (1s)") + tdSql.query("select _wduration,1 from stb_i interval (1s)") + tdSql.query("select _wduration,true from tb_i interval (1s)") + tdSql.query("select _wduration,true from ctb1_i interval (1s)") + tdSql.query("select _wduration,true from stb_i interval (1s)") + tdSql.query("select _wduration,'abc' from tb_i interval (1s)") + tdSql.query("select _wduration,'abc' from ctb1_i interval (1s)") + tdSql.query("select _wduration,'abc' from stb_i interval (1s)") + + #interval sliding + tdSql.query("select _wstart from tb_i interval (1s) sliding (1s)") + tdSql.query("select _wstart from ctb1_i interval (1s) sliding (1s)") + tdSql.query("select _wstart from stb_i interval (1s) sliding (1s)") + + tdSql.query("select _wstop from tb_i interval (1s) sliding (1s)") + tdSql.query("select _wstop from ctb1_i interval (1s) sliding (1s)") + tdSql.query("select _wstop from stb_i interval (1s) sliding (1s)") + + tdSql.query("select _wduration from tb_i interval (1s) sliding (1s)") + tdSql.query("select _wduration from ctb1_i interval (1s) sliding (1s)") + tdSql.query("select _wduration from stb_i interval (1s) sliding (1s)") + + #group by + tdSql.query("select _wstart from stb_i interval (1s) group by tbname") + + tdSql.query("select _wstop from stb_i interval (1s) group by tbname") + + tdSql.query("select _wduration from stb_i interval (1s) group by tbname") + + #order by + tdSql.query("select _wstart from tb_i interval (1s) order by ts") + tdSql.query("select _wstart from ctb1_i interval (1s) order by ts") + tdSql.query("select _wstart from stb_i interval (1s) order by ts") + tdSql.query("select _wstart from tb_i interval (1s) order by ts desc") + tdSql.query("select _wstart from ctb1_i interval (1s) order by ts desc") + tdSql.query("select _wstart from stb_i interval (1s) order by ts desc") + + tdSql.query("select _wstop from tb_i interval (1s) order by ts") + tdSql.query("select _wstop from ctb1_i interval (1s) order by ts") + tdSql.query("select _wstop from stb_i interval (1s) order by ts") + tdSql.query("select _wstop from tb_i interval (1s) order by ts desc") + tdSql.query("select _wstop from ctb1_i interval (1s) order by ts desc") + tdSql.query("select _wstop from stb_i interval (1s) order by ts desc") + + + tdSql.query("select _wduration from tb_i interval (1s) order by ts") + tdSql.query("select _wduration from ctb1_i interval (1s) order by ts") + tdSql.query("select _wduration from stb_i interval (1s) order by ts") + tdSql.query("select _wduration from tb_i interval (1s) order by ts desc") + tdSql.query("select _wduration from ctb1_i interval (1s) order by ts desc") + tdSql.query("select _wduration from stb_i interval (1s) order by ts desc") + + #limit + tdSql.query("select _wstart from tb_i interval (1s) limit 3") + tdSql.query("select _wstart from ctb1_i interval (1s) limit 3") + tdSql.query("select _wstart from stb_i interval (1s) limit 3") + + tdSql.query("select _wstop from tb_i interval (1s) limit 3") + tdSql.query("select _wstop from ctb1_i interval (1s) limit 3") + tdSql.query("select _wstop from stb_i interval (1s) limit 3") + + + tdSql.query("select _wduration from tb_i interval (1s) limit 3") + tdSql.query("select _wduration from ctb1_i interval (1s) limit 3") + tdSql.query("select _wduration from stb_i interval (1s) limit 3") + + ############# not supported ############### + tdSql.error("select _wstart from tb_i") + tdSql.error("select _wstart from ctb1_i") + tdSql.error("select _wstart from stb_i") + tdSql.error("select _wstart + 1 from tb_i interval (1s)") + tdSql.error("select _wstart + 1 from ctb1_i interval (1s)") + tdSql.error("select _wstart + 1 from stb_i interval (1s)") + tdSql.error("select _wstart + 1.0 from tb_i interval (1s)") + tdSql.error("select _wstart + 1.0 from ctb1_i interval (1s)") + tdSql.error("select _wstart + 1.0 from stb_i interval (1s)") + tdSql.error("select _wstart + true from tb_i interval (1s)") + tdSql.error("select _wstart + true from ctb1_i interval (1s)") + tdSql.error("select _wstart + true from stb_i interval (1s)") + tdSql.error("select _wstart + 'abc' from tb_i interval (1s)") + tdSql.error("select _wstart + 'abc' from ctb1_i interval (1s)") + tdSql.error("select _wstart + 'abc' from stb_i interval (1s)") + tdSql.error("select _wstart + 1s from tb_i interval (1s)") + tdSql.error("select _wstart + 1s from ctb1_i interval (1s)") + tdSql.error("select _wstart + 1s from stb_i interval (1s)") + tdSql.error("select _wstart + ts from tb_i interval (1s)") + tdSql.error("select _wstart + ts from ctb1_i interval (1s)") + tdSql.error("select _wstart + ts from stb_i interval (1s)") + tdSql.error("select _wstart + c0 from tb_i interval (1s)") + tdSql.error("select _wstart + c0 from ctb1_i interval (1s)") + tdSql.error("select _wstart + c0 from stb_i interval (1s)") + tdSql.error("select _wstart + _wstop from tb_i interval (1s)") + tdSql.error("select _wstart + _wstop from ctb1_i interval (1s)") + tdSql.error("select _wstart + _wstop from stb_i interval (1s)") + tdSql.error("select _wstart + _wduration from tb_i interval (1s)") + tdSql.error("select _wstart + _wduration from ctb1_i interval (1s)") + tdSql.error("select _wstart + _wduration from stb_i interval (1s)") + + tdSql.error("select _wstop from tb_i") + tdSql.error("select _wstop from ctb1_i") + tdSql.error("select _wstop from stb_i") + tdSql.error("select _wstop + 1 from tb_i interval (1s)") + tdSql.error("select _wstop + 1 from ctb1_i interval (1s)") + tdSql.error("select _wstop + 1 from stb_i interval (1s)") + tdSql.error("select _wstop + 1.0 from tb_i interval (1s)") + tdSql.error("select _wstop + 1.0 from ctb1_i interval (1s)") + tdSql.error("select _wstop + 1.0 from stb_i interval (1s)") + tdSql.error("select _wstop + true from tb_i interval (1s)") + tdSql.error("select _wstop + true from ctb1_i interval (1s)") + tdSql.error("select _wstop + true from stb_i interval (1s)") + tdSql.error("select _wstop + 'abc' from tb_i interval (1s)") + tdSql.error("select _wstop + 'abc' from ctb1_i interval (1s)") + tdSql.error("select _wstop + 'abc' from stb_i interval (1s)") + tdSql.error("select _wstop + 1s from tb_i interval (1s)") + tdSql.error("select _wstop + 1s from ctb1_i interval (1s)") + tdSql.error("select _wstop + 1s from stb_i interval (1s)") + tdSql.error("select _wstop + ts from tb_i interval (1s)") + tdSql.error("select _wstop + ts from ctb1_i interval (1s)") + tdSql.error("select _wstop + ts from stb_i interval (1s)") + tdSql.error("select _wstop + c0 from tb_i interval (1s)") + tdSql.error("select _wstop + c0 from ctb1_i interval (1s)") + tdSql.error("select _wstop + c0 from stb_i interval (1s)") + tdSql.error("select _wstop + _wstart from tb_i interval (1s)") + tdSql.error("select _wstop + _wstart from ctb1_i interval (1s)") + tdSql.error("select _wstop + _wstart from stb_i interval (1s)") + tdSql.error("select _wstop + _wduration from tb_i interval (1s)") + tdSql.error("select _wstop + _wduration from ctb1_i interval (1s)") + tdSql.error("select _wstop + _wduration from stb_i interval (1s)") + + tdSql.error("select _wduration from tb_i") + tdSql.error("select _wduration from ctb1_i") + tdSql.error("select _wduration from stb_i") + tdSql.error("select _wduration + 1 from tb_i interval (1s)") + tdSql.error("select _wduration + 1 from ctb1_i interval (1s)") + tdSql.error("select _wduration + 1 from stb_i interval (1s)") + tdSql.error("select _wduration + 1.0 from tb_i interval (1s)") + tdSql.error("select _wduration + 1.0 from ctb1_i interval (1s)") + tdSql.error("select _wduration + 1.0 from stb_i interval (1s)") + tdSql.error("select _wduration + true from tb_i interval (1s)") + tdSql.error("select _wduration + true from ctb1_i interval (1s)") + tdSql.error("select _wduration + true from stb_i interval (1s)") + tdSql.error("select _wduration + 'abc' from tb_i interval (1s)") + tdSql.error("select _wduration + 'abc' from ctb1_i interval (1s)") + tdSql.error("select _wduration + 'abc' from stb_i interval (1s)") + tdSql.error("select _wduration + 1s from tb_i interval (1s)") + tdSql.error("select _wduration + 1s from ctb1_i interval (1s)") + tdSql.error("select _wduration + 1s from stb_i interval (1s)") + tdSql.error("select _wduration + ts from tb_i interval (1s)") + tdSql.error("select _wduration + ts from ctb1_i interval (1s)") + tdSql.error("select _wduration + ts from stb_i interval (1s)") + tdSql.error("select _wduration + c0 from tb_i interval (1s)") + tdSql.error("select _wduration + c0 from ctb1_i interval (1s)") + tdSql.error("select _wduration + c0 from stb_i interval (1s)") + tdSql.error("select _wduration + _wstart from tb_i interval (1s)") + tdSql.error("select _wduration + _wstart from ctb1_i interval (1s)") + tdSql.error("select _wduration + _wstart from stb_i interval (1s)") + tdSql.error("select _wduration + _wduration from tb_i interval (1s)") + tdSql.error("select _wduration + _wduration from ctb1_i interval (1s)") + tdSql.error("select _wduration + _wduration from stb_i interval (1s)") + + + tdSql.execute('drop database db_m') + tdSql.execute('drop database db_u') + tdSql.execute('drop database db_n') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/2-query/ts_shortcut.py b/tests/develop-test/2-query/ts_shortcut.py new file mode 100644 index 0000000000000000000000000000000000000000..fa1af037ff169733f6c90f853822568ca4f233f0 --- /dev/null +++ b/tests/develop-test/2-query/ts_shortcut.py @@ -0,0 +1,107 @@ +################################################################### +# Copyright (c) 2021 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +from util.log import * +from util.cases import * +from util.sql import * + + +class TDTestCase: + def caseDescription(self): + ''' + case1: [TD-13970] timestamp format shortcut + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + self._conn = conn + + def run(self): + print("running {}".format(__file__)) + tdSql.execute("drop database if exists db") + tdSql.execute("create database if not exists db") + tdSql.execute('use db') + + tdSql.execute('create table tb(ts timestamp, c0 int)') + tdSql.execute('create stable stb(ts timestamp , c0 int) tags (t0 timestamp)') + + #INSERT + tdSql.execute('insert into tb values ("2020-02-02", 1);') + tdSql.query('select ts from tb'); + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + tdSql.execute('insert into ctb using stb tags("2020-02-02") values ("2020-02-02", 1)') + tdSql.query('select ts,t0 from ctb'); + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + tdSql.query('select ts,t0 from stb'); + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + res = tdSql.getData(0, 1) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + #SELECT WHERE + tdSql.query('select ts from tb where ts = "2020-02-02"') + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + tdSql.query('select ts from ctb where ts <= "2020-02-02"') + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + tdSql.query('select ts from stb where ts >= "2020-02-02"') + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + #CREATE TAG + tdSql.execute('create table ctb1 using stb tags("2020-02-02")') + tdSql.query('select t0 from ctb1'); + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + #TIME RELATED functions + tdSql.query('select to_unixtimestamp("2020-02-02") from tb') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 1580572800000) + + tdSql.query('select timetruncate("2020-02-02", 1h) from tb;') + tdSql.checkRows(1) + res = tdSql.getData(0, 0) + tdSql.checkEqual(str(res), "2020-02-02 00:00:00") + + tdSql.query('select timediff("2020-02-02", "2020-02-03", 1h) from tb;') + tdSql.checkRows(1) + tdSql.checkData(0, 0, 24) + + tdSql.execute('drop database db') + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/develop-test/3-connectors/R/test.sh b/tests/develop-test/3-connectors/R/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..90b94893659f04328d7eaef810018bb6a13c8c09 --- /dev/null +++ b/tests/develop-test/3-connectors/R/test.sh @@ -0,0 +1,41 @@ +#!/bin/sh + +function stopTaosd { + echo "Stop taosd" + sudo systemctl stop taosd || echo 'no sudo or systemctl or stop fail' + PID=`ps -ef|grep -w taosd | grep -v grep | awk '{print $2}'` + while [ -n "$PID" ] + do + pkill -TERM -x taosd + sleep 1 + PID=`ps -ef|grep -w taosd | grep -v grep | awk '{print $2}'` + done +} +stopTaosd +rm -rf /var/lib/taos/* +rm -rf /var/log/taos/* +nohup taosd -c /etc/taos/ > /dev/null 2>&1 & +sleep 10 +ls -al + +cd ../../ +WKC=`pwd` +#echo "WKC:${WKC}" + +JDBC_PATH=${WKC}'/src/connector/jdbc/' +CASE_PATH=${WKC}'/tests/examples/R/' +cd ${JDBC_PATH} +#echo "JDBC_PATH:${JDBC_PATH}" +#echo "CASE_PATH:${CASE_PATH}" + +mvn clean package -Dmaven.test.skip=true + +JDBC=`ls target|grep dist.jar` +JDBC_PATH=${JDBC_PATH}target + +#echo ${jdbc} +#echo ${jdbc_path} +cd ${WKC} + +# remove +Rscript ${CASE_PATH}rjdbc.sample.R ${JDBC_PATH} ${JDBC} diff --git a/tests/develop-test/3-connectors/TypeScript-REST/test.sh b/tests/develop-test/3-connectors/TypeScript-REST/test.sh new file mode 100755 index 0000000000000000000000000000000000000000..af548058bb911a6df219ef8b2e7dbfc3a6138c8a --- /dev/null +++ b/tests/develop-test/3-connectors/TypeScript-REST/test.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +function stopProcess { + echo "Stop $1" + sudo systemctl stop $1 || echo 'no sudo or systemctl or stop fail' + PID=`ps -ef|grep -w $1 | grep -v grep | awk '{print $2}'` + while [ -n "$PID" ] + do + pkill -TERM -x $1 + sleep 1 + PID=`ps -ef|grep -w $1 | grep -v grep | awk '{print $2}'` + done +} + +stopProcess taosadapter +stopProcess taosd +rm -rf /var/lib/taos/* +rm -rf /var/log/taos/* + +nohup taosd -c ${taosdConfig} > /dev/null 2>&1 & +nohup taosadapter -c ${adapterConfig} > /dev/null 2>&1 & +sleep 10 + +# echo `pwd` +cd ../../ +WKC=`pwd` +echo ${WKC} +cd ${WKC}/src/connector/TypeScript-REST + +npm install +npm run example +# npm run test + + + diff --git a/tests/develop-test/3-connectors/c#/test.sh b/tests/develop-test/3-connectors/c#/test.sh index 75a55fb41be3cd96c24bebfe93b209b13c3d3df8..8cfb3fe4fcff6ab820b53698e508189e557676ca 100755 --- a/tests/develop-test/3-connectors/c#/test.sh +++ b/tests/develop-test/3-connectors/c#/test.sh @@ -19,8 +19,13 @@ cd ../../ WKC=`pwd` cd ${WKC}/src/connector/C# dotnet test +# run example under Driver +cd ${WKC}/src/connector/C#/examples +dotnet run + #dotnet run --project src/test/Cases/Cases.csproj +# run example with neuget package cd ${WKC}/tests/examples/C# dotnet run --project C#checker/C#checker.csproj dotnet run --project TDengineTest/TDengineTest.csproj diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/commandline.py b/tests/develop-test/5-taos-tools/taosbenchmark/commandline.py index 672da9a56e9985785b966559911d3e84b428518a..ffc7d4860156107663a415b8b156ab91557d68c3 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/commandline.py +++ b/tests/develop-test/5-taos-tools/taosbenchmark/commandline.py @@ -32,7 +32,7 @@ class TDTestCase: tdSql.init(conn.cursor(), logSql) def run(self): - cmd = "taosBenchmark -F 7 -n 10 -t 2 -x -y -M -C -d newtest -l 5 -A binary,nchar\(31\) -b tinyint,binary\(23\),bool,nchar -w 29 -E -m $%^*" + cmd = "taosBenchmark -F 7 -H 9 -n 10 -t 2 -x -y -M -C -d newtest -l 5 -A binary,nchar\(31\) -b tinyint,binary\(23\),bool,nchar -w 29 -E -m $%^*" tdLog.info("%s" % cmd) os.system("%s" % cmd) tdSql.execute("use newtest") diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/custom_col_tag.py b/tests/develop-test/5-taos-tools/taosbenchmark/custom_col_tag.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d52df8030427086148300fc2596e1482f086f7 --- /dev/null +++ b/tests/develop-test/5-taos-tools/taosbenchmark/custom_col_tag.py @@ -0,0 +1,65 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- +import os +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import * + + +class TDTestCase: + def caseDescription(self): + ''' + [TD-13928] taosBenchmark improve user interface + ''' + return + + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor(), logSql) + + def run(self): + cmd = "taosBenchmark -f ./5-taos-tools/taosbenchmark/json/custom_col_tag.json" + tdLog.info("%s" % cmd) + os.system("%s" % cmd) + tdSql.execute("reset query cache") + tdSql.query("describe db.stb") + tdSql.checkData(0, 0, "ts") + tdSql.checkData(1, 0, "first") + tdSql.checkData(2, 0, "second") + tdSql.checkData(3, 0, "second_1") + tdSql.checkData(4, 0, "second_2") + tdSql.checkData(5, 0, "second_3") + tdSql.checkData(6, 0, "second_4") + tdSql.checkData(7, 0, "third") + tdSql.checkData(8, 0, "forth") + tdSql.checkData(9, 0, "forth_1") + tdSql.checkData(10, 0, "forth_2") + tdSql.checkData(11, 0, "single") + tdSql.checkData(12, 0, "multiple") + tdSql.checkData(13, 0, "multiple_1") + tdSql.checkData(14, 0, "multiple_2") + tdSql.checkData(15, 0, "multiple_3") + tdSql.checkData(16, 0, "multiple_4") + tdSql.checkData(17, 0, "thensingle") + tdSql.checkData(18, 0, "thenmultiple") + tdSql.checkData(19, 0, "thenmultiple_1") + tdSql.checkData(20, 0, "thenmultiple_2") + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/insert_alltypes_json.py b/tests/develop-test/5-taos-tools/taosbenchmark/insert_alltypes_json.py index 0b8dd11accef03243e5b285bbd86c80ab06f4267..107a48e117b66b28a0de3c4f974ec09005489e76 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/insert_alltypes_json.py +++ b/tests/develop-test/5-taos-tools/taosbenchmark/insert_alltypes_json.py @@ -70,6 +70,59 @@ class TDTestCase: tdSql.checkData(27, 1, "SMALLINT UNSIGNED") tdSql.checkData(28, 1, "BINARY") tdSql.checkData(28, 2, 19) + tdSql.query("select count(*) from db.stb where c0 >= 0 and c0 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c1 >= 0 and c1 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c2 >= 0 and c2 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c3 >= 0 and c3 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c4 >= 0 and c4 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c5 >= 0 and c5 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c6 >= 0 and c6 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c8 = 'd1' or c8 = 'd2'") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c9 >= 0 and c9 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c10 >= 0 and c10 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c11 >= 0 and c11 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c12 >= 0 and c12 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c13 = 'b1' or c13 = 'b2'") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t0 >= 0 and t0 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t1 >= 0 and t1 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t2 >= 0 and t2 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t3 >= 0 and t3 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t4 >= 0 and t4 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t5 >= 0 and t5 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t6 >= 0 and t6 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t8 = 'd1' or t8 = 'd2'") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t9 >= 0 and t9 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t10 >= 0 and t10 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t11 >= 0 and t11 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t12 >= 0 and t12 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t13 = 'b1' or t13 = 'b2'") + tdSql.checkData(0, 0, 160) + cmd = "taosBenchmark -f ./5-taos-tools/taosbenchmark/json/sml_insert_alltypes.json" tdLog.info("%s" % cmd) @@ -192,6 +245,58 @@ class TDTestCase: tdSql.checkData(27, 1, "SMALLINT UNSIGNED") tdSql.checkData(28, 1, "BINARY") tdSql.checkData(28, 2, 19) + tdSql.query("select count(*) from db.stb where c0 >= 0 and c0 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c1 >= 0 and c1 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c2 >= 0 and c2 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c3 >= 0 and c3 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c4 >= 0 and c4 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c5 >= 0 and c5 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c6 >= 0 and c6 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c8 like 'd1%' or c8 like 'd2%'") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c9 >= 0 and c9 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c10 >= 0 and c10 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c11 >= 0 and c11 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c12 >= 0 and c12 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where c13 like 'b1%' or c13 like 'b2%'") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t0 >= 0 and t0 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t1 >= 0 and t1 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t2 >= 0 and t2 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t3 >= 0 and t3 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t4 >= 0 and t4 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t5 >= 0 and t5 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t6 >= 0 and t6 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t8 like 'd1%' or t8 like 'd2%'") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t9 >= 0 and t9 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t10 >= 0 and t10 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t11 >= 0 and t11 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t12 >= 0 and t12 <= 10") + tdSql.checkData(0, 0, 160) + tdSql.query("select count(*) from db.stb where t13 like 'b1%' or t13 like 'b2%'") + tdSql.checkData(0, 0, 160) def stop(self): diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/invalid_commandline.py b/tests/develop-test/5-taos-tools/taosbenchmark/invalid_commandline.py index 99e3d1dc766b51f59927bfe75929605e774ddfa7..1ae8a775ae18639165bc1cb0fb85e7c1fabc43ac 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/invalid_commandline.py +++ b/tests/develop-test/5-taos-tools/taosbenchmark/invalid_commandline.py @@ -29,7 +29,7 @@ class TDTestCase: tdSql.init(conn.cursor(), logSql) def run(self): - cmd = "taosBenchmark -F abc -P abc -I abc -T abc -i abc -S abc -B abc -r abc -t abc -n abc -l abc -w abc -w 16385 -R abc -O abc -a abc -n 2 -t 2 -r 1 -y" + cmd = "taosBenchmark -F abc -P abc -I abc -T abc -H abc -i abc -S abc -B abc -r abc -t abc -n abc -l abc -w abc -w 16385 -R abc -O abc -a abc -n 2 -t 2 -r 1 -y" tdLog.info("%s" % cmd) os.system("%s" % cmd) tdSql.query("select count(*) from test.meters") diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/custom_col_tag.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/custom_col_tag.json new file mode 100644 index 0000000000000000000000000000000000000000..8f652b9d73f5d9f4cb72e2d146a8c66b49dd3533 --- /dev/null +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/custom_col_tag.json @@ -0,0 +1,91 @@ +{ + "filetype": "insert", + "cfgdir": "/etc/taos", + "host": "127.0.0.1", + "port": 6030, + "user": "root", + "password": "taosdata", + "thread_count": 4, + "connection_pool_size": 20, + "result_file": "./insert_res.txt", + "confirm_parameter_prompt": "no", + "prepared_rand": 10, + "chinese": "no", + "insert_interval": 0, + "num_of_records_per_req": 10, + "databases": [{ + "dbinfo": { + "name": "db", + "drop": "yes", + "replica": 1, + "days": 10, + "cache": 16, + "blocks": 8, + "precision": "ms", + "keep": 36500, + "minRows": 100, + "maxRows": 4096, + "comp":2, + "walLevel":1, + "cachelast":0, + "quorum":1, + "fsync":3000, + "update": 1 + }, + "super_tables": [{ + "name": "stb", + "child_table_exists":"no", + "childtable_count": 8, + "childtable_prefix": "stb_", + "escape_character": "yes", + "auto_create_table": "no", + "batch_create_tbl_num": 10, + "data_source": "rand", + "insert_mode": "taosc", + "line_protocol": "line", + "childtable_limit": -10, + "childtable_offset": 10, + "insert_rows": 20, + "insert_interval": 0, + "interlace_rows": 0, + "disorder_ratio": 0, + "disorder_range": 1000, + "timestamp_step": 1, + "start_timestamp": "2020-10-01 00:00:00.000", + "sample_file": "./sample.csv", + "use_sample_ts": "no", + "tags_file": "", + "partial_col_num": 0, + "columns": [{ + "type": "INT", + "name": "first" + }, { + "type": "UINT", + "name": "second", + "count": 5 + },{ + "type": "double", + "name": "third" + },{ + "type": "float", + "name": "forth", + "count": 3 + }], + "tags": [{ + "type": "INT", + "name": "single" + }, { + "type": "UINT", + "name": "multiple", + "count": 5 + },{ + "type": "double", + "name": "thensingle" + },{ + "type": "float", + "name": "thenmultiple", + "count": 3 + }] + }] + }] +} \ No newline at end of file diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/default.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/default.json index f0ad9d516e2f3855722ea41ea88cdee5c7f06de7..d4b2aae2fb7bf1a3612e60f395a1c5ed26ceca8f 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/default.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/default.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_auto_create_table.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_auto_create_table.json index 8dc121e5a89d6567c5fbe79aab15c717f5cb2881..a4706bf47dab35992e7b82a46f6ceff332f9da2d 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_auto_create_table.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_auto_create_table.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 100, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_insert_alltypes.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_insert_alltypes.json index e45ae7890af33a9ddc4b7d552adeb781aaa8a6ba..01e3950502ff363a42ab2837d0fd24938e54c743 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_insert_alltypes.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_insert_alltypes.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_query.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_query.json index 12d6c383d3af8b66f4a120b885173aaed67d5d84..459e496f0ba5f1b0b90f755969a1213a7f42fc6a 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_query.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/rest_query.json @@ -4,7 +4,7 @@ "confirm_parameter_prompt": "no", "databases": "db", "query_mode": "rest", - "thread_pool_size": 10, + "connection_pool_size": 10, "response_buffer": 10000, "specified_table_query": { diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_auto_create_table.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_auto_create_table.json index 3cdd2b911eaee7887312b659781d18f68caa1221..62846bf2b67015cb4f7a4c6b69dd3df2149cbcad 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_auto_create_table.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_auto_create_table.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 100, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_insert_alltypes.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_insert_alltypes.json index 7326cbcba2e2eefffe49d34771cb301bcee7a16f..8722d124d69bf630266e85456623f49ed9fed2ac 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_insert_alltypes.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_insert_alltypes.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_interlace.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_interlace.json index 5b55ceb4a1fe8f57ae26f74ed78a86e6bdc9a333..1aa5b093486e682afe251c331884d9a0bf2f8a79 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_interlace.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_interlace.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_json_alltypes.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_json_alltypes.json index d23d12e800362668c325ff5d252ff4ff9c411656..8806b52a1e63ea209196f194c62378d63982dc18 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_json_alltypes.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_json_alltypes.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_json.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_json.json index e037fff0aaa23fbb91cdc66e663aa1fe79d03864..1e9e28d4e847cd351c1ce9fee3699e14b3eb77f3 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_json.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_json.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_line.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_line.json index 5000da489fc4c97f1ee3515c095655d6b183bfff..deef77fdefa994487607ddc1edb3bf3a5cd83d32 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_line.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_line.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_telnet.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_telnet.json index c9c4554e015a3927fe0b7fa97e7b7dc8826a95d1..8893a73467bf36a1687cc25a0815a232a1ae86e9 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_telnet.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_rest_telnet.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_alltypes.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_alltypes.json index 739e0eaca4fed0985aa9ae06fea91e4a5f337373..0bf363e6734cdffdede500965f7c7fdc51f3c4a3 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_alltypes.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_alltypes.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_tcp.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_tcp.json index b76d3da3bd6d1ef90d2c51ebb5cccd3df4ec5b87..84419760c1f29bc5b69ce54ed0a55557703c5384 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_tcp.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/sml_telnet_tcp.json @@ -7,7 +7,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_auto_create_table.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_auto_create_table.json index d917bec0c94fec4ee66e2cfe33e7e91aac9e8a3e..2e5965c14b6c6882bb90a2e8248d5f6605817085 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_auto_create_table.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_auto_create_table.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 100, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_insert_alltypes.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_insert_alltypes.json index 806142bf2a24f0e868ab768db9313c3762e62a34..48f4e231669b150e5823e2dceafd429cd6af8b3c 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_insert_alltypes.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/stmt_insert_alltypes.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, @@ -55,8 +55,17 @@ "sample_file": "./sample.csv", "use_sample_ts": "no", "tags_file": "", - "columns": [{"type": "TIMESTAMP"},{"type": "INT"}, {"type": "BIGINT"}, {"type": "FLOAT"}, {"type": "DOUBLE"}, {"type": "SMALLINT"}, {"type": "TINYINT"}, {"type": "BOOL"}, {"type": "NCHAR","len": 29, "count":1}, {"type": "UINT"}, {"type": "UBIGINT"}, {"type": "UTINYINT"}, {"type": "USMALLINT"}, {"type": "BINARY", "len": 23, "count":1}], - "tags": [{"type": "TIMESTAMP"},{"type": "INT"}, {"type": "BIGINT"}, {"type": "FLOAT"}, {"type": "DOUBLE"}, {"type": "SMALLINT"}, {"type": "TINYINT"}, {"type": "BOOL"}, {"type": "NCHAR","len": 17, "count":1}, {"type": "UINT"}, {"type": "UBIGINT"}, {"type": "UTINYINT"}, {"type": "USMALLINT"}, {"type": "BINARY", "len": 19, "count":1}] + "partial_col_num": 999, + "columns": [{"type": "TIMESTAMP","max": 10, "min": 0},{"type": "INT","max": 10, "min": 0}, {"type": "BIGINT","max": 10, "min": 0}, {"type": "FLOAT","max": 10, "min": 0}, {"type": "DOUBLE","max": 10, "min": 0}, {"type": "SMALLINT","max": 10, "min": 0}, {"type": "TINYINT","max": 10, "min": 0}, {"type": "BOOL","max": 10, "min": 0}, {"type": "NCHAR","len": 29, "count":1, + "values": ["d1", "d2"] + }, {"type": "UINT","max": 10, "min": 0}, {"type": "UBIGINT","max": 10, "min": 0}, {"type": "UTINYINT","max": 10, "min": 0}, {"type": "USMALLINT","max": 10, "min": 0}, {"type": "BINARY", "len": 23, "count":1, + "values": ["b1","b2"] + }], + "tags": [{"type": "TIMESTAMP","max": 10, "min": 0},{"type": "INT","max": 10, "min": 0}, {"type": "BIGINT","max": 10, "min": 0}, {"type": "FLOAT","max": 10, "min": 0}, {"type": "DOUBLE","max": 10, "min": 0}, {"type": "SMALLINT","max": 10, "min": 0}, {"type": "TINYINT","max": 10, "min": 0}, {"type": "BOOL","max": 10, "min": 0}, {"type": "NCHAR","len": 17, "count":1, + "values": ["d1", "d2"] + }, {"type": "UINT","max": 10, "min": 0}, {"type": "UBIGINT","max": 10, "min": 0}, {"type": "UTINYINT","max": 10, "min": 0}, {"type": "USMALLINT","max": 10, "min": 0}, {"type": "BINARY", "len": 19, "count":1, + "values": ["b1","b2"] + }] }] }] } diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_auto_create_table.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_auto_create_table.json index 0895f1b45cad6b6978e7820db0bf8936f772ffcc..06c5be47bf7ca2effd70a0a8ee51915e57cf1fe8 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_auto_create_table.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_auto_create_table.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 10, + "connection_pool_size": 10, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 100, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_insert_alltypes.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_insert_alltypes.json index 6816ef5c3dd7dd9c59835a72bd10637814b4537d..1bb03b4fab5640fb98289384466b84307ea8ceb0 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_insert_alltypes.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_insert_alltypes.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, @@ -56,8 +56,16 @@ "use_sample_ts": "no", "tags_file": "", "partial_col_num": 999, - "columns": [{"type": "TIMESTAMP"},{"type": "INT"}, {"type": "BIGINT"}, {"type": "FLOAT"}, {"type": "DOUBLE"}, {"type": "SMALLINT"}, {"type": "TINYINT"}, {"type": "BOOL"}, {"type": "NCHAR","len": 29, "count":1}, {"type": "UINT"}, {"type": "UBIGINT"}, {"type": "UTINYINT"}, {"type": "USMALLINT"}, {"type": "BINARY", "len": 23, "count":1}], - "tags": [{"type": "TIMESTAMP"},{"type": "INT"}, {"type": "BIGINT"}, {"type": "FLOAT"}, {"type": "DOUBLE"}, {"type": "SMALLINT"}, {"type": "TINYINT"}, {"type": "BOOL"}, {"type": "NCHAR","len": 17, "count":1}, {"type": "UINT"}, {"type": "UBIGINT"}, {"type": "UTINYINT"}, {"type": "USMALLINT"}, {"type": "BINARY", "len": 19, "count":1}] + "columns": [{"type": "TIMESTAMP","max": 10, "min": 0},{"type": "INT","max": 10, "min": 0}, {"type": "BIGINT","max": 10, "min": 0}, {"type": "FLOAT","max": 10, "min": 0}, {"type": "DOUBLE","max": 10, "min": 0}, {"type": "SMALLINT","max": 10, "min": 0}, {"type": "TINYINT","max": 10, "min": 0}, {"type": "BOOL","max": 10, "min": 0}, {"type": "NCHAR","len": 29, "count":1, + "values": ["d1", "d2"] + }, {"type": "UINT","max": 10, "min": 0}, {"type": "UBIGINT","max": 10, "min": 0}, {"type": "UTINYINT","max": 10, "min": 0}, {"type": "USMALLINT","max": 10, "min": 0}, {"type": "BINARY", "len": 23, "count":1, + "values": ["b1","b2"] + }], + "tags": [{"type": "TIMESTAMP","max": 10, "min": 0},{"type": "INT","max": 10, "min": 0}, {"type": "BIGINT","max": 10, "min": 0}, {"type": "FLOAT","max": 10, "min": 0}, {"type": "DOUBLE","max": 10, "min": 0}, {"type": "SMALLINT","max": 10, "min": 0}, {"type": "TINYINT","max": 10, "min": 0}, {"type": "BOOL","max": 10, "min": 0}, {"type": "NCHAR","len": 17, "count":1, + "values": ["d1", "d2"] + }, {"type": "UINT","max": 10, "min": 0}, {"type": "UBIGINT","max": 10, "min": 0}, {"type": "UTINYINT","max": 10, "min": 0}, {"type": "USMALLINT","max": 10, "min": 0}, {"type": "BINARY", "len": 19, "count":1, + "values": ["b1","b2"] + }] }] }] } diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_json_tag.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_json_tag.json index 71fed3c48cf13123890f4212baa4c074b8b6df74..893b203aa85c49ea7bd069fa3a5b30e8c7ea6bc6 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_json_tag.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_json_tag.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_limit_offset.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_limit_offset.json index 346e3cd8680cf3836523daf693f46bb2a0e1cffd..b0e903347d5df00a229391144e77ee57b743b3f0 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_limit_offset.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_limit_offset.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_only_create_table.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_only_create_table.json index 46672bcc4c54082fbb2aedb73ac649976c73013f..4d42ed63fa81660a8ca84d40089f1d35c0afa54a 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_only_create_table.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_only_create_table.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_sample_use_ts.json b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_sample_use_ts.json index 8ac8aab93e2e948cdf9b92bd548ad8299470e57f..22bd13d5be32a9c35b6abed6fc632da3432a2a57 100644 --- a/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_sample_use_ts.json +++ b/tests/develop-test/5-taos-tools/taosbenchmark/json/taosc_sample_use_ts.json @@ -6,7 +6,7 @@ "user": "root", "password": "taosdata", "thread_count": 4, - "thread_pool_size": 20, + "connection_pool_size": 20, "result_file": "./insert_res.txt", "confirm_parameter_prompt": "no", "prepared_rand": 10, diff --git a/tests/develop-test/5-taos-tools/taosdump/taosdumpTestTypeBinary.py b/tests/develop-test/5-taos-tools/taosdump/taosdumpTestTypeBinary.py index 87ac1ba19287c7e9ae90c3b85b9727d7f6a1f5b7..4909eb376222bbea7102208d4418d608b827fbbf 100644 --- a/tests/develop-test/5-taos-tools/taosdump/taosdumpTestTypeBinary.py +++ b/tests/develop-test/5-taos-tools/taosdump/taosdumpTestTypeBinary.py @@ -98,10 +98,13 @@ class TDTestCase: tdSql.checkData(0, 0, 't2') tdSql.checkData(1, 0, 't1') - tdSql.query("select btag from st") - tdSql.checkRows(2) + tdSql.query("select btag from st where tbname = 't1'") + tdSql.checkRows(1) + tdSql.checkData(0, 0, "test") + + tdSql.query("select btag from st where tbname = 't2'") + tdSql.checkRows(1) tdSql.checkData(0, 0, None) - tdSql.checkData(1, 0, "test") tdSql.query("select * from st where btag = 'test'") tdSql.checkRows(2) diff --git a/tests/develop-test/fulltest-query.sh b/tests/develop-test/fulltest-query.sh index 3e39c1fc30794049ad41a4a009d130c6a1bc3d5c..deffe368288a4cd968b0ebc8ca2a2d96b1d95673 100755 --- a/tests/develop-test/fulltest-query.sh +++ b/tests/develop-test/fulltest-query.sh @@ -18,3 +18,4 @@ python3 ./test.py -f 2-query/TD-13246.py python3 ./test.py -f 2-query/TD-6347.py python3 ./test.py -f 2-query/math_funcs.py python3 ./test.py -f 2-query/function_histogram.py +python3 ./test.py -f 2-query/TD-13946.py diff --git a/tests/examples/C#/.gitignore b/tests/examples/C#/.gitignore deleted file mode 100644 index 2a959a77c900524f996f3214446d37f34026c6e4..0000000000000000000000000000000000000000 --- a/tests/examples/C#/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -C#checker/bin/ -C#checker/obj/ -TDengineTest/bin/ -TDengineTest/obj/ -schemaless/bin/ -schemaless/obj/ -stmt/TDengineDriver.cs -stmt/TaosBind.cs -stmt/TaosMultiBind.cs -stmt/bin/ -stmt/obj/ -taosdemo/bin/ -taosdemo/obj/ -jsonTag/bin/ -jsonTag/obj/ -insertCn/bin/ -insertCn/obj/ \ No newline at end of file diff --git a/tests/examples/C#/C#checker/C#checker.cs b/tests/examples/C#/C#checker/C#checker.cs deleted file mode 100644 index 29ad290343bb4fbacade48a0b59e0350bd35f213..0000000000000000000000000000000000000000 --- a/tests/examples/C#/C#checker/C#checker.cs +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -using System; -using System.Text; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Collections; - -namespace TDengineDriver -{ - class TDengineTest - { - //connect parameters - private string host; - private string configDir; - private string user; - private string password; - private short port = 0; - - //sql parameters - private string dbName; - private string tbName; - private string precision; - - private bool isInsertData; - private bool isQueryData; - - private long tableCount; - private long totalRows; - private long batchRows; - private long beginTimestamp = 1551369600000L; - - private IntPtr conn = IntPtr.Zero; - private long rowsInserted = 0; - - static void Main(string[] args) - { - TDengineTest tester = new TDengineTest(); - tester.ReadArgument(args); - - - tester.InitTDengine(); - tester.ConnectTDengine(); - tester.createDatabase(); - tester.useDatabase(); - tester.checkDropTable(); - tester.createTable(); - tester.checkInsert(); - tester.checkSelect(); - tester.checkDropTable(); - tester.dropDatabase(); - tester.CloseConnection(); - tester.cleanup(); - - - } - - public long GetArgumentAsLong(String[] argv, String argName, int minVal, int maxVal, int defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName != argv[i]) - { - continue; - } - if (i < argc - 1) - { - String tmp = argv[i + 1]; - if (tmp[0] == '-') - { - Console.WriteLine("option {0:G} requires an argument", tmp); - ExitProgram(); - } - - long tmpVal = Convert.ToInt64(tmp); - if (tmpVal < minVal || tmpVal > maxVal) - { - Console.WriteLine("option {0:G} should in range [{1:G}, {2:G}]", argName, minVal, maxVal); - ExitProgram(); - } - - return tmpVal; - } - } - - return defaultValue; - } - - public String GetArgumentAsString(String[] argv, String argName, String defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName != argv[i]) - { - continue; - } - if (i < argc - 1) - { - String tmp = argv[i + 1]; - if (tmp[0] == '-') - { - Console.WriteLine("option {0:G} requires an argument", tmp); - ExitProgram(); - } - return tmp; - } - } - - return defaultValue; - } - - public void PrintHelp(String[] argv) - { - for (int i = 0; i < argv.Length; ++i) - { - if ("--help" == argv[i]) - { - String indent = " "; - Console.WriteLine("taosTest is simple example to operate TDengine use C# Language.\n"); - Console.WriteLine("{0:G}{1:G}", indent, "-h"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "TDEngine server IP address to connect"); - Console.WriteLine("{0:G}{1:G}", indent, "-u"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "The TDEngine user name to use when connecting to the server, default is root"); - Console.WriteLine("{0:G}{1:G}", indent, "-p"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "The TDEngine user name to use when connecting to the server, default is taosdata"); - Console.WriteLine("{0:G}{1:G}", indent, "-d"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Database used to create table or import data, default is db"); - Console.WriteLine("{0:G}{1:G}", indent, "-s"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Super Tables used to create table, default is mt"); - Console.WriteLine("{0:G}{1:G}", indent, "-t"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Table prefixs, default is t"); - Console.WriteLine("{0:G}{1:G}", indent, "-w"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Whether to insert data"); - Console.WriteLine("{0:G}{1:G}", indent, "-r"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Whether to query data"); - Console.WriteLine("{0:G}{1:G}", indent, "-n"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "How many Tables to create, default is 10"); - Console.WriteLine("{0:G}{1:G}", indent, "-b"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "How many rows per insert batch, default is 10"); - Console.WriteLine("{0:G}{1:G}", indent, "-i"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "How many rows to insert, default is 100"); - Console.WriteLine("{0:G}{1:G}", indent, "-c"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Configuration directory"); - // - Console.WriteLine("{0:G}{1:G}", indent, "-ps"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Configurate db precision,default millisecond"); - ExitProgram(); - } - } - } - - public void ReadArgument(String[] argv) - { - PrintHelp(argv); - host = this.GetArgumentAsString(argv, "-h", "127.0.0.1"); - user = this.GetArgumentAsString(argv, "-u", "root"); - password = this.GetArgumentAsString(argv, "-p", "taosdata"); - dbName = this.GetArgumentAsString(argv, "-d", "test"); - tbName = this.GetArgumentAsString(argv, "-s", "weather"); - precision = this.GetArgumentAsString(argv, "-ps", "ms"); - isInsertData = this.GetArgumentAsLong(argv, "-w", 0, 1, 1) != 0; - isQueryData = this.GetArgumentAsLong(argv, "-r", 0, 1, 1) != 0; - tableCount = this.GetArgumentAsLong(argv, "-n", 1, 10000, 10); - batchRows = this.GetArgumentAsLong(argv, "-b", 1, 1000, 500); - totalRows = this.GetArgumentAsLong(argv, "-i", 1, 10000000, 10000); - configDir = this.GetArgumentAsString(argv, "-c", "C:/TDengine/cfg"); - } - - public void InitTDengine() - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, this.configDir); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - Console.WriteLine("init..."); - TDengine.Init(); - Console.WriteLine("get connection starting..."); - } - - public void ConnectTDengine() - { - string db = ""; - this.conn = TDengine.Connect(this.host, this.user, this.password, db, this.port); - if (this.conn == IntPtr.Zero) - { - Console.WriteLine("connection failed: " + this.host); - ExitProgram(); - } - else - { - Console.WriteLine("[ OK ] Connection established."); - } - } - public void createDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("create database if not exists ").Append(this.dbName).Append(" precision '").Append(this.precision).Append("'"); - execute(sql.ToString()); - } - public void useDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("use ").Append(this.dbName); - execute(sql.ToString()); - } - public void checkSelect() - { - StringBuilder sql = new StringBuilder(); - sql.Append("select * from ").Append(this.dbName).Append(".").Append(this.tbName); - ExecuteQuery(sql.ToString()); - } - public void createTable() - { - StringBuilder sql = new StringBuilder(); - sql.Append("create table if not exists ").Append(this.dbName).Append(".").Append(this.tbName).Append("(ts timestamp, temperature float, humidity int)"); - execute(sql.ToString()); - } - public void checkInsert() - { - StringBuilder sql = new StringBuilder(); - sql.Append("insert into ").Append(this.dbName).Append(".").Append(this.tbName).Append("(ts, temperature, humidity) values(now, 20.5, 34)"); - execute(sql.ToString()); - } - public void checkDropTable() - { - StringBuilder sql = new StringBuilder(); - sql.Append("drop table if exists ").Append(this.dbName).Append(".").Append(this.tbName).Append(""); - execute(sql.ToString()); - } - public void dropDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("drop database if exists ").Append(this.dbName); - execute(sql.ToString()); - } - public void execute(string sql) - { - DateTime dt1 = DateTime.Now; - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - DateTime dt2 = DateTime.Now; - TimeSpan span = dt2 - dt1; - - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - } - - public void ExecuteQuery(string sql) - { - - DateTime dt1 = DateTime.Now; - long queryRows = 0; - IntPtr res = TDengine.Query(conn, sql); - getPrecision(res); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - DateTime dt2 = DateTime.Now; - TimeSpan span = dt2 - dt1; - Console.WriteLine("[OK] time cost: " + span.ToString() + "ms, execute statement ====> " + sql.ToString()); - int fieldCount = TDengine.FieldCount(res); - - List metas = TDengine.FetchFields(res); - for (int j = 0; j < metas.Count; j++) - { - TDengineMeta meta = (TDengineMeta)metas[j]; - } - - IntPtr rowdata; - StringBuilder builder = new StringBuilder(); - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - builder.Append("---"); - - if (data == IntPtr.Zero) - { - builder.Append("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - builder.Append(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - byte v2 = Marshal.ReadByte(data); - builder.Append(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - builder.Append(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - builder.Append(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - builder.Append(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - builder.Append(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - builder.Append(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - string v8 = Marshal.PtrToStringAnsi(data); - builder.Append(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - builder.Append(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - string v10 = Marshal.PtrToStringAnsi(data); - builder.Append(v10); - break; - } - } - builder.Append("---"); - - if (queryRows <= 10) - { - Console.WriteLine(builder.ToString()); - } - builder.Clear(); - } - - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - } - Console.WriteLine(""); - - TDengine.FreeResult(res); - - } - - public void CloseConnection() - { - if (this.conn != IntPtr.Zero) - { - TDengine.Close(this.conn); - Console.WriteLine("connection closed."); - } - } - - static void ExitProgram() - { - System.Environment.Exit(0); - } - - public void cleanup() - { - Console.WriteLine("clean up..."); - System.Environment.Exit(0); - } - // method to get db precision - public void getPrecision(IntPtr res) - { - int psc=TDengine.ResultPrecision(res); - switch(psc) - { - case 0: - Console.WriteLine("db:[{0:G}]'s precision is {1:G}",this.dbName,"millisecond"); - break; - case 1: - Console.WriteLine("db:[{0:G}]'s precision is {1:G}",this.dbName,"microsecond"); - break; - case 2: - Console.WriteLine("db:[{0:G}]'s precision is {1:G}",this.dbName,"nanosecond"); - break; - } - - } - } -} diff --git a/tests/examples/C#/C#checker/C#checker.csproj b/tests/examples/C#/C#checker/C#checker.csproj deleted file mode 100644 index afeeaf3f01301210c0e945c8e02b40790ebec743..0000000000000000000000000000000000000000 --- a/tests/examples/C#/C#checker/C#checker.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - Exe - net5.0 - C_checker - - - - - - - diff --git a/tests/examples/C#/TDengineTest/TDengineTest.cs b/tests/examples/C#/TDengineTest/TDengineTest.cs deleted file mode 100644 index 9f84634ffb400e5d891a9fdeaeee0c013829f969..0000000000000000000000000000000000000000 --- a/tests/examples/C#/TDengineTest/TDengineTest.cs +++ /dev/null @@ -1,504 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -using System; -using System.Text; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Collections; - -namespace TDengineDriver -{ - class TDengineTest - { - //connect parameters - private string host; - private string configDir; - private string user; - private string password; - private short port = 0; - - //sql parameters - private string dbName; - private string stableName; - private string tablePrefix; - - private bool isInsertData; - private bool isQueryData; - - private long tableCount; - private long totalRows; - private long batchRows; - private long beginTimestamp = 1551369600000L; - - private IntPtr conn = IntPtr.Zero; - private long rowsInserted = 0; - - static void Main(string[] args) - { - TDengineTest tester = new TDengineTest(); - tester.ReadArgument(args); - - Console.WriteLine("---------------------------------------------------------------"); - Console.WriteLine("Starting Testing..."); - Console.WriteLine("---------------------------------------------------------------"); - - tester.InitTDengine(); - tester.ConnectTDengine(); - tester.CreateDbAndTable(); - tester.ExecuteInsert(); - tester.ExecuteQuery(); - tester.CloseConnection(); - - Console.WriteLine("---------------------------------------------------------------"); - Console.WriteLine("Stop Testing..."); - Console.WriteLine("---------------------------------------------------------------"); - - } - - public long GetArgumentAsLong(String[] argv, String argName, int minVal, int maxVal, int defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName != argv[i]) - { - continue; - } - if (i < argc - 1) - { - String tmp = argv[i + 1]; - if (tmp[0] == '-') - { - Console.WriteLine("option {0:G} requires an argument", tmp); - ExitProgram(); - } - - long tmpVal = Convert.ToInt64(tmp); - if (tmpVal < minVal || tmpVal > maxVal) - { - Console.WriteLine("option {0:G} should in range [{1:G}, {2:G}]", argName, minVal, maxVal); - ExitProgram(); - } - - return tmpVal; - } - } - - return defaultValue; - } - - public String GetArgumentAsString(String[] argv, String argName, String defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName != argv[i]) - { - continue; - } - if (i < argc - 1) - { - String tmp = argv[i + 1]; - if (tmp[0] == '-') - { - Console.WriteLine("option {0:G} requires an argument", tmp); - ExitProgram(); - } - return tmp; - } - } - - return defaultValue; - } - - public void PrintHelp(String[] argv) - { - for (int i = 0; i < argv.Length; ++i) - { - if ("--help" == argv[i]) - { - String indent = " "; - Console.WriteLine("taosTest is simple example to operate TDengine use C# Language.\n"); - Console.WriteLine("{0:G}{1:G}", indent, "-h"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "TDEngine server IP address to connect"); - Console.WriteLine("{0:G}{1:G}", indent, "-u"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "The TDEngine user name to use when connecting to the server, default is root"); - Console.WriteLine("{0:G}{1:G}", indent, "-p"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "The TDEngine user name to use when connecting to the server, default is taosdata"); - Console.WriteLine("{0:G}{1:G}", indent, "-d"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Database used to create table or import data, default is db"); - Console.WriteLine("{0:G}{1:G}", indent, "-s"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Super Tables used to create table, default is mt"); - Console.WriteLine("{0:G}{1:G}", indent, "-t"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Table prefixs, default is t"); - Console.WriteLine("{0:G}{1:G}", indent, "-w"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Whether to insert data"); - Console.WriteLine("{0:G}{1:G}", indent, "-r"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Whether to query data"); - Console.WriteLine("{0:G}{1:G}", indent, "-n"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "How many Tables to create, default is 10"); - Console.WriteLine("{0:G}{1:G}", indent, "-b"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "How many rows per insert batch, default is 10"); - Console.WriteLine("{0:G}{1:G}", indent, "-i"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "How many rows to insert, default is 100"); - Console.WriteLine("{0:G}{1:G}", indent, "-c"); - Console.WriteLine("{0:G}{1:G}{2:G}", indent, indent, "Configuration directory"); - - ExitProgram(); - } - } - } - - public void ReadArgument(String[] argv) - { - PrintHelp(argv); - host = this.GetArgumentAsString(argv, "-h", "127.0.0.1"); - user = this.GetArgumentAsString(argv, "-u", "root"); - password = this.GetArgumentAsString(argv, "-p", "taosdata"); - dbName = this.GetArgumentAsString(argv, "-d", "tdengint_test_cs"); - stableName = this.GetArgumentAsString(argv, "-s", "st"); - tablePrefix = this.GetArgumentAsString(argv, "-t", "t"); - isInsertData = this.GetArgumentAsLong(argv, "-w", 0, 1, 1) != 0; - isQueryData = this.GetArgumentAsLong(argv, "-r", 0, 1, 1) != 0; - tableCount = this.GetArgumentAsLong(argv, "-n", 1, 10000, 10); - batchRows = this.GetArgumentAsLong(argv, "-b", 1, 1000,500 ); - totalRows = this.GetArgumentAsLong(argv, "-i", 1, 10000000, 10000); - configDir = this.GetArgumentAsString(argv, "-c", "C:/TDengine/cfg"); - } - - public void InitTDengine() - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, this.configDir); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - TDengine.Init(); - Console.WriteLine("TDengine Initialization finished"); - } - - public void ConnectTDengine() - { - string db = ""; - Console.WriteLine("Host:{0}", this.host); - this.conn = TDengine.Connect(this.host, this.user, this.password, db, this.port); - if (this.conn == IntPtr.Zero) - { - Console.WriteLine("Connect to TDengine failed"); - ExitProgram(); - } - else - { - Console.WriteLine("Connect to TDengine success"); - } - } - - public void CreateDbAndTable() - { - if (!this.isInsertData) - { - return; - } - - StringBuilder sql = new StringBuilder(); - sql.Append("create database if not exists ").Append(this.dbName); - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - - sql.Clear(); - sql.Append("use ").Append(this.dbName); - res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - - sql.Clear(); - sql.Append("create table if not exists ").Append(this.stableName).Append("(ts timestamp, v1 bool, v2 tinyint, v3 smallint, v4 int, v5 bigint, v6 float, v7 double, v8 binary(10), v9 nchar(10)) tags(t1 int)"); - res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - - for (int i = 0; i < this.tableCount; i++) - { - sql.Clear(); - sql = sql.Append("create table if not exists ").Append(this.tablePrefix).Append(i) - .Append(" using ").Append(this.stableName).Append(" tags(").Append(i).Append(")"); - res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - } - - Console.WriteLine("create db and table success"); - } - - public void ExecuteInsert() - { - if (!this.isInsertData) - { - return; - } - - System.DateTime start = new System.DateTime(); - long loopCount = this.totalRows / this.batchRows; - - for (int table = 0; table < this.tableCount; ++table) - { - for (long loop = 0; loop < loopCount; loop++) - { - StringBuilder sql = new StringBuilder(); - sql.Append("insert into ").Append(this.tablePrefix).Append(table).Append(" values"); - for (int batch = 0; batch < this.batchRows; ++batch) - { - - long rows = loop * this.batchRows + batch; - sql.Append("(") - .Append(this.beginTimestamp + rows) - .Append(", 1, 2, 3,") - .Append(rows) - .Append(", 5, 6, 7, 'abc', 'def')"); - } - IntPtr res = TDengine.Query(this.conn,sql.ToString() ); - - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - } - - int affectRows = TDengine.AffectRows(res); - this.rowsInserted += affectRows; - - TDengine.FreeResult(res); - } - } - - System.DateTime end = new System.DateTime(); - TimeSpan ts = end - start; - - Console.Write("Total {0:G} rows inserted, {1:G} rows failed, time spend {2:G} seconds.\n" - , this.rowsInserted, this.totalRows * this.tableCount - this.rowsInserted, ts.TotalSeconds); - } - - public void ExecuteQuery() - { - if (!this.isQueryData) - { - return; - } - - System.DateTime start = new System.DateTime(); - long queryRows = 0; - - for (int i = 0; i < 1/*this.tableCount*/; ++i) - { - String sql = "select * from " + this.dbName + "." + tablePrefix + i; - Console.WriteLine(sql); - - IntPtr res = TDengine.Query(conn, sql); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - - int fieldCount = TDengine.FieldCount(res); - Console.WriteLine("field count: " + fieldCount); - - List metas = TDengine.FetchFields(res); - for (int j = 0; j < metas.Count; j++) - { - TDengineMeta meta = (TDengineMeta)metas[j]; - Console.WriteLine("index:" + j + ", type:" + meta.type + ", typename:" + meta.TypeName() + ", name:" + meta.name + ", size:" + meta.size); - } - - IntPtr rowdata; - StringBuilder builder = new StringBuilder(); - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - builder.Append("---"); - - if (data == IntPtr.Zero) - { - builder.Append("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - builder.Append(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - byte v2 = Marshal.ReadByte(data); - builder.Append(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - builder.Append(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - builder.Append(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - builder.Append(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - builder.Append(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - builder.Append(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - string v8 = Marshal.PtrToStringAnsi(data); - builder.Append(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - builder.Append(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - string v10 = Marshal.PtrToStringAnsi(data); - builder.Append(v10); - break; - case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: - byte v11 = Marshal.ReadByte(data); - builder.Append(v11); - break; - case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: - ushort v12 = (ushort)Marshal.ReadInt16(data); - builder.Append(v12); - break; - case TDengineDataType.TSDB_DATA_TYPE_UINT: - uint v13 = (uint)Marshal.ReadInt32(data); - builder.Append(v13); - break; - case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: - ulong v14 = (ulong)Marshal.ReadInt64(data); - builder.Append(v14); - break; - } - } - builder.Append("---"); - - if (queryRows <= 10) - { - Console.WriteLine(builder.ToString()); - } - builder.Clear(); - } - - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", - TDengine.ErrorNo(res), TDengine.Error(res)); - } - Console.WriteLine(""); - - TDengine.FreeResult(res); - } - - System.DateTime end = new System.DateTime(); - TimeSpan ts = end - start; - - Console.Write("Total {0:G} rows inserted, {1:G} rows query, time spend {2:G} seconds.\n" - , this.rowsInserted, queryRows, ts.TotalSeconds); - } - - public void CloseConnection() - { - if (this.conn != IntPtr.Zero) - { - TDengine.Close(this.conn); - } - } - - static void ExitProgram() - { - TDengine.Cleanup(); - System.Environment.Exit(0); - } - } -} diff --git a/tests/examples/C#/insertCn/Program.cs b/tests/examples/C#/insertCn/Program.cs deleted file mode 100644 index 85d3e42533897d5790f148a1e1f9ed286f56dbea..0000000000000000000000000000000000000000 --- a/tests/examples/C#/insertCn/Program.cs +++ /dev/null @@ -1,149 +0,0 @@ -using System; -using Test.UtilsTools; -using System.Runtime.InteropServices; -using System.Collections.Generic; -using Test.UtilsTools.ResultSet; - -namespace insertCn -{ - class Program - { - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - IntPtr conn = UtilsTools.TDConnection(); - string dbName = "insert_cn_to_nchar_sample_dotnet"; - string createDB = $"create database if not exists {dbName};"; - string dropDB = $"drop database if exists {dbName};"; - string useDB = $"use {dbName};"; - string table = "t1"; - string stable = "stb"; - UtilsTools.ExecuteUpdate(conn,createDB); - UtilsTools.ExecuteUpdate(conn,useDB); - - Console.WriteLine("=====================ntable===================="); - TestNtable(conn,table); - Console.WriteLine("=====================stable===================="); - TestStable(conn,stable); - - UtilsTools.ExecuteUpdate(conn,dropDB); - UtilsTools.CloseConnection(conn); - - } - - static void TestStable(IntPtr conn,string stable) - { - string createSql = $"create table if not exists {stable} (ts timestamp," + - $"v4 int," + - $"blob nchar(200)," + - $"locate nchar(200)," + - $"country binary(200)," + - $"city binary(50)" + - $")tags(" + - $"id int," + - $"name nchar(50)," + - $"addr nchar(200)," + - $"en_name binary(200));"; - - String dropTb = "drop table if exists " + stable; - String table = stable + "_subtable_1"; - var colData = new List{1637064040000,1,"涛思数据","保利广场","Beijing","China", - 1637064041000,2,"涛思数据taosdata","保利广场baoli","Beijing","China", - 1637064042000,3,"TDegnine涛思数据","time广场","NewYork","US", - 1637064043000,4,"4涛思数据","4广场南部","London","UK", - 1637064044000,5,"涛思数据5","!广场路中部123","Tokyo","JP", - 1637064045000,6,"taos涛思数据6","青年广场123号!","Washin","DC", - 1637064046000,7,"7涛思数据taos","asdf#壮年广场%#endregion","NewYork","US", - 1637064047000,8,"8&涛思数据taos","incluse阿斯顿发","NewYork","US", - 1637064048000,9,"&涛思数据taos9","123黑化肥werq会挥……&¥%发!afsdfa","NewYork","US", - }; - var tagData = new List{1,"涛思数据","中国北方&南方长江黄河!49wq","tdengine"}; - string insertSql = UtilsTools.ConstructInsertSql(table, stable, colData, tagData, 9); - string selectSql = $"select * from {stable};"; - List insertData = UtilsTools.CombineColAndTagData(colData,tagData,9); - - UtilsTools.ExecuteUpdate(conn,dropTb); - UtilsTools.ExecuteUpdate(conn,createSql); - UtilsTools.ExecuteUpdate(conn,insertSql); - IntPtr res = UtilsTools.ExecuteQuery(conn,selectSql); - - ResultSet resultSet = new ResultSet(res); - List queryResult = resultSet.GetResultData(); - - //display - int fieldsCount = resultSet.GetFieldsNum(); - for(int i = 0 ; i{1637064040000,1,"涛思数据","保利广场","Beijing","China", - 1637064041000,2,"涛思数据taosdata","保利广场baoli","Beijing","China", - 1637064042000,3,"TDegnine涛思数据","time广场","NewYork","US", - 1637064043000,4,"4涛思数据","4广场南部","London","UK", - 1637064044000,5,"涛思数据5","!广场路中部123","Tokyo","JP", - 1637064045000,6,"taos涛思数据6","青年广场123号!","Washin","DC", - 1637064046000,7,"7涛思数据taos","asdf#壮年广场%#endregion","NewYork","US", - 1637064047000,8,"8&涛思数据taos","incluse阿斯顿发","NewYork","US", - 1637064048000,9,"&涛思数据taos9","123黑化肥werq会挥……&¥%发!afsdfa","NewYork","US", - }; - - String dropTb = "drop table if exists " + tableName; - String createTb = $"create table if not exists {tableName} (ts timestamp,v4 int,blob nchar(200),location nchar(200),city binary(100),coutry nchar(200));"; - String insertSql = UtilsTools.ConstructInsertSql(tableName, "", colData, null, 9); - String selectSql = "select * from " + tableName; - - UtilsTools.ExecuteUpdate(conn, dropTb); - UtilsTools.ExecuteUpdate(conn, createTb); - UtilsTools.ExecuteUpdate(conn, insertSql); - IntPtr res = UtilsTools.ExecuteQuery(conn, selectSql); - - ResultSet resultSet = new ResultSet(res); - List queryResult = resultSet.GetResultData(); - int fieldsCount = resultSet.GetFieldsNum(); - - //display - for(int i = 0 ; i - * - * 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 . - */ - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; - -namespace TDengineDriver -{ - public enum TDengineDataType - { - TSDB_DATA_TYPE_NULL = 0, // 1 bytes - TSDB_DATA_TYPE_BOOL = 1, // 1 bytes - TSDB_DATA_TYPE_TINYINT = 2, // 1 bytes - TSDB_DATA_TYPE_SMALLINT = 3, // 2 bytes - TSDB_DATA_TYPE_INT = 4, // 4 bytes - TSDB_DATA_TYPE_BIGINT = 5, // 8 bytes - TSDB_DATA_TYPE_FLOAT = 6, // 4 bytes - TSDB_DATA_TYPE_DOUBLE = 7, // 8 bytes - TSDB_DATA_TYPE_BINARY = 8, // string - TSDB_DATA_TYPE_TIMESTAMP = 9,// 8 bytes - TSDB_DATA_TYPE_NCHAR = 10, // unicode string - TSDB_DATA_TYPE_UTINYINT = 11,// 1 byte - TSDB_DATA_TYPE_USMALLINT = 12,// 2 bytes - TSDB_DATA_TYPE_UINT = 13, // 4 bytes - TSDB_DATA_TYPE_UBIGINT = 14, // 8 bytes - TSDB_DATA_TYPE_JSONTAG = 15 //4096 bytes - } - - public enum TDengineInitOption - { - TSDB_OPTION_LOCALE = 0, - TSDB_OPTION_CHARSET = 1, - TSDB_OPTION_TIMEZONE = 2, - TDDB_OPTION_CONFIGDIR = 3, - TDDB_OPTION_SHELL_ACTIVITY_TIMER = 4 - } - enum TaosField - { - STRUCT_SIZE = 68, - NAME_LENGTH = 65, - TYPE_OFFSET = 65, - BYTES_OFFSET = 66, - - } - public class TDengineMeta - { - public string name; - public short size; - public byte type; - public string TypeName() - { - switch ((TDengineDataType)type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - return "BOOL"; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - return "TINYINT"; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - return "SMALLINT"; - case TDengineDataType.TSDB_DATA_TYPE_INT: - return "INT"; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - return "BIGINT"; - case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: - return "TINYINT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: - return "SMALLINT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_UINT: - return "INT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: - return "BIGINT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - return "FLOAT"; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - return "DOUBLE"; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - return "BINARY"; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - return "TIMESTAMP"; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - return "NCHAR"; - case TDengineDataType.TSDB_DATA_TYPE_JSONTAG: - return "JSON"; - default: - return "undefine"; - } - } - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - public struct TAOS_BIND - { - // column type - public int buffer_type; - // one column value - public IntPtr buffer; - // unused - public Int32 buffer_length; - // actual value length in buffer - public IntPtr length; - // indicates the column value is null or not - public IntPtr is_null; - // unused - public int is_unsigned; - // unused - public IntPtr error; - public Int64 u; - public uint allocated; - } - - - [StructLayout(LayoutKind.Sequential)] - public struct TAOS_MULTI_BIND - { - // column type - public int buffer_type; - - // array, one or more lines column value - public IntPtr buffer; - - //length of element in TAOS_MULTI_BIND.buffer (for binary and nchar it is the longest element's length) - public ulong buffer_length; - - //array, actual data length for each value - public IntPtr length; - - //array, indicates each column value is null or not - public IntPtr is_null; - - // line number, or the values number in buffer - public int num; - } - - - public class TDengine - { - public const int TSDB_CODE_SUCCESS = 0; - - [DllImport("taos", EntryPoint = "taos_init", CallingConvention = CallingConvention.Cdecl)] - static extern public void Init(); - - [DllImport("taos", EntryPoint = "taos_cleanup", CallingConvention = CallingConvention.Cdecl)] - static extern public void Cleanup(); - - [DllImport("taos", EntryPoint = "taos_options", CallingConvention = CallingConvention.Cdecl)] - static extern public void Options(int option, string value); - - [DllImport("taos", EntryPoint = "taos_connect", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr Connect(string ip, string user, string password, string db, short port); - - [DllImport("taos", EntryPoint = "taos_errstr", CallingConvention = CallingConvention.Cdecl)] - static extern private IntPtr taos_errstr(IntPtr res); - static public string Error(IntPtr res) - { - IntPtr errPtr = taos_errstr(res); - return Marshal.PtrToStringAnsi(errPtr); - } - - [DllImport("taos", EntryPoint = "taos_errno", CallingConvention = CallingConvention.Cdecl)] - static extern public int ErrorNo(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_query", CallingConvention = CallingConvention.Cdecl)] - // static extern public IntPtr Query(IntPtr conn, string sqlstr); - static extern private IntPtr Query(IntPtr conn, IntPtr byteArr); - - static public IntPtr Query(IntPtr conn,string command) - { - IntPtr res = IntPtr.Zero; - - IntPtr commandBuffer = Marshal.StringToCoTaskMemUTF8(command); - res = Query(conn,commandBuffer); - return res; - } - - [DllImport("taos", EntryPoint = "taos_affected_rows", CallingConvention = CallingConvention.Cdecl)] - static extern public int AffectRows(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_field_count", CallingConvention = CallingConvention.Cdecl)] - static extern public int FieldCount(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_fetch_fields", CallingConvention = CallingConvention.Cdecl)] - static extern private IntPtr taos_fetch_fields(IntPtr res); - static public List FetchFields(IntPtr res) - { - // const int fieldSize = 68; - - List metas = new List(); - if (res == IntPtr.Zero) - { - return metas; - } - - int fieldCount = FieldCount(res); - IntPtr fieldsPtr = taos_fetch_fields(res); - - for (int i = 0; i < fieldCount; ++i) - { - int offset = i * (int)TaosField.STRUCT_SIZE; - TDengineMeta meta = new TDengineMeta(); - meta.name = Marshal.PtrToStringAnsi(fieldsPtr + offset); - meta.type = Marshal.ReadByte(fieldsPtr + offset + (int)TaosField.TYPE_OFFSET); - meta.size = Marshal.ReadInt16(fieldsPtr + offset + (int)TaosField.BYTES_OFFSET); - metas.Add(meta); - } - - - return metas; - } - - [DllImport("taos", EntryPoint = "taos_fetch_row", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr FetchRows(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_free_result", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr FreeResult(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_close", CallingConvention = CallingConvention.Cdecl)] - static extern public int Close(IntPtr taos); - - //get precision of restultset - [DllImport("taos", EntryPoint = "taos_result_precision", CallingConvention = CallingConvention.Cdecl)] - static extern public int ResultPrecision(IntPtr taos); - - - - //stmt APIs: - /// - /// init a TAOS_STMT object for later use. - /// - /// a valid taos connection - /// - /// Not NULL returned for success, NULL for failure. And it should be freed with taos_stmt_close. - /// - [DllImport("taos", EntryPoint = "taos_stmt_init", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr StmtInit(IntPtr taos); - - /// - /// prepare a sql statement,'sql' should be a valid INSERT/SELECT statement. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// sql string,used to bind parameters with - /// no used - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_prepare", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtPrepare(IntPtr stmt, string sql); - - /// - /// For INSERT only. Used to bind table name as a parmeter for the input stmt object. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// table name you want to bind - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_set_tbname", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtSetTbname(IntPtr stmt, string name); - - /// - /// For INSERT only. - /// Set a table name for binding table name as parameter. Only used for binding all tables - /// in one stable, user application must call 'loadTableInfo' API to load all table - /// meta before calling this API. If the table meta is not cached locally, it will return error. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// table name which is belong to an stable - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_set_sub_tbname", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtSetSubTbname(IntPtr stmt, string name); - - /// - /// For INSERT only. - /// set a table name for binding table name as parameter and tag values for all tag parameters. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// use to set table name - /// - /// is an array contains all tag values,each item in the array represents a tag column's value. - /// the item number and sequence should keep consistence with that in stable tag definition. - /// - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_set_tbname_tags", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtSetTbnameTags(IntPtr stmt, string name, TAOS_BIND[] tags); - - /// - /// For both INSERT and SELECT. - /// bind a whole line data. - /// The usage of structure TAOS_BIND is the same with MYSQL_BIND in MySQL. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// - /// points to an array contains the whole line data. - /// the item number and sequence should keep consistence with columns in sql statement. - /// - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_bind_param", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] - static extern public int StmtBindParam(IntPtr stmt, TAOS_BIND[] bind); - - /// - /// bind a single column's data, INTERNAL used and for INSERT only. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// points to a column's data which could be the one or more lines. - /// the column's index in prepared sql statement, it starts from 0. - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_bind_single_param_batch", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtBindSingleParamBatch(IntPtr stmt, ref TAOS_MULTI_BIND bind, int colIdx); - - /// - /// for INSERT only - /// bind one or multiple lines data. The parameter 'bind' - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// - /// points to an array contains one or more lines data.Each item in array represents a column's value(s), - /// the item number and sequence should keep consistence with columns in sql statement. - /// - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_bind_param_batch", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtBindParamBatch(IntPtr stmt, [In, Out] TAOS_MULTI_BIND[] bind); - - /// - /// For INSERT only. - /// add all current bound parameters to batch process. Must be called after each call to - /// StmtBindParam/StmtBindSingleParamBatch, or all columns binds for one or more lines - /// with StmtBindSingleParamBatch. User application can call any bind parameter - /// API again to bind more data lines after calling to this API. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_add_batch", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtAddBatch(IntPtr stmt); - - /// - /// actually execute the INSERT/SELECT sql statement. - /// User application can continue to bind new data after calling to this API. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// - [DllImport("taos", EntryPoint = "taos_stmt_execute", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtExecute(IntPtr stmt); - - /// - /// For SELECT only,getting the query result. User application should free it with API 'FreeResult' at the end. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// Not NULL for success, NULL for failure. - [DllImport("taos", EntryPoint = "taos_stmt_use_result", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr StmtUseResult(IntPtr stmt); - - /// - /// close STMT object and free resources. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// 0 for success, non-zero for failure. - [DllImport("taos", EntryPoint = "taos_stmt_close", CallingConvention = CallingConvention.Cdecl)] - static extern public int StmtClose(IntPtr stmt); - - [DllImport("taos", EntryPoint = "taos_load_table_info", CallingConvention = CallingConvention.Cdecl)] - /// - /// user application must call this API to load all tables meta, - /// - /// taos connection - /// tablelist - /// - static extern private int LoadTableInfoDll(IntPtr taos, string tableList); - - /// - /// user application call this API to load all tables meta,this method call the native - /// method LoadTableInfoDll. - /// this method must be called before StmtSetSubTbname(IntPtr stmt, string name); - /// - /// taos connection - /// tables need to load meta info are form in an array - /// - static public int LoadTableInfo(IntPtr taos, string[] tableList) - { - string listStr = string.Join(",", tableList); - return LoadTableInfoDll(taos, listStr); - } - - /// - /// get detail error message when got failure for any stmt API call. If not failure, the result - /// returned in this API is unknown. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// piont the error message - [DllImport("taos", EntryPoint = "taos_stmt_errstr", CallingConvention = CallingConvention.Cdecl)] - static extern private IntPtr StmtErrPtr(IntPtr stmt); - - /// - /// get detail error message when got failure for any stmt API call. If not failure, the result - /// returned in this API is unknown. - /// - /// could be the value returned by 'StmtInit', that may be a valid object or NULL. - /// error string - static public string StmtErrorStr(IntPtr stmt) - { - IntPtr stmtErrPrt = StmtErrPtr(stmt); - return Marshal.PtrToStringAnsi(stmtErrPrt); - } - - [DllImport("taos", EntryPoint = "taos_fetch_lengths", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr FetchLengths(IntPtr taos); - } -} diff --git a/tests/examples/C#/insertCn/insertCn.csproj b/tests/examples/C#/insertCn/insertCn.csproj deleted file mode 100644 index 69ddfdfbbff10fd9c26c92dcb8c8c2928b5c8511..0000000000000000000000000000000000000000 --- a/tests/examples/C#/insertCn/insertCn.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - Exe - net5.0 - - - diff --git a/tests/examples/C#/insertCn/lib/ResultSetUtils.cs b/tests/examples/C#/insertCn/lib/ResultSetUtils.cs deleted file mode 100644 index e0fc4e2ccae00f38c5889f211d2d12a66bdaa31b..0000000000000000000000000000000000000000 --- a/tests/examples/C#/insertCn/lib/ResultSetUtils.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using TDengineDriver; -using System.Runtime.InteropServices; -using System.Text; -using System.Collections.Generic; -namespace Test.UtilsTools.ResultSet -{ - public class ResultSet - { - private List resultMeta; - private List resultData; - // private bool isValidResult = false; - public ResultSet(IntPtr res) - { - - resultMeta = UtilsTools.GetResField(res); - resultData = UtilsTools.GetResData(res); - } - - public ResultSet(List metas, List datas) - { - resultMeta = metas; - resultData = datas; - } - - public List GetResultData() - { - return resultData; - } - - public List GetResultMeta() - { - return resultMeta; - } - - public int GetFieldsNum() - { - return resultMeta.Count; - } - } - - -} \ No newline at end of file diff --git a/tests/examples/C#/insertCn/lib/Utils.cs b/tests/examples/C#/insertCn/lib/Utils.cs deleted file mode 100644 index b43268342fa17e2a690b21ab8c24246b1a653501..0000000000000000000000000000000000000000 --- a/tests/examples/C#/insertCn/lib/Utils.cs +++ /dev/null @@ -1,442 +0,0 @@ -using System; -using TDengineDriver; -using System.Runtime.InteropServices; -using System.Text; -using System.Collections.Generic; -namespace Test.UtilsTools -{ - public class UtilsTools - { - - static string ip = "127.0.0.1"; - static string user = "root"; - static string password = "taosdata"; - static string db = ""; - static short port = 0; - //get a tdengine connection - public static IntPtr TDConnection() - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, GetConfigPath()); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - TDengine.Init(); - IntPtr conn = TDengine.Connect(ip, user, password, db, port); - return conn; - } - //get taos.cfg file based on different os - public static string GetConfigPath() - { - string configDir = "" ; - if(OperatingSystem.IsOSPlatform("Windows")) - { - configDir = "C:/TDengine/cfg"; - } - else if(OperatingSystem.IsOSPlatform("Linux")) - { - configDir = "/etc/taos"; - } - else if(OperatingSystem.IsOSPlatform("macOS")) - { - configDir = "/etc/taos"; - } - return configDir; - } - - public static IntPtr ExecuteQuery(IntPtr conn, String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if (!IsValidResult(res)) - { - Console.Write(sql.ToString() + " failure, "); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - return res; - } - - public static IntPtr ExecuteErrorQuery(IntPtr conn, String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if (!IsValidResult(res)) - { - Console.Write(sql.ToString() + " failure, "); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - - } - return res; - } - - public static void ExecuteUpdate(IntPtr conn, String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if (!IsValidResult(res)) - { - Console.Write(sql.ToString() + " failure, "); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - - } - TDengine.FreeResult(res); - } - - - // public static List> GetResultSet(IntPtr res) - // { - // List> result = new List>(); - // List colName = new List(); - // List dataRaw = new List(); - // if (!IsValidResult(res)) - // { - // ExitProgram(); - // } - - // List metas = GetResField(res); - // result.Add(colName); - - // dataRaw = QueryRes(res, metas); - // result.Add(dataRaw); - - // if (TDengine.ErrorNo(res) != 0) - // { - // Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - // } - // return result; - // } - - public static bool IsValidResult(IntPtr res) - { - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - return false; - } - Console.WriteLine(""); - return false; - } - return true; - } - public static void CloseConnection(IntPtr conn) - { - if (conn != IntPtr.Zero) - { - if (TDengine.Close(conn) == 0) - { - Console.WriteLine("close connection sucess"); - } - else - { - Console.WriteLine("close Connection failed"); - } - } - TDengine.Cleanup(); - } - public static List GetResField(IntPtr res) - { - List metas = TDengine.FetchFields(res); - return metas; - } - public static void AssertEqual(string expectVal, string actualVal) - { - if (expectVal == actualVal) - { - Console.WriteLine("{0}=={1} pass", expectVal, actualVal); - } - else - { - Console.WriteLine("{0}=={1} failed", expectVal, actualVal); - ExitProgram(); - } - } - public static void ExitProgram() - { - TDengine.Cleanup(); - System.Environment.Exit(0); - } - public static List GetResData(IntPtr res) - { - List dataRaw = new List(); - if (!IsValidResult(res)) - { - ExitProgram(); - } - List metas = GetResField(res); - dataRaw = QueryRes(res, metas); - return dataRaw; - } - - public static TDengineMeta ConstructTDengineMeta(string name, string type) - { - - TDengineMeta _meta = new TDengineMeta(); - _meta.name = name; - char[] separators = new char[] { '(', ')' }; - string[] subs = type.Split(separators, StringSplitOptions.RemoveEmptyEntries); - - switch (subs[0].ToUpper()) - { - case "BOOL": - _meta.type = 1; - _meta.size = 1; - break; - case "TINYINT": - _meta.type = 2; - _meta.size = 1; - break; - case "SMALLINT": - _meta.type = 3; - _meta.size = 2; - break; - case "INT": - _meta.type = 4; - _meta.size = 4; - break; - case "BIGINT": - _meta.type = 5; - _meta.size = 8; - break; - case "TINYINT UNSIGNED": - _meta.type = 11; - _meta.size = 1; - break; - case "SMALLINT UNSIGNED": - _meta.type = 12; - _meta.size = 2; - break; - case "INT UNSIGNED": - _meta.type = 13; - _meta.size = 4; - break; - case "BIGINT UNSIGNED": - _meta.type = 14; - _meta.size = 8; - break; - case "FLOAT": - _meta.type = 6; - _meta.size = 4; - break; - case "DOUBLE": - _meta.type = 7; - _meta.size = 8; - break; - case "BINARY": - _meta.type = 8; - _meta.size = short.Parse(subs[1]); - break; - case "TIMESTAMP": - _meta.type = 9; - _meta.size = 8; - break; - case "NCHAR": - _meta.type = 10; - _meta.size = short.Parse(subs[1]); - break; - case "JSON": - _meta.type = 15; - _meta.size = 4096; - break; - default: - _meta.type = byte.MaxValue; - _meta.size = 0; - break; - } - return _meta; - } - - private static List QueryRes(IntPtr res, List metas) - { - IntPtr rowdata; - long queryRows = 0; - List dataRaw = new List(); - int fieldCount = metas.Count; - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - IntPtr colLengthPtr = TDengine.FetchLengths(res); - int[] colLengthArr = new int[fieldCount]; - Marshal.Copy(colLengthPtr, colLengthArr, 0, fieldCount); - - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - if (data == IntPtr.Zero) - { - dataRaw.Add("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - dataRaw.Add(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - sbyte v2 = (sbyte)Marshal.ReadByte(data); - dataRaw.Add(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - dataRaw.Add(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - dataRaw.Add(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - dataRaw.Add(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - dataRaw.Add(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - dataRaw.Add(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - // string v8 = Marshal.PtrToStringAnsi(data, colLengthArr[fields]); - string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[fields]); - dataRaw.Add(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - dataRaw.Add(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - // string v10 = Marshal.PtrToStringAnsi(data, colLengthArr[fields]); - string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[fields]); - dataRaw.Add(v10); - break; - case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: - byte v12 = Marshal.ReadByte(data); - dataRaw.Add(v12); - break; - case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: - ushort v13 = (ushort)Marshal.ReadInt16(data); - dataRaw.Add(v13); - break; - case TDengineDataType.TSDB_DATA_TYPE_UINT: - uint v14 = (uint)Marshal.ReadInt32(data); - dataRaw.Add(v14); - break; - case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: - ulong v15 = (ulong)Marshal.ReadInt64(data); - dataRaw.Add(v15); - break; - default: - dataRaw.Add("unknown value"); - break; - } - } - - } - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - } - TDengine.FreeResult(res); - Console.WriteLine(""); - return dataRaw; - } - - // Generate insert sql for the with the coldata and tag data - public static string ConstructInsertSql(string table,string stable,List colData,List tagData,int numOfRows) - { - int numofFileds = colData.Count / numOfRows; - StringBuilder insertSql; - - if (stable == "") - { - insertSql = new StringBuilder($"insert into {table} values("); - } - else - { - insertSql = new StringBuilder($"insert into {table} using {stable} tags("); - - for (int j = 0; j < tagData.Count; j++) - { - if (tagData[j] is String) - { - insertSql.Append('\''); - insertSql.Append(tagData[j]); - insertSql.Append('\''); - } - else - { - insertSql.Append(tagData[j]); - } - if (j + 1 != tagData.Count) - { - insertSql.Append(','); - } - } - - insertSql.Append(")values("); - } - for (int i = 0; i < colData.Count; i++) - { - - if (colData[i] is String) - { - insertSql.Append('\''); - insertSql.Append(colData[i]); - insertSql.Append('\''); - } - else - { - insertSql.Append(colData[i]); - } - - if ((i + 1) % numofFileds == 0 && (i + 1) != colData.Count) - { - insertSql.Append(")("); - } - else if ((i + 1) == colData.Count) - { - insertSql.Append(')'); - } - else - { - insertSql.Append(','); - } - } - insertSql.Append(';'); - //Console.WriteLine(insertSql.ToString()); - - return insertSql.ToString(); - } - - public static List CombineColAndTagData(List colData,List tagData, int numOfRows) - { - var list = new List(); - for (int i = 0; i < colData.Count; i++) - { - list.Add(colData[i]); - if ((i + 1) % (colData.Count / numOfRows) == 0) - { - for (int j = 0; j < tagData.Count; j++) - { - list.Add(tagData[j]); - } - } - } - return list; - } - } -} - diff --git a/tests/examples/C#/jsonTag/JsonTag.cs b/tests/examples/C#/jsonTag/JsonTag.cs deleted file mode 100644 index 453e54eabdc9a4ec61cdc2a061af69ed64753416..0000000000000000000000000000000000000000 --- a/tests/examples/C#/jsonTag/JsonTag.cs +++ /dev/null @@ -1,365 +0,0 @@ -using System; -using Utils; - -namespace Cases -{ - - class Program - { - static void Main(string[] args) - { - IntPtr conn = IntPtr.Zero; - Console.WriteLine("===================JsonTagTest===================="); - conn = conn = UtilsTools.TDConnection("127.0.0.1", "root", "taosdata", "", 0); - UtilsTools.ExecuteUpdate(conn, "create database if not exists csharp_sample keep 3650"); - UtilsTools.ExecuteUpdate(conn, "use csharp"); - JsonTagSample jsonTagSample = new JsonTagSample(); - jsonTagSample.Test(conn); - } - - } - - public class JsonTagSample - { - public void Test(IntPtr conn) - { - Console.WriteLine("STEP 1 prepare data & validate json string===== "); - UtilsTools.ExecuteQuery(conn, "create table if not exists jsons1(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_1 using jsons1 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 1, false, 'json1', '涛思数据') (1591060608000, 23, true, '涛思数据', 'json')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_2 using jsons1 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060628000, 2, true, 'json2', 'sss')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_3 using jsons1 tags('{\"tag1\":false,\"tag2\":\"beijing\"}') values (1591060668000, 3, false, 'json3', 'efwe')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_4 using jsons1 tags('{\"tag1\":null,\"tag2\":\"shanghai\",\"tag3\":\"hello\"}') values (1591060728000, 4, true, 'json4', '323sd')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_5 using jsons1 tags('{\"tag1\":1.232, \"tag2\":null}') values(1591060928000, 1, false, '涛思数据', 'ewe')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_6 using jsons1 tags('{\"tag1\":11,\"tag2\":\"\",\"tag2\":null}') values(1591061628000, 11, false, '涛思数据','')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_7 using jsons1 tags('{\"tag1\":\"涛思数据\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '涛思数据', 'dws')"); - Console.WriteLine(""); - - Console.WriteLine("test duplicate key using the first one. elimate empty key======== "); - UtilsTools.ExecuteQuery(conn, "CREATE TABLE if not exists jsons1_8 using jsons1 tags('{\"tag1\":null, \"tag1\":true, \"tag1\":45, \"1tag$\":2, \" \":90}')"); - Console.WriteLine(""); - - Console.WriteLine("test empty json string, save as jtag is NULL========== "); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_9 using jsons1 tags('\t') values (1591062328000, 24, NULL, '涛思数据', '2sdw')"); - UtilsTools.ExecuteQuery(conn, "CREATE TABLE if not exists jsons1_10 using jsons1 tags('')"); - UtilsTools.ExecuteQuery(conn, "CREATE TABLE if not exists jsons1_11 using jsons1 tags(' ')"); - UtilsTools.ExecuteQuery(conn, "CREATE TABLE if not exists jsons1_12 using jsons1 tags('{}')"); - UtilsTools.ExecuteQuery(conn, "CREATE TABLE if not exists jsons1_13 using jsons1 tags('null')"); - Console.WriteLine(""); - - Console.WriteLine("test invalidate json==================== "); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('\"efwewf\"')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('3333')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('33.33')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('false')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('[1,true]')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{222}')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"fe\"}')"); - Console.WriteLine(""); - - Console.WriteLine("test invalidate json key, key must can be printed assic char========== "); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":[1,true]}')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"tag1\":{}}')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"。loc\":\"fff\"}')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\":\"fff\"}')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"\t\":\"fff\"}')"); - UtilsTools.ExecuteErrorQuery(conn, "CREATE TABLE if not exists jsons1_14 using jsons1 tags('{\"试试\":\"fff\"}')"); - Console.WriteLine(""); - - Console.WriteLine("STEP 2 alter table json tag============"); - UtilsTools.ExecuteErrorQuery(conn, "ALTER STABLE jsons1 add tag tag2 nchar(20)"); - UtilsTools.ExecuteErrorQuery(conn, "ALTER STABLE jsons1 drop tag jtag"); - UtilsTools.ExecuteErrorQuery(conn, "ALTER TABLE jsons1_1 SET TAG jtag=4"); - UtilsTools.ExecuteQuery(conn, "ALTER TABLE jsons1_1 SET TAG jtag='{\"tag1\":\"femail\",\"tag2\":35,\"tag3\":true}'"); - Console.WriteLine(""); - - Console.WriteLine("STEP 3 query table============"); - Console.WriteLine("test error syntax============"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->tag1='beijing'"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->'location'"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->''"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->''=9"); - UtilsTools.ExecuteErrorQuery(conn, "select -> from jsons1"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where contains"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->"); - UtilsTools.ExecuteErrorQuery(conn, "select jtag->location from jsons1"); - UtilsTools.ExecuteErrorQuery(conn, "select jtag contains location from jsons1"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag contains location"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag contains''"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag contains 'location'='beijing'"); - Console.WriteLine(""); - - Console.WriteLine("test select normal column==========="); - IntPtr res = IntPtr.Zero; - res = UtilsTools.ExecuteQuery(conn, "select dataint from jsons1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test select json tag==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select jtag from jsons1"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select jtag from jsons1 where jtag is null"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select jtag from jsons1 where jtag is not null"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test #line 41==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag from jsons1_8"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test #line 72==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag from jsons1_1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test jtag is NULL==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag from jsons1_9"); - UtilsTools.DisplayRes(res); - - - Console.WriteLine("test select json tag->'key', value is string ==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from jsons1_1"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag2' from jsons1_6"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test select json tag->'key', value is int==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag2' from jsons1_1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test select json tag->'key', value is bool==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag3' from jsons1_1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test select json tag->'key', value is null==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from jsons1_4"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test select json tag->'key', value is double==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from jsons1_5"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test select json tag->'key', key is not exist==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag10' from jsons1_4"); - UtilsTools.DisplayRes(res); - - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from jsons1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test header name==========="); - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from jsons1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test where with json tag==========="); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1_1 where jtag is not null"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag='{\"tag1\":11,\"tag2\":\"\"}'"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->'tag1'={}"); - - Console.WriteLine("where json value is string==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select dataint,tbname,jtag->'tag1',jtag from jsons1 where jtag->'tag2'='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'='涛思数据'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'>'beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'>='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'<'beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'<='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'!='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2'=''"); - UtilsTools.DisplayRes(res); - - - Console.WriteLine("where json value is int==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=5"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=10"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'<54"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'<=11"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'>4"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'>=5"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'!=5"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'!=55"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("where json value is double==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=1.232"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'<1.232"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'<=1.232"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'>1.23"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'>=1.232"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'!=1.232"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'!=3.232"); - UtilsTools.DisplayRes(res); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->'tag1'/0=3"); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->'tag1'/5=1"); - - Console.WriteLine("where json value is bool==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=true"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=false"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'!=false"); - UtilsTools.DisplayRes(res); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->'tag1'>false"); - - Console.WriteLine("where json value is null==========="); - Console.WriteLine("only json suport =null. This synatx will change later.==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=null"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("where json is null==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag is null"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag is not null"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("where json key is null==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag_no_exist'=3"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("where json value is not exist==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1' is null"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag4' is null"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag3' is not null"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test contains==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag contains 'tag1'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag contains 'tag3'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag contains 'tag_no_exist'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test json tag in where condition with and/or==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=false or jtag->'tag2'='beijing'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=false and jtag->'tag2'='shanghai'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'=13 or jtag->'tag2'>35"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1' is not null and jtag contains 'tag3'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1'='femail' and jtag contains 'tag3'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test with tbname/normal column==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where tbname = 'jsons1_1'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=3"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where tbname = 'jsons1_1' and jtag contains 'tag3' and dataint=23"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test where condition like==========="); - res = UtilsTools.ExecuteQuery(conn, "select *,tbname from jsons1 where jtag->'tag2' like 'bei%'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select *,tbname from jsons1 where jtag->'tag1' like 'fe%' and jtag->'tag2' is not null"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test where condition in no support in==========="); - UtilsTools.ExecuteErrorQuery(conn, "select * from jsons1 where jtag->'tag1' in ('beijing')"); - - Console.WriteLine("test where condition match==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1' match 'ma'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1' match 'ma$'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag2' match 'jing$'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select * from jsons1 where jtag->'tag1' match '收到'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test distinct==========="); - UtilsTools.ExecuteQuery(conn, "insert into jsons1_14 using jsons1 tags('{\"tag1\":\"涛思数据\",\"tag2\":\"\",\"tag3\":null}') values(1591062628000, 2, NULL, '涛思数据', 'dws')"); - res = UtilsTools.ExecuteQuery(conn, "select distinct jtag->'tag1' from jsons1"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select distinct jtag from jsons1"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test dumplicate key with normal colomn==========="); - UtilsTools.ExecuteQuery(conn, "INSERT INTO jsons1_15 using jsons1 tags('{\"tbname\":\"tt\",\"databool\":true,\"datastr\":\"涛思数据\"}') values(1591060828000, 4, false, 'jjsf', \"你就会\")"); - res = UtilsTools.ExecuteQuery(conn, "select *,tbname,jtag from jsons1 where jtag->'datastr' match '涛思数据' and datastr match 'js'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select tbname,jtag->'tbname' from jsons1 where jtag->'tbname'='tt' and tbname='jsons1_14'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test join==========="); - UtilsTools.ExecuteQuery(conn, "create table if not exists jsons2(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - UtilsTools.ExecuteQuery(conn, "insert into jsons2_1 using jsons2 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 2, false, 'json2', '涛思数据2')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons2_2 using jsons2 tags('{\"tag1\":5,\"tag2\":null}') values (1591060628000, 2, true, 'json2', 'sss')"); - UtilsTools.ExecuteQuery(conn, "create table if not exists jsons3(ts timestamp, dataInt int, dataBool bool, dataStr nchar(50), dataStrBin binary(150)) tags(jtag json)"); - UtilsTools.ExecuteQuery(conn, "insert into jsons3_1 using jsons3 tags('{\"tag1\":\"fff\",\"tag2\":5, \"tag3\":true}') values(1591060618000, 3, false, 'json3', '涛思数据3')"); - UtilsTools.ExecuteQuery(conn, "insert into jsons3_2 using jsons3 tags('{\"tag1\":5,\"tag2\":\"beijing\"}') values (1591060638000, 2, true, 'json3', 'sss')"); - - res = UtilsTools.ExecuteQuery(conn, "select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select 'sss',33,a.jtag->'tag3' from jsons2 a,jsons3 b where a.ts=b.ts and a.jtag->'tag1'=b.jtag->'tag1'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test group by & order by json tag==========="); - res = UtilsTools.ExecuteQuery(conn, "select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' desc"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select count(*) from jsons1 group by jtag->'tag1' order by jtag->'tag1' asc"); - UtilsTools.DisplayRes(res); - - - Console.WriteLine("test stddev with group by json tag==========="); - res = UtilsTools.ExecuteQuery(conn, "select stddev(dataint) from jsons1 group by jtag->'tag1'"); - UtilsTools.DisplayRes(res); - res = UtilsTools.ExecuteQuery(conn, "select stddev(dataint) from jsons1 group by jsons1.jtag->'tag1'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("test top/bottom with group by json tag==========="); - res = UtilsTools.ExecuteQuery(conn, "select top(dataint,100) from jsons1 group by jtag->'tag1'"); - UtilsTools.DisplayRes(res); - - Console.WriteLine("subquery with json tag==========="); - res = UtilsTools.ExecuteQuery(conn, "select * from (select jtag, dataint from jsons1)"); - UtilsTools.DisplayRes(res); - - - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); - UtilsTools.DisplayRes(res); - - res = UtilsTools.ExecuteQuery(conn, "select jtag->'tag1' from (select jtag->'tag1', dataint from jsons1)"); - UtilsTools.DisplayRes(res); - - res = UtilsTools.ExecuteQuery(conn, "select ts,tbname,jtag->'tag1' from (select jtag->'tag1',tbname,ts from jsons1 order by ts)"); - UtilsTools.DisplayRes(res); - Console.WriteLine(""); - - - } - } -} \ No newline at end of file diff --git a/tests/examples/C#/jsonTag/Util.cs b/tests/examples/C#/jsonTag/Util.cs deleted file mode 100644 index 5138938df60532616e75b45d8a95597c322dfd1a..0000000000000000000000000000000000000000 --- a/tests/examples/C#/jsonTag/Util.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using TDengineDriver; -using System.Runtime.InteropServices; -using System.Text; -using System.Collections.Generic; -namespace Utils -{ - public class UtilsTools - { - - static string configDir = "/etc/taos";//"C:/TDengine/cfg"; - - public static IntPtr TDConnection(string ip, string user, string password, string db, short port) - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, configDir); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - TDengine.Init(); - return TDengine.Connect(ip, user, password, db, port); - } - - public static IntPtr ExecuteQuery(IntPtr conn, String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - return res; - } - - public static IntPtr ExecuteErrorQuery(IntPtr conn, String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - - } - Console.WriteLine(""); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - - } - return res; - } - - public static void ExecuteUpdate(IntPtr conn, String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - - } - TDengine.FreeResult(res); - } - - public static void DisplayRes(IntPtr res) - { - long queryRows = 0; - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - - int fieldCount = TDengine.FieldCount(res); - List metas = TDengine.FetchFields(res); - for (int j = 0; j < metas.Count; j++) - { - TDengineMeta meta = (TDengineMeta)metas[j]; - } - - IntPtr rowdata; - StringBuilder builder = new StringBuilder(); - - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - IntPtr colLengthPtr = TDengine.FetchLengths(res); - int[] colLengthArr = new int[fieldCount]; - Marshal.Copy(colLengthPtr, colLengthArr, 0, fieldCount); - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - builder.Append("---"); - - if (data == IntPtr.Zero) - { - builder.Append("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - builder.Append(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - byte v2 = Marshal.ReadByte(data); - builder.Append(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - builder.Append(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - builder.Append(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - builder.Append(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - builder.Append(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - builder.Append(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - string v8 = Marshal.PtrToStringAnsi(data, colLengthArr[fields]); - builder.Append(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - builder.Append(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - string v10 = Marshal.PtrToStringAnsi(data, colLengthArr[fields]); - builder.Append(v10); - break; - case TDengineDataType.TSDB_DATA_TYPE_JSONTAG: - string v11 = Marshal.PtrToStringAnsi(data); - builder.Append(v11); - break; - } - } - builder.Append("---"); - - if (queryRows <= 10) - { - Console.WriteLine(builder.ToString()); - } - builder.Clear(); - } - - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - } - TDengine.FreeResult(res); Console.WriteLine(""); - } - - public static bool IsValidResult(IntPtr res) - { - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - return false; - } - Console.WriteLine(""); - return false; - } - return true; - } - public static void CloseConnection(IntPtr conn) - { - if (conn != IntPtr.Zero) - { - if (TDengine.Close(conn) == 0) - { - Console.WriteLine("close connection sucess"); - } - else - { - Console.WriteLine("close Connection failed"); - } - } - } - public static void ExitProgram() - { - TDengine.Cleanup(); - System.Environment.Exit(0); - } - } -} \ No newline at end of file diff --git a/tests/examples/C#/jsonTag/jsonTag.csproj b/tests/examples/C#/jsonTag/jsonTag.csproj deleted file mode 100644 index ed3af6e806f0321828742597d226011bfb4d5185..0000000000000000000000000000000000000000 --- a/tests/examples/C#/jsonTag/jsonTag.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - net5.0 - - - - - - - diff --git a/tests/examples/C#/schemaless/TDengineDriver.cs b/tests/examples/C#/schemaless/TDengineDriver.cs deleted file mode 100644 index 8dd9ce0c929df66fd82bd40d6ff77a868c630efe..0000000000000000000000000000000000000000 --- a/tests/examples/C#/schemaless/TDengineDriver.cs +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; - -namespace TDengineDriver -{ - enum TDengineDataType - { - TSDB_DATA_TYPE_NULL = 0, // 1 bytes - TSDB_DATA_TYPE_BOOL = 1, // 1 bytes - TSDB_DATA_TYPE_TINYINT = 2, // 1 bytes - TSDB_DATA_TYPE_SMALLINT = 3, // 2 bytes - TSDB_DATA_TYPE_INT = 4, // 4 bytes - TSDB_DATA_TYPE_BIGINT = 5, // 8 bytes - TSDB_DATA_TYPE_FLOAT = 6, // 4 bytes - TSDB_DATA_TYPE_DOUBLE = 7, // 8 bytes - TSDB_DATA_TYPE_BINARY = 8, // string - TSDB_DATA_TYPE_TIMESTAMP = 9,// 8 bytes - TSDB_DATA_TYPE_NCHAR = 10, // unicode string - TSDB_DATA_TYPE_UTINYINT = 11,// 1 byte - TSDB_DATA_TYPE_USMALLINT = 12,// 2 bytes - TSDB_DATA_TYPE_UINT = 13, // 4 bytes - TSDB_DATA_TYPE_UBIGINT = 14 // 8 bytes - } - - enum TDengineInitOption - { - TSDB_OPTION_LOCALE = 0, - TSDB_OPTION_CHARSET = 1, - TSDB_OPTION_TIMEZONE = 2, - TDDB_OPTION_CONFIGDIR = 3, - TDDB_OPTION_SHELL_ACTIVITY_TIMER = 4 - } - enum TDengineSchemalessProtocol - { - TSDB_SML_UNKNOWN_PROTOCOL = 0, - TSDB_SML_LINE_PROTOCOL = 1, - TSDB_SML_TELNET_PROTOCOL = 2, - TSDB_SML_JSON_PROTOCOL = 3 - - } - enum TDengineSchemalessPrecision - { - TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0, - TSDB_SML_TIMESTAMP_HOURS = 1, - TSDB_SML_TIMESTAMP_MINUTES = 2, - TSDB_SML_TIMESTAMP_SECONDS = 3, - TSDB_SML_TIMESTAMP_MILLI_SECONDS = 4, - TSDB_SML_TIMESTAMP_MICRO_SECONDS = 5, - TSDB_SML_TIMESTAMP_NANO_SECONDS = 6 - } - - class TDengineMeta - { - public string name; - public short size; - public byte type; - public string TypeName() - { - switch ((TDengineDataType)type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - return "BOOL"; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - return "TINYINT"; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - return "SMALLINT"; - case TDengineDataType.TSDB_DATA_TYPE_INT: - return "INT"; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - return "BIGINT"; - case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: - return "TINYINT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: - return "SMALLINT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_UINT: - return "INT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: - return "BIGINT UNSIGNED"; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - return "FLOAT"; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - return "DOUBLE"; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - return "STRING"; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - return "TIMESTAMP"; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - return "NCHAR"; - default: - return "undefine"; - } - } - } - - class TDengine - { - public const int TSDB_CODE_SUCCESS = 0; - - [DllImport("taos", EntryPoint = "taos_init", CallingConvention = CallingConvention.Cdecl)] - static extern public void Init(); - - [DllImport("taos", EntryPoint = "taos_cleanup", CallingConvention = CallingConvention.Cdecl)] - static extern public void Cleanup(); - - [DllImport("taos", EntryPoint = "taos_options", CallingConvention = CallingConvention.Cdecl)] - static extern public void Options(int option, string value); - - [DllImport("taos", EntryPoint = "taos_connect", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr Connect(string ip, string user, string password, string db, short port); - - [DllImport("taos", EntryPoint = "taos_errstr", CallingConvention = CallingConvention.Cdecl)] - static extern private IntPtr taos_errstr(IntPtr res); - static public string Error(IntPtr res) - { - IntPtr errPtr = taos_errstr(res); - return Marshal.PtrToStringAnsi(errPtr); - } - - [DllImport("taos", EntryPoint = "taos_errno", CallingConvention = CallingConvention.Cdecl)] - static extern public int ErrorNo(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_query", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr Query(IntPtr conn, string sqlstr); - - [DllImport("taos", EntryPoint = "taos_affected_rows", CallingConvention = CallingConvention.Cdecl)] - static extern public int AffectRows(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_field_count", CallingConvention = CallingConvention.Cdecl)] - static extern public int FieldCount(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_fetch_fields", CallingConvention = CallingConvention.Cdecl)] - static extern private IntPtr taos_fetch_fields(IntPtr res); - static public List FetchFields(IntPtr res) - { - const int fieldSize = 68; - - List metas = new List(); - if (res == IntPtr.Zero) - { - return metas; - } - - int fieldCount = FieldCount(res); - IntPtr fieldsPtr = taos_fetch_fields(res); - - for (int i = 0; i < fieldCount; ++i) - { - int offset = i * fieldSize; - - TDengineMeta meta = new TDengineMeta(); - meta.name = Marshal.PtrToStringAnsi(fieldsPtr + offset); - meta.type = Marshal.ReadByte(fieldsPtr + offset + 65); - meta.size = Marshal.ReadInt16(fieldsPtr + offset + 66); - metas.Add(meta); - } - - return metas; - } - - [DllImport("taos", EntryPoint = "taos_fetch_row", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr FetchRows(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_free_result", CallingConvention = CallingConvention.Cdecl)] - static extern public IntPtr FreeResult(IntPtr res); - - [DllImport("taos", EntryPoint = "taos_close", CallingConvention = CallingConvention.Cdecl)] - static extern public int Close(IntPtr taos); - - //get precision in restultset - [DllImport("taos", EntryPoint = "taos_result_precision", CallingConvention = CallingConvention.Cdecl)] - 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); - } -} diff --git a/tests/examples/C#/schemaless/schemaless.csproj b/tests/examples/C#/schemaless/schemaless.csproj deleted file mode 100644 index d132e34589525826d5b0ff0f0055156fad2d5a38..0000000000000000000000000000000000000000 --- a/tests/examples/C#/schemaless/schemaless.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - net5.0 - - - - - - - diff --git a/tests/examples/C#/schemaless/schemalessSample.cs b/tests/examples/C#/schemaless/schemalessSample.cs deleted file mode 100644 index f27ac352a6fc8a3fbbaf84966ae3b82e6036e91a..0000000000000000000000000000000000000000 --- a/tests/examples/C#/schemaless/schemalessSample.cs +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -using System; -using System.Text; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Collections; - -namespace TDengineDriver -{ - class SchemalessSample - { - // connect parameters - private string host = "127.0.0.1"; - private string configDir = "C:/TDengine/cfg"; - private string user = "root"; - private string passwd = "taosdata"; - private short port = 0; - - private IntPtr conn = IntPtr.Zero; - private string dbName = "csharp"; - private string dbPrecision = "ms"; - - static void Main(string[] args) - { - string[] lines = { - "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000" - }; - string[] jsonStr = { - "{" - +"\"metric\": \"stb0_0\"," - +"\"timestamp\": 1626006833," - +"\"value\": 10," - +"\"tags\": {" - +" \"t1\": true," - +"\"t2\": false," - +"\"t3\": 10," - +"\"t4\": \"123_abc_.!@#$%^&*:;,./?|+-=()[]{}<>\"" - +"}" - +"}" - }; - - SchemalessSample sample = new SchemalessSample(); - sample.InitTDengine(); - sample.ConnectTDengine(); - sample.dropDatabase(); - sample.createDatabase(); - sample.useDatabase(); - sample.schemalessInsert(lines, 2, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NANO_SECONDS); - sample.checkSelect("stg"); - sample.schemalessInsert(jsonStr,1,(int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,(int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_SECONDS); - sample.checkSelect("stb0_0"); - sample.CloseConnection(); - sample.cleanup(); - } - - public void InitTDengine() - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, this.configDir); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - Console.WriteLine("init..."); - TDengine.Init(); - Console.WriteLine("get connection starting..."); - } - - public void ConnectTDengine() - { - string db = ""; - this.conn = TDengine.Connect(host, this.user, this.passwd, db, this.port); - if (this.conn == IntPtr.Zero) - { - Console.WriteLine("connection failed: " + this.host); - ExitProgram(); - } - else - { - Console.WriteLine("[ OK ] Connection established."); - } - } - public void createDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("create database if not exists ").Append(this.dbName).Append(" precision '").Append(this.dbPrecision).Append("'"); - execute(sql.ToString()); - } - public void useDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("use ").Append(this.dbName); - execute(sql.ToString()); - } - public void checkSelect(String tableName) - { - StringBuilder sql = new StringBuilder(); - sql.Append("select * from ").Append(this.dbName).Append(".").Append(tableName); - ExecuteQuery(sql.ToString()); - } - - public void schemalessInsert(string[] sqlstr, int lineCnt, int protocol, int precision) - { - - IntPtr res = TDengine.SchemalessInsert(this.conn, sqlstr, lineCnt, protocol, precision); - - if (TDengine.ErrorNo(res) != 0) - { - Console.WriteLine("schemaless_insert failed:{0}", TDengine.Error(res)); - Console.WriteLine("line string:{0}", sqlstr); - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine("else"); - Console.WriteLine("schemaless insert success:{0}", TDengine.ErrorNo(res)); - } - DisplayRes(res); - } - public void dropDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("drop database if exists ").Append(this.dbName); - execute(sql.ToString()); - } - public void execute(string sql) - { - DateTime dt1 = DateTime.Now; - - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - - DateTime dt2 = DateTime.Now; - TimeSpan span = dt2 - dt1; - - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - } - public void DisplayRes(IntPtr res) - { - long queryRows = 0; - int fieldCount = TDengine.FieldCount(res); - - List metas = TDengine.FetchFields(res); - for (int j = 0; j < metas.Count; j++) - { - TDengineMeta meta = (TDengineMeta)metas[j]; - } - - IntPtr rowdata; - StringBuilder builder = new StringBuilder(); - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - builder.Append("---"); - - if (data == IntPtr.Zero) - { - builder.Append("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - builder.Append(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - byte v2 = Marshal.ReadByte(data); - builder.Append(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - builder.Append(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - builder.Append(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - builder.Append(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - builder.Append(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - builder.Append(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - string v8 = Marshal.PtrToStringAnsi(data); - builder.Append(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - builder.Append(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - string v10 = Marshal.PtrToStringAnsi(data); - builder.Append(v10); - break; - } - } - builder.Append("---"); - - if (queryRows <= 10) - { - Console.WriteLine(builder.ToString()); - } - builder.Clear(); - } - - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - } - Console.WriteLine(""); - - TDengine.FreeResult(res); - - } - public void ExecuteQuery(string sql) - { - - DateTime dt1 = DateTime.Now; - - IntPtr res = TDengine.Query(conn, sql); - - DateTime dt2 = DateTime.Now; - TimeSpan span = dt2 - dt1; - - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - - Console.WriteLine("[OK] time cost: " + span.ToString() + "ms, execute statement ====> " + sql.ToString()); - DisplayRes(res); - - } - - public void CloseConnection() - { - if (this.conn != IntPtr.Zero) - { - TDengine.Close(this.conn); - Console.WriteLine("connection closed."); - } - } - - static void ExitProgram() - { - System.Environment.Exit(0); - } - - public void cleanup() - { - Console.WriteLine("clean up..."); - System.Environment.Exit(0); - } - // method to get db precision - } -} diff --git a/tests/examples/C#/stmt/StmtDemo.cs b/tests/examples/C#/stmt/StmtDemo.cs deleted file mode 100644 index fdd647fdb5f9c4bb528a2e99acc6975adf4c30a3..0000000000000000000000000000000000000000 --- a/tests/examples/C#/stmt/StmtDemo.cs +++ /dev/null @@ -1,549 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ -using System; -using System.Text; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Collections; -namespace TDengineDriver -{ - public class StmtDemo - { - //connection parameters - private string host = "127.0.0.1"; - private string configDir = "C:/TDengine/cfg"; - private string user = "root"; - private string passwd = "taosdata"; - private short port = 0; - - private IntPtr conn = IntPtr.Zero; - private IntPtr stmt = IntPtr.Zero; - - static void Main(string[] args) - { - string dropDB = "drop database if exists csharp"; - string createDB = "create database if not exists csharp keep 36500"; - string selectDB = "use csharp"; - string stmtSql = "insert into ? using stmtdemo tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - string createTable = "create stable stmtdemo (ts timestamp " - + ",b bool" - + ",v1 tinyint" - + ",v2 smallint" - + ",v4 int" - + ",v8 bigint" - + ",f4 float" - + ",f8 double" - + ",u1 tinyint unsigned" - + ",u2 smallint unsigned" - + ",u4 int unsigned" - + ",u8 bigint unsigned" - + ",bin binary(200)" - + ",blob nchar(200)" - + ")tags(" - + "bo bool" - + ",tt tinyint" - + ",si smallint" - + ",ii int" - + ",bi bigint" - + ",tu tinyint unsigned" - + ",su smallint unsigned" - + ",iu int unsigned" - + ",bu bigint unsigned" - + ",ff float " - + ",dd double " - + ",bb binary(200)" - + ",nc nchar(200)" - + ")"; - - string dropTable = "drop table if exists stmtdemo"; - - string tableName = "t1"; - StmtDemo stmtDemo = new StmtDemo(); - Console.WriteLine("---------------------------------------------------------------"); - Console.WriteLine("Start StmtDemo insert Testing..."); - Console.WriteLine("---------------------------------------------------------------"); - stmtDemo.InitTDengine(); - //TDengine connect - stmtDemo.ConnectTDengine(); - - //before stmt - stmtDemo.ExecuteQuery(dropDB); - stmtDemo.ExecuteQuery(createDB); - stmtDemo.ExecuteQuery(selectDB); - stmtDemo.ExecuteQuery(dropTable); - stmtDemo.ExecuteQuery(createTable); - - stmtDemo.StmtInit(); - // string[] tableList = { "stmtdemo" }; - // stmtDemo.loadTableInfo(tableList); - - stmtDemo.StmtPrepare(stmtSql); - TAOS_BIND[] binds = stmtDemo.InitBindArr(); - TAOS_MULTI_BIND[] mbinds = stmtDemo.InitMultBindArr(); - stmtDemo.SetTableNameTags(tableName, binds); - stmtDemo.BindParamBatch(mbinds); - stmtDemo.AddBatch(); - stmtDemo.StmtExecute(); - TaosBind.FreeTaosBind(binds); - TaosMultiBind.FreeTaosBind(mbinds); - stmtDemo.StmtClose(); - - Console.WriteLine("---------------------------------------------------------------"); - Console.WriteLine("start StmtDemo select Testing..."); - Console.WriteLine("---------------------------------------------------------------"); - - stmtDemo.StmtInit(); - string selectSql = "SELECT * FROM stmtdemo WHERE v1 > ? AND v4 < ?"; - - stmtDemo.StmtPrepare(selectSql); - - TAOS_BIND[] queryCondition = new TAOS_BIND[2]; - queryCondition[0] = TaosBind.BindTinyInt(0); - queryCondition[1] = TaosBind.BindInt(1000); - - Console.WriteLine(selectSql); - stmtDemo.BindParam(queryCondition); - stmtDemo.StmtExecute(); - - stmtDemo.StmtUseResult(); - - stmtDemo.StmtClose(); - TaosBind.FreeTaosBind(queryCondition); - Console.WriteLine("---------------------------------------------------------------"); - Console.WriteLine("Stop StmtDemo Testing..."); - Console.WriteLine("---------------------------------------------------------------"); - - stmtDemo.CloseConnection(); - } - public TAOS_BIND[] InitBindArr() - { - TAOS_BIND[] binds = new TAOS_BIND[13]; - binds[0] = TaosBind.BindBool(true); - binds[1] = TaosBind.BindTinyInt(-2); - binds[2] = TaosBind.BindSmallInt(short.MaxValue); - binds[3] = TaosBind.BindInt(int.MaxValue); - binds[4] = TaosBind.BindBigInt(Int64.MaxValue); - binds[5] = TaosBind.BindUTinyInt(byte.MaxValue - 1); - binds[6] = TaosBind.BindUSmallInt(UInt16.MaxValue - 1); - binds[7] = TaosBind.BindUInt(uint.MinValue + 1); - binds[8] = TaosBind.BindUBigInt(UInt64.MinValue + 1); - binds[9] = TaosBind.BindFloat(11.11F); - binds[10] = TaosBind.BindDouble(22.22D); - binds[11] = TaosBind.BindBinary("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}"); - binds[12] = TaosBind.BindNchar("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}"); - return binds; - } - - public TAOS_MULTI_BIND[] InitMultBindArr() - { - TAOS_MULTI_BIND[] mBinds = new TAOS_MULTI_BIND[14]; - long[] tsArr = new long[5] { 1637064040000, 1637064041000, 1637064042000, 1637064043000, 1637064044000 }; - bool?[] boolArr = new bool?[5] { true, false, null, true, true }; - sbyte?[] tinyIntArr = new sbyte?[5] { -127, 0, null, 8, 127 }; - short?[] shortArr = new short?[5] { short.MinValue + 1, -200, null, 100, short.MaxValue }; - int?[] intArr = new int?[5] { -200, -100, null, 0, 300 }; - long?[] longArr = new long?[5] { long.MinValue + 1, -2000, null, 1000, long.MaxValue }; - float?[] floatArr = new float?[5] { float.MinValue + 1, -12.1F, null, 0F, float.MaxValue }; - double?[] doubleArr = new double?[5] { double.MinValue + 1, -19.112D, null, 0D, double.MaxValue }; - byte?[] uTinyIntArr = new byte?[5] { byte.MinValue, 12, null, 89, byte.MaxValue - 1 }; - ushort?[] uShortArr = new ushort?[5] { ushort.MinValue, 200, null, 400, ushort.MaxValue - 1 }; - uint?[] uIntArr = new uint?[5] { uint.MinValue, 100, null, 2, uint.MaxValue - 1 }; - ulong?[] uLongArr = new ulong?[5] { ulong.MinValue, 2000, null, 1000, long.MaxValue - 1 }; - string[] binaryArr = new string[5] { "1234567890~!@#$%^&*()_+=-`[]{}:,./<>?", String.Empty, null, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890~!@#$%^&*()_+=-`[]{}:,./<>?" }; - string[] ncharArr = new string[5] { "1234567890~!@#$%^&*()_+=-`[]{}:,./<>?", null, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890~!@#$%^&*()_+=-`[]{}:,./<>?", string.Empty }; - mBinds[0] = TaosMultiBind.MultiBindTimestamp(tsArr); - mBinds[1] = TaosMultiBind.MultiBindBool(boolArr); - mBinds[2] = TaosMultiBind.MultiBindTinyInt(tinyIntArr); - mBinds[3] = TaosMultiBind.MultiBindSmallInt(shortArr); - mBinds[4] = TaosMultiBind.MultiBindInt(intArr); - mBinds[5] = TaosMultiBind.MultiBindBigint(longArr); - mBinds[6] = TaosMultiBind.MultiBindFloat(floatArr); - mBinds[7] = TaosMultiBind.MultiBindDouble(doubleArr); - mBinds[8] = TaosMultiBind.MultiBindUTinyInt(uTinyIntArr); - mBinds[9] = TaosMultiBind.MultiBindUSmallInt(uShortArr); - mBinds[10] = TaosMultiBind.MultiBindUInt(uIntArr); - mBinds[11] = TaosMultiBind.MultiBindUBigInt(uLongArr); - mBinds[12] = TaosMultiBind.MultiBindBinary(binaryArr); - mBinds[13] = TaosMultiBind.MultiBindNchar(ncharArr); - return mBinds; - } - - public void loadTableInfo(string[] arr) - { - if (TDengine.LoadTableInfo(this.conn, arr) == 0) - { - Console.WriteLine("load table info success"); - } - else - { - Console.WriteLine("load table info failed"); - ExitProgram(); - } - } - - public void InitTDengine() - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, this.configDir); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - TDengine.Init(); - Console.WriteLine("TDengine Initialization finished"); - } - - public void ConnectTDengine() - { - string db = ""; - this.conn = TDengine.Connect(this.host, this.user, this.passwd, db, this.port); - if (this.conn == IntPtr.Zero) - { - Console.WriteLine("Connect to TDengine failed"); - ExitProgram(); - } - else - { - Console.WriteLine("Connect to TDengine success"); - } - } - - public void ExecuteQuery(String sql) - { - IntPtr res = TDengine.Query(conn, sql); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - else - { - Console.WriteLine(sql.ToString() + " success"); - } - TDengine.FreeResult(res); - } - - public void StmtInit() - { - this.stmt = TDengine.StmtInit(conn); - if (this.stmt == IntPtr.Zero) - { - Console.WriteLine("Init stmt failed"); - ExitProgram(); - } - else - { - Console.WriteLine("Init stmt success"); - } - } - - public void StmtPrepare(string sql) - { - int res = TDengine.StmtPrepare(this.stmt, sql); - if (res == 0) - { - Console.WriteLine("stmt prepare success"); - } - else - { - Console.WriteLine("stmt prepare failed " + TDengine.StmtErrorStr(stmt)); - ExitProgram(); - } - } - - public void SetTableName(String tableName) - { - int res = TDengine.StmtSetTbname(this.stmt, tableName); - Console.WriteLine("setTableName():" + res); - if (res == 0) - { - Console.WriteLine("set_tbname success"); - } - else - { - Console.Write("set_tbname failed, " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - - public void SetTableNameTags(String tableName, TAOS_BIND[] tags) - { - int res = TDengine.StmtSetTbnameTags(this.stmt, tableName, tags); - if (res == 0) - { - Console.WriteLine("set tbname && tags success"); - - } - else - { - Console.Write("set tbname && tags failed, " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - - public void SetSubTableName(string name) - { - int res = TDengine.StmtSetSubTbname(this.stmt, name); - if (res == 0) - { - Console.WriteLine("set subtable name success"); - } - else - { - Console.Write("set subtable name failed, " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - - } - - public void BindParam(TAOS_BIND[] binds) - { - Console.WriteLine("in bindParam()"); - - int res = TDengine.StmtBindParam(this.stmt, binds); - if (res == 0) - { - Console.WriteLine("bind para success"); - } - else - { - Console.Write("bind para failed, " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - - public void BindSingleParamBatch(TAOS_MULTI_BIND bind, int index) - { - int res = TDengine.StmtBindSingleParamBatch(this.stmt,ref bind, index); - if (res == 0) - { - Console.WriteLine("single bind batch success"); - } - else - { - Console.Write("single bind batch failed: " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - - public void BindParamBatch(TAOS_MULTI_BIND[] bind) - { - int res = TDengine.StmtBindParamBatch(this.stmt, bind); - if (res == 0) - { - Console.WriteLine("bind parameter batch success"); - } - else - { - Console.WriteLine("bind parameter batch failed, " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - - public void AddBatch() - { - int res = TDengine.StmtAddBatch(this.stmt); - if (res == 0) - { - Console.WriteLine("stmt add batch success"); - } - else - { - Console.Write("stmt add batch failed,reason: " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - public void StmtExecute() - { - int res = TDengine.StmtExecute(this.stmt); - if (res == 0) - { - Console.WriteLine("Execute stmt success"); - } - else - { - Console.Write("Execute stmt failed,reason: " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - public void StmtClose() - { - int res = TDengine.StmtClose(this.stmt); - if (res == 0) - { - Console.WriteLine("close stmt success"); - } - else - { - Console.WriteLine("close stmt failed, " + TDengine.StmtErrorStr(stmt)); - StmtClose(); - ExitProgram(); - } - } - public void CloseConnection() - { - if (this.conn != IntPtr.Zero) - { - if (TDengine.Close(this.conn) == 0) - { - Console.WriteLine("close connection sucess"); - } - else - { - Console.WriteLine("close Connection failed"); - } - } - } - - //select only - public void StmtUseResult() - { - IntPtr res = TDengine.StmtUseResult(this.stmt); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - StmtClose(); - CloseConnection(); - ExitProgram(); - } - else - { - Console.WriteLine("{0},query success"); - DisplayRes(res); - TDengine.FreeResult(res); - } - - } - - public void DisplayRes(IntPtr res) - { - - long queryRows = 0; - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - if (res != IntPtr.Zero) - { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - ExitProgram(); - } - - int fieldCount = TDengine.FieldCount(res); - List metas = TDengine.FetchFields(res); - for (int j = 0; j < metas.Count; j++) - { - TDengineMeta meta = (TDengineMeta)metas[j]; - } - - IntPtr rowdata; - StringBuilder builder = new StringBuilder(); - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - builder.Append("---"); - - if (data == IntPtr.Zero) - { - builder.Append("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - builder.Append(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - byte v2 = Marshal.ReadByte(data); - builder.Append(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - builder.Append(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - builder.Append(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - builder.Append(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - builder.Append(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - builder.Append(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - string v8 = Marshal.PtrToStringAnsi(data); - builder.Append(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - builder.Append(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - string v10 = Marshal.PtrToStringAnsi(data); - builder.Append(v10); - break; - } - } - builder.Append("---"); - - if (queryRows <= 10) - { - Console.WriteLine(builder.ToString()); - } - builder.Clear(); - } - - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res)); - } - Console.WriteLine(""); - - } - public static void ExitProgram() - { - TDengine.Cleanup(); - System.Environment.Exit(0); - } - } -} diff --git a/tests/examples/C#/stmt/stmt.csproj b/tests/examples/C#/stmt/stmt.csproj deleted file mode 100644 index f0370cbf5684418edb026b56e306d7d7295a6638..0000000000000000000000000000000000000000 --- a/tests/examples/C#/stmt/stmt.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - Exe - net5.0 - - - diff --git a/tests/examples/C#/taosdemo/Dockerfile b/tests/examples/C#/taosdemo/Dockerfile deleted file mode 100644 index 4eefc6c75248b1e1e1d6daf305386cca5b11e606..0000000000000000000000000000000000000000 --- a/tests/examples/C#/taosdemo/Dockerfile +++ /dev/null @@ -1,24 +0,0 @@ -FROM tdengine/tdengine-beta:latest - -ENV DEBIAN_FRONTEND=noninteractive -ARG MIRROR=archive.ubuntu.com -RUN sed -Ei 's/\w+.ubuntu.com/'${MIRROR}'/' /etc/apt/sources.list && apt update && apt install mono-devel -y -RUN apt-get install wget -y \ - && wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb \ - && dpkg -i packages-microsoft-prod.deb \ - && rm packages-microsoft-prod.deb \ - && apt-get update && apt-get install -y dotnet-sdk-5.0 -COPY ./*.cs *.csproj /tmp/ -WORKDIR /tmp/ -RUN dotnet build -c Release && cp bin/Release/net5.0/taosdemo bin/Release/net5.0/taosdemo.* /usr/local/bin/ && rm -rf /tmp/* - -FROM tdengine/tdengine-beta:latest - -ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update && apt-get install wget -y \ - && wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb \ - && dpkg -i packages-microsoft-prod.deb \ - && rm packages-microsoft-prod.deb \ - && apt-get update && apt-get install -y dotnet-runtime-5.0 -COPY --from=0 /usr/local/bin/taosdemo* /usr/local/bin/ -CMD ["/usr/local/bin/taosdemo"] diff --git a/tests/examples/C#/taosdemo/README.md b/tests/examples/C#/taosdemo/README.md deleted file mode 100644 index 3cba3529bf513e2bf3d4ab0c169e7f3d03b2e6a8..0000000000000000000000000000000000000000 --- a/tests/examples/C#/taosdemo/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# C# Taosdemo - -## For Mono - -install build environment - -```sh -yum/apt install mono-complete -``` - -build C# version taosdemo. - -```sh -mcs -out:taosdemo *.cs -./taosdemo --help -``` - -## For DotNet - -install dotnet environment. - -```sh -wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb \ - && dpkg -i packages-microsoft-prod.deb \ - && rm packages-microsoft-prod.deb \ - && apt-get update && apt-get install -y dotnet-sdk-5.0 -``` - -Build DotNet version taosdemo. - -```sh -dotnet build -c Release -./bin/Release/net5.0/taosdemo --help -``` - -## Usage - -``` -Usage: mono taosdemo.exe [OPTION...] - - --help Show usage. - - -h host, The host to connect to TDengine. Default is localhost. - -p port, The TCP/IP port number to use for the connection. Default is 0. - -u user, The user name to use when connecting to the server. Default is 'root'. - -P password, The password to use when connecting to the server. Default is 'taosdata'. - -d database, Destination database. Default is 'test'. - -a replica, Set the replica parameters of the database, Default 1, min: 1, max: 5. - -m table_prefix, Table prefix name. Default is 't'. - -M stable, Use super table. - -s stable_prefix, STable prefix name. Default is 'st' - -Q query, Execute query command. set 'DEFAULT' means select * from each table - -T num_of_threads, The number of threads. Default is 10. - -r num_of_records_per_req, The number of records per request. Default is 1000. - -t num_of_tables, The number of tables. Default is 1. - -n num_of_records_per_table, The number of records per table. Default is 1. - -c config_directory, Configuration directory. Default is '/etc/taos/'. - -x flag, Insert only flag. - -O order, Insert mode--0: In order, 1: Out of order. Default is in order. - -R rate, Out of order data's rate--if order=1 Default 10, min: 0, max: 50. - -D Delete data methods 0: don't delete, 1: delete by table, 2: delete by stable, 3: delete by database. - -v Print verbose output - -g Print debug output - -y Skip read key for continous test, default is not skip -``` diff --git a/tests/examples/C#/taosdemo/taosdemo.cs b/tests/examples/C#/taosdemo/taosdemo.cs deleted file mode 100644 index e62a502d1508c1339e559160b50da39e622a021f..0000000000000000000000000000000000000000 --- a/tests/examples/C#/taosdemo/taosdemo.cs +++ /dev/null @@ -1,908 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -using System; -using System.Text; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Collections; -using System.Threading; -using System.Diagnostics; - -namespace TDengineDriver -{ - class TDengineTest - { - //connect parameters - private string host = "127.0.0.1"; - private string configDir = "C:/TDengine/cfg"; - private string user = "root"; - private string password = "taosdata"; - private short port = 0; - - //sql parameters - private string dbName = "db"; - private string stablePrefix = "st"; - private string tablePrefix = "t"; - - private bool isInsertOnly = false; - private string query = "NONE"; - private short queryMode = 1; - - private long recordsPerTable = 1; - private int recordsPerRequest = 1; - private int colsPerRecord = 3; - private long batchRows = 1000; - private long numOfTables = 1; - private short replica = 1; - - private IntPtr conn = IntPtr.Zero; - // private long rowsInserted = 0; - private bool useStable = false; - private short methodOfDelete = 0; - private long numOfThreads = 1; - private short rateOfOutorder = 10; - private bool order = true; - private bool skipReadKey = false; - private bool verbose = false; - private bool debug = false; - - - static void HelpPrint(string arg, string desc) - { - string indent = " "; - Console.WriteLine("{0}{1}", indent, arg.PadRight(25) + desc); - } - - static void PrintHelp(String[] argv) - { - for (int i = 0; i < argv.Length; ++i) - { - if ("--help" == argv[i]) - { - Console.WriteLine("Usage: mono taosdemo.exe [OPTION...]"); - Console.WriteLine(""); - HelpPrint("--help", "Show usage."); - Console.WriteLine(""); - - HelpPrint("-h ", "host, The host to connect to TDengine. Default is localhost."); - HelpPrint("-p ", "port, The TCP/IP port number to use for the connection. Default is 0."); - HelpPrint("-u ", "user, The user name to use when connecting to the server. Default is 'root'."); - HelpPrint("-P ", "password, The password to use when connecting to the server. Default is 'taosdata'."); - HelpPrint("-d ", "database, Destination database. Default is 'test'."); - HelpPrint("-a ", "replica, Set the replica parameters of the database, Default 1, min: 1, max: 5."); - HelpPrint("-m
", "table_prefix, Table prefix name. Default is 't'."); - HelpPrint("-M", "stable, Use super table."); - HelpPrint("-s ", "stable_prefix, STable prefix name. Default is 'st'"); - HelpPrint("-Q ", "query, Execute query command. set 'DEFAULT' means select * from each table"); - /* NOT SUPPORT SO FAR - HelpPrint("-o", "outputfile, Direct output to the named file. Default is './output.txt'."); - HelpPrint("-q", "query_mode, Query mode--0: SYNC, 1: ASYNC. Default is SYNC."); - HelpPrint("-b", "type_of_cols, data_type of columns: 'INT', 'TINYINT', 'SMALLINT', 'BIGINT', 'FLOAT', 'DOUBLE', 'BINARY'. Default is 'INT'."); - HelpPrint("-w", "length_of_binary, The length of data_type 'BINARY'. Only applicable when type of cols is 'BINARY'. Default is 8"); - HelpPrint("-l", "num_of_cols_per_record, The number of columns per record. Default is 3."); - */ - HelpPrint("-T ", "num_of_threads, The number of threads. Default is 10."); - HelpPrint("-r ", "num_of_records_per_req, The number of records per request. Default is 1000."); - HelpPrint("-t ", "num_of_tables, The number of tables. Default is 1."); - HelpPrint("-n ", "num_of_records_per_table, The number of records per table. Default is 1."); - HelpPrint("-c ", "config_directory, Configuration directory. Default is '/etc/taos/'."); - HelpPrint("-x", "flag, Insert only flag."); - HelpPrint("-O", "order, Insert mode--0: In order, 1: Out of order. Default is in order."); - HelpPrint("-R ", "rate, Out of order data's rate--if order=1 Default 10, min: 0, max: 50."); - HelpPrint("-D ", "Delete data methods 0: don't delete, 1: delete by table, 2: delete by stable, 3: delete by database."); - HelpPrint("-v", "Print verbose output"); - HelpPrint("-g", "Print debug output"); - HelpPrint("-y", "Skip read key for continous test, default is not skip"); - - System.Environment.Exit(0); - } - } - } - - public void ReadArgument(String[] argv) - { - host = this.GetArgumentAsString(argv, "-h", "127.0.0.1"); - port = (short)this.GetArgumentAsLong(argv, "-p", 0, 65535, 6030); - user = this.GetArgumentAsString(argv, "-u", "root"); - password = this.GetArgumentAsString(argv, "-P", "taosdata"); - dbName = this.GetArgumentAsString(argv, "-d", "taosdemo_cs"); - stablePrefix = this.GetArgumentAsString(argv, "-s", "st"); - tablePrefix = this.GetArgumentAsString(argv, "-m", "t"); - isInsertOnly = this.GetArgumentAsFlag(argv, "-x", true); - query = this.GetArgumentAsString(argv, "-Q", "NONE"); - queryMode = (short)this.GetArgumentAsLong(argv, "-q", 0, 1, 0); - numOfTables = this.GetArgumentAsLong(argv, "-t", 1, 1000000000, 1); - batchRows = this.GetArgumentAsLong(argv, "-r", 1, 10000, 1000); - recordsPerTable = this.GetArgumentAsLong(argv, "-n", 1, 100000000000, 1); - recordsPerRequest = (int)this.GetArgumentAsLong(argv, "-r", 1, 10000, 1); - colsPerRecord = (int)this.GetArgumentAsLong(argv, "-l", 1, 1024, 3); - configDir = this.GetArgumentAsString(argv, "-c", "C:/TDengine/cfg"); - useStable = this.GetArgumentAsFlag(argv, "-M", true); - - replica = (short)this.GetArgumentAsLong(argv, "-a", 1, 5, 1); - methodOfDelete = (short)this.GetArgumentAsLong(argv, "-D", 0, 3, 0); - numOfThreads = (short)this.GetArgumentAsLong(argv, "-T", 1, 10000, 1); - order = this.GetArgumentAsFlag(argv, "-O", false); - rateOfOutorder = (short)this.GetArgumentAsLong(argv, "-R", 0, 50, 10); - - skipReadKey = this.GetArgumentAsFlag(argv, "-y", true); - verbose = this.GetArgumentAsFlag(argv, "-v", true); - debug = this.GetArgumentAsFlag(argv, "-g", true); - - VerbosePrint("###################################################################\n"); - VerbosePrintFormat("# Server IP: {0}\n", host); - VerbosePrintFormat("# User: {0}\n", user); - VerbosePrintFormat("# Password: {0}\n", password); - VerbosePrintFormat("# Number of Columns per record: {0}\n", colsPerRecord); - VerbosePrintFormat("# Number of Threads: {0}\n", numOfThreads); - VerbosePrintFormat("# Number of Tables: {0}\n", numOfTables); - VerbosePrintFormat("# Number of records per Table: {0}\n", recordsPerTable); - VerbosePrintFormat("# Records/Request: {0}\n", recordsPerRequest); - VerbosePrintFormat("# Database name: {0}\n", dbName); - VerbosePrintFormat("# Replica: {0}\n", replica); - VerbosePrintFormat("# Use STable: {0}\n", useStable); - VerbosePrintFormat("# Table prefix: {0}\n", tablePrefix); - if (useStable == true) - { - VerbosePrintFormat("# STable prefix: {0}\n", stablePrefix); - } - VerbosePrintFormat("# Data order: {0}\n", order); - VerbosePrintFormat("# Data out of order rate: {0}\n", rateOfOutorder); - VerbosePrintFormat("# Delete method: {0}\n", methodOfDelete); - VerbosePrintFormat("# Query command: {0}\n", query); - VerbosePrintFormat("# Query Mode: {0}\n", queryMode); - VerbosePrintFormat("# Insert Only: {0}\n", isInsertOnly); - VerbosePrintFormat("# Verbose output {0}\n", verbose); - VerbosePrintFormat("# Test time: {0}\n", DateTime.Now.ToString("h:mm:ss tt")); - - VerbosePrint("###################################################################\n"); - - if (skipReadKey == false) - { - Console.Write("Press any key to continue..\n"); - Console.ReadKey(); - } - } - - public bool GetArgumentAsFlag(String[] argv, String argName, bool defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName == argv[i]) - { - return defaultValue; - } - } - return !defaultValue; - } - - public long GetArgumentAsLong(String[] argv, String argName, int minVal, long maxVal, int defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName != argv[i]) - { - continue; - } - if (i < argc - 1) - { - String tmp = argv[i + 1]; - if (tmp[0] == '-') - { - Console.WriteLine("option {0:G} requires an argument", argName); - ExitProgram(1); - } - - long tmpVal = Convert.ToInt64(tmp); - if (tmpVal < minVal || tmpVal > maxVal) - { - Console.WriteLine("option {0:G} value should in range [{1:G}, {2:G}]", argName, minVal, maxVal); - ExitProgram(1); - } - - return tmpVal; - } - } - - return defaultValue; - } - - public String GetArgumentAsString(String[] argv, String argName, String defaultValue) - { - int argc = argv.Length; - for (int i = 0; i < argc; ++i) - { - if (argName != argv[i]) - { - continue; - } - if (i < argc - 1) - { - String tmp = argv[i + 1]; - if (tmp[0] == '-') - { - Console.WriteLine("option {0:G} requires an argument", argName); - ExitProgram(1); - } - return tmp; - } - } - - return defaultValue; - } - - static void CleanAndExitProgram(int ret) - { - TDengine.Cleanup(); - System.Environment.Exit(ret); - } - - static void ExitProgram(int ret) - { - System.Environment.Exit(ret); - } - - private void VerbosePrintFormat(string format, params object[] parameters) - { - if (verbose == true) - { - Console.Write(format, parameters); - } - } - - private void VerbosePrint(string str) - { - if (verbose == true) - { - Console.Write(str); - } - } - - private void DebugPrintFormat(string format, params object[] parameters) - { - if (debug == true) - { - Console.Write(format, parameters); - } - } - - private void DebugPrint(string str) - { - if (debug == true) - { - Console.Write(str); - } - } - - public void InitTDengine() - { - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, this.configDir); - TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60"); - TDengine.Init(); - VerbosePrint("TDengine Initialization finished\n"); - } - - public void ConnectTDengine() - { - string db = ""; - VerbosePrintFormat("host:{0} user:{1}, pass:{2}; db:{3}, port:{4}\n", - this.host, this.user, this.password, db, this.port); - this.conn = TDengine.Connect(this.host, this.user, this.password, db, this.port); - if (this.conn == IntPtr.Zero) - { - Console.WriteLine("Connect to TDengine failed"); - CleanAndExitProgram(1); - } - else - { - VerbosePrint("Connect to TDengine success\n"); - } - } - - public void CreateTablesByThreads() - { - Thread[] threadArr = new Thread[numOfThreads]; - - long quotition = numOfTables / numOfThreads; - if (quotition < 1) - { - numOfThreads = numOfTables; - quotition = 1; - } - - long remainder = 0; - if (numOfThreads != 0) - { - remainder = numOfTables % numOfThreads; - } - - long last = 0; - - for (int i = 0; i < numOfThreads; i++) - { - CreateTableThread createTableThread = new CreateTableThread(); - createTableThread.id = i; - createTableThread.verbose = verbose; - createTableThread.debug = debug; - createTableThread.dbName = this.dbName; - createTableThread.tablePrefix = this.tablePrefix; - createTableThread.useStable = useStable; - if (useStable) - { - createTableThread.stablePrefix = stablePrefix; - } - createTableThread.conn = conn; - - createTableThread.start = last; - if (i < remainder) - { - createTableThread.end = last + quotition; - } - else - { - createTableThread.end = last + quotition - 1; - } - last = createTableThread.end + 1; - - threadArr[i] = new Thread(createTableThread.ThreadMain); - threadArr[i].Start(); - } - for (int j = 0; j < numOfThreads; j++) - { - threadArr[j].Join(); - } - } - - public void dropDatabase() - { - StringBuilder sql = new StringBuilder(); - sql.Append("DROP DATABASE IF EXISTS ").Append(this.dbName); - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - CleanAndExitProgram(1); - } - else - { - VerbosePrint(sql.ToString() + " success\n"); - } - } - - public void CreateDb() - { - StringBuilder sql = new StringBuilder(); - sql.Append("CREATE DATABASE IF NOT EXISTS ").Append(this.dbName).Append(" replica ").Append(this.replica).Append(" keep 36500"); - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - CleanAndExitProgram(1); - } - else - { - VerbosePrint(sql.ToString() + " success\n"); - } - TDengine.FreeResult(res); - } - - public void CreateStable() - { - StringBuilder sql = new StringBuilder(); - - sql.Clear(); - sql.Append("CREATE TABLE IF NOT EXISTS "). - Append(this.dbName).Append(".").Append(this.stablePrefix). - Append("(ts timestamp, v1 bool, v2 tinyint, v3 smallint, v4 int, v5 bigint, v6 float, v7 double, v8 binary(10), v9 nchar(10), v10 tinyint unsigned, v11 smallint unsigned, v12 int unsigned, v13 bigint unsigned) tags(t1 int)"); - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - CleanAndExitProgram(1); - } - else - { - VerbosePrint(sql.ToString() + " success\n"); - } - TDengine.FreeResult(res); - } - - public void InsertByThreads() - { - Thread[] threadArr = new Thread[numOfThreads]; - - long quotition = numOfTables / numOfThreads; - if (quotition < 1) - { - numOfThreads = numOfTables; - quotition = 1; - } - - long remainder = 0; - if (numOfThreads != 0) - { - remainder = numOfTables % numOfThreads; - } - - long last = 0; - - for (int i = 0; i < numOfThreads; i++) - { - InsertDataThread insertThread = new InsertDataThread(); - insertThread.id = i; - insertThread.recordsPerTable = recordsPerTable; - insertThread.batchRows = batchRows; - insertThread.numOfTables = numOfTables; - insertThread.verbose = verbose; - insertThread.debug = debug; - insertThread.dbName = this.dbName; - insertThread.tablePrefix = this.tablePrefix; - insertThread.order = this.order; - insertThread.rateOfOutorder = this.rateOfOutorder; - if (useStable) - { - insertThread.stablePrefix = stablePrefix; - } - insertThread.conn = conn; - - insertThread.start = last; - if (i < remainder) - { - insertThread.end = last + quotition; - } - else - { - insertThread.end = last + quotition - 1; - } - last = insertThread.end + 1; - - threadArr[i] = new Thread(insertThread.ThreadMain); - threadArr[i].Start(); - } - for (int j = 0; j < numOfThreads; j++) - { - threadArr[j].Join(); - } - } - - public void ExecuteQuery() - { - long queryRows = 0; - - for (int i = 0; i < this.numOfTables; ++i) - { - string sql; - - if (query == "DEFAULT") - { - sql = "select * from " + this.dbName + "." + tablePrefix + i; - } - else - { - sql = query; - } - DebugPrintFormat("query: {0}, sql:{1}\n", query, sql); - - IntPtr res = TDengine.Query(conn, sql); - DebugPrintFormat("res: {0}\n", res); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - CleanAndExitProgram(1); - } - - int fieldCount = TDengine.FieldCount(res); - DebugPrint("field count: " + fieldCount + "\n"); - - List metas = TDengine.FetchFields(res); - for (int j = 0; j < metas.Count; j++) - { - TDengineMeta meta = (TDengineMeta)metas[j]; - DebugPrint("index:" + j + ", type:" + meta.type + ", typename:" + meta.TypeName() + ", name:" + meta.name + ", size:" + meta.size + "\n"); - } - - IntPtr rowdata; - StringBuilder builder = new StringBuilder(); - - while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero) - { - queryRows++; - for (int fields = 0; fields < fieldCount; ++fields) - { - TDengineMeta meta = metas[fields]; - int offset = IntPtr.Size * fields; - IntPtr data = Marshal.ReadIntPtr(rowdata, offset); - - builder.Append(" | "); - - if (data == IntPtr.Zero) - { - builder.Append("NULL"); - continue; - } - - switch ((TDengineDataType)meta.type) - { - case TDengineDataType.TSDB_DATA_TYPE_BOOL: - bool v1 = Marshal.ReadByte(data) == 0 ? false : true; - builder.Append(v1); - break; - case TDengineDataType.TSDB_DATA_TYPE_TINYINT: - sbyte v2 = (sbyte)Marshal.ReadByte(data); - builder.Append(v2); - break; - case TDengineDataType.TSDB_DATA_TYPE_SMALLINT: - short v3 = Marshal.ReadInt16(data); - builder.Append(v3); - break; - case TDengineDataType.TSDB_DATA_TYPE_INT: - int v4 = Marshal.ReadInt32(data); - builder.Append(v4); - break; - case TDengineDataType.TSDB_DATA_TYPE_BIGINT: - long v5 = Marshal.ReadInt64(data); - builder.Append(v5); - break; - case TDengineDataType.TSDB_DATA_TYPE_FLOAT: - float v6 = (float)Marshal.PtrToStructure(data, typeof(float)); - builder.Append(v6); - break; - case TDengineDataType.TSDB_DATA_TYPE_DOUBLE: - double v7 = (double)Marshal.PtrToStructure(data, typeof(double)); - builder.Append(v7); - break; - case TDengineDataType.TSDB_DATA_TYPE_BINARY: - string v8 = Marshal.PtrToStringAnsi(data); - builder.Append(v8); - break; - case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP: - long v9 = Marshal.ReadInt64(data); - builder.Append(v9); - break; - case TDengineDataType.TSDB_DATA_TYPE_NCHAR: - string v10 = Marshal.PtrToStringAnsi(data); - builder.Append(v10); - break; - case TDengineDataType.TSDB_DATA_TYPE_UTINYINT: - byte v11 = Marshal.ReadByte(data); - builder.Append(v11); - break; - case TDengineDataType.TSDB_DATA_TYPE_USMALLINT: - ushort v12 = (ushort)Marshal.ReadInt16(data); - builder.Append(v12); - break; - case TDengineDataType.TSDB_DATA_TYPE_UINT: - uint v13 = (uint)Marshal.ReadInt32(data); - builder.Append(v13); - break; - case TDengineDataType.TSDB_DATA_TYPE_UBIGINT: - ulong v14 = (ulong)Marshal.ReadInt64(data); - builder.Append(v14); - break; - } - } - builder.Append(" | "); - - VerbosePrint(builder.ToString() + "\n"); - builder.Clear(); - } - - if (TDengine.ErrorNo(res) != 0) - { - Console.Write("Query is not complete, Error {0:G}", - TDengine.ErrorNo(res), TDengine.Error(res)); - } - - TDengine.FreeResult(res); - } - } - - public void CloseConnection() - { - if (this.conn != IntPtr.Zero) - { - TDengine.Close(this.conn); - } - } - - // Main entry - static void Main(string[] args) - { - PrintHelp(args); - - TDengineTest tester = new TDengineTest(); - tester.ReadArgument(args); - - tester.InitTDengine(); - tester.ConnectTDengine(); - - if (tester.isInsertOnly == false) - { - tester.dropDatabase(); - tester.CreateDb(); - - - if (tester.useStable == true) - { - tester.CreateStable(); - } - - tester.CreateTablesByThreads(); - } - - Stopwatch watch = Stopwatch.StartNew(); - tester.InsertByThreads(); - watch.Stop(); - double elapsedMs = watch.Elapsed.TotalMilliseconds; - - Console.WriteLine("C# taosdemo: Spent {0} seconds to insert {1} records with {2} record(s) per request: {3} records/second", - elapsedMs / 1000, - tester.recordsPerTable * tester.numOfTables, - tester.batchRows, - (tester.recordsPerTable * tester.numOfTables * 1000) / elapsedMs); - - tester.DebugPrintFormat("query command:{0}\n", tester.query); - if (tester.query != "NONE") - { - watch = Stopwatch.StartNew(); - tester.ExecuteQuery(); - watch.Stop(); - elapsedMs = watch.Elapsed.TotalMilliseconds; - Console.WriteLine("C# taosdemo: Spent {0} seconds to query {1} records.\n", - elapsedMs / 1000, - tester.recordsPerTable * tester.numOfTables - ); - } - tester.CloseConnection(); - - Console.WriteLine("End."); - CleanAndExitProgram(0); - } - - public class InsertDataThread - { - public long id { set; get; } - public long start { set; get; } - public long end { set; get; } - public string dbName { set; get; } - public IntPtr conn { set; get; } - public string tablePrefix { set; get; } - public string stablePrefix { set; get; } - public long recordsPerTable { set; get; } - public long batchRows { set; get; } - public long numOfTables { set; get; } - public bool verbose { set; get; } - public bool debug { set; get; } - public bool order { set; get; } - public short rateOfOutorder { set; get; } - - private void VerbosePrintFormat(string format, params object[] parameters) - { - if (verbose == true) - { - Console.Write(format, parameters); - } - } - - private void VerbosePrint(string str) - { - if (verbose == true) - { - Console.Write(str); - } - } - - private void DebugPrintFormat(string format, params object[] parameters) - { - if (debug == true) - { - Console.Write(format, parameters); - } - } - - private void DebugPrint(string str) - { - if (debug == true) - { - Console.Write(str); - } - } - - public void ThreadMain() - { - VerbosePrintFormat("InsertDataThread {0} from {1} to {2}\n", id, start, end); - StringBuilder sql = new StringBuilder(); - - DateTime now = DateTime.Now; - int h = now.Hour; - int m = now.Minute; - int s = now.Second; - - long baseTimestamp = -16094340000; // 1969-06-29 01:21:00 - VerbosePrintFormat("beginTime is {0} + {1}h:{2}m:{3}s\n", baseTimestamp, h, m, s); - long beginTimestamp = baseTimestamp + ((h * 60 + m) * 60 + s) * 1000; - Random random = new Random(); - - long rowsInserted = 0; - - long i = 0; - while (i < recordsPerTable) - { - for (long table = start; table <= end; ++table) - { - long inserted = i; - - sql.Clear(); - sql.Append("INSERT INTO "). - Append(this.dbName).Append(".").Append(this.tablePrefix).Append(table). - Append(" VALUES"); - if (recordsPerTable < batchRows) - { - batchRows = recordsPerTable; - } - for (int batch = 0; batch < batchRows; ++batch) - { - long writeTimeStamp = beginTimestamp + i + batch; - int rnd = 100; - if (this.order == false) - { - rnd = random.Next(1, 100); - if (rnd <= this.rateOfOutorder) - { - writeTimeStamp = writeTimeStamp + rnd * 10000; - DebugPrint("### "); - } - DebugPrintFormat("order:{0} rnd:{1} timestamp:{2}\n", this.order, rnd, writeTimeStamp); - } - else - { - DebugPrintFormat("order:{0} timestamp:{1}\n", this.order, writeTimeStamp); - } - - sql.Append("(") - .Append(writeTimeStamp) - .Append(", 1, -2, -3,") - .Append(i + batch - 127) - .Append(", -5, -6, -7, 'abc', 'def', 254, 65534,") - .Append(4294967294 - (uint)i - (uint)batch) - .Append(",") - .Append(18446744073709551614 - (ulong)i - (ulong)batch) - .Append(")"); - - } - VerbosePrint(sql.ToString() + "\n"); - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - } - - inserted += this.batchRows; - - int affectRows = TDengine.AffectRows(res); - rowsInserted += affectRows; - - TDengine.FreeResult(res); - if (table == end) - { - i = inserted; - } - } - } - - } - } - - public class CreateTableThread - { - public long id { set; get; } - public long start { set; get; } - public long end { set; get; } - public string dbName { set; get; } - public IntPtr conn { set; get; } - public string tablePrefix { set; get; } - public string stablePrefix { set; get; } - public bool verbose { set; get; } - public bool debug { set; get; } - public bool useStable { set; get; } - - private void VerbosePrintFormat(string format, params object[] parameters) - { - if (verbose == true) - { - Console.Write(format, parameters); - } - } - - private void VerbosePrint(string str) - { - if (verbose == true) - { - Console.Write(str); - } - } - - private void DebugPrintFormat(string format, params object[] parameters) - { - if (debug == true) - { - Console.Write(format, parameters); - } - } - - public void ThreadMain() - { - VerbosePrintFormat("CreateTable {0} from {1} to {2}\n", id, start, end); - - StringBuilder sql = new StringBuilder(); - - for (long tableId = start; tableId <= end; tableId++) - { - sql.Clear(); - sql = sql.Append("CREATE TABLE IF NOT EXISTS "). - Append(this.dbName).Append(".").Append(this.tablePrefix).Append(tableId); - if (useStable == true) - { - sql = sql.Append(" USING ").Append(this.dbName).Append(".").Append(this.stablePrefix). - Append(" TAGS(").Append(tableId).Append(")"); - } - else - { - sql = sql.Append("(ts timestamp, v1 bool, v2 tinyint, v3 smallint, v4 int, v5 bigint, v6 float, v7 double, v8 binary(10), v9 nchar(10), v10 tinyint unsigned, v11 smallint unsigned, v12 int unsigned, v13 bigint unsigned)"); - } - IntPtr res = TDengine.Query(this.conn, sql.ToString()); - if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0)) - { - Console.Write(sql.ToString() + " failure, "); - if (res != IntPtr.Zero) { - Console.Write("reason: " + TDengine.Error(res)); - } - Console.WriteLine(""); - CleanAndExitProgram(1); - } - else - { - VerbosePrint(sql.ToString() + " success\n"); - } - TDengine.FreeResult(res); - } - - } - } - } -} diff --git a/tests/examples/C#/taosdemo/taosdemo.csproj b/tests/examples/C#/taosdemo/taosdemo.csproj deleted file mode 100644 index 8d4b786ba3a99b600783a5b4ee55d99f03e47655..0000000000000000000000000000000000000000 --- a/tests/examples/C#/taosdemo/taosdemo.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - Exe - net5.0 - false - - - - - - - diff --git a/tests/examples/JDBC/JDBCDemo/.gitignore b/tests/examples/JDBC/JDBCDemo/.gitignore deleted file mode 100644 index b79f223d17fd22185243066700aede395f6328fd..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -# custom -/out/ -/logs/ -*.jar - -# Created by .ignore support plugin (hsz.mobi) -.gitignore - -# Build Artifacts -.gradle/* -build/* -target/* -bin/* -dependency-reduced-pom.xml - -# Eclipse Project Files -.classpath -.project -.settings/* diff --git a/tests/examples/JDBC/JDBCDemo/README-jdbc-windows.md b/tests/examples/JDBC/JDBCDemo/README-jdbc-windows.md deleted file mode 100644 index 17c5c8df00ab8727d1adfe493d3fbbd32891a676..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/README-jdbc-windows.md +++ /dev/null @@ -1,268 +0,0 @@ -# 如何在 windows环境下使用jdbc进行TDengine应用开发 - -本文以windows环境为例,介绍java如何进行TDengine开发应用 - -## 环境准备 - -(1)安装jdk - -官网下载jdk-1.8,下载页面:https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html - -安装,配置环境变量,把jdk加入到环境变量里。 - -命令行内查看java的版本。 - -```shell ->java -version -java version "1.8.0_131" -Java(TM) SE Runtime Environment (build 1.8.0_131-b11) -Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode) -``` - - -(2)安装配置maven - -官网下载maven,下载地址:http://maven.apache.org/download.cgi - -配置环境变量MAVEN_HOME,将MAVEN_HOME/bin添加到PATH - -命令行里查看maven的版本 - -```shell ->mvn --version -Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T03:39:06+08:00) -Maven home: D:\apache-maven-3.5.0\bin\.. -Java version: 1.8.0_131, vendor: Oracle Corporation -Java home: C:\Program Files\Java\jdk1.8.0_131\jre -Default locale: zh_CN, platform encoding: GBK -OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" -``` - -为了加快maven下载依赖的速度,可以为maven配置mirror,修改MAVEN_HOME\config\settings.xml文件 - -```xml - - - D:\apache-maven-localRepository - - - - - alimaven - aliyun maven - http://maven.aliyun.com/nexus/content/groups/public/ - central - - - - - - - jdk-1.8 - - true - 1.8 - - - 1.8 - 1.8 - 1.8 - - - - -``` - - - -(3)在linux服务器上安装TDengine-server - -在taosdata官网下载TDengine-server,下载地址:https://www.taosdata.com/cn/all-downloads/ - -在linux服务器上安装TDengine-server - -```shell -# tar -zxvf package/TDengine-server-2.0.1.1-Linux-x64.tar.gz -# cd TDengine-server/ -# ./install.sh -``` - -启动taosd - -```shell -# systemctl start taosd -``` - -在server上用taos连接taosd - -```shell -# taos -taos> show dnodes; - id | end_point | vnodes | cores | status | role | create_time | -================================================================================================================== - 1 | td01:6030 | 2 | 4 | ready | any | 2020-08-19 18:40:25.045 | -Query OK, 1 row(s) in set (0.005765s) -``` - -如果可以正确连接到taosd实例,并打印出databases的信息,说明TDengine的server已经正确启动。这里查看server的hostname - -```shell -# hostname -f -td01 -``` - -注意,如果安装TDengine后,使用默认的taos.cfg配置文件,taosd会使用当前server的hostname创建dnode实例。之后,在client也需要使用这个hostname来连接taosd。 - - - -(4)在windows上安装TDengine-client - -在taosdata官网下载taos客户端,下载地址: -https://www.taosdata.com/cn/all-downloads/ -下载后,双击exe安装。 - -修改client的hosts文件(C:\Windows\System32\drivers\etc\hosts),将server的hostname和ip配置到client的hosts文件中 - -``` -192.168.236.136 td01 -``` - -配置完成后,在命令行内使用taos shell连接server端 - -```shell -C:\TDengine>taos -h td01 -Welcome to the TDengine shell from Linux, Client Version:2.0.1.1 -Copyright (c) 2017 by TAOS Data, Inc. All rights reserved. - -taos> show databases; - name | created_time | ntables | vgroups | replica | quorum | days | keep0,keep1,keep(D) | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | precision | status | -=================================================================================================================================================================================================================================================================== - test | 2020-08-19 18:43:50.731 | 1 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready | - log | 2020-08-19 18:40:28.064 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready | -Query OK, 2 row(s) in set (0.068000s) -``` - -如果windows上的client能够正常连接,并打印database信息,说明client可以正常连接server了。 - - - -## 应用开发 - -(1)新建maven工程,在pom.xml中引入taos-jdbcdriver依赖。 - -```xml - - - 4.0.0 - - com.taosdata.demo - JdbcDemo - 1.0-SNAPSHOT - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.8 - - - -``` - -(2)使用jdbc查询TDengine数据库 - -下面是示例代码: - -```java -public class JdbcDemo { - - public static void main(String[] args) throws Exception { - Connection conn = getConn(); - Statement stmt = conn.createStatement(); - // create database - stmt.executeUpdate("create database if not exists db"); - // use database - stmt.executeUpdate("use db"); - // create table - stmt.executeUpdate("create table if not exists tb (ts timestamp, temperature int, humidity float)"); - // insert data - int affectedRows = stmt.executeUpdate("insert into tb values(now, 23, 10.3) (now + 1s, 20, 9.3)"); - System.out.println("insert " + affectedRows + " rows."); - // query data - ResultSet resultSet = stmt.executeQuery("select * from tb"); - Timestamp ts = null; - int temperature = 0; - float humidity = 0; - while(resultSet.next()){ - ts = resultSet.getTimestamp(1); - temperature = resultSet.getInt(2); - humidity = resultSet.getFloat("humidity"); - System.out.printf("%s, %d, %s\n", ts, temperature, humidity); - } - } - - public static Connection getConn() throws Exception{ - Class.forName("com.taosdata.jdbc.TSDBDriver"); - String jdbcUrl = "jdbc:TAOS://td01:0/log?user=root&password=taosdata"; - Properties connProps = new Properties(); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - Connection conn = DriverManager.getConnection(jdbcUrl, connProps); - return conn; - } - -} -``` - -(3)测试jdbc访问tdengine的sever实例 - -console输出: - -``` -insert 2 rows. -2020-08-26 00:06:34.575, 23, 10.3 -2020-08-26 00:06:35.575, 20, 9.3 -``` - - - -## 指南 - -(1)如何设置主机名和hosts - -在server上查看hostname和fqdn -```shell -查看hostname -# hostname -taos-server - -查看fqdn -# hostname -f -taos-server -``` - -windows下hosts文件位于: -C:\\Windows\System32\drivers\etc\hosts -修改hosts文件,添加server的ip和hostname - -```s -192.168.56.101 node5 -``` - -(2)什么是fqdn? - - -> 什么是FQDN? -> -> FQDN(Full qualified domain name)全限定域名,fqdn由2部分组成:hostname+domainname。 -> -> 例如,一个邮件服务器的fqdn可能是:mymail.somecollege.edu,其中mymail是hostname(主机名),somcollege.edu是domainname(域名)。本例中,.edu是顶级域名,.somecollege是二级域名。 -> -> 当连接服务器时,必须指定fqdn,然后,dns服务器通过查看dns表,将hostname解析为相应的ip地址。如果只指定hostname(不指定domainname),应用程序可能服务解析主机名。因为如果你试图访问不在本地的远程服务器时,本地的dns服务器和可能没有远程服务器的hostname列表。 -> -> 参考:https://kb.iu.edu/d/aiuv diff --git a/tests/examples/JDBC/JDBCDemo/pom.xml b/tests/examples/JDBC/JDBCDemo/pom.xml deleted file mode 100644 index b0b07d58f4e59645e5ebe78a938d0043558a9c80..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - - com.taosdata.jdbc - JDBCDemo - SNAPSHOT - jar - - - src/main/resources/assembly - - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.36 - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.3.0 - - - - JdbcDemo - - JdbcDemo - - - com.taosdata.example.JdbcDemo - - - - jar-with-dependencies - - - package - - single - - - - - JdbcRestfulDemo - - JdbcRestfulDemo - - - com.taosdata.example.JdbcRestfulDemo - - - - jar-with-dependencies - - - package - - single - - - - - SubscribeDemo - - SubscribeDemo - - - com.taosdata.example.SubscribeDemo - - - - jar-with-dependencies - - - package - - single - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - UTF-8 - - - - - - - diff --git a/tests/examples/JDBC/JDBCDemo/readme.md b/tests/examples/JDBC/JDBCDemo/readme.md deleted file mode 100644 index da638a0bcc485cb3d73f75b59348ec260cc871d2..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/readme.md +++ /dev/null @@ -1,37 +0,0 @@ -# How to Run the JDBC Demo Code On Linux OS -TDengine's JDBC demo project is organized in a Maven way so that users can easily compile, package and run the project. If you don't have Maven on your server, you may install it using -``` -sudo apt-get install maven -``` - -## Install TDengine Client -Make sure you have already installed a tdengine client on your current develop environment. -Download the tdengine package on our website: ``https://www.taosdata.com/cn/all-downloads/`` and install the client. - -## Run jdbcDemo using mvn plugin -run command: -``` -mvn clean compile exec:java -Dexec.mainClass="com.taosdata.example.JdbcDemo" -``` - -and run with your customed args -``` -mvn clean compile exec:java -Dexec.mainClass="com.taosdata.example.JdbcDemo" -Dexec.args="-host [HOSTNAME]" -``` - -## Compile the Demo Code and Run It -To compile taos-jdbcdriver, go to the source directory ``TDengine/src/connector/jdbc`` and execute -``` -mvn clean package -Dmaven.test.skip=true -``` - -To compile the demo project, go to the source directory ``TDengine/tests/examples/JDBC/JDBCDemo`` and execute -``` -mvn clean package assembly:single -``` - -To run JDBCDemo.jar, go to ``TDengine/tests/examples/JDBC/JDBCDemo`` and execute -``` -java -Djava.ext.dirs=../../../../src/connector/jdbc/target:$JAVA_HOME/jre/lib/ext -jar target/JDBCDemo-SNAPSHOT-jar-with-dependencies.jar -host [HOSTNAME] -``` - diff --git a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/BatchInsert.java b/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/BatchInsert.java deleted file mode 100644 index a2566bd07e96ddd245c9b548a3192d0e4f343147..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/BatchInsert.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.taosdata.example; - -import java.sql.*; -import java.util.*; - -public class BatchInsert { - - private static final String host = "127.0.0.1"; - private static final String user = "root"; - private static final String password = "taosdata"; - - - private static final String dbname = "test"; - private static final String stbname = "stb"; - private static final int tables= 100; - private static final int rows = 500; - private static final long ts = 1604877767000l; - - private Connection conn; - - private void init() { - // final String url = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; - final String url = "jdbc:TAOS-RS://" + host + ":6041/?user=" + user + "&password=" + password; - - // get connection - try { - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); - conn = DriverManager.getConnection(url, properties); - if (conn != null){ - System.out.println("[ OK ] Connection established."); - } - - Statement stmt = conn.createStatement(); - - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table " + dbname + "." + stbname + "(ts timestamp, col int) tags(id int)"); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private String generateSql() { - StringBuilder sb = new StringBuilder(); - Random rand = new Random(); - sb.append("insert into "); - for (int i = 0; i < tables; i++) { - sb.append(dbname + ".tb" + i + " using " + dbname + "." + stbname + " tags(" + i + ") values"); - for (int j = 0; j < rows; j++) { - sb.append("("); - sb.append(ts + j); - sb.append(","); - sb.append(rand.nextInt(1000)); - sb.append(") "); - } - } - return sb.toString(); - } - - private void executeQuery(String sql) { - try (Statement stmt = conn.createStatement()) { - long start = System.currentTimeMillis(); - stmt.execute(sql); - long end = System.currentTimeMillis(); - - System.out.println("insert " + tables * rows + " records, cost " + (end - start)+ "ms"); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - - public static void main(String[] args) { - BatchInsert bi = new BatchInsert(); - - String sql = bi.generateSql(); - bi.init(); - bi.executeQuery(sql); - } - - -} diff --git a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ClientParameterSetting.java b/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ClientParameterSetting.java deleted file mode 100644 index 09fb8f1b19f069305464a52df15f748d29ddd5d8..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ClientParameterSetting.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.TSDBDriver; - -import java.sql.*; -import java.util.Properties; - -public class ClientParameterSetting { - private static final String host = "127.0.0.1"; - - public static void main(String[] args) throws SQLException { - setParameterInJdbcUrl(); - - setParameterInProperties(); - } - - private static void setParameterInJdbcUrl() throws SQLException { - String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?debugFlag=135&asyncLog=0"; - - Connection connection = DriverManager.getConnection(jdbcUrl, "root", "taosdata"); - - printDatabase(connection); - - connection.close(); - } - - private static void setParameterInProperties() throws SQLException { - String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; - Properties properties = new Properties(); - properties.setProperty("user", "root"); - properties.setProperty("password", "taosdata"); - properties.setProperty("debugFlag", "135"); - properties.setProperty("asyncLog", "0"); - properties.setProperty("maxSQLLength", "1048576"); - - try (Connection conn = DriverManager.getConnection(jdbcUrl, properties)) { - printDatabase(conn); - } - } - - private static void printDatabase(Connection connection) throws SQLException { - try (Statement stmt = connection.createStatement()) { - ResultSet rs = stmt.executeQuery("show databases"); - - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t"); - } - System.out.println(); - } - } - } -} diff --git a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcDemo.java b/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcDemo.java deleted file mode 100644 index 5bc23403087578c0791b0a5e6fca74a47aad8184..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcDemo.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.taosdata.example; - -import java.sql.*; -import java.util.Properties; - -public class JdbcDemo { - private static String host; - private static final String dbName = "test"; - private static final String tbName = "weather"; - private static final String user = "root"; - private static final String password = "taosdata"; - - private Connection connection; - - public static void main(String[] args) { - for (int i = 0; i < args.length; i++) { - if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) - host = args[++i]; - } - if (host == null) { - printHelp(); - } - JdbcDemo demo = new JdbcDemo(); - demo.init(); - demo.createDatabase(); - demo.useDatabase(); - demo.dropTable(); - demo.createTable(); - demo.insert(); - demo.select(); - demo.dropTable(); - demo.close(); - } - - private void init() { - final String url = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; - // get connection - try { - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); - connection = DriverManager.getConnection(url, properties); - if (connection != null) - System.out.println("[ OK ] Connection established."); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void createDatabase() { - String sql = "create database if not exists " + dbName; - exuete(sql); - } - - private void useDatabase() { - String sql = "use " + dbName; - exuete(sql); - } - - private void dropTable() { - final String sql = "drop table if exists " + dbName + "." + tbName + ""; - exuete(sql); - } - - private void createTable() { - final String sql = "create table if not exists " + dbName + "." + tbName + " (ts timestamp, temperature float, humidity int)"; - exuete(sql); - } - - private void insert() { - final String sql = "insert into " + dbName + "." + tbName + " (ts, temperature, humidity) values(now, 20.5, 34)"; - exuete(sql); - } - - private void select() { - final String sql = "select * from " + dbName + "." + tbName; - executeQuery(sql); - } - - private void close() { - try { - if (connection != null) { - this.connection.close(); - System.out.println("connection closed."); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void executeQuery(String sql) { - long start = System.currentTimeMillis(); - try (Statement statement = connection.createStatement()) { - ResultSet resultSet = statement.executeQuery(sql); - long end = System.currentTimeMillis(); - printSql(sql, true, (end - start)); - printResult(resultSet); - } catch (SQLException e) { - long end = System.currentTimeMillis(); - printSql(sql, false, (end - start)); - e.printStackTrace(); - } - } - - private void printResult(ResultSet resultSet) throws SQLException { - ResultSetMetaData metaData = resultSet.getMetaData(); - while (resultSet.next()) { - for (int i = 1; i <= metaData.getColumnCount(); i++) { - String columnLabel = metaData.getColumnLabel(i); - String value = resultSet.getString(i); - System.out.printf("%s: %s\t", columnLabel, value); - } - System.out.println(); - } - } - - private void printSql(String sql, boolean succeed, long cost) { - System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql); - } - - private void exuete(String sql) { - long start = System.currentTimeMillis(); - try (Statement statement = connection.createStatement()) { - boolean execute = statement.execute(sql); - long end = System.currentTimeMillis(); - printSql(sql, true, (end - start)); - } catch (SQLException e) { - long end = System.currentTimeMillis(); - printSql(sql, false, (end - start)); - e.printStackTrace(); - } - } - - private static void printHelp() { - System.out.println("Usage: java -jar JDBCDemo.jar -host "); - System.exit(0); - } - -} diff --git a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcRestfulDemo.java b/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcRestfulDemo.java deleted file mode 100644 index d89476b8ca718dab24202e2320e842366533a763..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcRestfulDemo.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.taosdata.example; - -import java.sql.*; -import java.util.Properties; - -public class JdbcRestfulDemo { - private static final String host = "localhost"; - private static final String dbname = "test"; - private static final String user = "root"; - private static final String password = "taosdata"; - - public static void main(String[] args) { - try { - // use port 6041 in url when use JDBC-restful - String url = "jdbc:TAOS-RS://" + host + ":6041/?user=" + user + "&password=" + password; - - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - - Connection conn = DriverManager.getConnection(url, properties); - Statement stmt = conn.createStatement(); - - stmt.execute("drop database if exists " + dbname); - stmt.execute("create database if not exists " + dbname); - stmt.execute("use " + dbname); - stmt.execute("create table " + dbname + ".weather(ts timestamp, temperature float) tags(location nchar(64))"); - stmt.executeUpdate("insert into t1 using " + dbname + ".weather tags('北京') values(now, 18.2)"); - ResultSet rs = stmt.executeQuery("select * from " + dbname + ".weather"); - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t"); - } - System.out.println(); - } - - rs.close(); - stmt.close(); - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingDemo.java b/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingDemo.java deleted file mode 100644 index 726b57b1465f678d703f0dc9c524f92b856e034e..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingDemo.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.TSDBPreparedStatement; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Random; - -public class ParameterBindingDemo { - - private static final String host = "127.0.0.1"; - private static final Random random = new Random(System.currentTimeMillis()); - private static final int BINARY_COLUMN_SIZE = 20; - private static final String[] schemaList = { - "create table stable1(ts timestamp, f1 tinyint, f2 smallint, f3 int, f4 bigint) tags(t1 tinyint, t2 smallint, t3 int, t4 bigint)", - "create table stable2(ts timestamp, f1 float, f2 double) tags(t1 float, t2 double)", - "create table stable3(ts timestamp, f1 bool) tags(t1 bool)", - "create table stable4(ts timestamp, f1 binary(" + BINARY_COLUMN_SIZE + ")) tags(t1 binary(" + BINARY_COLUMN_SIZE + "))", - "create table stable5(ts timestamp, f1 nchar(" + BINARY_COLUMN_SIZE + ")) tags(t1 nchar(" + BINARY_COLUMN_SIZE + "))" - }; - private static final int numOfSubTable = 10, numOfRow = 10; - - public static void main(String[] args) throws SQLException { - - String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; - Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata"); - - init(conn); - - bindInteger(conn); - - bindFloat(conn); - - bindBoolean(conn); - - bindBytes(conn); - - bindString(conn); - - conn.close(); - } - - private static void init(Connection conn) throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("drop database if exists test_parabind"); - stmt.execute("create database if not exists test_parabind"); - stmt.execute("use test_parabind"); - for (int i = 0; i < schemaList.length; i++) { - stmt.execute(schemaList[i]); - } - } - } - - private static void bindInteger(Connection conn) throws SQLException { - String sql = "insert into ? using stable1 tags(?,?,?,?) values(?,?,?,?,?)"; - - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("t1_" + i); - // set tags - pstmt.setTagByte(0, Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); - pstmt.setTagShort(1, Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); - pstmt.setTagInt(2, random.nextInt(Integer.MAX_VALUE)); - pstmt.setTagLong(3, random.nextLong()); - // set columns - ArrayList tsList = new ArrayList<>(); - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) - tsList.add(current + j); - pstmt.setTimestamp(0, tsList); - - ArrayList f1List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f1List.add(Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); - pstmt.setByte(1, f1List); - - ArrayList f2List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f2List.add(Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); - pstmt.setShort(2, f2List); - - ArrayList f3List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f3List.add(random.nextInt(Integer.MAX_VALUE)); - pstmt.setInt(3, f3List); - - ArrayList f4List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f4List.add(random.nextLong()); - pstmt.setLong(4, f4List); - - // add column - pstmt.columnDataAddBatch(); - } - // execute column - pstmt.columnDataExecuteBatch(); - } - - } - - private static void bindFloat(Connection conn) throws SQLException { - String sql = "insert into ? using stable2 tags(?,?) values(?,?,?)"; - - TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class); - - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("t2_" + i); - // set tags - pstmt.setTagFloat(0, random.nextFloat()); - pstmt.setTagDouble(1, random.nextDouble()); - // set columns - ArrayList tsList = new ArrayList<>(); - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) - tsList.add(current + j); - pstmt.setTimestamp(0, tsList); - - ArrayList f1List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f1List.add(random.nextFloat()); - pstmt.setFloat(1, f1List); - - ArrayList f2List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f2List.add(random.nextDouble()); - pstmt.setDouble(2, f2List); - - // add column - pstmt.columnDataAddBatch(); - } - // execute - pstmt.columnDataExecuteBatch(); - // close if no try-with-catch statement is used - pstmt.close(); - } - - private static void bindBoolean(Connection conn) throws SQLException { - String sql = "insert into ? using stable3 tags(?) values(?,?)"; - - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("t3_" + i); - // set tags - pstmt.setTagBoolean(0, random.nextBoolean()); - // set columns - ArrayList tsList = new ArrayList<>(); - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) - tsList.add(current + j); - pstmt.setTimestamp(0, tsList); - - ArrayList f1List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - f1List.add(random.nextBoolean()); - pstmt.setBoolean(1, f1List); - - // add column - pstmt.columnDataAddBatch(); - } - // execute - pstmt.columnDataExecuteBatch(); - } - } - - private static void bindBytes(Connection conn) throws SQLException { - String sql = "insert into ? using stable4 tags(?) values(?,?)"; - - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("t4_" + i); - // set tags - pstmt.setTagString(0, new String("abc")); - - // set columns - ArrayList tsList = new ArrayList<>(); - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) - tsList.add(current + j); - pstmt.setTimestamp(0, tsList); - - ArrayList f1List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) { - f1List.add(new String("abc")); - } - pstmt.setString(1, f1List, BINARY_COLUMN_SIZE); - - // add column - pstmt.columnDataAddBatch(); - } - // execute - pstmt.columnDataExecuteBatch(); - } - } - - private static void bindString(Connection conn) throws SQLException { - String sql = "insert into ? using stable5 tags(?) values(?,?)"; - - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("t5_" + i); - // set tags - pstmt.setTagNString(0, "北京-abc"); - - // set columns - ArrayList tsList = new ArrayList<>(); - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) - tsList.add(current + j); - pstmt.setTimestamp(0, tsList); - - ArrayList f1List = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) { - f1List.add("北京-abc"); - } - pstmt.setNString(1, f1List, BINARY_COLUMN_SIZE); - - // add column - pstmt.columnDataAddBatch(); - } - // execute - pstmt.columnDataExecuteBatch(); - } - } - - -} diff --git a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SubscribeDemo.java b/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SubscribeDemo.java deleted file mode 100644 index 4c499b0b3abb518b48b222eca9bbbcb388bd2008..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SubscribeDemo.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.TSDBConnection; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.TSDBResultSet; -import com.taosdata.jdbc.TSDBSubscribe; - -import java.sql.DriverManager; -import java.sql.ResultSetMetaData; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -public class SubscribeDemo { - private static final String usage = "java -jar SubscribeDemo.jar -host -database -topic -sql "; - - public static void main(String[] args) { - // parse args from command line - String host = "", database = "", topic = "", sql = ""; - for (int i = 0; i < args.length; i++) { - if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) { - host = args[++i]; - } - if ("-database".equalsIgnoreCase(args[i]) && i < args.length - 1) { - database = args[++i]; - } - if ("-topic".equalsIgnoreCase(args[i]) && i < args.length - 1) { - topic = args[++i]; - } - if ("-sql".equalsIgnoreCase(args[i]) && i < args.length - 1) { - sql = args[++i]; - } - } - if (host.isEmpty() || database.isEmpty() || topic.isEmpty() || sql.isEmpty()) { - System.out.println(usage); - return; - } - - try { - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - final String url = "jdbc:TAOS://" + host + ":6030/" + database + "?user=root&password=taosdata"; - // get TSDBConnection - TSDBConnection connection = (TSDBConnection) DriverManager.getConnection(url, properties); - // create TSDBSubscribe - TSDBSubscribe sub = connection.subscribe(topic, sql, false); - - int total = 0; - while (true) { - TSDBResultSet rs = sub.consume(); - int count = 0; - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t"); - } - System.out.println(); - count++; - } - total += count; -// System.out.printf("%d rows consumed, total %d\n", count, total); - if (total >= 10) - break; - TimeUnit.SECONDS.sleep(1); - } - sub.close(false); - connection.close(); - } catch (Exception e) { - System.out.println("host: " + host + ", database: " + database + ", topic: " + topic + ", sql: " + sql); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/SpringJdbcTemplate/.gitignore b/tests/examples/JDBC/SpringJdbcTemplate/.gitignore deleted file mode 100644 index 175de5c653d2f49b2ad1227764e60f741110592d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -HELP.md -target/ -.mvn/ -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ - -### VS Code ### -.vscode/ diff --git a/tests/examples/JDBC/SpringJdbcTemplate/pom.xml b/tests/examples/JDBC/SpringJdbcTemplate/pom.xml deleted file mode 100644 index eac3dec0a92a4c8aa519cd426b9c8d3895047be6..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - 4.0.0 - - com.taosdata.jdbc - SpringJdbcTemplate - 1.0-SNAPSHOT - - SpringJdbcTemplate - http://www.taosdata.com - - - UTF-8 - 1.8 - 1.8 - - - - - - org.springframework - spring-context - 5.2.8.RELEASE - - - - org.springframework - spring-jdbc - 5.1.9.RELEASE - - - - org.springframework - spring-test - 5.1.9.RELEASE - - - - junit - junit - 4.13.1 - test - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.18 - - - - - - - - maven-compiler-plugin - 3.8.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.1.0 - - - - com.taosdata.example.jdbcTemplate.App - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - - diff --git a/tests/examples/JDBC/SpringJdbcTemplate/readme.md b/tests/examples/JDBC/SpringJdbcTemplate/readme.md deleted file mode 100644 index b70a6565f88d0a08b8a26a60676e729ecdb39e2e..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/readme.md +++ /dev/null @@ -1,32 +0,0 @@ - -## TDengine Spring JDBC Template Demo - -`Spring JDBC Template` 简化了原生 JDBC Connection 获取释放等操作,使得操作数据库更加方便。 - -### 配置 - -修改 `src/main/resources/applicationContext.xml` 文件中 TDengine 的配置信息: - -```xml - - - - - - - - - - -``` - -### 打包运行 - -进入 `TDengine/tests/examples/JDBC/SpringJdbcTemplate` 目录下,执行以下命令可以生成可执行 jar 包。 -```shell -mvn clean package -``` -打包成功之后,进入 `target/` 目录下,执行以下命令就可运行测试: -```shell -java -jar SpringJdbcTemplate-1.0-SNAPSHOT-jar-with-dependencies.jar -``` \ No newline at end of file diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/App.java b/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/App.java deleted file mode 100644 index 6942d62a83adafb85496a81ce93866cd0d53611d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/App.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.taosdata.example.jdbcTemplate; - - -import com.taosdata.example.jdbcTemplate.dao.ExecuteAsStatement; -import com.taosdata.example.jdbcTemplate.dao.WeatherDao; -import com.taosdata.example.jdbcTemplate.domain.Weather; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import java.sql.Timestamp; -import java.util.Date; -import java.util.List; -import java.util.Random; - -public class App { - - private static Random random = new Random(System.currentTimeMillis()); - - public static void main(String[] args) { - - ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); - - ExecuteAsStatement executor = ctx.getBean(ExecuteAsStatement.class); - // drop database - executor.doExecute("drop database if exists test"); - // create database - executor.doExecute("create database if not exists test"); - //use database - executor.doExecute("use test"); - // create table - executor.doExecute("create table if not exists test.weather (ts timestamp, temperature int, humidity float)"); - - WeatherDao weatherDao = ctx.getBean(WeatherDao.class); - Weather weather = new Weather(new Timestamp(new Date().getTime()), random.nextFloat() * 50.0f, random.nextInt(100)); - // insert rows - int affectedRows = weatherDao.add(weather); - System.out.println("insert success " + affectedRows + " rows."); - - // query for list - int limit = 10, offset = 0; - List weatherList = weatherDao.queryForList(limit, offset); - for (Weather w : weatherList) { - System.out.println(w); - } - - } - -} diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/ExecuteAsStatement.java b/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/ExecuteAsStatement.java deleted file mode 100644 index 5947438e408b3b359b138bf989477f60fc327404..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/ExecuteAsStatement.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.taosdata.example.jdbcTemplate.dao; - -public interface ExecuteAsStatement{ - - void doExecute(String sql); -} diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/ExecuteAsStatementImpl.java b/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/ExecuteAsStatementImpl.java deleted file mode 100644 index 059e3dda15ea36bcaad4309a434a06f020d0301b..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/ExecuteAsStatementImpl.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.taosdata.example.jdbcTemplate.dao; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Repository; - - -@Repository -public class ExecuteAsStatementImpl implements ExecuteAsStatement { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Override - public void doExecute(String sql) { - jdbcTemplate.execute(sql); - } -} diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/WeatherDao.java b/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/WeatherDao.java deleted file mode 100644 index 19a07597f8df869dada4e258c4951f67132107a0..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/WeatherDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.taosdata.example.jdbcTemplate.dao; - -import com.taosdata.example.jdbcTemplate.domain.Weather; - -import java.util.List; - -public interface WeatherDao { - - - int add(Weather weather); - - int[] batchInsert(List weatherList); - - List queryForList(int limit, int offset); - - int count(); -} diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/WeatherDaoImpl.java b/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/WeatherDaoImpl.java deleted file mode 100644 index 8d4ca47d5ee5d351a48bcc1554531566116f5a52..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/dao/WeatherDaoImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.taosdata.example.jdbcTemplate.dao; - -import com.taosdata.example.jdbcTemplate.domain.Weather; -import com.taosdata.example.jdbcTemplate.dao.WeatherDao; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Repository; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.List; - -@Repository -public class WeatherDaoImpl implements WeatherDao { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Override - public int add(Weather weather) { - return jdbcTemplate.update( - "insert into test.weather(ts, temperature, humidity) VALUES(?,?,?)", - weather.getTs(), weather.getTemperature(), weather.getHumidity() - ); - } - - @Override - public int[] batchInsert(List weatherList) { - return jdbcTemplate.batchUpdate("insert into test.weather(ts, temperature, humidity) values( ?, ?, ?)", new BatchPreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps, int i) throws SQLException { - ps.setTimestamp(1, weatherList.get(i).getTs()); - ps.setFloat(2, weatherList.get(i).getTemperature()); - ps.setInt(3, weatherList.get(i).getHumidity()); - } - - @Override - public int getBatchSize() { - return weatherList.size(); - } - }); - } - - @Override - public List queryForList(int limit, int offset) { - return jdbcTemplate.query("select * from test.weather limit ? offset ?", (rs, rowNum) -> { - Timestamp ts = rs.getTimestamp("ts"); - float temperature = rs.getFloat("temperature"); - int humidity = rs.getInt("humidity"); - return new Weather(ts, temperature, humidity); - }, limit, offset); - } - - @Override - public int count() { - return jdbcTemplate.queryForObject("select count(*) from test.weather", Integer.class); - } -} diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/domain/Weather.java b/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/domain/Weather.java deleted file mode 100644 index 1787a08c3554e017645fefbd35d7c4fd1bc60bd4..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/java/com/taosdata/example/jdbcTemplate/domain/Weather.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.taosdata.example.jdbcTemplate.domain; - -import java.sql.Timestamp; - -public class Weather { - - private Timestamp ts; - private float temperature; - private int humidity; - - public Weather() { - } - - public Weather(Timestamp ts, float temperature, int humidity) { - this.ts = ts; - this.temperature = temperature; - this.humidity = humidity; - } - - @Override - public String toString() { - return "Weather{" + - "ts=" + ts + - ", temperature=" + temperature + - ", humidity=" + humidity + - '}'; - } - - public Timestamp getTs() { - return ts; - } - - public void setTs(Timestamp ts) { - this.ts = ts; - } - - public float getTemperature() { - return temperature; - } - - public void setTemperature(float temperature) { - this.temperature = temperature; - } - - public int getHumidity() { - return humidity; - } - - public void setHumidity(int humidity) { - this.humidity = humidity; - } - - -} diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/main/resources/applicationContext.xml b/tests/examples/JDBC/SpringJdbcTemplate/src/main/resources/applicationContext.xml deleted file mode 100644 index 6d6cf6047e2545256ffd6f39e1e6160a965a6fa8..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/main/resources/applicationContext.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/tests/examples/JDBC/SpringJdbcTemplate/src/test/java/com/taosdata/example/jdbcTemplate/BatcherInsertTest.java b/tests/examples/JDBC/SpringJdbcTemplate/src/test/java/com/taosdata/example/jdbcTemplate/BatcherInsertTest.java deleted file mode 100644 index 29d0f79fd4982d43078e590b4320c0df457ee44c..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/SpringJdbcTemplate/src/test/java/com/taosdata/example/jdbcTemplate/BatcherInsertTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.taosdata.example.jdbcTemplate; - - -import com.taosdata.example.jdbcTemplate.dao.ExecuteAsStatement; -import com.taosdata.example.jdbcTemplate.dao.WeatherDao; -import com.taosdata.example.jdbcTemplate.domain.Weather; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({"classpath:applicationContext.xml"}) -public class BatcherInsertTest { - - - @Autowired - private WeatherDao weatherDao; - @Autowired - private ExecuteAsStatement executor; - - private static final int numOfRecordsPerTable = 1000; - private static long ts = 1496732686000l; - private static Random random = new Random(System.currentTimeMillis()); - - @Before - public void before() { - // drop database - executor.doExecute("drop database if exists test"); - // create database - executor.doExecute("create database if not exists test"); - //use database - executor.doExecute("use test"); - // create table - executor.doExecute("create table if not exists test.weather (ts timestamp, temperature int, humidity float)"); - } - - @Test - public void batchInsert() { - List weatherList = new ArrayList<>(); - for (int i = 0; i < numOfRecordsPerTable; i++) { - ts += 1000; - Weather weather = new Weather(new Timestamp(ts), random.nextFloat() * 50.0f, random.nextInt(100)); - weatherList.add(weather); - } - long start = System.currentTimeMillis(); - weatherDao.batchInsert(weatherList); - long end = System.currentTimeMillis(); - System.out.println("batch insert(" + numOfRecordsPerTable + " rows) time cost ==========> " + (end - start) + " ms"); - - int count = weatherDao.count(); - assertEquals(count, numOfRecordsPerTable); - } - -} diff --git a/tests/examples/JDBC/connectionPools/README-cn.md b/tests/examples/JDBC/connectionPools/README-cn.md deleted file mode 100644 index 9b26df3c2eb2c23171a673643891a292af4c920c..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/README-cn.md +++ /dev/null @@ -1,32 +0,0 @@ -这个example中,我们适配了java常见的连接池: -* HikariCP(默认) -* druid -* dbcp -* c3p0 - -### 说明 -ConnectionPoolDemo的程序逻辑: -1. 创建到host的connection连接池 -2. 创建名称为pool_test的database,创建表超级weather,创建tableSize个子表 -3. 总共插入totalNumber条数据。 - -### 如何运行这个例子: - -```shell script -mvn clean package assembly:single -java -jar target/connectionPools-1.0-SNAPSHOT-jar-with-dependencies.jar -host 127.0.0.1 -``` -使用mvn运行ConnectionPoolDemo的main方法,可以指定参数 -```shell script -Usage: -java -jar target/connectionPools-1.0-SNAPSHOT-jar-with-dependencies.jar --host : hostname --poolType --poolSize --tableSize --batchSize : 每条Insert SQL中values的数量 --sleep : 每次插入任务提交后的 -``` - -### 日志 -使用log4j,将日志和错误分别输出到了debug.log和error.log中 \ No newline at end of file diff --git a/tests/examples/JDBC/connectionPools/pom.xml b/tests/examples/JDBC/connectionPools/pom.xml deleted file mode 100644 index d50c7a20709e0d0471261a64365873814242a619..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/pom.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - 4.0.0 - - - 1.8 - 1.8 - - - com.taosdata.demo - connectionPools - 1.0-SNAPSHOT - - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.34 - - - - com.alibaba - druid - 1.1.17 - - - - com.zaxxer - HikariCP - 3.2.0 - - - - commons-pool - commons-pool - 1.5.4 - - - commons-dbcp - commons-dbcp - 1.4 - - - - com.mchange - c3p0 - 0.9.5.4 - - - - org.apache.logging.log4j - log4j-core - 2.17.1 - - - - com.cloudhopper.proxool - proxool - 0.9.1 - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.3.0 - - - ConnectionPoolDemo - - ConnectionPoolDemo - - - com.taosdata.example.ConnectionPoolDemo - - - - jar-with-dependencies - - - package - - single - - - - - ProxoolDemo - - ProxoolDemo - - - com.taosdata.example.ProxoolDemo - - - - jar-with-dependencies - - - package - - single - - - - - - - - - diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/ConnectionPoolDemo.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/ConnectionPoolDemo.java deleted file mode 100644 index 96ad65aa4fc10bf81f6107a4bb2e5a4224891298..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/ConnectionPoolDemo.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.example.common.InsertTask; -import com.taosdata.example.pool.C3p0Builder; -import com.taosdata.example.pool.DbcpBuilder; -import com.taosdata.example.pool.DruidPoolBuilder; -import com.taosdata.example.pool.HikariCpBuilder; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class ConnectionPoolDemo { - - private static Logger logger = LogManager.getLogger(DruidPoolBuilder.class); - private static final String dbName = "pool_test"; - - private static String poolType = "hikari"; - private static long totalSize = 1_000_000l; - private static long tableSize = 1; - private static long batchSize = 1; - - private static int poolSize = 50; - private static int threadCount = 50; - private static int sleep = 0; - - public static void main(String[] args) { - String host = null; - for (int i = 0; i < args.length; i++) { - if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) { - host = args[++i]; - } - if ("-poolType".equalsIgnoreCase(args[i]) && i < args.length - 1) { - poolType = args[++i]; - } - if ("-recordNumber".equalsIgnoreCase(args[i]) && i < args.length - 1) { - totalSize = Long.parseLong(args[++i]); - } - if ("-tableNumber".equalsIgnoreCase(args[i]) && i < args.length - 1) { - tableSize = Long.parseLong(args[++i]); - } - if ("-batchNumber".equalsIgnoreCase(args[i]) && i < args.length - 1) { - batchSize = Long.parseLong(args[++i]); - } - - } - if (host == null) { - System.out.println("Usage: java -jar XXX.jar -host " + - "-poolType " + - "-recordNumber " + - "-tableNumber " + - "-batchNumber " + - "-sleep " - ); - return; - } - - DataSource dataSource; - switch (poolType) { - case "c3p0": - dataSource = C3p0Builder.getDataSource(host, poolSize); - break; - case "dbcp": - dataSource = DbcpBuilder.getDataSource(host, poolSize); - break; - case "druid": - dataSource = DruidPoolBuilder.getDataSource(host, poolSize); - break; - case "hikari": - default: - dataSource = HikariCpBuilder.getDataSource(host, poolSize); - poolType = "hikari"; - } - - logger.info(">>>>>>>>>>>>>> connection pool Type: " + poolType); - init(dataSource); - -// try { -// Connection connection = dataSource.getConnection(); -// Statement statement = connection.createStatement(); -// String sql = "insert into " + dbName + ".t_1 values('2020-01-01 00:00:00.000',12.12,111)"; -// int affectRows = statement.executeUpdate(sql); -// System.out.println("affectRows >>> " + affectRows); -// affectRows = statement.executeUpdate(sql); -// System.out.println("affectRows >>> " + affectRows); -// statement.close(); -// connection.close(); -// } catch (SQLException e) { -// e.printStackTrace(); -// } - - ExecutorService executor = Executors.newFixedThreadPool(threadCount); - for (long i = 0; i < totalSize / tableSize / batchSize; i++) { - executor.execute(new InsertTask(dataSource, dbName, tableSize, batchSize)); - // sleep few seconds - try { - if (sleep > 0) - TimeUnit.MILLISECONDS.sleep(sleep); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - executor.shutdown(); - - } - - private static void init(DataSource dataSource) { - try (Connection conn = dataSource.getConnection()) { - execute(conn, "drop database if exists " + dbName + ""); - execute(conn, "create database if not exists " + dbName + ""); - execute(conn, "use " + dbName + ""); - execute(conn, "create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"); - for (int tb_ind = 1; tb_ind <= tableSize; tb_ind++) { - execute(conn, "create table t_" + tb_ind + " using weather tags('beijing'," + (tb_ind + 1) + ")"); - } - logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>> init finished."); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private static void execute(Connection con, String sql) { - try (Statement stmt = con.createStatement()) { - stmt.executeUpdate(sql); - logger.info("SQL >>> " + sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - -} diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/ProxoolDemo.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/ProxoolDemo.java deleted file mode 100644 index 632ad8c9bf69d13d137d06c1f23c964904c8e050..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/ProxoolDemo.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.taosdata.example; - -import org.logicalcobwebs.proxool.ProxoolException; -import org.logicalcobwebs.proxool.configuration.JAXPConfigurator; - -import java.sql.*; - -public class ProxoolDemo { - - - public static void main(String[] args) { - - String xml = parseConfigurationXml(args); - if (xml == null) { - printHelp(); - System.exit(0); - } - - try { - JAXPConfigurator.configure(xml, false); - Class.forName("org.logicalcobwebs.proxool.ProxoolDriver"); - Connection connection = DriverManager.getConnection("proxool.ds"); - - Statement stmt = connection.createStatement(); - - ResultSet rs = stmt.executeQuery("show databases"); - ResultSetMetaData metaData = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= metaData.getColumnCount(); i++) { - System.out.print(metaData.getColumnLabel(i) + ": " + rs.getString(i)); - } - System.out.println(); - } - - stmt.close(); - - } catch (ClassNotFoundException | SQLException | ProxoolException e) { - e.printStackTrace(); - } - } - - private static String parseConfigurationXml(String[] args) { - String host = null; - for (int i = 0; i < args.length; i++) { - if ("--xml".equalsIgnoreCase(args[i]) && i < args.length - 1) { - host = args[++i]; - } - } - return host; - } - - private static void printHelp() { - System.out.println("Usage: java -jar ProxoolDemo.jar --xml [xml]"); - } - -} diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/common/InsertTask.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/common/InsertTask.java deleted file mode 100644 index f8f1555c08f1f5847bf0a34a56341ef6d22dde50..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/common/InsertTask.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.taosdata.example.common; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Random; - -public class InsertTask implements Runnable { - private final Random random = new Random(System.currentTimeMillis()); - private static final Logger logger = LogManager.getLogger(InsertTask.class); - - private final DataSource ds; - private final String dbName; - private final long tableSize; - private final long batchSize; - - public InsertTask(DataSource ds, String dbName, long tableSize, long batchSize) { - this.ds = ds; - this.dbName = dbName; - this.tableSize = tableSize; - this.batchSize = batchSize; - } - - @Override - public void run() { - int affectedRows = 0; - long start = System.currentTimeMillis(); - try (Connection conn = ds.getConnection(); Statement stmt = conn.createStatement()) { - for (int tb_index = 1; tb_index <= tableSize; tb_index++) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(dbName).append(".t_").append(tb_index).append("(ts, temperature, humidity) values "); - for (int i = 0; i < batchSize; i++) { - sb.append("(").append(start + i).append(", ").append(random.nextFloat() * 30).append(", ").append(random.nextInt(70)).append(") "); - } - logger.info("SQL >>> " + sb.toString()); - affectedRows += stmt.executeUpdate(sb.toString()); - } - } catch (SQLException e) { - e.printStackTrace(); - } - logger.info(">>> affectedRows:" + affectedRows + " TimeCost:" + (System.currentTimeMillis() - start) + " ms"); - } -} diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/C3p0Builder.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/C3p0Builder.java deleted file mode 100644 index 235db0bb796ee507b2d93838c8e7bfa7de870fcd..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/C3p0Builder.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.taosdata.example.pool; - -import com.mchange.v2.c3p0.ComboPooledDataSource; - -import javax.sql.DataSource; -import java.beans.PropertyVetoException; - -public class C3p0Builder { - - public static DataSource getDataSource(String host, int poolSize) { - ComboPooledDataSource ds = new ComboPooledDataSource(); - - try { - ds.setDriverClass("com.taosdata.jdbc.TSDBDriver"); - } catch (PropertyVetoException e) { - e.printStackTrace(); - } - ds.setJdbcUrl("jdbc:TAOS://" + host + ":6030"); - ds.setUser("root"); - ds.setPassword("taosdata"); - - ds.setMinPoolSize(poolSize); - ds.setMaxPoolSize(poolSize); - ds.setAcquireIncrement(5); - return ds; - } -} diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/DbcpBuilder.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/DbcpBuilder.java deleted file mode 100644 index 3aa9e4ebcf2d07ba1e6a51a2dae216cf44e88486..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/DbcpBuilder.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.taosdata.example.pool; - -import org.apache.commons.dbcp.BasicDataSource; - -import javax.sql.DataSource; - -public class DbcpBuilder { - - public static DataSource getDataSource(String host, int poolSize) { - BasicDataSource ds = new BasicDataSource(); - ds.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); - ds.setUrl("jdbc:TAOS://" + host + ":6030"); - ds.setUsername("root"); - ds.setPassword("taosdata"); - - ds.setMaxActive(poolSize); - ds.setMinIdle(poolSize); - ds.setInitialSize(poolSize); - return ds; - } -} diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/DruidPoolBuilder.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/DruidPoolBuilder.java deleted file mode 100644 index 500f0e9e97cc09c2c5e9990234f051d0bbc72044..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/DruidPoolBuilder.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.taosdata.example.pool; - -import com.alibaba.druid.pool.DruidDataSource; - -import javax.sql.DataSource; - -public class DruidPoolBuilder { - - public static DataSource getDataSource(String host, int poolSize) { - final String url = "jdbc:TAOS://" + host + ":6030"; - - DruidDataSource dataSource = new DruidDataSource(); - // jdbc properties - dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); - dataSource.setUrl(url); - dataSource.setUsername("root"); - dataSource.setPassword("taosdata"); - // pool configurations - dataSource.setInitialSize(poolSize); - dataSource.setMinIdle(poolSize); - dataSource.setMaxActive(poolSize); - dataSource.setMaxWait(30000); - dataSource.setValidationQuery("select server_status()"); - return dataSource; - } - -} diff --git a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/HikariCpBuilder.java b/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/HikariCpBuilder.java deleted file mode 100644 index 7e151de3e052495b3ce50ffe042732717fcc38f4..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/pool/HikariCpBuilder.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.taosdata.example.pool; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; - -import javax.sql.DataSource; - -public class HikariCpBuilder { - - public static DataSource getDataSource(String host, int poolSize) { - HikariConfig config = new HikariConfig(); - // jdbc properties - config.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); - config.setJdbcUrl("jdbc:TAOS://" + host + ":6030"); - config.setUsername("root"); - config.setPassword("taosdata"); - // pool configurations - config.setMinimumIdle(poolSize); //minimum number of idle connection - config.setMaximumPoolSize(poolSize); //maximum number of connection in the pool - config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool - config.setMaxLifetime(0); // maximum life time for each connection - config.setIdleTimeout(0); // max idle time for recycle idle connection - config.setConnectionTestQuery("select server_status()"); //validation query - - HikariDataSource ds = new HikariDataSource(config); - return ds; - } -} diff --git a/tests/examples/JDBC/connectionPools/src/main/resources/log4j.properties b/tests/examples/JDBC/connectionPools/src/main/resources/log4j.properties deleted file mode 100644 index 1299357be3d2e99ca6b79227f14ca7a587718914..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/resources/log4j.properties +++ /dev/null @@ -1,21 +0,0 @@ -### 设置### -log4j.rootLogger=debug,stdout,DebugLog,ErrorLog -### 输出信息到控制抬 ### -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n -### 输出DEBUG 级别以上的日志到=logs/debug.log -log4j.appender.DebugLog=org.apache.log4j.DailyRollingFileAppender -log4j.appender.DebugLog.File=logs/debug.log -log4j.appender.DebugLog.Append=true -log4j.appender.DebugLog.Threshold=DEBUG -log4j.appender.DebugLog.layout=org.apache.log4j.PatternLayout -log4j.appender.DebugLog.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n -### 输出ERROR 级别以上的日志到=logs/error.log -log4j.appender.ErrorLog=org.apache.log4j.DailyRollingFileAppender -log4j.appender.ErrorLog.File=logs/error.log -log4j.appender.ErrorLog.Append=true -log4j.appender.ErrorLog.Threshold=ERROR -log4j.appender.ErrorLog.layout=org.apache.log4j.PatternLayout -log4j.appender.ErrorLog.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/tests/examples/JDBC/connectionPools/src/main/resources/proxool.xml b/tests/examples/JDBC/connectionPools/src/main/resources/proxool.xml deleted file mode 100644 index 67baa1c3931aa57591af8fc306ed441328606978..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/connectionPools/src/main/resources/proxool.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - ds - - jdbc:TAOS-RS://127.0.0.1:6041/log - - com.taosdata.jdbc.rs.RestfulDriver - - - - - - - 100 - - 100 - - 1 - - 5 - - 30000 - - select server_status() - - \ No newline at end of file diff --git a/tests/examples/JDBC/mybatisplus-demo/.gitignore b/tests/examples/JDBC/mybatisplus-demo/.gitignore deleted file mode 100644 index b56f1dd0d04da4e03f710af3917e4fbdd9be4aa8..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -README.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/MavenWrapperDownloader.java b/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index a45eb6ba269cd38f8965cef786729790945d9537..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if (mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if (mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if (!outputFile.getParentFile().exists()) { - if (!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/maven-wrapper.jar b/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a55c0cd0092912bf49ae38b3a9e3fd0054..0000000000000000000000000000000000000000 Binary files a/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/maven-wrapper.properties b/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 642d572ce90e5085986bdd9c9204b9404f028084..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/tests/examples/JDBC/mybatisplus-demo/mvnw b/tests/examples/JDBC/mybatisplus-demo/mvnw deleted file mode 100755 index 3c8a5537314954d53ec2fb774b34fe5d5a5f253a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/mvnw +++ /dev/null @@ -1,322 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ]; then - - if [ -f /etc/mavenrc ]; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ]; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false -darwin=false -mingw=false -case "$(uname)" in -CYGWIN*) cygwin=true ;; -MINGW*) mingw=true ;; -Darwin*) - darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="$(/usr/libexec/java_home)" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ]; then - if [ -r /etc/gentoo-release ]; then - JAVA_HOME=$(java-config --jre-home) - fi -fi - -if [ -z "$M2_HOME" ]; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ]; do - ls=$(ls -ld "$PRG") - link=$(expr "$ls" : '.*-> \(.*\)$') - if expr "$link" : '/.*' >/dev/null; then - PRG="$link" - else - PRG="$(dirname "$PRG")/$link" - fi - done - - saveddir=$(pwd) - - M2_HOME=$(dirname "$PRG")/.. - - # make it fully qualified - M2_HOME=$(cd "$M2_HOME" && pwd) - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=$(cygpath --unix "$M2_HOME") - [ -n "$JAVA_HOME" ] && - JAVA_HOME=$(cygpath --unix "$JAVA_HOME") - [ -n "$CLASSPATH" ] && - CLASSPATH=$(cygpath --path --unix "$CLASSPATH") -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw; then - [ -n "$M2_HOME" ] && - M2_HOME="$( ( - cd "$M2_HOME" - pwd - ))" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="$( ( - cd "$JAVA_HOME" - pwd - ))" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="$(which javac)" - if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=$(which readlink) - if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then - if $darwin; then - javaHome="$(dirname \"$javaExecutable\")" - javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" - else - javaExecutable="$(readlink -f \"$javaExecutable\")" - fi - javaHome="$(dirname \"$javaExecutable\")" - javaHome=$(expr "$javaHome" : '\(.*\)/bin') - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ]; then - if [ -n "$JAVA_HOME" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="$(which java)" - fi -fi - -if [ ! -x "$JAVACMD" ]; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ]; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ]; then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ]; do - if [ -d "$wdir"/.mvn ]; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=$( - cd "$wdir/.." - pwd - ) - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' <"$1")" - fi -} - -BASE_DIR=$(find_maven_basedir "$(pwd)") -if [ -z "$BASE_DIR" ]; then - exit 1 -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in wrapperUrl) - jarUrl="$value" - break - ;; - esac - done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") - fi - - if command -v wget >/dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl >/dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=$(cygpath --path --windows "$javaClass") - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=$(cygpath --path --windows "$M2_HOME") - [ -n "$JAVA_HOME" ] && - JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") - [ -n "$CLASSPATH" ] && - CLASSPATH=$(cygpath --path --windows "$CLASSPATH") - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/tests/examples/JDBC/mybatisplus-demo/mvnw.cmd b/tests/examples/JDBC/mybatisplus-demo/mvnw.cmd deleted file mode 100644 index c8d43372c986d97911cdc21bd87e0cbe3d83bdda..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM https://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/tests/examples/JDBC/mybatisplus-demo/pom.xml b/tests/examples/JDBC/mybatisplus-demo/pom.xml deleted file mode 100644 index ad6a63e800fb73dd3c768a8aca941f70cec235b3..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/pom.xml +++ /dev/null @@ -1,100 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.4.0 - - - com.taosdata.example - mybatisplus-demo - 0.0.1-SNAPSHOT - mybatisplus-demo - Demo project for tdengine - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - org.projectlombok - lombok - true - - - com.baomidou - mybatis-plus-boot-starter - 3.1.2 - - - com.h2database - h2 - runtime - - - com.alibaba - druid - 1.1.17 - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.18 - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-starter-test - test - - - junit - junit - 4.13.1 - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.17 - - - **/*Test.java - - - **/Abstract*.java - - - - - - - - diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/MybatisplusDemoApplication.java b/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/MybatisplusDemoApplication.java deleted file mode 100644 index 7aaebca0846c15c2055596c95ae76d0cee773e41..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/MybatisplusDemoApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.taosdata.example.mybatisplusdemo; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -@MapperScan("com.taosdata.example.mybatisplusdemo.mapper") -public class MybatisplusDemoApplication { - - public static void main(String[] args) { - SpringApplication.run(MybatisplusDemoApplication.class, args); - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/config/MybatisPlusConfig.java b/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/config/MybatisPlusConfig.java deleted file mode 100644 index a6ac7f7fc247a361286333de4b3c03ffba306336..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/config/MybatisPlusConfig.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.config; - -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class MybatisPlusConfig { - - - /** mybatis 3.4.1 pagination config start ***/ -// @Bean -// public MybatisPlusInterceptor mybatisPlusInterceptor() { -// MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); -// interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); -// return interceptor; -// } - -// @Bean -// public ConfigurationCustomizer configurationCustomizer() { -// return configuration -> configuration.setUseDeprecatedExecutor(false); -// } - - @Bean - public PaginationInterceptor paginationInterceptor() { -// return new PaginationInterceptor(); - PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); - //TODO: mybatis-plus do not support TDengine, use postgresql Dialect - paginationInterceptor.setDialectType("postgresql"); - - return paginationInterceptor; - } - -} diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/domain/Temperature.java b/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/domain/Temperature.java deleted file mode 100644 index 97e50b06f6b71c26d1edd65c5ae9e7ff29a03e4d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/domain/Temperature.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.domain; - -import lombok.Data; - -import java.sql.Timestamp; - -@Data -public class Temperature { - - private Timestamp ts; - private float temperature; - private String location; - private int tbIndex; - -} diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/domain/Weather.java b/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/domain/Weather.java deleted file mode 100644 index 361757411a15d29e742a07a92060e20190921223..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/domain/Weather.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.domain; - -import lombok.Data; - -import java.sql.Timestamp; - -@Data -public class Weather { - - private Timestamp ts; - private float temperature; - private int humidity; - private String location; - -} diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/mapper/TemperatureMapper.java b/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/mapper/TemperatureMapper.java deleted file mode 100644 index 3e122524d57b5a54e08ff1cfc54101d517f32c32..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/mapper/TemperatureMapper.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.taosdata.example.mybatisplusdemo.domain.Temperature; -import org.apache.ibatis.annotations.Insert; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Update; - -public interface TemperatureMapper extends BaseMapper { - - @Update("CREATE TABLE if not exists temperature(ts timestamp, temperature float) tags(location nchar(64), tbIndex int)") - int createSuperTable(); - - @Update("create table #{tbName} using temperature tags( #{location}, #{tbindex})") - int createTable(@Param("tbName") String tbName, @Param("location") String location, @Param("tbindex") int tbindex); - - @Update("drop table if exists temperature") - void dropSuperTable(); - - @Insert("insert into t${tbIndex}(ts, temperature) values(#{ts}, #{temperature})") - int insertOne(Temperature one); - -} diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/mapper/WeatherMapper.java b/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/mapper/WeatherMapper.java deleted file mode 100644 index 6733cbded9d1d180408eccaad9e8badad7d39a3d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/java/com/taosdata/example/mybatisplusdemo/mapper/WeatherMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.taosdata.example.mybatisplusdemo.domain.Weather; - -public interface WeatherMapper extends BaseMapper { - -} diff --git a/tests/examples/JDBC/mybatisplus-demo/src/main/resources/application.yml b/tests/examples/JDBC/mybatisplus-demo/src/main/resources/application.yml deleted file mode 100644 index 38180c6d75a620a63bcaab9ec350d97e65f9dd16..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/main/resources/application.yml +++ /dev/null @@ -1,24 +0,0 @@ -spring: - datasource: - driver-class-name: com.taosdata.jdbc.TSDBDriver - url: jdbc:TAOS://localhost:6030/mp_test?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8 - user: root - password: taosdata - - druid: - initial-size: 5 - min-idle: 5 - max-active: 5 - -mybatis-plus: - configuration: - map-underscore-to-camel-case: false - -logging: - level: - com: - taosdata: - example: - mybatisplusdemo: - mapper: debug - diff --git a/tests/examples/JDBC/mybatisplus-demo/src/test/java/com/taosdata/example/mybatisplusdemo/mapper/TemperatureMapperTest.java b/tests/examples/JDBC/mybatisplus-demo/src/test/java/com/taosdata/example/mybatisplusdemo/mapper/TemperatureMapperTest.java deleted file mode 100644 index 4331d15d3476d3428e72a186664ed77cc59aad3e..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/test/java/com/taosdata/example/mybatisplusdemo/mapper/TemperatureMapperTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.mapper; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.taosdata.example.mybatisplusdemo.domain.Temperature; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.sql.Timestamp; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest -public class TemperatureMapperTest { - - private static Random random = new Random(System.currentTimeMillis()); - private static String[] locations = {"北京", "上海", "深圳", "广州", "杭州"}; - - @Before - public void before() { - mapper.dropSuperTable(); - // create table temperature - mapper.createSuperTable(); - // create table t_X using temperature - for (int i = 0; i < 10; i++) { - mapper.createTable("t" + i, locations[random.nextInt(locations.length)], i); - } - // insert into table - int affectRows = 0; - // insert 10 tables - for (int i = 0; i < 10; i++) { - // each table insert 5 rows - for (int j = 0; j < 5; j++) { - Temperature one = new Temperature(); - one.setTs(new Timestamp(1605024000000l)); - one.setTemperature(random.nextFloat() * 50); - one.setLocation("望京"); - one.setTbIndex(i); - affectRows += mapper.insertOne(one); - } - } - Assert.assertEquals(50, affectRows); - } - - @After - public void after() { - mapper.dropSuperTable(); - } - - @Autowired - private TemperatureMapper mapper; - - /*** - * test SelectList - * **/ - @Test - public void testSelectList() { - List temperatureList = mapper.selectList(null); - temperatureList.forEach(System.out::println); - } - - /*** - * test InsertOne which is a custom metheod - * ***/ - @Test - public void testInsert() { - Temperature one = new Temperature(); - one.setTs(new Timestamp(1605024000000l)); - one.setTemperature(random.nextFloat() * 50); - one.setLocation("望京"); - int affectRows = mapper.insertOne(one); - Assert.assertEquals(1, affectRows); - } - - /*** - * test SelectOne - * **/ - @Test - public void testSelectOne() { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("location", "beijing"); - Temperature one = mapper.selectOne(wrapper); - System.out.println(one); - Assert.assertNotNull(one); - } - - /*** - * test select By map - * ***/ - @Test - public void testSelectByMap() { - Map map = new HashMap<>(); - map.put("location", "beijing"); - List temperatures = mapper.selectByMap(map); - Assert.assertEquals(1, temperatures.size()); - } - - /*** - * test selectObjs - * **/ - @Test - public void testSelectObjs() { - List ts = mapper.selectObjs(null); - System.out.println(ts); - } - - /** - * test selectC ount - * **/ - @Test - public void testSelectCount() { - int count = mapper.selectCount(null); - Assert.assertEquals(5, count); - } - - /**** - * 分页 - */ - @Test - public void testSelectPage() { - IPage page = new Page(1, 2); - IPage temperatureIPage = mapper.selectPage(page, null); - System.out.println("total : " + temperatureIPage.getTotal()); - System.out.println("pages : " + temperatureIPage.getPages()); - for (Temperature temperature : temperatureIPage.getRecords()) { - System.out.println(temperature); - } - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/mybatisplus-demo/src/test/java/com/taosdata/example/mybatisplusdemo/mapper/WeatherMapperTest.java b/tests/examples/JDBC/mybatisplus-demo/src/test/java/com/taosdata/example/mybatisplusdemo/mapper/WeatherMapperTest.java deleted file mode 100644 index 1699344552f89e1595d1317019c992dcd3820e77..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/mybatisplus-demo/src/test/java/com/taosdata/example/mybatisplusdemo/mapper/WeatherMapperTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.taosdata.example.mybatisplusdemo.mapper; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.taosdata.example.mybatisplusdemo.domain.Weather; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.sql.Timestamp; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest -public class WeatherMapperTest { - - private static Random random = new Random(System.currentTimeMillis()); - - @Autowired - private WeatherMapper mapper; - - @Test - public void testSelectList() { - List weathers = mapper.selectList(null); - weathers.forEach(System.out::println); - } - - @Test - public void testInsert() { - Weather one = new Weather(); - one.setTs(new Timestamp(1605024000000l)); - one.setTemperature(random.nextFloat() * 50); - one.setHumidity(random.nextInt(100)); - one.setLocation("望京"); - int affectRows = mapper.insert(one); - Assert.assertEquals(1, affectRows); - } - - @Test - public void testSelectOne() { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("location", "beijing"); - Weather one = mapper.selectOne(wrapper); - System.out.println(one); - Assert.assertEquals(12.22f, one.getTemperature(), 0.00f); - Assert.assertEquals("beijing", one.getLocation()); - } - - @Test - public void testSelectByMap() { - Map map = new HashMap<>(); - map.put("location", "beijing"); - List weathers = mapper.selectByMap(map); - Assert.assertEquals(1, weathers.size()); - } - - @Test - public void testSelectObjs() { - List ts = mapper.selectObjs(null); - System.out.println(ts); - } - - @Test - public void testSelectCount() { - int count = mapper.selectCount(null); -// Assert.assertEquals(5, count); - System.out.println(count); - } - - @Test - public void testSelectPage() { - IPage page = new Page(1, 2); - IPage weatherIPage = mapper.selectPage(page, null); - System.out.println("total : " + weatherIPage.getTotal()); - System.out.println("pages : " + weatherIPage.getPages()); - for (Weather weather : weatherIPage.getRecords()) { - System.out.println(weather); - } - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/readme.md b/tests/examples/JDBC/readme.md deleted file mode 100644 index 35dfb341d7d62bb283897523f928e04dabea962d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -# TDengine examples - -| No. | Name | Describe | -| :--: | :----------------: | ------------------------------------------------------------ | -| 1 | JDBCDemo | Example codes for JDBC-JNI, JDBC-RESTful, Subscribe | -| 2 | connectionPools | Example codes for HikariCP, Druid, dbcp, c3p0 connection pools | -| 3 | SpringJdbcTemplate | Example codes for spring jdbcTemplate | -| 4 | mybatisplus-demo | Example codes for mybatis | -| 5 | springbootdemo | Example codes for springboot | -| 6 | taosdemo | This is an internal tool for testing Our JDBC-JNI, JDBC-RESTful, RESTful interfaces | - - -more detail: https://www.taosdata.com/cn/documentation20/connector/java diff --git a/tests/examples/JDBC/springbootdemo/.gitignore b/tests/examples/JDBC/springbootdemo/.gitignore deleted file mode 100644 index b8a47adccb623c653c547481ff9d3221210f31ef..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -.mvn/ -target/ -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ - -### VS Code ### -.vscode/ diff --git a/tests/examples/JDBC/springbootdemo/.mvn/wrapper/MavenWrapperDownloader.java b/tests/examples/JDBC/springbootdemo/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index 74f4de40122aca522184d5b1aac4f0ac29888b1a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.5"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if (mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if (mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if (!outputFile.getParentFile().exists()) { - if (!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/tests/examples/JDBC/springbootdemo/.mvn/wrapper/maven-wrapper.jar b/tests/examples/JDBC/springbootdemo/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 0d5e649888a4843c1520054d9672f80c62ebbb48..0000000000000000000000000000000000000000 Binary files a/tests/examples/JDBC/springbootdemo/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/tests/examples/JDBC/springbootdemo/.mvn/wrapper/maven-wrapper.properties b/tests/examples/JDBC/springbootdemo/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 7d59a01f2594defa27705a493da0e4d57465aa2d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar diff --git a/tests/examples/JDBC/springbootdemo/mvnw b/tests/examples/JDBC/springbootdemo/mvnw deleted file mode 100755 index 21d3ee84568ff68c4712677da7c3b06f61ab5543..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/tests/examples/JDBC/springbootdemo/mvnw.cmd b/tests/examples/JDBC/springbootdemo/mvnw.cmd deleted file mode 100644 index 84d60abc339b13f80f3300b00387f2d4cc4eb328..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM https://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/tests/examples/JDBC/springbootdemo/pom.xml b/tests/examples/JDBC/springbootdemo/pom.xml deleted file mode 100644 index 9126813b67e71691692109920f891a6fb4cc5ab5..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.2.1.RELEASE - - - com.taosdata.example - springbootdemo - 0.0.1-SNAPSHOT - springbootdemo - Demo project for using tdengine with Spring Boot - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jdbc - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.mybatis.spring.boot - mybatis-spring-boot-starter - 2.1.1 - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - org.springframework.boot - spring-boot-starter-aop - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.34 - - - - com.alibaba - druid-spring-boot-starter - 1.1.17 - - - - - - - src/main/resources - - **/*.properties - **/*.xml - - true - - - src/main/java - - **/*.properties - **/*.xml - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/tests/examples/JDBC/springbootdemo/readme.md b/tests/examples/JDBC/springbootdemo/readme.md deleted file mode 100644 index 67a28947d2dfb8fc069bf94fd139a7006d35a22b..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/readme.md +++ /dev/null @@ -1,96 +0,0 @@ -## TDengine SpringBoot + Mybatis Demo - -### 配置 application.properties -```properties -# datasource config -spring.datasource.driver-class-name=com.taosdata.jdbc.TSDBDriver -spring.datasource.url=jdbc:TAOS://127.0.0.1:6030/log -spring.datasource.username=root -spring.datasource.password=taosdata - -spring.datasource.druid.initial-size=5 -spring.datasource.druid.min-idle=5 -spring.datasource.druid.max-active=5 -# max wait time for get connection, ms -spring.datasource.druid.max-wait=60000 - -spring.datasource.druid.validation-query=select server_status(); -spring.datasource.druid.validation-query-timeout=5000 -spring.datasource.druid.test-on-borrow=false -spring.datasource.druid.test-on-return=false -spring.datasource.druid.test-while-idle=true -spring.datasource.druid.time-between-eviction-runs-millis=60000 -spring.datasource.druid.min-evictable-idle-time-millis=600000 -spring.datasource.druid.max-evictable-idle-time-millis=900000 - -# mybatis -mybatis.mapper-locations=classpath:mapper/*.xml - -# log -logging.level.com.taosdata.jdbc.springbootdemo.dao=debug -``` - -### 主要功能 - -* 创建数据库和表 -```xml - - - create database if not exists test; - - - - create table if not exists test.weather(ts timestamp, temperature int, humidity float); - -``` - -* 插入单条记录 -```xml - - - insert into test.weather (ts, temperature, humidity) values (now, #{temperature,jdbcType=INTEGER}, #{humidity,jdbcType=FLOAT}) - -``` -* 插入多条记录 -```xml - - - insert into test.weather (ts, temperature, humidity) values - - (now + #{index}a, #{weather.temperature}, #{weather.humidity}) - - -``` -* 分页查询 -```xml - - - - - - - - - - - - - - ts, temperature, humidity - - - - -``` - diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/SpringbootdemoApplication.java b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/SpringbootdemoApplication.java deleted file mode 100644 index 53edaa5796cccc7e4a4f274048c83a9ca7bbc7bb..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/SpringbootdemoApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.taosdata.example.springbootdemo; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@MapperScan(basePackages = {"com.taosdata.example.springbootdemo"}) -@SpringBootApplication -public class SpringbootdemoApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringbootdemoApplication.class, args); - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/controller/WeatherController.java b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/controller/WeatherController.java deleted file mode 100644 index ed720fe6c02dd3a7eba6e645ea1e76d704c04d0c..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/controller/WeatherController.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.taosdata.example.springbootdemo.controller; - -import com.taosdata.example.springbootdemo.domain.Weather; -import com.taosdata.example.springbootdemo.service.WeatherService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; - -@RequestMapping("/weather") -@RestController -public class WeatherController { - - @Autowired - private WeatherService weatherService; - - @GetMapping("/lastOne") - public Weather lastOne() { - return weatherService.lastOne(); - } - - @GetMapping("/init") - public int init() { - return weatherService.init(); - } - - @GetMapping("/{limit}/{offset}") - public List queryWeather(@PathVariable Long limit, @PathVariable Long offset) { - return weatherService.query(limit, offset); - } - - @PostMapping("/{temperature}/{humidity}") - public int saveWeather(@PathVariable float temperature, @PathVariable float humidity) { - return weatherService.save(temperature, humidity); - } - - @GetMapping("/count") - public int count() { - return weatherService.count(); - } - - @GetMapping("/subTables") - public List getSubTables() { - return weatherService.getSubTables(); - } - - @GetMapping("/avg") - public List avg() { - return weatherService.avg(); - } - -} diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/dao/WeatherMapper.java b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/dao/WeatherMapper.java deleted file mode 100644 index d9202b45b4cc3dddf8e5a082ac339c1f88d4ec01..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/dao/WeatherMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.taosdata.example.springbootdemo.dao; - -import com.taosdata.example.springbootdemo.domain.Weather; -import org.apache.ibatis.annotations.Param; - -import java.util.List; -import java.util.Map; - -public interface WeatherMapper { - - Map lastOne(); - - void dropDB(); - - void createDB(); - - void createSuperTable(); - - void createTable(Weather weather); - - List select(@Param("limit") Long limit, @Param("offset") Long offset); - - int insert(Weather weather); - - int count(); - - List getSubTables(); - - List avg(); - -} diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/dao/WeatherMapper.xml b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/dao/WeatherMapper.xml deleted file mode 100644 index 91938ca24e3cf9c3e0f2895cf40f214d484c55d5..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/dao/WeatherMapper.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - drop - database if exists test - - - - create - database if not exists test - - - - create table if not exists test.weather - ( - ts - timestamp, - temperature - float, - humidity - float, - note - binary - ( - 64 - )) tags - ( - location nchar - ( - 64 - ), groupId int) - - - - create table if not exists test.t#{groupId} using test.weather tags - ( - #{location}, - #{groupId} - ) - - - - - - insert into test.t#{groupId} (ts, temperature, humidity, note) - values (#{ts}, ${temperature}, ${humidity}, #{note}) - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/domain/Weather.java b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/domain/Weather.java deleted file mode 100644 index e4238127bd32b0f6ad21a514f3a1f07f6069b6d5..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/domain/Weather.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.taosdata.example.springbootdemo.domain; - -import com.fasterxml.jackson.annotation.JsonFormat; - -import java.sql.Timestamp; - -public class Weather { - - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8") - private Timestamp ts; - private Float temperature; - private Float humidity; - private String location; - private String note; - private int groupId; - - public Weather() { - } - - public Weather(Timestamp ts, float temperature, float humidity) { - this.ts = ts; - this.temperature = temperature; - this.humidity = humidity; - } - - public Timestamp getTs() { - return ts; - } - - public void setTs(Timestamp ts) { - this.ts = ts; - } - - public Float getTemperature() { - return temperature; - } - - public void setTemperature(Float temperature) { - this.temperature = temperature; - } - - public Float getHumidity() { - return humidity; - } - - public void setHumidity(Float humidity) { - this.humidity = humidity; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public int getGroupId() { - return groupId; - } - - public void setGroupId(int groupId) { - this.groupId = groupId; - } - - public String getNote() { - return note; - } - - public void setNote(String note) { - this.note = note; - } -} diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/service/WeatherService.java b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/service/WeatherService.java deleted file mode 100644 index 2264b200afc3e0c2b7dd8e496e607649f940581d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/service/WeatherService.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.taosdata.example.springbootdemo.service; - -import com.taosdata.example.springbootdemo.dao.WeatherMapper; -import com.taosdata.example.springbootdemo.domain.Weather; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.sql.Timestamp; -import java.util.List; -import java.util.Map; -import java.util.Random; - -@Service -public class WeatherService { - - @Autowired - private WeatherMapper weatherMapper; - private Random random = new Random(System.currentTimeMillis()); - private String[] locations = {"北京", "上海", "广州", "深圳", "天津"}; - - public int init() { - weatherMapper.dropDB(); - weatherMapper.createDB(); - weatherMapper.createSuperTable(); - long ts = System.currentTimeMillis(); - long thirtySec = 1000 * 30; - int count = 0; - for (int i = 0; i < 20; i++) { - Weather weather = new Weather(new Timestamp(ts + (thirtySec * i)), 30 * random.nextFloat(), random.nextInt(100)); - weather.setLocation(locations[random.nextInt(locations.length)]); - weather.setGroupId(i % locations.length); - weather.setNote("note-" + i); - weatherMapper.createTable(weather); - count += weatherMapper.insert(weather); - } - return count; - } - - public List query(Long limit, Long offset) { - return weatherMapper.select(limit, offset); - } - - public int save(float temperature, float humidity) { - Weather weather = new Weather(); - weather.setTemperature(temperature); - weather.setHumidity(humidity); - - return weatherMapper.insert(weather); - } - - public int count() { - return weatherMapper.count(); - } - - public List getSubTables() { - return weatherMapper.getSubTables(); - } - - public List avg() { - return weatherMapper.avg(); - } - - public Weather lastOne() { - Map result = weatherMapper.lastOne(); - - long ts = (long) result.get("ts"); - float temperature = (float) result.get("temperature"); - float humidity = (float) result.get("humidity"); - String note = (String) result.get("note"); - int groupId = (int) result.get("groupid"); - String location = (String) result.get("location"); - - Weather weather = new Weather(new Timestamp(ts), temperature, humidity); - weather.setNote(note); - weather.setGroupId(groupId); - weather.setLocation(location); - return weather; - } -} diff --git a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/util/TaosAspect.java b/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/util/TaosAspect.java deleted file mode 100644 index 80dad1bd7d669ba6b912c7e5fa816c29b7e37c87..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/java/com/taosdata/example/springbootdemo/util/TaosAspect.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.taosdata.example.springbootdemo.util; - -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.springframework.stereotype.Component; - -import java.sql.Timestamp; -import java.util.Map; - -@Aspect -@Component -public class TaosAspect { - - @Around("execution(java.util.Map com.taosdata.example.springbootdemo.dao.*.*(..))") - public Object handleType(ProceedingJoinPoint joinPoint) { - Map result = null; - try { - result = (Map) joinPoint.proceed(); - for (String key : result.keySet()) { - Object obj = result.get(key); - if (obj instanceof byte[]) { - obj = new String((byte[]) obj); - result.put(key, obj); - } - if (obj instanceof Timestamp) { - obj = ((Timestamp) obj).getTime(); - result.put(key, obj); - } - } - } catch (Throwable e) { - e.printStackTrace(); - } - return result; - } -} diff --git a/tests/examples/JDBC/springbootdemo/src/main/resources/application.properties b/tests/examples/JDBC/springbootdemo/src/main/resources/application.properties deleted file mode 100644 index 06daa81bbb06450d99ab3f6e640c9795c0ad5d2e..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/springbootdemo/src/main/resources/application.properties +++ /dev/null @@ -1,20 +0,0 @@ -# datasource config - JDBC-JNI -#spring.datasource.driver-class-name=com.taosdata.jdbc.TSDBDriver -#spring.datasource.url=jdbc:TAOS://localhost:6030/?timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8 -#spring.datasource.username=root -#spring.datasource.password=taosdata -# datasource config - JDBC-RESTful -spring.datasource.driver-class-name=com.taosdata.jdbc.rs.RestfulDriver -spring.datasource.url=jdbc:TAOS-RS://localhsot:6041/test?timezone=UTC-8&charset=UTF-8&locale=en_US.UTF-8 -spring.datasource.username=root -spring.datasource.password=taosdata -spring.datasource.druid.initial-size=5 -spring.datasource.druid.min-idle=5 -spring.datasource.druid.max-active=5 -spring.datasource.druid.max-wait=30000 -spring.datasource.druid.validation-query=select server_status(); -spring.aop.auto=true -spring.aop.proxy-target-class=true -#mybatis -mybatis.mapper-locations=classpath:mapper/*.xml -logging.level.com.taosdata.jdbc.springbootdemo.dao=debug diff --git a/tests/examples/JDBC/taosdemo/.gitignore b/tests/examples/JDBC/taosdemo/.gitignore deleted file mode 100644 index 549e00a2a96fa9d7c5dbc9859664a78d980158c2..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/tests/examples/JDBC/taosdemo/.mvn/wrapper/MavenWrapperDownloader.java b/tests/examples/JDBC/taosdemo/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index a45eb6ba269cd38f8965cef786729790945d9537..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if (mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if (mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if (!outputFile.getParentFile().exists()) { - if (!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/tests/examples/JDBC/taosdemo/.mvn/wrapper/maven-wrapper.jar b/tests/examples/JDBC/taosdemo/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a55c0cd0092912bf49ae38b3a9e3fd0054..0000000000000000000000000000000000000000 Binary files a/tests/examples/JDBC/taosdemo/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/tests/examples/JDBC/taosdemo/.mvn/wrapper/maven-wrapper.properties b/tests/examples/JDBC/taosdemo/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 642d572ce90e5085986bdd9c9204b9404f028084..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/tests/examples/JDBC/taosdemo/mvnw b/tests/examples/JDBC/taosdemo/mvnw deleted file mode 100755 index 3c8a5537314954d53ec2fb774b34fe5d5a5f253a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/mvnw +++ /dev/null @@ -1,322 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ]; then - - if [ -f /etc/mavenrc ]; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ]; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false -darwin=false -mingw=false -case "$(uname)" in -CYGWIN*) cygwin=true ;; -MINGW*) mingw=true ;; -Darwin*) - darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="$(/usr/libexec/java_home)" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ]; then - if [ -r /etc/gentoo-release ]; then - JAVA_HOME=$(java-config --jre-home) - fi -fi - -if [ -z "$M2_HOME" ]; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ]; do - ls=$(ls -ld "$PRG") - link=$(expr "$ls" : '.*-> \(.*\)$') - if expr "$link" : '/.*' >/dev/null; then - PRG="$link" - else - PRG="$(dirname "$PRG")/$link" - fi - done - - saveddir=$(pwd) - - M2_HOME=$(dirname "$PRG")/.. - - # make it fully qualified - M2_HOME=$(cd "$M2_HOME" && pwd) - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=$(cygpath --unix "$M2_HOME") - [ -n "$JAVA_HOME" ] && - JAVA_HOME=$(cygpath --unix "$JAVA_HOME") - [ -n "$CLASSPATH" ] && - CLASSPATH=$(cygpath --path --unix "$CLASSPATH") -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw; then - [ -n "$M2_HOME" ] && - M2_HOME="$( ( - cd "$M2_HOME" - pwd - ))" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="$( ( - cd "$JAVA_HOME" - pwd - ))" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="$(which javac)" - if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=$(which readlink) - if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then - if $darwin; then - javaHome="$(dirname \"$javaExecutable\")" - javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" - else - javaExecutable="$(readlink -f \"$javaExecutable\")" - fi - javaHome="$(dirname \"$javaExecutable\")" - javaHome=$(expr "$javaHome" : '\(.*\)/bin') - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ]; then - if [ -n "$JAVA_HOME" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="$(which java)" - fi -fi - -if [ ! -x "$JAVACMD" ]; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ]; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ]; then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ]; do - if [ -d "$wdir"/.mvn ]; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=$( - cd "$wdir/.." - pwd - ) - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' <"$1")" - fi -} - -BASE_DIR=$(find_maven_basedir "$(pwd)") -if [ -z "$BASE_DIR" ]; then - exit 1 -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in wrapperUrl) - jarUrl="$value" - break - ;; - esac - done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") - fi - - if command -v wget >/dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl >/dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=$(cygpath --path --windows "$javaClass") - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=$(cygpath --path --windows "$M2_HOME") - [ -n "$JAVA_HOME" ] && - JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") - [ -n "$CLASSPATH" ] && - CLASSPATH=$(cygpath --path --windows "$CLASSPATH") - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/tests/examples/JDBC/taosdemo/mvnw.cmd b/tests/examples/JDBC/taosdemo/mvnw.cmd deleted file mode 100644 index c8d43372c986d97911cdc21bd87e0cbe3d83bdda..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM https://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/tests/examples/JDBC/taosdemo/pom.xml b/tests/examples/JDBC/taosdemo/pom.xml deleted file mode 100644 index e249d83e16def830b61e9f8ab82197d30e7e0d33..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/pom.xml +++ /dev/null @@ -1,168 +0,0 @@ - - - 4.0.0 - com.taosdata - taosdemo - 2.0.1 - taosdemo - jar - Demo project for TDengine - - - 5.3.14 - - - - - - org.springframework - spring-context - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - - - org.springframework - spring-aop - ${spring.version} - - - org.springframework - spring-aspects - ${spring.version} - - - org.springframework - spring-test - ${spring.version} - test - - - org.springframework - spring-jdbc - ${spring.version} - - - - - com.zaxxer - HikariCP - 3.4.5 - - - - com.taosdata.jdbc - taos-jdbcdriver - 2.0.20 - - - - - - com.alibaba - fastjson - 1.2.75 - - - - mysql - mysql-connector-java - 8.0.16 - test - - - - org.apache.logging.log4j - log4j-core - 2.17.1 - - - - junit - junit - 4.13.1 - test - - - - org.projectlombok - lombok - 1.18.16 - provided - - - - - - - src/main/resources - - **/*.properties - **/*.xml - **/*.jar - - true - - - src/main/java - - **/*.properties - **/*.xml - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.1.0 - - - - - com.taosdata.taosdemo.TaosDemoApplication - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - - - - diff --git a/tests/examples/JDBC/taosdemo/readme.md b/tests/examples/JDBC/taosdemo/readme.md deleted file mode 100644 index 451fa2960adb98e2deb8499732aefde11f4810a1..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -``` -cd tests/examples/JDBC/taosdemo -mvn clean package -Dmaven.test.skip=true -# 先建表,再插入的 -java -jar target/taosdemo-2.0-jar-with-dependencies.jar -host [hostname] -database [database] -doCreateTable true -superTableSQL "create table weather(ts timestamp, f1 int) tags(t1 nchar(4))" -numOfTables 1000 -numOfRowsPerTable 100000000 -numOfThreadsForInsert 10 -numOfTablesPerSQL 10 -numOfValuesPerSQL 100 -# 不建表,直接插入的 -java -jar target/taosdemo-2.0-jar-with-dependencies.jar -host [hostname] -database [database] -doCreateTable false -superTableSQL "create table weather(ts timestamp, f1 int) tags(t1 nchar(4))" -numOfTables 1000 -numOfRowsPerTable 100000000 -numOfThreadsForInsert 10 -numOfTablesPerSQL 10 -numOfValuesPerSQL 100 -``` - -需求: -1. 可以读lowa的配置文件 -2. 支持JDBC-JNI和JDBC-restful -3. 读取配置文件,持续执行查询 \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/TaosDemoApplication.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/TaosDemoApplication.java deleted file mode 100644 index d4f5ff26886b9f90a4235d47bfd004dae9de93f6..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/TaosDemoApplication.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.taosdata.taosdemo; - -import com.taosdata.taosdemo.components.DataSourceFactory; -import com.taosdata.taosdemo.components.JdbcTaosdemoConfig; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.service.DatabaseService; -import com.taosdata.taosdemo.service.SqlExecuteTask; -import com.taosdata.taosdemo.service.SubTableService; -import com.taosdata.taosdemo.service.SuperTableService; -import com.taosdata.taosdemo.service.data.SuperTableMetaGenerator; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import javax.sql.DataSource; -import java.io.IOException; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class TaosDemoApplication { - - private static final Logger logger = LogManager.getLogger(TaosDemoApplication.class); - - public static void main(String[] args) throws IOException { - // 读配置参数 - JdbcTaosdemoConfig config = new JdbcTaosdemoConfig(args); - boolean isHelp = Arrays.asList(args).contains("--help"); - if (isHelp || config.host == null || config.host.isEmpty()) { - JdbcTaosdemoConfig.printHelp(); - System.exit(0); - } - // 初始化 - final DataSource dataSource = DataSourceFactory.getInstance(config.host, config.port, config.user, config.password); - if (config.executeSql != null && !config.executeSql.isEmpty() && !config.executeSql.replaceAll("\\s", "").isEmpty()) { - Thread task = new Thread(new SqlExecuteTask(dataSource, config.executeSql)); - task.start(); - try { - task.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return; - } - - final DatabaseService databaseService = new DatabaseService(dataSource); - final SuperTableService superTableService = new SuperTableService(dataSource); - final SubTableService subTableService = new SubTableService(dataSource); - - // 创建数据库 - long start = System.currentTimeMillis(); - Map databaseParam = new HashMap<>(); - databaseParam.put("database", config.database); - databaseParam.put("keep", Integer.toString(config.keep)); - databaseParam.put("days", Integer.toString(config.days)); - databaseParam.put("replica", Integer.toString(config.replica)); - //TODO: other database parameters - databaseService.createDatabase(databaseParam); - databaseService.useDatabase(config.database); - long end = System.currentTimeMillis(); - logger.info(">>> create database time cost : " + (end - start) + " ms."); - /**********************************************************************************/ - // 构造超级表的meta - SuperTableMeta superTableMeta; - // create super table - if (config.superTableSQL != null) { - // use a sql to create super table - superTableMeta = SuperTableMetaGenerator.generate(config.superTableSQL); - if (config.database != null && !config.database.isEmpty()) - superTableMeta.setDatabase(config.database); - } else if (config.numOfFields == 0) { - String sql = "create table " + config.database + "." + config.superTable + " (ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"; - superTableMeta = SuperTableMetaGenerator.generate(sql); - } else { - // create super table with specified field size and tag size - superTableMeta = SuperTableMetaGenerator.generate(config.database, config.superTable, config.numOfFields, config.prefixOfFields, config.numOfTags, config.prefixOfTags); - } - /**********************************************************************************/ - // 建表 - start = System.currentTimeMillis(); - if (config.doCreateTable) { - superTableService.drop(superTableMeta.getDatabase(), superTableMeta.getName()); - superTableService.create(superTableMeta); - if (!config.autoCreateTable) { - // 批量建子表 - subTableService.createSubTable(superTableMeta, config.numOfTables, config.prefixOfTable, config.numOfThreadsForCreate); - } - } - end = System.currentTimeMillis(); - logger.info(">>> create table time cost : " + (end - start) + " ms."); - /**********************************************************************************/ - // 插入 - long tableSize = config.numOfTables; - int threadSize = config.numOfThreadsForInsert; - long startTime = getProperStartTime(config.startTime, config.keep); - - if (tableSize < threadSize) - threadSize = (int) tableSize; - long gap = (long) Math.ceil((0.0d + tableSize) / threadSize); - - start = System.currentTimeMillis(); - // multi threads to insert - int affectedRows = subTableService.insertMultiThreads(superTableMeta, threadSize, tableSize, startTime, gap, config); - end = System.currentTimeMillis(); - logger.info("insert " + affectedRows + " rows, time cost: " + (end - start) + " ms"); - /**********************************************************************************/ - // 查询 - - - /**********************************************************************************/ - // 删除表 - if (config.dropTable) { - superTableService.drop(config.database, config.superTable); - } - System.exit(0); - } - - private static long getProperStartTime(long startTime, int keep) { - Instant now = Instant.now(); - long earliest = now.minus(Duration.ofDays(keep - 1)).toEpochMilli(); - if (startTime == 0 || startTime < earliest) { - startTime = earliest; - } - return startTime; - } - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/DataSourceFactory.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/DataSourceFactory.java deleted file mode 100644 index a7d08e96ea373c4773e872bcaf9b3a7b98d5bf9a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/DataSourceFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.taosdata.taosdemo.components; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.springframework.stereotype.Component; - -import javax.sql.DataSource; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -@Component -public class DataSourceFactory { - - private static DataSource instance; - - public static DataSource getInstance(String host, int port, String user, String password) throws IOException { - if (instance == null) { - synchronized (DataSourceFactory.class) { - if (instance == null) { - InputStream is = DataSourceFactory.class.getClassLoader().getResourceAsStream("application.properties"); - Properties properties = new Properties(); - properties.load(is); - - HikariConfig config = new HikariConfig(); - if (properties.containsKey("jdbc.driver")) { -// String driverName = properties.getProperty("jdbc.driver"); -// System.out.println(">>> load driver : " + driverName); -// try { -// Class.forName(driverName); -// } catch (ClassNotFoundException e) { -// e.printStackTrace(); -// } - config.setDriverClassName(properties.getProperty("jdbc.driver")); - } else { - config.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); - } - if ("com.taosdata.jdbc.rs.RestfulDriver".equalsIgnoreCase(properties.getProperty("jdbc.driver"))) - config.setJdbcUrl("jdbc:TAOS-RS://" + host + ":6041/?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8"); - else - config.setJdbcUrl("jdbc:TAOS://" + host + ":" + port + "/?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8"); - config.setUsername(user); - config.setPassword(password); - // maximum-pool-size - if (properties.containsKey("hikari.maximum-pool-size")) - config.setMaximumPoolSize(Integer.parseInt(properties.getProperty("hikari.maximum-pool-size"))); - else - config.setMaximumPoolSize(500); - // minimum-idle - if (properties.containsKey("hikari.minimum-idle")) - config.setMinimumIdle(Integer.parseInt(properties.getProperty("hikari.minimum-idle"))); - else - config.setMinimumIdle(100); - config.setMaxLifetime(0); - instance = new HikariDataSource(config); - } - } - } - return instance; - } - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/JdbcTaosdemoConfig.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/JdbcTaosdemoConfig.java deleted file mode 100644 index 974a2755a5a029d3a5fc681bc8c59b0aca1a7ca4..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/JdbcTaosdemoConfig.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.taosdata.taosdemo.components; - -import com.taosdata.taosdemo.utils.TimeStampUtil; - -public final class JdbcTaosdemoConfig { - // instance - public String host; //host - public int port = 6030; //port - public String user = "root"; //user - public String password = "taosdata"; //password - // database - public String database = "jdbcdb"; //database - public int keep = 3650; //keep - public int days = 30; //days - public int replica = 1; //replica - public int blocks = 16; - public int cache = 8; - public String precision = "ms"; - - //super table - public boolean doCreateTable = true; - public String superTable = "weather"; //super table name - public String prefixOfFields = "col"; - public int numOfFields; - public String prefixOfTags = "tag"; - public int numOfTags; - public String superTableSQL; - //sub table - public String prefixOfTable = "t"; - // insert task - public boolean autoCreateTable; - public long numOfTables = 10; - public long numOfRowsPerTable = 10; - public int numOfTablesPerSQL = 1; - public int numOfValuesPerSQL = 1; - public int numOfThreadsForCreate = 1; - public int numOfThreadsForInsert = 1; - public long startTime; - public long timeGap = 1; - public int frequency; - public int order; - public int rate = 10; - public long range = 1000l; - // select task - public String executeSql; - // drop task - public boolean dropTable = false; - - public static void printHelp() { - System.out.println("Usage: java -jar jdbc-taosdemo-2.0.jar [OPTION...]"); - // instance - System.out.println("-host The host to connect to TDengine which you must specify"); - System.out.println("-port The TCP/IP port number to use for the connection. Default is 6030"); - System.out.println("-user The TDengine user name to use when connecting to the server. Default is 'root'"); - System.out.println("-password The password to use when connecting to the server.Default is 'taosdata'"); - // database - System.out.println("-database Destination database. Default is 'jdbcdb'"); - System.out.println("-keep database keep parameter. Default is 3650"); - System.out.println("-days database days parameter. Default is 30"); - System.out.println("-replica database replica parameter. Default 1, min: 1, max: 3"); - System.out.println("-blocks database blocks parameter. Default is 16"); - System.out.println("-cache database cache parameter. Default is 8"); - System.out.println("-precision database precision parameter. Default is ms"); - - // super table - System.out.println("-doCreateTable do create super table and sub table, true or false, Default true"); - System.out.println("-superTable super table name. Default 'weather'"); - System.out.println("-prefixOfFields The prefix of field in super table. Default is 'col'"); - System.out.println("-numOfFields The number of field in super table. Default is (ts timestamp, temperature float, humidity int)."); - System.out.println("-prefixOfTags The prefix of tag in super table. Default is 'tag'"); - System.out.println("-numOfTags The number of tag in super table. Default is (location nchar(64), groupId int)."); - System.out.println("-superTableSQL specify a sql statement for the super table.\n" + - " Default is 'create table weather(ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int). \n" + - " if you use this parameter, the numOfFields and numOfTags will be invalid'"); - // sub table - System.out.println("-prefixOfTable The prefix of sub tables. Default is 't'"); - System.out.println("-numOfTables The number of tables. Default is 1"); - System.out.println("-numOfThreadsForCreate The number of thread during create sub table. Default is 1"); - // insert task - System.out.println("-autoCreateTable Use auto Create sub tables SQL. Default is false"); - System.out.println("-numOfRowsPerTable The number of records per table. Default is 1"); - System.out.println("-numOfThreadsForInsert The number of threads during insert row. Default is 1"); - System.out.println("-numOfTablesPerSQL The number of table per SQL. Default is 1"); - System.out.println("-numOfValuesPerSQL The number of value per SQL. Default is 1"); - System.out.println("-startTime start time for insert task, The format is \"yyyy-MM-dd HH:mm:ss.SSS\"."); - System.out.println("-timeGap the number of time gap. Default is 1000 ms"); - System.out.println("-frequency the number of records per second inserted into one table. default is 0, do not control frequency"); - System.out.println("-order Insert mode--0: In order, 1: Out of order. Default is in order"); - System.out.println("-rate The proportion of data out of order. effective only if order is 1. min 0, max 100, default is 10"); - System.out.println("-range The range of data out of order. effective only if order is 1. default is 1000 ms"); - // query task - System.out.println("-executeSql execute a specific sql."); - // drop task - System.out.println("-dropTable Drop data before quit. Default is false"); - System.out.println("--help Give this help list"); - } - - /** - * parse args from command line - * - * @param args command line args - * @return JdbcTaosdemoConfig - */ - public JdbcTaosdemoConfig(String[] args) { - for (int i = 0; i < args.length; i++) { - // instance - if ("-host".equals(args[i]) && i < args.length - 1) { - host = args[++i]; - } - if ("-port".equals(args[i]) && i < args.length - 1) { - port = Integer.parseInt(args[++i]); - } - if ("-user".equals(args[i]) && i < args.length - 1) { - user = args[++i]; - } - if ("-password".equals(args[i]) && i < args.length - 1) { - password = args[++i]; - } - // database - if ("-database".equals(args[i]) && i < args.length - 1) { - database = args[++i]; - } - if ("-keep".equals(args[i]) && i < args.length - 1) { - keep = Integer.parseInt(args[++i]); - } - if ("-days".equals(args[i]) && i < args.length - 1) { - days = Integer.parseInt(args[++i]); - } - if ("-replica".equals(args[i]) && i < args.length - 1) { - replica = Integer.parseInt(args[++i]); - } - if ("-blocks".equals(args[i]) && i < args.length - 1) { - blocks = Integer.parseInt(args[++i]); - } - if ("-cache".equals(args[i]) && i < args.length - 1) { - cache = Integer.parseInt(args[++i]); - } - if ("-precision".equals(args[i]) && i < args.length - 1) { - precision = args[++i]; - } - // super table - if ("-doCreateTable".equals(args[i]) && i < args.length - 1) { - doCreateTable = Boolean.parseBoolean(args[++i]); - } - if ("-superTable".equals(args[i]) && i < args.length - 1) { - superTable = args[++i]; - } - if ("-prefixOfFields".equals(args[i]) && i < args.length - 1) { - prefixOfFields = args[++i]; - } - if ("-numOfFields".equals(args[i]) && i < args.length - 1) { - numOfFields = Integer.parseInt(args[++i]); - } - if ("-prefixOfTags".equals(args[i]) && i < args.length - 1) { - prefixOfTags = args[++i]; - } - if ("-numOfTags".equals(args[i]) && i < args.length - 1) { - numOfTags = Integer.parseInt(args[++i]); - } - if ("-superTableSQL".equals(args[i]) && i < args.length - 1) { - superTableSQL = args[++i]; - } - // sub table - if ("-prefixOfTable".equals(args[i]) && i < args.length - 1) { - prefixOfTable = args[++i]; - } - if ("-numOfTables".equals(args[i]) && i < args.length - 1) { - numOfTables = Long.parseLong(args[++i]); - } - if ("-autoCreateTable".equals(args[i]) && i < args.length - 1) { - autoCreateTable = Boolean.parseBoolean(args[++i]); - } - if ("-numOfThreadsForCreate".equals(args[i]) && i < args.length - 1) { - numOfThreadsForCreate = Integer.parseInt(args[++i]); - } - // insert task - if ("-numOfRowsPerTable".equals(args[i]) && i < args.length - 1) { - numOfRowsPerTable = Long.parseLong(args[++i]); - } - if ("-numOfThreadsForInsert".equals(args[i]) && i < args.length - 1) { - numOfThreadsForInsert = Integer.parseInt(args[++i]); - } - if ("-numOfTablesPerSQL".equals(args[i]) && i < args.length - 1) { - numOfTablesPerSQL = Integer.parseInt(args[++i]); - } - if ("-numOfValuesPerSQL".equals(args[i]) && i < args.length - 1) { - numOfValuesPerSQL = Integer.parseInt(args[++i]); - } - if ("-startTime".equals(args[i]) && i < args.length - 1) { - startTime = TimeStampUtil.datetimeToLong(args[++i]); - } - if ("-timeGap".equals(args[i]) && i < args.length - 1) { - timeGap = Long.parseLong(args[++i]); - } - if ("-frequency".equals(args[i]) && i < args.length - 1) { - frequency = Integer.parseInt(args[++i]); - } - if ("-order".equals(args[i]) && i < args.length - 1) { - order = Integer.parseInt(args[++i]); - } - if ("-rate".equals(args[i]) && i < args.length - 1) { - rate = Integer.parseInt(args[++i]); - if (rate < 0 || rate > 100) - throw new IllegalArgumentException("rate must between 0 and 100"); - } - if ("-range".equals(args[i]) && i < args.length - 1) { - range = Integer.parseInt(args[++i]); - } - // select task - if ("-executeSql".equals(args[i]) && i < args.length - 1) { - executeSql = args[++i]; - } - - // drop task - if ("-dropTable".equals(args[i]) && i < args.length - 1) { - dropTable = Boolean.parseBoolean(args[++i]); - } - } - } - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/JsonConfig.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/JsonConfig.java deleted file mode 100644 index 1c44610095f4b383f82a74dfdc11030a28afb246..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/components/JsonConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.taosdata.taosdemo.components; - -import com.alibaba.fastjson.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class JsonConfig { - - public static void main(String[] args) { - - JsonConfig config = new JsonConfig(); - String str = config.read("insert.json"); - JSONObject jsonObject = JSONObject.parseObject(str); - System.out.println(jsonObject); - - } - - private String read(String fileName) { - try { - BufferedReader reader = new BufferedReader( - new InputStreamReader(JsonConfig.class.getClassLoader().getResourceAsStream(fileName)) - ); - StringBuilder sb = new StringBuilder(); - String line = null; - while ((line = reader.readLine()) != null) { - sb.append(line); - } - return sb.toString(); - } catch (IOException e) { - e.printStackTrace(); - } - - return fileName; - } - - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/DatabaseMapper.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/DatabaseMapper.java deleted file mode 100644 index 56e38d2bfce8ba5801d0f8dc48093d198852fbca..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/DatabaseMapper.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import java.util.Map; - -public interface DatabaseMapper { - - // create database if not exists XXX - void createDatabase(String dbname); - - // drop database if exists XXX - void dropDatabase(String dbname); - - // create database if not exists XXX keep XX days XX replica XX - void createDatabaseWithParameters(Map map); - - // use XXX - void useDatabase(String dbname); - - //TODO: alter database - - //TODO: show database - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/DatabaseMapperImpl.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/DatabaseMapperImpl.java deleted file mode 100644 index 9340fc3fdd0ce7242d4121a5fb259af48f7ada5f..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/DatabaseMapperImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.utils.SqlSpeller; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.sql.DataSource; -import java.util.Map; - -public class DatabaseMapperImpl implements DatabaseMapper { - private static final Logger logger = LogManager.getLogger(DatabaseMapperImpl.class); - - private final JdbcTemplate jdbcTemplate; - - public DatabaseMapperImpl(DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - @Override - public void createDatabase(String dbname) { - String sql = "create database if not exists " + dbname; - jdbcTemplate.execute(sql); - logger.debug("SQL >>> " + sql); - } - - @Override - public void dropDatabase(String dbname) { - String sql = "drop database if exists " + dbname; - jdbcTemplate.update(sql); - logger.debug("SQL >>> " + sql); - } - - @Override - public void createDatabaseWithParameters(Map map) { - String sql = SqlSpeller.createDatabase(map); - jdbcTemplate.execute(sql); - logger.debug("SQL >>> " + sql); - } - - @Override - public void useDatabase(String dbname) { - String sql = "use " + dbname; - jdbcTemplate.execute(sql); - logger.debug("SQL >>> " + sql); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SubTableMapper.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SubTableMapper.java deleted file mode 100644 index e0ddd220c19066afd1cc332f007a82e2fdab2b07..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SubTableMapper.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.domain.SubTableMeta; -import com.taosdata.taosdemo.domain.SubTableValue; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface SubTableMapper { - - // 创建:子表 - void createUsingSuperTable(SubTableMeta subTableMeta); - - // 插入:一张子表多个values - int insertOneTableMultiValues(SubTableValue subTableValue); - - // 插入:一张子表多个values, 自动建表 - int insertOneTableMultiValuesUsingSuperTable(SubTableValue subTableValue); - - // 插入:多张表多个values - int insertMultiTableMultiValues(List tables); - - // 插入:多张表多个values,自动建表 - int insertMultiTableMultiValuesUsingSuperTable(List tables); - - // - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SubTableMapperImpl.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SubTableMapperImpl.java deleted file mode 100644 index db0d43ff05a56b673ed08a522b645d3388f8e091..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SubTableMapperImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.domain.SubTableMeta; -import com.taosdata.taosdemo.domain.SubTableValue; -import com.taosdata.taosdemo.utils.SqlSpeller; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.sql.DataSource; -import java.util.List; - -public class SubTableMapperImpl implements SubTableMapper { - - private static final Logger logger = LogManager.getLogger(SubTableMapperImpl.class); - private final JdbcTemplate jdbcTemplate; - - public SubTableMapperImpl(DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Override - public void createUsingSuperTable(SubTableMeta subTableMeta) { - String sql = SqlSpeller.createTableUsingSuperTable(subTableMeta); - logger.debug("SQL >>> " + sql); - jdbcTemplate.execute(sql); - } - - @Override - public int insertOneTableMultiValues(SubTableValue subTableValue) { - String sql = SqlSpeller.insertOneTableMultiValues(subTableValue); - logger.debug("SQL >>> " + sql); - - int affectRows = 0; - try { - affectRows = jdbcTemplate.update(sql); - } catch (Exception e) { - e.printStackTrace(); - } - return affectRows; - } - - @Override - public int insertOneTableMultiValuesUsingSuperTable(SubTableValue subTableValue) { - String sql = SqlSpeller.insertOneTableMultiValuesUsingSuperTable(subTableValue); - logger.debug("SQL >>> " + sql); - - int affectRows = 0; - try { - affectRows = jdbcTemplate.update(sql); - } catch (Exception e) { - e.printStackTrace(); - } - return affectRows; - } - - @Override - public int insertMultiTableMultiValues(List tables) { - String sql = SqlSpeller.insertMultiSubTableMultiValues(tables); - logger.debug("SQL >>> " + sql); - int affectRows = 0; - try { - affectRows = jdbcTemplate.update(sql); - } catch (Exception e) { - e.printStackTrace(); - } - return affectRows; - } - - @Override - public int insertMultiTableMultiValuesUsingSuperTable(List tables) { - String sql = SqlSpeller.insertMultiTableMultiValuesUsingSuperTable(tables); - logger.debug("SQL >>> " + sql); - int affectRows = 0; - try { - affectRows = jdbcTemplate.update(sql); - } catch (Exception e) { - e.printStackTrace(); - } - return affectRows; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SuperTableMapper.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SuperTableMapper.java deleted file mode 100644 index 9f8cec9e8fa5af8741d9efbdce72f240aa7a09aa..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SuperTableMapper.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.domain.SuperTableMeta; -import org.springframework.stereotype.Repository; - -@Repository -public interface SuperTableMapper { - - // 创建超级表 create table if not exists xxx.xxx (f1 type1, f2 type2, ... ) tags( t1 type1, t2 type2 ...) - void createSuperTable(SuperTableMeta tableMetadata); - - // 删除超级表 drop table if exists xxx; - void dropSuperTable(String database, String name); - - // - - // - - // - - // - - // - - // - - // - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SuperTableMapperImpl.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SuperTableMapperImpl.java deleted file mode 100644 index 658a403a0ca3883831bca1ad2b6d579ef4713f7d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/SuperTableMapperImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.utils.SqlSpeller; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.sql.DataSource; - -public class SuperTableMapperImpl implements SuperTableMapper { - private static final Logger logger = LogManager.getLogger(SuperTableMapperImpl.class); - private JdbcTemplate jdbcTemplate; - - public SuperTableMapperImpl(DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Override - public void createSuperTable(SuperTableMeta tableMetadata) { - String sql = SqlSpeller.createSuperTable(tableMetadata); - logger.debug("SQL >>> " + sql); - jdbcTemplate.execute(sql); - } - - @Override - public void dropSuperTable(String database, String name) { - String sql = "drop table if exists " + database + "." + name; - logger.debug("SQL >>> " + sql); - jdbcTemplate.execute(sql); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/TableMapper.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/TableMapper.java deleted file mode 100644 index 32d1875e4d1a82f7dfb658d68ed0e63a5cbfa040..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/TableMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.domain.TableMeta; -import com.taosdata.taosdemo.domain.TableValue; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface TableMapper { - - // 创建:普通表 - void create(TableMeta tableMeta); - - // 插入:一张表多个value - int insertOneTableMultiValues(TableValue values); - - // 插入: 一张表多个value,指定的列 - int insertOneTableMultiValuesWithColumns(TableValue values); - - // 插入:多个表多个value - int insertMultiTableMultiValues(List tables); - - // 插入:多个表多个value, 指定的列 - int insertMultiTableMultiValuesWithColumns(List tables); - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/TableMapperImpl.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/TableMapperImpl.java deleted file mode 100644 index 16bc094848f6ff585e826bf3181cc4e8c03ee822..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/dao/TableMapperImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.taosdata.taosdemo.dao; - -import com.taosdata.taosdemo.domain.TableMeta; -import com.taosdata.taosdemo.domain.TableValue; -import com.taosdata.taosdemo.utils.SqlSpeller; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.util.List; - -public class TableMapperImpl implements TableMapper { - private static final Logger logger = LogManager.getLogger(TableMapperImpl.class); - private JdbcTemplate template; - - @Override - public void create(TableMeta tableMeta) { - String sql = SqlSpeller.createTable(tableMeta); - logger.debug("SQL >>> " + sql); - template.execute(sql); - } - - @Override - public int insertOneTableMultiValues(TableValue values) { - String sql = SqlSpeller.insertOneTableMultiValues(values); - logger.debug("SQL >>> " + sql); - return template.update(sql); - } - - @Override - public int insertOneTableMultiValuesWithColumns(TableValue values) { - String sql = SqlSpeller.insertOneTableMultiValuesWithColumns(values); - logger.debug("SQL >>> " + sql); - return template.update(sql); - } - - @Override - public int insertMultiTableMultiValues(List tables) { - String sql = SqlSpeller.insertMultiTableMultiValues(tables); - logger.debug("SQL >>> " + sql); - return template.update(sql); - } - - @Override - public int insertMultiTableMultiValuesWithColumns(List tables) { - String sql = SqlSpeller.insertMultiTableMultiValuesWithColumns(tables); - logger.debug("SQL >>> " + sql); - return template.update(sql); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/FieldMeta.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/FieldMeta.java deleted file mode 100644 index 8a45e99989821562fdf9333b90a2972388cf6003..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/FieldMeta.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -@Data -public class FieldMeta { - private String name; - private String type; - - public FieldMeta() { - } - - public FieldMeta(String name, String type) { - this.name = name; - this.type = type; - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/FieldValue.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/FieldValue.java deleted file mode 100644 index 44805c0d7c2f4e0df60d723afd598f2aa788ee65..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/FieldValue.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -@Data -public class FieldValue { - private String name; - private T value; - - public FieldValue() { - } - - public FieldValue(String name, T value) { - this.name = name; - this.value = value; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/RowValue.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/RowValue.java deleted file mode 100644 index a444fa78dcdeb8f1bb76974a29051c98348a055b..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/RowValue.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -import java.util.List; - -@Data -public class RowValue { - private List fields; - - public RowValue(List fields) { - this.fields = fields; - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SubTableMeta.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SubTableMeta.java deleted file mode 100644 index 81de882448121532a3c840296702d1fb24c37326..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SubTableMeta.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -import java.util.List; - -@Data -public class SubTableMeta { - - private String database; - private String supertable; - private String name; - private List tags; - private List fields; -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SubTableValue.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SubTableValue.java deleted file mode 100644 index 74fb9598bc8e920123180f948b88fb98baf9218e..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SubTableValue.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -import java.util.List; - -@Data -public class SubTableValue { - - private String database; - private String supertable; - private String name; - private List tags; - private List values; -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SuperTableMeta.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SuperTableMeta.java deleted file mode 100644 index c5c65a4599b776faeead19ffbf065361b293b44b..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/SuperTableMeta.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -import java.util.List; - -@Data -public class SuperTableMeta { - - private String database; - private String name; - private List fields; - private List tags; -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TableMeta.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TableMeta.java deleted file mode 100644 index 3ab0a75c0b8ddda46f016c93e0a4893ff1ef21fa..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TableMeta.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -import java.util.List; - -@Data -public class TableMeta { - - private String database; - private String name; - private List fields; -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TableValue.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TableValue.java deleted file mode 100644 index d5502aa46f3508d2f6dcc3668e741adde5b0a4f0..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TableValue.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -import java.util.List; - -@Data -public class TableValue { - - private String database; - private String name; - private List columns; - private List values; - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TagMeta.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TagMeta.java deleted file mode 100644 index a385bb4e125e46fe37c1f9542817a4d81301d72f..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TagMeta.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -@Data -public class TagMeta { - private String name; - private String type; - - public TagMeta() { - - } - - public TagMeta(String name, String type) { - this.name = name; - this.type = type; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TagValue.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TagValue.java deleted file mode 100644 index 98ea8c0dc97ebfd330c57f8852eaf2fa379aef50..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/domain/TagValue.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.taosdata.taosdemo.domain; - -import lombok.Data; - -@Data -public class TagValue { - private String name; - private T value; - - public TagValue() { - } - - public TagValue(String name, T value) { - this.name = name; - this.value = value; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/AbstractService.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/AbstractService.java deleted file mode 100644 index 4afbe9dae82516e050eb7d729d6ecb8eb1e59d6b..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/AbstractService.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.taosdata.taosdemo.service; - -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -public class AbstractService { - - protected int getAffectRows(List> futureList) { - int count = 0; - for (Future future : futureList) { - try { - count += future.get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - return count; - } - - protected int getAffectRows(Future future) { - int count = 0; - try { - count += future.get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - return count; - } - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/DatabaseService.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/DatabaseService.java deleted file mode 100644 index 3c8e9624066bf629a74ebcaa3959a2e15338c363..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/DatabaseService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.dao.DatabaseMapper; -import com.taosdata.taosdemo.dao.DatabaseMapperImpl; - -import javax.sql.DataSource; -import java.util.Map; - -public class DatabaseService { - - private final DatabaseMapper databaseMapper; - - public DatabaseService(DataSource dataSource) { - this.databaseMapper = new DatabaseMapperImpl(dataSource); - } - - // 建库,指定 name - public void createDatabase(String database) { - databaseMapper.createDatabase(database); - } - - // 建库,指定参数 keep,days,replica等 - public void createDatabase(Map map) { - if (map.isEmpty()) - return; - if (map.containsKey("database") && map.size() == 1) { - createDatabase(map.get("database")); - return; - } - databaseMapper.createDatabaseWithParameters(map); - } - - // drop database - public void dropDatabase(String dbname) { - databaseMapper.dropDatabase(dbname); - } - - // use database - public void useDatabase(String dbname) { - databaseMapper.useDatabase(dbname); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/QueryService.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/QueryService.java deleted file mode 100644 index efabff6afe904516ad9682cd7197412dc02765ef..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/QueryService.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.jdbc.utils.SqlSyntaxValidator; - -import javax.sql.DataSource; -import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class QueryService { - - private final DataSource dataSource; - - public QueryService(DataSource dataSource) { - this.dataSource = dataSource; - } - - /* only select or show SQL Statement is valid for executeQuery */ - public Boolean[] areValidQueries(String[] sqls) { - Boolean[] ret = new Boolean[sqls.length]; - for (int i = 0; i < sqls.length; i++) { - ret[i] = true; - if (!SqlSyntaxValidator.isValidForExecuteQuery(sqls[i])) { - ret[i] = false; - continue; - } - try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) { - stmt.executeQuery(sqls[i]); - } catch (SQLException e) { - ret[i] = false; - continue; - } - } - return ret; - } - - public String[] generateSuperTableQueries(String dbName) { - List sqls = new ArrayList<>(); - try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) { - stmt.execute("use " + dbName); - ResultSet rs = stmt.executeQuery("show stables"); - while (rs.next()) { - String name = rs.getString("name"); - sqls.add("select count(*) from " + dbName + "." + name); - sqls.add("select first(*) from " + dbName + "." + name); - sqls.add("select last(*) from " + dbName + "." + name); - sqls.add("select last_row(*) from " + dbName + "." + name); - } - } catch (SQLException e) { - e.printStackTrace(); - } - String[] sqlArr = new String[sqls.size()]; - return sqls.toArray(sqlArr); - } - - public void querySuperTable(String[] sqls, int interval, int threadCount, long queryTimes) { - List threads = IntStream.range(0, threadCount).mapToObj(i -> new Thread(() -> { - // do query - try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) { - long count = queryTimes; - if (count == 0) - count = Long.MAX_VALUE; - while (count > 0) { - for (String sql : sqls) { - long start = System.currentTimeMillis(); - ResultSet rs = stmt.executeQuery(sql); - printResultSet(rs); - long end = System.currentTimeMillis(); - long timecost = end - start; - if (interval - timecost > 0) { - TimeUnit.MILLISECONDS.sleep(interval - timecost); - } - } - count--; - } - - } catch (SQLException | InterruptedException e) { - e.printStackTrace(); - } - - })).collect(Collectors.toList()); - threads.stream().forEach(Thread::start); - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - private void printResultSet(ResultSet rs) throws SQLException { - ResultSetMetaData meta = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= meta.getColumnCount(); i++) { - System.out.print(meta.getColumnLabel(i) + ": " + rs.getString(i) + "\t"); - } - System.out.println(); - } - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SqlExecuteTask.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SqlExecuteTask.java deleted file mode 100644 index ff2e4d0af068a10e62933837817d2d2df0712a4c..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SqlExecuteTask.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.utils.Printer; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -public class SqlExecuteTask implements Runnable { - private final DataSource dataSource; - private final String sql; - - public SqlExecuteTask(DataSource dataSource, String sql) { - this.dataSource = dataSource; - this.sql = sql; - } - - @Override - public void run() { - try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) { - long start = System.currentTimeMillis(); - boolean execute = stmt.execute(sql); - long end = System.currentTimeMillis(); - if (execute) { - ResultSet rs = stmt.getResultSet(); - Printer.printResult(rs); - } else { - Printer.printSql(sql, true, (end - start)); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SubTableService.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SubTableService.java deleted file mode 100644 index b0a79dea78f429d85804bae4cb0bbec9e712ec1a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SubTableService.java +++ /dev/null @@ -1,209 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.components.JdbcTaosdemoConfig; -import com.taosdata.taosdemo.dao.SubTableMapper; -import com.taosdata.taosdemo.dao.SubTableMapperImpl; -import com.taosdata.taosdemo.domain.SubTableMeta; -import com.taosdata.taosdemo.domain.SubTableValue; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.service.data.SubTableMetaGenerator; -import com.taosdata.taosdemo.service.data.SubTableValueGenerator; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import javax.sql.DataSource; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.*; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class SubTableService extends AbstractService { - - private SubTableMapper mapper; - private static final Logger logger = LogManager.getLogger(SubTableService.class); - - public SubTableService(DataSource datasource) { - this.mapper = new SubTableMapperImpl(datasource); - } - - public void createSubTable(SuperTableMeta superTableMeta, long numOfTables, String prefixOfTable, int numOfThreadsForCreate) { - ExecutorService executor = Executors.newFixedThreadPool(numOfThreadsForCreate); - for (long i = 0; i < numOfTables; i++) { - long tableIndex = i; - executor.execute(() -> createSubTable(superTableMeta, prefixOfTable + (tableIndex + 1))); - } - executor.shutdown(); - try { - executor.awaitTermination(Long.MAX_VALUE,TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public void createSubTable(SuperTableMeta superTableMeta, String tableName) { - // 构造数据 - SubTableMeta meta = SubTableMetaGenerator.generate(superTableMeta, tableName); - createSubTable(meta); - } - - // 创建一张子表,可以指定database,supertable,tablename,tag值 - public void createSubTable(SubTableMeta subTableMeta) { - mapper.createUsingSuperTable(subTableMeta); - } - - /*************************************************************************************************************************/ - // 插入:多线程,多表 - public int insert(List subTableValues, int threadSize, int frequency) { - ExecutorService executor = Executors.newFixedThreadPool(threadSize); - Future future = executor.submit(() -> insert(subTableValues)); - executor.shutdown(); - //TODO:frequency - return getAffectRows(future); - } - - // 插入:单表,insert into xxx values(),()... - public int insert(SubTableValue subTableValue) { - return mapper.insertOneTableMultiValues(subTableValue); - } - - // 插入: 多表,insert into xxx values(),()... xxx values(),()... - public int insert(List subTableValues) { - return mapper.insertMultiTableMultiValues(subTableValues); - } - - // 插入:单表,自动建表, insert into xxx using xxx tags(...) values(),()... - public int insertAutoCreateTable(SubTableValue subTableValue) { - return mapper.insertOneTableMultiValuesUsingSuperTable(subTableValue); - } - - // 插入:多表,自动建表, insert into xxx using XXX tags(...) values(),()... xxx using XXX tags(...) values(),()... - public int insertAutoCreateTable(List subTableValues) { - return mapper.insertMultiTableMultiValuesUsingSuperTable(subTableValues); - } - - public int insertMultiThreads(SuperTableMeta superTableMeta, int threadSize, long tableSize, long startTime, long gap, JdbcTaosdemoConfig config) { - List taskList = new ArrayList<>(); - List threads = IntStream.range(0, threadSize) - .mapToObj(i -> { - long startInd = i * gap; - long endInd = (i + 1) * gap < tableSize ? (i + 1) * gap : tableSize; - FutureTask task = new FutureTask<>( - new InsertTask(superTableMeta, - startInd, endInd, - startTime, config.timeGap, - config.numOfRowsPerTable, config.numOfTablesPerSQL, config.numOfValuesPerSQL, - config.order, config.rate, config.range, - config.prefixOfTable, config.autoCreateTable) - ); - taskList.add(task); - return new Thread(task, "InsertThread-" + i); - }).collect(Collectors.toList()); - - threads.stream().forEach(Thread::start); - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - int affectedRows = 0; - for (FutureTask task : taskList) { - try { - affectedRows += task.get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - - return affectedRows; - } - - private class InsertTask implements Callable { - - private final long startTableInd; // included - private final long endTableInd; // excluded - private final long startTime; - private final long timeGap; - private final long numOfRowsPerTable; - private long numOfTablesPerSQL; - private long numOfValuesPerSQL; - private final SuperTableMeta superTableMeta; - private final int order; - private final int rate; - private final long range; - private final String prefixOfTable; - private final boolean autoCreateTable; - - public InsertTask(SuperTableMeta superTableMeta, long startTableInd, long endTableInd, - long startTime, long timeGap, - long numOfRowsPerTable, long numOfTablesPerSQL, long numOfValuesPerSQL, - int order, int rate, long range, - String prefixOfTable, boolean autoCreateTable) { - this.superTableMeta = superTableMeta; - this.startTableInd = startTableInd; - this.endTableInd = endTableInd; - this.startTime = startTime; - this.timeGap = timeGap; - this.numOfRowsPerTable = numOfRowsPerTable; - this.numOfTablesPerSQL = numOfTablesPerSQL; - this.numOfValuesPerSQL = numOfValuesPerSQL; - this.order = order; - this.rate = rate; - this.range = range; - this.prefixOfTable = prefixOfTable; - this.autoCreateTable = autoCreateTable; - } - - - @Override - public Integer call() { - - long numOfTables = endTableInd - startTableInd; - if (numOfRowsPerTable < numOfValuesPerSQL) - numOfValuesPerSQL = (int) numOfRowsPerTable; - if (numOfTables < numOfTablesPerSQL) - numOfTablesPerSQL = (int) numOfTables; - - int affectRows = 0; - // row - for (long rowCnt = 0; rowCnt < numOfRowsPerTable; ) { - long rowSize = numOfValuesPerSQL; - if (rowCnt + rowSize > numOfRowsPerTable) { - rowSize = numOfRowsPerTable - rowCnt; - } - //table - for (long tableCnt = startTableInd; tableCnt < endTableInd; ) { - long tableSize = numOfTablesPerSQL; - if (tableCnt + tableSize > endTableInd) { - tableSize = endTableInd - tableCnt; - } - long startTime = this.startTime + rowCnt * timeGap; -// System.out.println(Thread.currentThread().getName() + " >>> " + "rowCnt: " + rowCnt + ", rowSize: " + rowSize + ", " + "tableCnt: " + tableCnt + ",tableSize: " + tableSize + ", " + "startTime: " + startTime + ",timeGap: " + timeGap + ""); - /***********************************************/ - // 生成数据 - List data = SubTableValueGenerator.generate(superTableMeta, prefixOfTable, tableCnt, tableSize, rowSize, startTime, timeGap); - // 乱序 - if (order != 0) - SubTableValueGenerator.disrupt(data, rate, range); - // insert - if (autoCreateTable) - affectRows += insertAutoCreateTable(data); - else - affectRows += insert(data); - /***********************************************/ - tableCnt += tableSize; - } - rowCnt += rowSize; - } - - return affectRows; - } - } - - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SuperTableService.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SuperTableService.java deleted file mode 100644 index b91348e2d008bc1ac32faffc5912a8509adf42bd..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/SuperTableService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.dao.SuperTableMapper; -import com.taosdata.taosdemo.dao.SuperTableMapperImpl; -import com.taosdata.taosdemo.domain.SuperTableMeta; - -import javax.sql.DataSource; - -public class SuperTableService { - - private SuperTableMapper superTableMapper; - - public SuperTableService(DataSource dataSource) { - this.superTableMapper = new SuperTableMapperImpl(dataSource); - } - - // 创建超级表,指定每个field的名称和类型,每个tag的名称和类型 - public void create(SuperTableMeta superTableMeta) { - superTableMapper.createSuperTable(superTableMeta); - } - - public void drop(String database, String name) { - superTableMapper.dropSuperTable(database, name); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/TableService.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/TableService.java deleted file mode 100644 index 2504fdb0b4cd48ec263d94ec377e1bb8902ea9a7..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/TableService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.dao.TableMapper; -import com.taosdata.taosdemo.domain.TableMeta; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class TableService extends AbstractService { - - private TableMapper tableMapper; - - //创建一张表 - public void create(TableMeta tableMeta) { - tableMapper.create(tableMeta); - } - - //创建多张表 - public void create(List tables) { - tables.stream().forEach(this::create); - } - - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/FieldValueGenerator.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/FieldValueGenerator.java deleted file mode 100644 index 73cd981a4651bf589d636b8f57c0af44979f09f1..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/FieldValueGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.FieldMeta; -import com.taosdata.taosdemo.domain.FieldValue; -import com.taosdata.taosdemo.domain.RowValue; -import com.taosdata.taosdemo.utils.DataGenerator; - -import java.util.*; - -public class FieldValueGenerator { - - public static Random random = new Random(System.currentTimeMillis()); - - // 生成start到end的时间序列,时间戳为顺序,不含有乱序,field的value为随机生成 - public static List generate(long start, long end, long timeGap, List fieldMetaList) { - List values = new ArrayList<>(); - - for (long ts = start; ts < end; ts += timeGap) { - List fieldValues = new ArrayList<>(); - // timestamp - fieldValues.add(new FieldValue(fieldMetaList.get(0).getName(), ts)); - // other values - for (int fieldInd = 1; fieldInd < fieldMetaList.size(); fieldInd++) { - FieldMeta fieldMeta = fieldMetaList.get(fieldInd); - fieldValues.add(new FieldValue(fieldMeta.getName(), DataGenerator.randomValue(fieldMeta.getType()))); - } - values.add(new RowValue(fieldValues)); - } - return values; - } - - // 生成start到end的时间序列,时间戳为顺序,含有乱序,rate为乱序的比例,range为乱序前跳范围,field的value为随机生成 - public static List disrupt(List values, int rate, long range) { - long timeGap = (long) (values.get(1).getFields().get(0).getValue()) - (long) (values.get(0).getFields().get(0).getValue()); - int bugSize = values.size() * rate / 100; - Set bugIndSet = new HashSet<>(); - while (bugIndSet.size() < bugSize) { - bugIndSet.add(random.nextInt(values.size())); - } - for (Integer bugInd : bugIndSet) { - Long timestamp = (Long) values.get(bugInd).getFields().get(0).getValue(); - Long newTimestamp = timestamp - timeGap - random.nextInt((int) range); - values.get(bugInd).getFields().get(0).setValue(newTimestamp); - } - - return values; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SubTableMetaGenerator.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SubTableMetaGenerator.java deleted file mode 100644 index 88e3c0d26a5a7558c1c07f0fc38ae21710438dbe..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SubTableMetaGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.SubTableMeta; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.domain.TagValue; - -import java.util.ArrayList; -import java.util.List; - -public class SubTableMetaGenerator { - - // 创建tableSize张子表,使用tablePrefix作为子表名的前缀,使用superTableMeta的元数据 - // create table xxx using XXX tags(XXX) - public static List generate(SuperTableMeta superTableMeta, int tableSize, String tablePrefix) { - List subTableMetaList = new ArrayList<>(); - for (int i = 1; i <= tableSize; i++) { - SubTableMeta subTableMeta = new SubTableMeta(); - // create table xxx.xxx using xxx tags(...) - subTableMeta.setDatabase(superTableMeta.getDatabase()); - subTableMeta.setName(tablePrefix + i); - subTableMeta.setSupertable(superTableMeta.getName()); - subTableMeta.setFields(superTableMeta.getFields()); - List tagValues = TagValueGenerator.generate(superTableMeta.getTags()); - subTableMeta.setTags(tagValues); - subTableMetaList.add(subTableMeta); - } - return subTableMetaList; - } - - public static SubTableMeta generate(SuperTableMeta superTableMeta, String tableName) { - SubTableMeta subTableMeta = new SubTableMeta(); - // create table xxx.xxx using xxx tags(...) - subTableMeta.setDatabase(superTableMeta.getDatabase()); - subTableMeta.setName(tableName); - subTableMeta.setSupertable(superTableMeta.getName()); - subTableMeta.setFields(superTableMeta.getFields()); - List tagValues = TagValueGenerator.generate(superTableMeta.getTags()); - subTableMeta.setTags(tagValues); - return subTableMeta; - } - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SubTableValueGenerator.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SubTableValueGenerator.java deleted file mode 100644 index 8c318dbd3abf2ddfec8b51e83f32246421c49d51..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SubTableValueGenerator.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.*; -import com.taosdata.taosdemo.utils.TimeStampUtil; -import org.springframework.beans.BeanUtils; - -import java.util.ArrayList; -import java.util.List; - -public class SubTableValueGenerator { - - public static List generate(SuperTableMeta superTableMeta, String prefixOfTables, long tableIndex, long tableSize, long valueSize, long startTime, long timeGap) { - List subTableValues = new ArrayList<>(); - for (int i = 1; i <= tableSize; i++) { - SubTableValue subTableValue = new SubTableValue(); - subTableValue.setDatabase(superTableMeta.getDatabase()); - subTableValue.setName(prefixOfTables + (tableIndex + i)); - subTableValue.setSupertable(superTableMeta.getName()); - TimeStampUtil.TimeTuple tuple = TimeStampUtil.range(startTime, timeGap, valueSize); - List tags = TagValueGenerator.generate(superTableMeta.getTags()); - subTableValue.setTags(tags); - List values = FieldValueGenerator.generate(tuple.start, tuple.end, tuple.timeGap, superTableMeta.getFields()); - subTableValue.setValues(values); - - subTableValues.add(subTableValue); - } - return subTableValues; - } - - public static List generate(List subTableMetaList, int numOfRowsPerTable, long start, long timeGap) { - return generate(subTableMetaList, 0, subTableMetaList.size(), numOfRowsPerTable, start, timeGap); - } - - public static void disrupt(List subTableValueList, int rate, long range) { - subTableValueList.stream().forEach((tableValue) -> { - List values = tableValue.getValues(); - FieldValueGenerator.disrupt(values, rate, range); - }); - } - - public static List> split(List subTableValueList, int numOfTables, int numOfTablesPerSQL, int numOfRowsPerTable, int numOfValuesPerSQL) { - List> dataList = new ArrayList<>(); - if (numOfRowsPerTable < numOfValuesPerSQL) - numOfValuesPerSQL = numOfRowsPerTable; - if (numOfTables < numOfTablesPerSQL) - numOfTablesPerSQL = numOfTables; - //table - for (int tableCnt = 0; tableCnt < numOfTables; ) { - int tableSize = numOfTablesPerSQL; - if (tableCnt + tableSize > numOfTables) { - tableSize = numOfTables - tableCnt; - } - // row - for (int rowCnt = 0; rowCnt < numOfRowsPerTable; ) { - int rowSize = numOfValuesPerSQL; - if (rowCnt + rowSize > numOfRowsPerTable) { - rowSize = numOfRowsPerTable - rowCnt; - } - // System.out.println("rowCnt: " + rowCnt + ", rowSize: " + rowSize + ", tableCnt: " + tableCnt + ", tableSize: " + tableSize); - // split - List blocks = subTableValueList.subList(tableCnt, tableCnt + tableSize); - List newBlocks = new ArrayList<>(); - for (int i = 0; i < blocks.size(); i++) { - SubTableValue subTableValue = blocks.get(i); - SubTableValue newSubTableValue = new SubTableValue(); - BeanUtils.copyProperties(subTableValue, newSubTableValue); - List values = subTableValue.getValues().subList(rowCnt, rowCnt + rowSize); - newSubTableValue.setValues(values); - newBlocks.add(newSubTableValue); - } - dataList.add(newBlocks); - - rowCnt += rowSize; - } - tableCnt += tableSize; - } - return dataList; - } - - public static void main(String[] args) { - split(null, 99, 10, 99, 10); - } - - public static List generate(List subTableMetaList, int tableCnt, int tableSize, int rowSize, long startTime, long timeGap) { - List subTableValueList = new ArrayList<>(); - for (int i = 0; i < tableSize; i++) { - SubTableMeta subTableMeta = subTableMetaList.get(tableCnt + i); - SubTableValue subTableValue = new SubTableValue(); - subTableValue.setDatabase(subTableMeta.getDatabase()); - subTableValue.setName(subTableMeta.getName()); - subTableValue.setSupertable(subTableMeta.getSupertable()); - subTableValue.setTags(subTableMeta.getTags()); - TimeStampUtil.TimeTuple tuple = TimeStampUtil.range(startTime, timeGap, rowSize); - List values = FieldValueGenerator.generate(tuple.start, tuple.end, tuple.timeGap, subTableMeta.getFields()); - subTableValue.setValues(values); - subTableValueList.add(subTableValue); - } - return subTableValueList; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SuperTableMetaGenerator.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SuperTableMetaGenerator.java deleted file mode 100644 index 05aefd01ac8ef5c0bd2d4952e16f557ee7aef8ce..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/SuperTableMetaGenerator.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.FieldMeta; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.domain.TagMeta; -import com.taosdata.taosdemo.utils.TaosConstants; - -import java.util.ArrayList; -import java.util.List; - -public class SuperTableMetaGenerator { - - // 创建超级表,使用指定SQL语句 - public static SuperTableMeta generate(String superTableSQL) { - SuperTableMeta tableMeta = new SuperTableMeta(); - // for example : create table superTable (ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int) - superTableSQL = superTableSQL.trim().toLowerCase(); - if (!superTableSQL.startsWith("create")) - throw new RuntimeException("invalid create super table SQL"); - - if (superTableSQL.contains("tags")) { - String tagSQL = superTableSQL.substring(superTableSQL.indexOf("tags") + 4).trim(); - tagSQL = tagSQL.substring(tagSQL.indexOf("(") + 1, tagSQL.lastIndexOf(")")); - String[] tagPairs = tagSQL.split(","); - List tagMetaList = new ArrayList<>(); - for (String tagPair : tagPairs) { - String name = tagPair.trim().split("\\s+")[0]; - String type = tagPair.trim().split("\\s+")[1]; - tagMetaList.add(new TagMeta(name, type)); - } - tableMeta.setTags(tagMetaList); - superTableSQL = superTableSQL.substring(0, superTableSQL.indexOf("tags")); - } - if (superTableSQL.contains("(")) { - String fieldSQL = superTableSQL.substring(superTableSQL.indexOf("(") + 1, superTableSQL.indexOf(")")); - String[] fieldPairs = fieldSQL.split(","); - List fieldList = new ArrayList<>(); - for (String fieldPair : fieldPairs) { - String name = fieldPair.trim().split("\\s+")[0]; - String type = fieldPair.trim().split("\\s+")[1]; - fieldList.add(new FieldMeta(name, type)); - } - tableMeta.setFields(fieldList); - superTableSQL = superTableSQL.substring(0, superTableSQL.indexOf("(")); - } - superTableSQL = superTableSQL.substring(superTableSQL.indexOf("table") + 5).trim(); - if (superTableSQL.contains(".")) { - String database = superTableSQL.split("\\.")[0]; - tableMeta.setDatabase(database); - superTableSQL = superTableSQL.substring(superTableSQL.indexOf(".") + 1); - } - tableMeta.setName(superTableSQL.trim()); - - return tableMeta; - } - - // 创建超级表,指定field和tag的个数 - public static SuperTableMeta generate(String database, String name, int fieldSize, String fieldPrefix, int tagSize, String tagPrefix) { - if (fieldSize < 2 || tagSize < 1) { - throw new RuntimeException("create super table but fieldSize less than 2 or tagSize less than 1"); - } - SuperTableMeta tableMetadata = new SuperTableMeta(); - tableMetadata.setDatabase(database); - tableMetadata.setName(name); - // fields - List fields = new ArrayList<>(); - fields.add(new FieldMeta("ts", "timestamp")); - for (int i = 1; i <= fieldSize; i++) { - fields.add(new FieldMeta(fieldPrefix + "" + i, TaosConstants.DATA_TYPES[i % TaosConstants.DATA_TYPES.length])); - } - tableMetadata.setFields(fields); - // tags - List tags = new ArrayList<>(); - for (int i = 1; i <= tagSize; i++) { - tags.add(new TagMeta(tagPrefix + "" + i, TaosConstants.DATA_TYPES[i % TaosConstants.DATA_TYPES.length])); - } - tableMetadata.setTags(tags); - return tableMetadata; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/TagValueGenerator.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/TagValueGenerator.java deleted file mode 100644 index b8024fea45c000d7d0944f0ba2d47449d3907d89..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/service/data/TagValueGenerator.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.TagMeta; -import com.taosdata.taosdemo.domain.TagValue; -import com.taosdata.taosdemo.utils.DataGenerator; - -import java.util.ArrayList; -import java.util.List; - -public class TagValueGenerator { - - // 创建标签值:使用tagMetas - public static List generate(List tagMetas) { - List tagValues = new ArrayList<>(); - for (int i = 0; i < tagMetas.size(); i++) { - TagMeta tagMeta = tagMetas.get(i); - TagValue tagValue = new TagValue(); - tagValue.setName(tagMeta.getName()); - tagValue.setValue(DataGenerator.randomValue(tagMeta.getType())); - tagValues.add(tagValue); - } - return tagValues; - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/DataGenerator.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/DataGenerator.java deleted file mode 100644 index a200d17ef6c4c4987160c9966a50737773153bc9..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/DataGenerator.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.taosdata.taosdemo.utils; - -import java.util.Random; - -public class DataGenerator { - private static Random random = new Random(System.currentTimeMillis()); - private static final String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - - // "timestamp", "int", "bigint", "float", "double", "binary(64)", "smallint", "tinyint", "bool", "nchar(64)", - - public static Object randomValue(String type) { - int length = 64; - if (type.contains("(")) { - length = Integer.parseInt(type.substring(type.indexOf("(") + 1, type.indexOf(")"))); - type = type.substring(0, type.indexOf("(")); - } - switch (type.trim().toLowerCase()) { - case "timestamp": - return randomTimestamp(); - case "int": - return randomInt(); - case "bigint": - return randomBigint(); - case "float": - return randomFloat(); - case "double": - return randomDouble(); - case "binary": - return randomBinary(length); - case "smallint": - return randomSmallint(); - case "tinyint": - return randomTinyint(); - case "bool": - return randomBoolean(); - case "nchar": - return randomNchar(length); - default: - throw new IllegalArgumentException("Unexpected value: " + type); - } - } - - public static Long randomTimestamp() { - long start = System.currentTimeMillis(); - return randomTimestamp(start, start + 60l * 60l * 1000l); - } - - public static Long randomTimestamp(Long start, Long end) { - return start + (long) random.nextInt((int) (end - start)); - } - - public static String randomNchar(int length) { - return randomChinese(length); - } - - public static Boolean randomBoolean() { - return random.nextBoolean(); - } - - public static Integer randomTinyint() { - return randomInt(-127, 127); - } - - public static Integer randomSmallint() { - return randomInt(-32767, 32767); - } - - public static String randomBinary(int length) { - return randomString(length); - } - - public static String randomString(int length) { - String zh_en = ""; - for (int i = 0; i < length; i++) { - zh_en += alphabet.charAt(random.nextInt(alphabet.length())); - } - return zh_en; - } - - public static String randomChinese(int length) { - String zh_cn = ""; - int bottom = Integer.parseInt("4e00", 16); - int top = Integer.parseInt("9fa5", 16); - - for (int i = 0; i < length; i++) { - char c = (char) (random.nextInt(top - bottom + 1) + bottom); - zh_cn += new String(new char[]{c}); - } - return zh_cn; - } - - public static Double randomDouble() { - return randomDouble(0, 100); - } - - public static Double randomDouble(double bottom, double top) { - return bottom + (top - bottom) * random.nextDouble(); - } - - public static Float randomFloat() { - return randomFloat(0, 100); - } - - public static Float randomFloat(float bottom, float top) { - return bottom + (top - bottom) * random.nextFloat(); - } - - public static Long randomBigint() { - return random.nextLong(); - } - - public static Integer randomInt(int bottom, int top) { - return bottom + random.nextInt((top - bottom)); - } - - public static Integer randomInt() { - return randomInt(0, 100); - } - -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/SqlSpeller.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/SqlSpeller.java deleted file mode 100644 index a60f0641d3a4441195c3a60639fbe3a197115dc3..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/SqlSpeller.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.taosdata.taosdemo.utils; - -import com.taosdata.taosdemo.domain.*; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -public class SqlSpeller { - - // create database if not exists xxx keep xx days xx replica xx cache xx... - public static String createDatabase(Map map) { - StringBuilder sb = new StringBuilder(); - sb.append("create database if not exists ").append(map.get("database")).append(" "); - if (map.containsKey("keep")) - sb.append("keep ").append(map.get("keep")).append(" "); - if (map.containsKey("days")) - sb.append("days ").append(map.get("days")).append(" "); - if (map.containsKey("replica")) - sb.append("replica ").append(map.get("replica")).append(" "); - if (map.containsKey("cache")) - sb.append("cache ").append(map.get("cache")).append(" "); - if (map.containsKey("blocks")) - sb.append("blocks ").append(map.get("blocks")).append(" "); - if (map.containsKey("minrows")) - sb.append("minrows ").append(map.get("minrows")).append(" "); - if (map.containsKey("maxrows")) - sb.append("maxrows ").append(map.get("maxrows")).append(" "); - if (map.containsKey("precision")) - sb.append("precision ").append(map.get("precision")).append(" "); - if (map.containsKey("comp")) - sb.append("comp ").append(map.get("comp")).append(" "); - if (map.containsKey("walLevel")) - sb.append("walLevel ").append(map.get("walLevel")).append(" "); - if (map.containsKey("quorum")) - sb.append("quorum ").append(map.get("quorum")).append(" "); - if (map.containsKey("fsync")) - sb.append("fsync ").append(map.get("fsync")).append(" "); - if (map.containsKey("update")) - sb.append("update ").append(map.get("update")).append(" "); - return sb.toString(); - } - - // create table if not exists xx.xx using xx.xx tags(x,x,x) - public static String createTableUsingSuperTable(SubTableMeta subTableMeta) { - StringBuilder sb = new StringBuilder(); - sb.append("create table if not exists ").append(subTableMeta.getDatabase()).append(".").append(subTableMeta.getName()).append(" "); - sb.append("using ").append(subTableMeta.getDatabase()).append(".").append(subTableMeta.getSupertable()).append(" "); -// String tagStr = subTableMeta.getTags().stream().filter(Objects::nonNull) -// .map(tagValue -> tagValue.getName() + " '" + tagValue.getValue() + "' ") -// .collect(Collectors.joining(",", "(", ")")); - sb.append("tags ").append(tagValues(subTableMeta.getTags())); - return sb.toString(); - } - - // insert into xx.xxx values(x,x,x),(x,x,x)... - public static String insertOneTableMultiValues(SubTableValue subTableValue) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(subTableValue.getDatabase()).append(".").append(subTableValue.getName() + " "); - sb.append("values").append(rowValues(subTableValue.getValues())); - return sb.toString(); - } - - //f1, f2, f3 - private static String fieldValues(List fields) { - return IntStream.range(0, fields.size()).mapToObj(i -> { - if (i == 0) { - return "" + fields.get(i).getValue() + ""; - } else { - return "'" + fields.get(i).getValue() + "'"; - } - }).collect(Collectors.joining(",", "(", ")")); - -// return fields.stream() -// .filter(Objects::nonNull) -// .map(fieldValue -> "'" + fieldValue.getValue() + "'") -// .collect(Collectors.joining(",", "(", ")")); - } - - //(f1, f2, f3),(f1, f2, f3) - private static String rowValues(List rowValues) { - return rowValues.stream().filter(Objects::nonNull) - .map(rowValue -> fieldValues(rowValue.getFields())) - .collect(Collectors.joining(",", "", "")); - } - - // insert into xx.xxx using xx.xx tags(x,x,x) values(x,x,x),(x,x,x)... - public static String insertOneTableMultiValuesUsingSuperTable(SubTableValue subTableValue) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(subTableValue.getDatabase()).append(".").append(subTableValue.getName()).append(" "); - sb.append("using ").append(subTableValue.getDatabase()).append(".").append(subTableValue.getSupertable()).append(" "); - sb.append("tags ").append(tagValues(subTableValue.getTags()) + " "); - sb.append("values ").append(rowValues(subTableValue.getValues())); - return sb.toString(); - } - - // (t1,t2,t3...) - private static String tagValues(List tags) { - return tags.stream().filter(Objects::nonNull) - .map(tagValue -> "'" + tagValue.getValue() + "'") - .collect(Collectors.joining(",", "(", ")")); - } - - // insert into xx.xx values(),(),()... xx.xx values(),()... - public static String insertMultiSubTableMultiValues(List tables) { - return "insert into " + tables.stream().filter(Objects::nonNull) - .map(table -> table.getDatabase() + "." + table.getName() + " values " + rowValues(table.getValues())) - .collect(Collectors.joining(" ", "", "")); - } - - // insert into xx.xx using xx.xx tags(xx,xx) values(),()... - public static String insertMultiTableMultiValuesUsingSuperTable(List tables) { - return "insert into " + tables.stream().filter(Objects::nonNull) - .map(table -> { - StringBuilder sb = new StringBuilder(); - sb.append(table.getDatabase()).append(".").append(table.getName()); - sb.append(" using ").append(table.getDatabase()).append(".").append(table.getSupertable()); - sb.append(" tags ").append(tagValues(table.getTags())); - sb.append(" values ").append(rowValues(table.getValues())); - return sb.toString(); - }).collect(Collectors.joining(" ")); - } - - // create table if not exists xx.xx (f1 xx,f2 xx...) tags(t1 xx, t2 xx...) - public static String createSuperTable(SuperTableMeta tableMetadata) { - StringBuilder sb = new StringBuilder(); - sb.append("create table if not exists ").append(tableMetadata.getDatabase()).append(".").append(tableMetadata.getName()); - String fields = tableMetadata.getFields().stream() - .filter(Objects::nonNull).map(field -> field.getName() + " " + field.getType() + " ") - .collect(Collectors.joining(",", "(", ")")); - sb.append(fields); - sb.append(" tags "); - String tags = tableMetadata.getTags().stream().filter(Objects::nonNull) - .map(tag -> tag.getName() + " " + tag.getType() + " ") - .collect(Collectors.joining(",", "(", ")")); - sb.append(tags); - return sb.toString(); - } - - - public static String createTable(TableMeta tableMeta) { - StringBuilder sb = new StringBuilder(); - sb.append("create table if not exists ").append(tableMeta.getDatabase()).append(".").append(tableMeta.getName()).append(" "); - String fields = tableMeta.getFields().stream() - .filter(Objects::nonNull).map(field -> field.getName() + " " + field.getType() + " ") - .collect(Collectors.joining(",", "(", ")")); - sb.append(fields); - return sb.toString(); - } - - // insert into xx.xx values() - public static String insertOneTableMultiValues(TableValue table) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(table.getDatabase()).append(".").append(table.getName() + " "); - sb.append("values").append(rowValues(table.getValues())); - return sb.toString(); - - } - - // insert into xx.xx (f1, f2, f3...) values(xx,xx,xx),(xx,xx,xx)... - public static String insertOneTableMultiValuesWithColumns(TableValue table) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(table.getDatabase()).append(".").append(table.getName()).append(" "); - sb.append(columnNames(table.getColumns())); - sb.append(" values ").append(rowValues(table.getValues())); - return sb.toString(); - } - - // (f1, f2, f3...) - private static String columnNames(List fields) { - return fields.stream() - .filter(Objects::nonNull) - .map(column -> column.getName() + " ") - .collect(Collectors.joining(",", "(", ")")); - } - - public static String insertMultiTableMultiValuesWithColumns(List tables) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(tables.stream().filter(Objects::nonNull) - .map(table -> table.getDatabase() + "." + table.getName() + " " + columnNames(table.getColumns()) + " values " + rowValues(table.getValues())) - .collect(Collectors.joining(" "))); - return sb.toString(); - } - - public static String insertMultiTableMultiValues(List tables) { - StringBuilder sb = new StringBuilder(); - sb.append("insert into ").append(tables.stream().filter(Objects::nonNull).map(table -> - table.getDatabase() + "." + table.getName() + " values " + rowValues(table.getValues()) - ).collect(Collectors.joining(" "))); - return sb.toString(); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/TaosConstants.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/TaosConstants.java deleted file mode 100644 index 23c3c5279a15a1dbe529c66398d1378c826ce99a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/TaosConstants.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.taosdata.taosdemo.utils; - -public class TaosConstants { - public static final String[] DATA_TYPES = { - "timestamp", "int", "bigint", "float", "double", - "binary(64)", "smallint", "tinyint", "bool", "nchar(64)", - }; -} diff --git a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/TimeStampUtil.java b/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/TimeStampUtil.java deleted file mode 100644 index 9cfce16d828510be2c62a9a383e8e3d3badb622e..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/java/com/taosdata/taosdemo/utils/TimeStampUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.taosdata.taosdemo.utils; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class TimeStampUtil { - - private static final String datetimeFormat = "yyyy-MM-dd HH:mm:ss.SSS"; - - public static long datetimeToLong(String dateTime) { - SimpleDateFormat sdf = new SimpleDateFormat(datetimeFormat); - try { - return sdf.parse(dateTime).getTime(); - } catch (ParseException e) { - throw new IllegalArgumentException("invalid datetime string >>> " + dateTime); - } - } - - public static String longToDatetime(long time) { - SimpleDateFormat sdf = new SimpleDateFormat(datetimeFormat); - return sdf.format(new Date(time)); - } - - public static class TimeTuple { - public Long start; - public Long end; - public Long timeGap; - - TimeTuple(long start, long end, long timeGap) { - this.start = start; - this.end = end; - this.timeGap = timeGap; - } - } - - public static TimeTuple range(long start, long timeGap, long size) { - long now = System.currentTimeMillis(); - if (timeGap < 1) - timeGap = 1; - if (start == 0) - start = now - size * timeGap; - - // 如果size小于1异常 - if (size < 1) - throw new IllegalArgumentException("size less than 1."); - // 如果timeGap为1,已经超长,需要前移start - if (start + size > now) { - start = now - size; - return new TimeTuple(start, now, 1); - } - long end = start + (long) (timeGap * size); - if (end > now) { - //压缩timeGap - end = now; - double gap = (end - start) / (size * 1.0f); - if (gap < 1.0f) { - timeGap = 1; - start = end - size; - } else { - timeGap = (long) gap; - end = start + (long) (timeGap * size); - } - } - return new TimeTuple(start, end, timeGap); - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/resources/application.properties b/tests/examples/JDBC/taosdemo/src/main/resources/application.properties deleted file mode 100644 index 488185196f1d2325fd9896d30068cbb202180a3f..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -jdbc.driver=com.taosdata.jdbc.rs.RestfulDriver -#jdbc.driver=com.taosdata.jdbc.TSDBDriver -hikari.maximum-pool-size=20 -hikari.minimum-idle=20 -hikari.max-lifetime=0 \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/resources/insert.json b/tests/examples/JDBC/taosdemo/src/main/resources/insert.json deleted file mode 100644 index 66b967202fd55cadefb2d10c2e4a7a9ad258d1e6..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/resources/insert.json +++ /dev/null @@ -1,117 +0,0 @@ -{ - "filetype": "insert", - "cfgdir": "/etc/taos", - "host": "127.0.0.1", - "port": 6030, - "user": "root", - "password": "taosdata", - "thread_count": 2, - "databases": [ - { - "dbinfo": { - "name": "db04", - "drop": "no", - "replica": 1, - "days": 2, - "cache": 16, - "blocks": 8, - "precision": "ms", - "keep": 36500, - "minRows": 100, - "maxRows": 4096, - "comp": 2, - "walLevel": 1, - "quorum": 1, - "fsync": 3000, - "update": 0 - }, - "super_tables": [ - { - "name": "stb04", - "child_table_exists": "no", - "childtable_count": 10, - "childtable_prefix": "stb01_", - "auto_create_table": "no", - "data_source": "rand", - "insert_mode": "taosc", - "insert_rate": 0, - "insert_rows": 100, - "interlace_rows": 3, - "max_sql_len": 1024, - "disorder_ratio": 0, - "disorder_range": 1000, - "timestamp_step": 10, - "start_timestamp": "2020-10-01 00:00:00.000", - "sample_format": "csv", - "sample_file": "./sample.csv", - "tags_file": "", - "columns": [ - { - "type": "TINYINT" - }, - { - "type": "SMALLINT" - }, - { - "type": "INT" - }, - { - "type": "BIGINT" - }, - { - "type": "BOOL" - }, - { - "type": "FLOAT" - }, - { - "type": "DOUBLE" - }, - { - "type": "TIMESTAMP" - }, - { - "type": "BINARY", - "len": 16 - }, - { - "type": "NCHAR", - "len": 4 - } - ], - "tags": [ - { - "type": "TINYINT" - }, - { - "type": "SMALLINT" - }, - { - "type": "INT" - }, - { - "type": "BIGINT" - }, - { - "type": "BOOL" - }, - { - "type": "FLOAT" - }, - { - "type": "DOUBLE" - }, - { - "type": "BINARY", - "len": 16 - }, - { - "type": "NCHAR", - "len": 4 - } - ] - } - ] - } - ] -} diff --git a/tests/examples/JDBC/taosdemo/src/main/resources/log4j.properties b/tests/examples/JDBC/taosdemo/src/main/resources/log4j.properties deleted file mode 100644 index 352545854d0f68f07e4da6a98504ffa7754b03b1..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/resources/log4j.properties +++ /dev/null @@ -1,21 +0,0 @@ -### 设置### -log4j.rootLogger=info,stdout -### 输出信息到控制抬 ### -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n -### 输出DEBUG 级别以上的日志到=logs/debug.log -log4j.appender.DebugLog=org.apache.log4j.DailyRollingFileAppender -log4j.appender.DebugLog.File=logs/debug.log -log4j.appender.DebugLog.Append=true -log4j.appender.DebugLog.Threshold=DEBUG -log4j.appender.DebugLog.layout=org.apache.log4j.PatternLayout -log4j.appender.DebugLog.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n -### 输出ERROR 级别以上的日志到=logs/error.log -log4j.appender.ErrorLog=org.apache.log4j.DailyRollingFileAppender -log4j.appender.ErrorLog.File=logs/error.log -log4j.appender.ErrorLog.Append=true -log4j.appender.ErrorLog.Threshold=ERROR -log4j.appender.ErrorLog.layout=org.apache.log4j.PatternLayout -log4j.appender.ErrorLog.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/main/resources/query.json b/tests/examples/JDBC/taosdemo/src/main/resources/query.json deleted file mode 100644 index cc6900d77c3941e6af3274efdfe782c42a557990..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/resources/query.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "filetype":"query", - "cfgdir": "/etc/taos", - "host": "127.0.0.1", - "port": 6030, - "user": "root", - "password": "taosdata", - "databases": "db01", - "super_table_query": - {"rate":1, "concurrent":1,"time":10000, - "sqls": [{"sql": "select count(*) from stb01", "result": "./query_res0.txt"}] - }, - "sub_table_query": - {"stblname": "stb01", "rate":1, "threads":1, - "sqls": [{"sql": "select count(*) from xxxx", "result": "./query_res1.txt"}] - } -} diff --git a/tests/examples/JDBC/taosdemo/src/main/resources/templates/index.html b/tests/examples/JDBC/taosdemo/src/main/resources/templates/index.html deleted file mode 100644 index 953a058032612c7eac8eacc68f738d5fef03ec39..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/main/resources/templates/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Index - - -

Developing~~~

- - \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/DatabaseServiceTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/DatabaseServiceTest.java deleted file mode 100644 index 621ba7df5da4bb29747a5a4af1f91d51f6a1d7d4..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/DatabaseServiceTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.taosdata.taosdemo.service; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -public class DatabaseServiceTest { - private DatabaseService service; - - @Test - public void testCreateDatabase1() { - service.createDatabase("testXXXX"); - } - - @Test - public void dropDatabase() { - service.dropDatabase("testXXXX"); - } - - @Test - public void useDatabase() { - service.useDatabase("test"); - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/QueryServiceTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/QueryServiceTest.java deleted file mode 100644 index f2ad25710c1a82136d6316ed69e379bc3925897d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/QueryServiceTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.junit.BeforeClass; -import org.junit.Test; - -public class QueryServiceTest { - private static QueryService queryService; - - @Test - public void areValidQueries() { - - } - - @Test - public void generateSuperTableQueries() { - String[] sqls = queryService.generateSuperTableQueries("restful_test"); - for (String sql : sqls) { - System.out.println(sql); - } - } - - @Test - public void querySuperTable() { - String[] sqls = queryService.generateSuperTableQueries("restful_test"); - queryService.querySuperTable(sqls, 1000, 10, 10); - } - - @BeforeClass - public static void beforeClass() throws ClassNotFoundException { - Class.forName("com.taosdata.jdbc.TSDBDriver"); - HikariConfig config = new HikariConfig(); - config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/?charset=UTF-8&locale=en_US.UTF-8&timezone=UTC-8"); - config.setUsername("root"); - config.setPassword("taosdata"); - HikariDataSource dataSource = new HikariDataSource(config); - queryService = new QueryService(dataSource); - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/SubTableServiceTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/SubTableServiceTest.java deleted file mode 100644 index f7e5cd45057472602ad6e7a43a8d8bdb31a02b40..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/SubTableServiceTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.domain.SubTableMeta; -import com.taosdata.taosdemo.domain.TagValue; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class SubTableServiceTest { - - private SubTableService service; - - private List subTables; - - @Before - public void before() { - subTables = new ArrayList<>(); - for (int i = 1; i <= 1; i++) { - SubTableMeta subTableMeta = new SubTableMeta(); - subTableMeta.setDatabase("test"); - subTableMeta.setSupertable("weather"); - subTableMeta.setName("t" + i); - List tags = new ArrayList<>(); - tags.add(new TagValue("location", "beijing")); - tags.add(new TagValue("groupId", i)); - subTableMeta.setTags(tags); - subTables.add(subTableMeta); - } - } - - @Test - public void testCreateSubTable() { - - } - - @Test - public void testCreateSubTableList() { - - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/SuperTableServiceTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/SuperTableServiceTest.java deleted file mode 100644 index 33e52af1eaa779e7ed402a63633bf0dbb9fbadd7..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/SuperTableServiceTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.domain.FieldMeta; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.domain.TagMeta; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class SuperTableServiceTest { - - private SuperTableService service; - - @Test - public void testCreate() { - SuperTableMeta superTableMeta = new SuperTableMeta(); - superTableMeta.setDatabase("test"); - superTableMeta.setName("weather"); - List fields = new ArrayList<>(); - fields.add(new FieldMeta("ts", "timestamp")); - fields.add(new FieldMeta("temperature", "float")); - fields.add(new FieldMeta("humidity", "int")); - superTableMeta.setFields(fields); - List tags = new ArrayList<>(); - tags.add(new TagMeta("location", "nchar(64)")); - tags.add(new TagMeta("groupId", "int")); - superTableMeta.setTags(tags); - service.create(superTableMeta); - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/TableServiceTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/TableServiceTest.java deleted file mode 100644 index 1f52198d68823326dd81d8c419fc02d89e15ef2d..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/TableServiceTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.taosdata.taosdemo.service; - -import com.taosdata.taosdemo.domain.TableMeta; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class TableServiceTest { - private TableService tableService; - - private List tables; - - @Before - public void before() { - tables = new ArrayList<>(); - for (int i = 0; i < 1; i++) { - TableMeta tableMeta = new TableMeta(); - tableMeta.setDatabase("test"); - tableMeta.setName("weather" + (i + 1)); - tables.add(tableMeta); - } - } - - @Test - public void testCreate() { - tableService.create(tables); - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/FieldValueGeneratorTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/FieldValueGeneratorTest.java deleted file mode 100644 index aea3cc76ca74951a6bbcc91fe3c6b5c7e078f0df..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/FieldValueGeneratorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.FieldMeta; -import com.taosdata.taosdemo.domain.RowValue; -import com.taosdata.taosdemo.utils.TimeStampUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class FieldValueGeneratorTest { - - private List rowValues; - - @Test - public void generate() { - List fieldMetas = new ArrayList<>(); - fieldMetas.add(new FieldMeta("ts", "timestamp")); - fieldMetas.add(new FieldMeta("temperature", "float")); - fieldMetas.add(new FieldMeta("humidity", "int")); - - long start = TimeStampUtil.datetimeToLong("2020-01-01 00:00:00.000"); - long end = TimeStampUtil.datetimeToLong("2020-01-01 10:00:00.000"); - - rowValues = FieldValueGenerator.generate(start, end, 1000l * 3600, fieldMetas); - Assert.assertEquals(10, rowValues.size()); - } - - @Test - public void disrupt() { - List fieldMetas = new ArrayList<>(); - fieldMetas.add(new FieldMeta("ts", "timestamp")); - fieldMetas.add(new FieldMeta("temperature", "float")); - fieldMetas.add(new FieldMeta("humidity", "int")); - - long start = TimeStampUtil.datetimeToLong("2020-01-01 00:00:00.000"); - long end = TimeStampUtil.datetimeToLong("2020-01-01 10:00:00.000"); - - rowValues = FieldValueGenerator.generate(start, end, 1000l * 3600l, fieldMetas); - - FieldValueGenerator.disrupt(rowValues, 20, 1000); - Assert.assertEquals(10, rowValues.size()); - } - - @After - public void after() { - for (RowValue row : rowValues) { - row.getFields().stream().forEach(field -> { - if (field.getName().equals("ts")) { - System.out.print(TimeStampUtil.longToDatetime((Long) field.getValue())); - } else - System.out.print(" ," + field.getValue()); - }); - System.out.println(); - } - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/SubTableMetaGeneratorTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/SubTableMetaGeneratorTest.java deleted file mode 100644 index 78c8e9283f9a045b251419e5a07b1c97bd105254..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/SubTableMetaGeneratorTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.FieldMeta; -import com.taosdata.taosdemo.domain.SubTableMeta; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.domain.TagMeta; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class SubTableMetaGeneratorTest { - List subTableMetas; - - @Test - public void generate() { - SuperTableMeta superTableMeta = new SuperTableMeta(); - superTableMeta.setDatabase("test"); - superTableMeta.setName("weather"); - List fields = new ArrayList<>(); - fields.add(new FieldMeta("ts", "timestamp")); - fields.add(new FieldMeta("temperature", "float")); - fields.add(new FieldMeta("humidity", "int")); - superTableMeta.setFields(fields); - List tags = new ArrayList<>(); - tags.add(new TagMeta("location", "nchar(64)")); - tags.add(new TagMeta("groupId", "int")); - superTableMeta.setTags(tags); - - subTableMetas = SubTableMetaGenerator.generate(superTableMeta, 10, "t"); - Assert.assertEquals(10, subTableMetas.size()); - Assert.assertEquals("t1", subTableMetas.get(0).getName()); - Assert.assertEquals("t2", subTableMetas.get(1).getName()); - Assert.assertEquals("t3", subTableMetas.get(2).getName()); - Assert.assertEquals("t4", subTableMetas.get(3).getName()); - Assert.assertEquals("t5", subTableMetas.get(4).getName()); - Assert.assertEquals("t6", subTableMetas.get(5).getName()); - Assert.assertEquals("t7", subTableMetas.get(6).getName()); - Assert.assertEquals("t8", subTableMetas.get(7).getName()); - Assert.assertEquals("t9", subTableMetas.get(8).getName()); - Assert.assertEquals("t10", subTableMetas.get(9).getName()); - } - - @After - public void after() { - for (SubTableMeta subTableMeta : subTableMetas) { - System.out.println(subTableMeta); - } - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/SuperTableMetaGeneratorImplTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/SuperTableMetaGeneratorImplTest.java deleted file mode 100644 index 11c5312cf6c9b4893681728115519509985a42a2..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/SuperTableMetaGeneratorImplTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.FieldMeta; -import com.taosdata.taosdemo.domain.SuperTableMeta; -import com.taosdata.taosdemo.domain.TagMeta; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -public class SuperTableMetaGeneratorImplTest { - private SuperTableMeta meta; - - @Test - public void generate() { - String sql = "create table test.weather (ts timestamp, temperature float, humidity int) tags(location nchar(64), groupId int)"; - meta = SuperTableMetaGenerator.generate(sql); - Assert.assertEquals("test", meta.getDatabase()); - Assert.assertEquals("weather", meta.getName()); - Assert.assertEquals(3, meta.getFields().size()); - Assert.assertEquals("ts", meta.getFields().get(0).getName()); - Assert.assertEquals("timestamp", meta.getFields().get(0).getType()); - Assert.assertEquals("temperature", meta.getFields().get(1).getName()); - Assert.assertEquals("float", meta.getFields().get(1).getType()); - Assert.assertEquals("humidity", meta.getFields().get(2).getName()); - Assert.assertEquals("int", meta.getFields().get(2).getType()); - - Assert.assertEquals("location", meta.getTags().get(0).getName()); - Assert.assertEquals("nchar(64)", meta.getTags().get(0).getType()); - Assert.assertEquals("groupid", meta.getTags().get(1).getName()); - Assert.assertEquals("int", meta.getTags().get(1).getType()); - } - - @Test - public void generate2() { - meta = SuperTableMetaGenerator.generate("test", "weather", 10, "col", 10, "tag"); - Assert.assertEquals("test", meta.getDatabase()); - Assert.assertEquals("weather", meta.getName()); - Assert.assertEquals(11, meta.getFields().size()); - for (FieldMeta fieldMeta : meta.getFields()) { - Assert.assertNotNull(fieldMeta.getName()); - Assert.assertNotNull(fieldMeta.getType()); - } - for (TagMeta tagMeta : meta.getTags()) { - Assert.assertNotNull(tagMeta.getName()); - Assert.assertNotNull(tagMeta.getType()); - } - } - - @After - public void after() { - System.out.println(meta.getDatabase()); - System.out.println(meta.getName()); - for (FieldMeta fieldMeta : meta.getFields()) { - System.out.println(fieldMeta); - } - for (TagMeta tagMeta : meta.getTags()) { - System.out.println(tagMeta); - } - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/TagValueGeneratorTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/TagValueGeneratorTest.java deleted file mode 100644 index 37c9051c941b3540fd24371cff20be426d4fecba..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/service/data/TagValueGeneratorTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.taosdata.taosdemo.service.data; - -import com.taosdata.taosdemo.domain.TagMeta; -import com.taosdata.taosdemo.domain.TagValue; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -public class TagValueGeneratorTest { - List tagvalues; - - @Test - public void generate() { - List tagMetaList = new ArrayList<>(); - tagMetaList.add(new TagMeta("location", "nchar(10)")); - tagMetaList.add(new TagMeta("groupId", "int")); - tagMetaList.add(new TagMeta("ts", "timestamp")); - tagMetaList.add(new TagMeta("temperature", "float")); - tagMetaList.add(new TagMeta("humidity", "double")); - tagMetaList.add(new TagMeta("text", "binary(10)")); - tagvalues = TagValueGenerator.generate(tagMetaList); - Assert.assertEquals("location", tagvalues.get(0).getName()); - Assert.assertEquals("groupId", tagvalues.get(1).getName()); - Assert.assertEquals("ts", tagvalues.get(2).getName()); - Assert.assertEquals("temperature", tagvalues.get(3).getName()); - Assert.assertEquals("humidity", tagvalues.get(4).getName()); - Assert.assertEquals("text", tagvalues.get(5).getName()); - } - - @After - public void after() { - tagvalues.stream().forEach(System.out::println); - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/DataGeneratorTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/DataGeneratorTest.java deleted file mode 100644 index 7d12782526e4d64e120ba5e4c72809846356cd00..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/DataGeneratorTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.taosdata.taosdemo.utils; - -import org.junit.Assert; -import org.junit.Test; - -public class DataGeneratorTest { - - @Test - public void randomValue() { - for (int i = 0; i < TaosConstants.DATA_TYPES.length; i++) { - System.out.println(TaosConstants.DATA_TYPES[i] + " >>> " + DataGenerator.randomValue(TaosConstants.DATA_TYPES[i])); - } - } - - @Test - public void randomNchar() { - String s = DataGenerator.randomNchar(10); - Assert.assertEquals(10, s.length()); - } -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/SqlSpellerTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/SqlSpellerTest.java deleted file mode 100644 index daabd51ca75a6c9f4bfeead0b747c4de69f40a7a..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/SqlSpellerTest.java +++ /dev/null @@ -1,254 +0,0 @@ -package com.taosdata.taosdemo.utils; - -import com.taosdata.taosdemo.domain.*; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class SqlSpellerTest { - - @Test - public void createDatabase() { - HashMap map = new HashMap<>(); - map.put("database", "jdbcdb"); - map.put("keep", "3650"); - map.put("days", "30"); - map.put("replica", "1"); - map.put("minRows", "100"); - map.put("maxRows", "1000"); - map.put("cache", "16"); - map.put("blocks", "8"); - map.put("precision", "ms"); - map.put("comp", "2"); - map.put("walLevel", "1"); - map.put("quorum", "1"); - map.put("fsync", "3000"); - map.put("update", "0"); - String sql = SqlSpeller.createDatabase(map); - System.out.println(sql); - } - - @Test - public void createTableUsingSuperTable() { - SubTableMeta subTableMeta = new SubTableMeta(); - subTableMeta.setDatabase("test"); - subTableMeta.setSupertable("weather"); - subTableMeta.setName("t1"); - List tags = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - tags.add(new TagValue("tag" + (i + 1), "nchar(64)")); - } - subTableMeta.setTags(tags); - String sql = SqlSpeller.createTableUsingSuperTable(subTableMeta); - System.out.println(sql); - } - - @Test - public void insertOneTableMultiValues() { - String sql = SqlSpeller.insertOneTableMultiValues(tables.get(0)); - System.out.println(sql); - } - - @Test - public void insertOneTableMultiValuesUsingSuperTable() { - String sql = SqlSpeller.insertOneTableMultiValuesUsingSuperTable(tables.get(0)); - System.out.println(sql); - } - - @Test - public void insertMultiTableMultiValues() { - String sql = SqlSpeller.insertMultiSubTableMultiValues(tables); - System.out.println(sql); - } - - @Test - public void insertMultiTableMultiValuesUsingSuperTable() { - String sql = SqlSpeller.insertMultiTableMultiValuesUsingSuperTable(tables); - System.out.println(sql); - } - - private List tables; - - @Before - public void before() { - tables = new ArrayList<>(); - for (int ind = 0; ind < 3; ind++) { - SubTableValue table = new SubTableValue(); - table.setDatabase("test"); - // supertable - table.setSupertable("weather"); - table.setName("t" + (ind + 1)); - // tags - List tags = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - tags.add(new TagValue("tag" + (i + 1), "beijing")); - } - table.setTags(tags); - // values - List values = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - List fields = new ArrayList<>(); - for (int j = 0; j < 4; j++) { - fields.add(new FieldValue("f" + (j + 1), (j + 1) * 10)); - } - values.add(new RowValue(fields)); - } - table.setValues(values); - - tables.add(table); - } - } - - @Test - public void createSuperTable() { - SuperTableMeta superTableMeta = new SuperTableMeta(); - superTableMeta.setDatabase("test"); - superTableMeta.setName("weather"); - List fields = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - fields.add(new FieldMeta("f" + (i + 1), "int")); - } - superTableMeta.setFields(fields); - List tags = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - tags.add(new TagMeta("t" + (i + 1), "nchar(64)")); - } - superTableMeta.setTags(tags); - - String sql = SqlSpeller.createSuperTable(superTableMeta); - System.out.println(sql); - } - - @Test - public void createTable() { - TableMeta table = new TableMeta(); - table.setDatabase("test"); - table.setName("t1"); - List fields = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - FieldMeta field = new FieldMeta(); - field.setName("f" + (i + 1)); - field.setType("nchar(64)"); - fields.add(field); - } - table.setFields(fields); - String sql = SqlSpeller.createTable(table); - System.out.println(sql); - } - - - @Test - public void testInsertOneTableMultiValues() { - TableValue table = new TableValue(); - table.setDatabase("test"); - table.setName("t1"); - List values = new ArrayList<>(); - for (int j = 0; j < 5; j++) { - List fields = new ArrayList<>(); - for (int k = 0; k < 2; k++) { - FieldValue field = new FieldValue<>(); - field.setValue((k + 1) * 100); - fields.add(field); - } - values.add(new RowValue(fields)); - } - table.setValues(values); - - String sql = SqlSpeller.insertOneTableMultiValues(table); - System.out.println(sql); - } - - @Test - public void insertOneTableMultiValuesWithColumns() { - TableValue tableValue = new TableValue(); - tableValue.setDatabase("test"); - tableValue.setName("weather"); - // columns - List columns = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - FieldMeta field = new FieldMeta(); - field.setName("f" + (i + 1)); - columns.add(field); - } - tableValue.setColumns(columns); - // values - List values = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - List fields = new ArrayList<>(); - for (int j = 0; j < 3; j++) { - FieldValue field = new FieldValue(); - field.setValue(j); - fields.add(field); - } - values.add(new RowValue(fields)); - } - tableValue.setValues(values); - - String sql = SqlSpeller.insertOneTableMultiValuesWithColumns(tableValue); - System.out.println(sql); - } - - @Test - public void insertMultiTableMultiValuesWithColumns() { - List tables = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - TableValue table = new TableValue(); - table.setDatabase("test"); - table.setName("t" + (i + 1)); - // columns - List columns = new ArrayList<>(); - for (int j = 0; j < 3; j++) { - FieldMeta field = new FieldMeta(); - field.setName("f" + (j + 1)); - columns.add(field); - } - table.setColumns(columns); - // values - List values = new ArrayList<>(); - for (int j = 0; j < 5; j++) { - List fields = new ArrayList<>(); - for (int k = 0; k < columns.size(); k++) { - FieldValue field = new FieldValue<>(); - field.setValue((k + 1) * 10); - fields.add(field); - } - values.add(new RowValue(fields)); - } - table.setValues(values); - tables.add(table); - } - - String sql = SqlSpeller.insertMultiTableMultiValuesWithColumns(tables); - System.out.println(sql); - } - - @Test - public void testInsertMultiTableMultiValues() { - List tables = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - TableValue table = new TableValue(); - table.setDatabase("test"); - table.setName("t" + (i + 1)); - List values = new ArrayList<>(); - for (int j = 0; j < 5; j++) { - List fields = new ArrayList<>(); - for (int k = 0; k < 2; k++) { - FieldValue field = new FieldValue<>(); - field.setValue((k + 1) * 10); - fields.add(field); - } - values.add(new RowValue(fields)); - } - table.setValues(values); - - tables.add(table); - } - - String sql = SqlSpeller.insertMultiTableMultiValues(tables); - System.out.println(sql); - } - -} \ No newline at end of file diff --git a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/TimeStampUtilTest.java b/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/TimeStampUtilTest.java deleted file mode 100644 index a4845677c55897c71791eba40104ea23de644f5c..0000000000000000000000000000000000000000 --- a/tests/examples/JDBC/taosdemo/src/test/java/com/taosdata/taosdemo/utils/TimeStampUtilTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.taosdata.taosdemo.utils; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class TimeStampUtilTest { - - @Test - public void datetimeToLong() { - final String startTime = "2005-01-01 00:00:00.000"; - long start = TimeStampUtil.datetimeToLong(startTime); - assertEquals(1104508800000l, start); - String dateTimeStr = TimeStampUtil.longToDatetime(start); - assertEquals("2005-01-01 00:00:00.000", dateTimeStr); - } - - @Test - public void longToDatetime() { - System.out.println(TimeStampUtil.longToDatetime(1293334499006l)); - - String datetime = TimeStampUtil.longToDatetime(1510000000000L); - assertEquals("2017-11-07 04:26:40.000", datetime); - long timestamp = TimeStampUtil.datetimeToLong(datetime); - assertEquals(1510000000000L, timestamp); - } - - @Test - public void range() { - long start = TimeStampUtil.datetimeToLong("2020-10-01 00:00:00.000"); - long timeGap = 1000; - long numOfRowsPerTable = 1000l * 3600l * 24l * 90l; - TimeStampUtil.TimeTuple timeTuple = TimeStampUtil.range(start, timeGap, numOfRowsPerTable); - System.out.println(TimeStampUtil.longToDatetime(timeTuple.start)); - System.out.println(TimeStampUtil.longToDatetime(timeTuple.end)); - System.out.println(timeTuple.timeGap); - - } - -} \ No newline at end of file diff --git a/tests/examples/R/command.txt b/tests/examples/R/command.txt deleted file mode 100644 index 9a549ff200968d96336666c23999e13aa07dbb3f..0000000000000000000000000000000000000000 --- a/tests/examples/R/command.txt +++ /dev/null @@ -1,55 +0,0 @@ -# Linux Platform -install.packages('rJDBC', repos='http://cran.us.r-project.org') - -# Loading RJDBC packages -library('RJDBC') -# Set up working path and JDBC driver storage location -setwd('C:/TDengine') - -# Load JDBC Driver for TDengine -drv<-JDBC("com.taosdata.jdbc.TSDBDriver","JDBCDriver-1.0.0-dist.jar", identifier.quote="\"") - -# Connect to the database -conn<-dbConnect(drv,"jdbc:TSDB://192.168.1.114:0/?user=root&password=taosdata","root","taosdata") - -# Get connection information -dbGetInfo(conn) - -# Using database test -dbSendUpdate(conn, "use test") - -# Insert data -dbSendUpdate(conn, "insert into t1 values(now, 99)") - -# View all tables -table1<-dbGetQuery(conn,"show tables") - -# Functional support for RJDBC - -# List all tables -dbListTables(conn) - -# Is there table iris -dbExistsTable(conn,”iris”) - -# Connect summary information -summary(conn) -dbGetInfo(conn) - -# Read all the data from the T1 table -dbReadTable(conn, "t1") - -# Delete table t1 -dbRemoveTable(conn,"t1") - -# Execute any non-query SQL statements -dbSendUpdate(conn, "create table t1(a timestamp, b int, c nchar(12))"); - -# Write data -dbWriteTable(conn, "t1", t_demo_n, overwrite=FALSE, append=TRUE) - -# Extracting data on demand using SQL statements -dbGetQuery(conn, "select k from tu") - -# Close the connection -dbDisconnect(conn) diff --git a/tests/examples/bash/demo.csv b/tests/examples/bash/demo.csv deleted file mode 100644 index 5b9d6eb8117b20f209d3c94c3608bdedf0d7a469..0000000000000000000000000000000000000000 --- a/tests/examples/bash/demo.csv +++ /dev/null @@ -1,10 +0,0 @@ -1503851026421, 220, 1.10 -1503851026422, 221, 1.20 -1503851026423, 219, 1.09 -1503851026424, 222, 1.11 -1503851026425, 220, 1.08 -'2019-07-22 10:00:01.000', 219, 1.06 -'2019-07-22 10:00:02.000', 218, 1.04 -'2019-07-22 10:01:02.000', 220, 1.12 -'2019-07-22 11:01:02.000', 221, 1.11 -'2019-07-23 11:01:02.000', 220, 1.09 diff --git a/tests/examples/bash/demo.sql b/tests/examples/bash/demo.sql deleted file mode 100644 index 8c3c4124519ff3906cd4c7c39db57eac0c76f902..0000000000000000000000000000000000000000 --- a/tests/examples/bash/demo.sql +++ /dev/null @@ -1,14 +0,0 @@ -create database if not exists db0 -create table if not exists db0.tb0 (ts timestamp, voltage int, current float) -import into db0.tb0 file demo.csv - - -create database if not exists db1 -use db1 -create table if not exists tb1 (ts timestamp, temperature int, humidity float) -insert into tb1 values('2010-07-23 11:01:02.000', 37, 50.1) -insert into tb1 values(now, 36, 47.8); -insert into tb1 values(now+1a, 38, 65.3); -insert into tb1 values(now+1s, 38, 53.9 ); -insert into tb1 values(now+1m, 37, 45.6); -insert into tb1 values(now+1h, 35, 41.1); diff --git a/tests/examples/c/CMakeLists.txt b/tests/examples/c/CMakeLists.txt deleted file mode 100644 index 3c0a4d32db154a942fbc05183ed7379b3e2fe5ad..0000000000000000000000000000000000000000 --- a/tests/examples/c/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -PROJECT(TDengine) - -IF (TD_LINUX) - INCLUDE_DIRECTORIES(. ${TD_COMMUNITY_DIR}/src/inc ${TD_COMMUNITY_DIR}/src/client/inc ${TD_COMMUNITY_DIR}/inc) - AUX_SOURCE_DIRECTORY(. SRC) - ADD_EXECUTABLE(demo apitest.c) - TARGET_LINK_LIBRARIES(demo taos_static trpc tutil pthread ) - ADD_EXECUTABLE(sml schemaless.c) - TARGET_LINK_LIBRARIES(sml taos_static trpc tutil pthread ) - ADD_EXECUTABLE(sqlperf sqlperf.c) - TARGET_LINK_LIBRARIES(sqlperf taos_static trpc tutil pthread ) - ADD_EXECUTABLE(subscribe subscribe.c) - TARGET_LINK_LIBRARIES(subscribe taos_static trpc tutil pthread ) - ADD_EXECUTABLE(epoll epoll.c) - TARGET_LINK_LIBRARIES(epoll taos_static trpc tutil pthread ${LINK_LUA}) -ENDIF () -IF (TD_DARWIN) - INCLUDE_DIRECTORIES(. ${TD_COMMUNITY_DIR}/src/inc ${TD_COMMUNITY_DIR}/src/client/inc ${TD_COMMUNITY_DIR}/inc) - AUX_SOURCE_DIRECTORY(. SRC) - ADD_EXECUTABLE(demo demo.c) - TARGET_LINK_LIBRARIES(demo taos_static trpc tutil pthread ${LINK_LUA}) - ADD_EXECUTABLE(epoll epoll.c) - TARGET_LINK_LIBRARIES(epoll taos_static trpc tutil pthread ${LINK_LUA}) - - ADD_EXECUTABLE(parameter-binding parameter-binding.c) - TARGET_LINK_LIBRARIES(parameter-binding taos) -ENDIF () diff --git a/tests/examples/c/apitest.c b/tests/examples/c/apitest.c deleted file mode 100644 index 2c197887e7d7f1e6397213641a02ee8b37a84190..0000000000000000000000000000000000000000 --- a/tests/examples/c/apitest.c +++ /dev/null @@ -1,455 +0,0 @@ -// sample code to verify all TDengine API -// to compile: gcc -o apitest apitest.c -ltaos - -#include "taoserror.h" - -#include -#include -#include -#include -#include - - -static void prepare_data(TAOS* taos) { - TAOS_RES* result; - result = taos_query(taos, "drop database if exists test;"); - taos_free_result(result); - usleep(100000); - result = taos_query(taos, "create database test precision 'ns';"); - taos_free_result(result); - usleep(100000); - taos_select_db(taos, "test"); - - result = taos_query(taos, "create table meters(ts timestamp, a int) tags(area int);"); - taos_free_result(result); - - result = taos_query(taos, "create table t0 using meters tags(0);"); - taos_free_result(result); - result = taos_query(taos, "create table t1 using meters tags(1);"); - taos_free_result(result); - result = taos_query(taos, "create table t2 using meters tags(2);"); - taos_free_result(result); - result = taos_query(taos, "create table t3 using meters tags(3);"); - taos_free_result(result); - result = taos_query(taos, "create table t4 using meters tags(4);"); - taos_free_result(result); - result = taos_query(taos, "create table t5 using meters tags(5);"); - taos_free_result(result); - result = taos_query(taos, "create table t6 using meters tags(6);"); - taos_free_result(result); - result = taos_query(taos, "create table t7 using meters tags(7);"); - taos_free_result(result); - result = taos_query(taos, "create table t8 using meters tags(8);"); - taos_free_result(result); - result = taos_query(taos, "create table t9 using meters tags(9);"); - taos_free_result(result); - - result = taos_query(taos, - "insert into t0 values('2020-01-01 00:00:00.000', 0)" - " ('2020-01-01 00:01:00.000', 0)" - " ('2020-01-01 00:02:00.000', 0)" - " t1 values('2020-01-01 00:00:00.000', 0)" - " ('2020-01-01 00:01:00.000', 0)" - " ('2020-01-01 00:02:00.000', 0)" - " ('2020-01-01 00:03:00.000', 0)" - " t2 values('2020-01-01 00:00:00.000', 0)" - " ('2020-01-01 00:01:00.000', 0)" - " ('2020-01-01 00:01:01.000', 0)" - " ('2020-01-01 00:01:02.000', 0)" - " t3 values('2020-01-01 00:01:02.000', 0)" - " t4 values('2020-01-01 00:01:02.000', 0)" - " t5 values('2020-01-01 00:01:02.000', 0)" - " t6 values('2020-01-01 00:01:02.000', 0)" - " t7 values('2020-01-01 00:01:02.000', 0)" - " t8 values('2020-01-01 00:01:02.000', 0)" - " t9 values('2020-01-01 00:01:02.000', 0)"); - int affected = taos_affected_rows(result); - if (affected != 18) { - printf("\033[31m%d rows affected by last insert statement, but it should be 18\033[0m\n", affected); - } - taos_free_result(result); - // super tables subscription - usleep(1000000); -} - -static int print_result(TAOS_RES* res, int blockFetch) { - TAOS_ROW row = NULL; - int num_fields = taos_num_fields(res); - TAOS_FIELD* fields = taos_fetch_fields(res); - int nRows = 0; - - if (blockFetch) { - int rows = 0; - while ((rows = taos_fetch_block(res, &row))) { - // for (int i = 0; i < rows; i++) { - // char temp[256]; - // taos_print_row(temp, row + i, fields, num_fields); - // puts(temp); - //} - nRows += rows; - } - } else { - while ((row = taos_fetch_row(res))) { - char temp[256] = {0}; - taos_print_row(temp, row, fields, num_fields); - puts(temp); - nRows++; - } - } - - printf("%d rows consumed.\n", nRows); - return nRows; -} - -static void check_row_count(int line, TAOS_RES* res, int expected) { - int actual = print_result(res, expected % 2); - if (actual != expected) { - printf("\033[31mline %d: row count mismatch, expected: %d, actual: %d\033[0m\n", line, expected, actual); - } else { - printf("line %d: %d rows consumed as expected\n", line, actual); - } -} - -static void verify_query(TAOS* taos) { - prepare_data(taos); - - int code = taos_load_table_info(taos, "t0,t1,t2,t3,t4,t5,t6,t7,t8,t9"); - if (code != 0) { - printf("\033[31mfailed to load table info: 0x%08x\033[0m\n", code); - } - - code = taos_validate_sql(taos, "select * from nonexisttable"); - if (code == 0) { - printf("\033[31mimpossible, the table does not exists\033[0m\n"); - } - - code = taos_validate_sql(taos, "select * from meters"); - if (code != 0) { - printf("\033[31mimpossible, the table does exists: 0x%08x\033[0m\n", code); - } - - TAOS_RES* res = taos_query(taos, "select * from meters"); - check_row_count(__LINE__, res, 18); - printf("result precision is: %d\n", taos_result_precision(res)); - int c = taos_field_count(res); - printf("field count is: %d\n", c); - int* lengths = taos_fetch_lengths(res); - for (int i = 0; i < c; i++) { - printf("length of column %d is %d\n", i, lengths[i]); - } - taos_free_result(res); - - res = taos_query(taos, "select * from t0"); - check_row_count(__LINE__, res, 3); - taos_free_result(res); - - res = taos_query(taos, "select * from nonexisttable"); - code = taos_errno(res); - printf("code=%d, error msg=%s\n", code, taos_errstr(res)); - taos_free_result(res); - - res = taos_query(taos, "select * from meters"); - taos_stop_query(res); - taos_free_result(res); -} - -void subscribe_callback(TAOS_SUB* tsub, TAOS_RES* res, void* param, int code) { - int rows = print_result(res, *(int*)param); - printf("%d rows consumed in subscribe_callback\n", rows); -} - -static void verify_subscribe(TAOS* taos) { - prepare_data(taos); - - TAOS_SUB* tsub = taos_subscribe(taos, 0, "test", "select * from meters;", NULL, NULL, 0); - TAOS_RES* res = taos_consume(tsub); - check_row_count(__LINE__, res, 18); - - res = taos_consume(tsub); - check_row_count(__LINE__, res, 0); - - TAOS_RES* result; - result = taos_query(taos, "insert into t0 values('2020-01-01 00:02:00.001', 0);"); - taos_free_result(result); - result = taos_query(taos, "insert into t8 values('2020-01-01 00:01:03.000', 0);"); - taos_free_result(result); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 2); - - result = taos_query(taos, "insert into t2 values('2020-01-01 00:01:02.001', 0);"); - taos_free_result(result); - result = taos_query(taos, "insert into t1 values('2020-01-01 00:03:00.001', 0);"); - taos_free_result(result); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 2); - - result = taos_query(taos, "insert into t1 values('2020-01-01 00:03:00.002', 0);"); - taos_free_result(result); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 1); - - // keep progress information and restart subscription - taos_unsubscribe(tsub, 1); - result = taos_query(taos, "insert into t0 values('2020-01-01 00:04:00.000', 0);"); - taos_free_result(result); - tsub = taos_subscribe(taos, 1, "test", "select * from meters;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 24); - - // keep progress information and continue previous subscription - taos_unsubscribe(tsub, 1); - tsub = taos_subscribe(taos, 0, "test", "select * from meters;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 0); - - // don't keep progress information and continue previous subscription - taos_unsubscribe(tsub, 0); - tsub = taos_subscribe(taos, 0, "test", "select * from meters;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 24); - - // single meter subscription - - taos_unsubscribe(tsub, 0); - tsub = taos_subscribe(taos, 0, "test", "select * from t0;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 5); - - res = taos_consume(tsub); - check_row_count(__LINE__, res, 0); - - result = taos_query(taos, "insert into t0 values('2020-01-01 00:04:00.001', 0);"); - taos_free_result(result); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 1); - - taos_unsubscribe(tsub, 0); - - int blockFetch = 0; - tsub = taos_subscribe(taos, 1, "test", "select * from meters;", subscribe_callback, &blockFetch, 1000); - usleep(2000000); - result = taos_query(taos, "insert into t0 values('2020-01-01 00:05:00.001', 0);"); - taos_free_result(result); - usleep(2000000); - taos_unsubscribe(tsub, 0); -} - -void retrieve_callback(void* param, TAOS_RES* tres, int numOfRows) { - if (numOfRows > 0) { - printf("%d rows async retrieved\n", numOfRows); - taos_fetch_rows_a(tres, retrieve_callback, param); - } else { - if (numOfRows < 0) { - printf("\033[31masync retrieve failed, code: %d\033[0m\n", numOfRows); - } else { - printf("async retrieve completed\n"); - } - taos_free_result(tres); - } -} - -void select_callback(void* param, TAOS_RES* tres, int code) { - if (code == 0 && tres) { - taos_fetch_rows_a(tres, retrieve_callback, param); - } else { - printf("\033[31masync select failed, code: %d\033[0m\n", code); - } -} - -void verify_async(TAOS* taos) { - prepare_data(taos); - taos_query_a(taos, "select * from meters", select_callback, NULL); - usleep(1000000); -} - -void stream_callback(void* param, TAOS_RES* res, TAOS_ROW row) { - if (res == NULL || row == NULL) { - return; - } - - int num_fields = taos_num_fields(res); - TAOS_FIELD* fields = taos_fetch_fields(res); - - printf("got one row from stream_callback\n"); - char temp[256] = {0}; - taos_print_row(temp, row, fields, num_fields); - puts(temp); -} - -void verify_stream(TAOS* taos) { - prepare_data(taos); - TAOS_STREAM* strm = - taos_open_stream(taos, "select count(*) from meters interval(1m)", stream_callback, 0, NULL, NULL); - printf("waiting for stream data\n"); - usleep(100000); - TAOS_RES* result = taos_query(taos, "insert into t0 values(now, 0)(now+5s,1)(now+10s, 2);"); - taos_free_result(result); - usleep(200000000); - taos_close_stream(strm); -} - -void verify_schema_less(TAOS* taos) { - TAOS_RES* result; - result = taos_query(taos, "drop database if exists test;"); - taos_free_result(result); - usleep(100000); - result = taos_query(taos, "create database test precision 'ns' update 1 keep 36500;"); - taos_free_result(result); - usleep(100000); - - taos_select_db(taos, "test"); - result = taos_query(taos, "create stable ste(ts timestamp, f int) tags(t1 bigint)"); - taos_free_result(result); - usleep(100000); - - int code = 0, affected_rows = 0; - - char* lines[] = { - "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000", - "ste,t2=5f64,t3=L\"ste\" c1=true,c2=4i64,c3=\"iam\" 1626056811823316532", - "st,t1=4i64,t2=5f64,t3=\"t4\" c1=3i64,c3=L\"passitagain\",c2=true,c4=5f64 1626006833642000000", - "ste,t2=5f64,t3=L\"ste2\" c3=\"iamszhou\",c4=false 1626056811843316532", - "ste,t2=5f64,t3=L\"ste2\" c3=\"iamszhou\",c4=false,c5=32i8,c6=64i16,c7=32i32,c8=88.88f32 1626056812843316532", - "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000", - "stf,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000", - "stf,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641000000" - }; - - result = taos_schemaless_insert(taos, lines , sizeof(lines)/sizeof(char*), TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines1]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - char* lines2[] = { - "stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000" - }; - result = taos_schemaless_insert(taos, &lines2[0], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines2_0]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - result = taos_schemaless_insert(taos, &lines2[1], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines2_1]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - char* lines3[] = { - "sth,t1=4i64,t2=5f64,t4=5f64,ID=childTable c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933641", - "sth,t1=4i64,t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin_stf\",c2=false,c5=5f64,c6=7u64 1626006933654" - }; - result = taos_schemaless_insert(taos, lines3, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines3]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - char* lines4[] = { - "st123456,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "dgtyqodr,t2=5f64,t3=L\"ste\" c1=tRue,c2=4i64,c3=\"iam\" 1626056811823316532" - }; - result = taos_schemaless_insert(taos, lines4, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines4]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - - char* lines5[] = { - "zqlbgs,id=zqlbgs_39302_21680,t0=f,t1=127i8,t2=32767i16,t3=2147483647i32,t4=9223372036854775807i64,t5=11.12345f32,t6=22.123456789f64,t7=\"binaryTagValue\",t8=L\"ncharTagValue\" c0=f,c1=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=11.12345f32,c6=22.123456789f64,c7=\"binaryColValue\",c8=L\"ncharColValue\",c9=7u64 1626006833639000000", - "zqlbgs,t9=f,id=zqlbgs_39302_21680,t0=f,t1=127i8,t11=127i8,t2=32767i16,t3=2147483647i32,t4=9223372036854775807i64,t5=11.12345f32,t6=22.123456789f64,t7=\"binaryTagValue\",t8=L\"ncharTagValue\",t10=L\"ncharTagValue\" c10=f,c0=f,c1=127i8,c12=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=11.12345f32,c6=22.123456789f64,c7=\"binaryColValue\",c8=L\"ncharColValue\",c9=7u64,c11=L\"ncharColValue\" 1626006833639000000" - }; - result = taos_schemaless_insert(taos, &lines5[0], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines5_0]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - result = taos_schemaless_insert(taos, &lines5[1], 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines5_1]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - char* lines6[] = { - "st123456,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000", - "dgtyqodr,t2=5f64,t3=L\"ste\" c1=tRue,c2=4i64,c3=\"iam\" 1626056811823316532" - }; - result = taos_schemaless_insert(taos, lines6, 2, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANO_SECONDS); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines6]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - - //Test timestamp precision - char* lines7[] = { - "stts,t1=10i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1", - }; - - for (int precision = TSDB_SML_TIMESTAMP_HOURS; precision <= TSDB_SML_TIMESTAMP_NANO_SECONDS; ++precision) { - result = taos_schemaless_insert(taos, lines7, 1, TSDB_SML_LINE_PROTOCOL, precision); - code = taos_errno(result); - if (code != TSDB_CODE_SUCCESS) { - affected_rows = taos_affected_rows(result); - printf("\033[31m [lines7_%d]taos_schemaless_insert failed, code: %d,%s, affected rows:%d \033[0m\n", precision, code, taos_errstr(result), affected_rows); - } - taos_free_result(result); - } - -} - -int main(int argc, char* argv[]) { - const char* host = "127.0.0.1"; - const char* user = "root"; - const char* passwd = "taosdata"; - - taos_options(TSDB_OPTION_TIMEZONE, "GMT-8"); - TAOS* taos = taos_connect(host, user, passwd, "", 0); - if (taos == NULL) { - printf("\033[31mfailed to connect to db, reason:%s\033[0m\n", taos_errstr(taos)); - exit(1); - } - - char* info = taos_get_server_info(taos); - printf("server info: %s\n", info); - info = taos_get_client_info(taos); - printf("client info: %s\n", info); - - printf("************ verify schema-less *************\n"); - verify_schema_less(taos); - - printf("************ verify query *************\n"); - verify_query(taos); - - printf("********* verify async query **********\n"); - verify_async(taos); - - printf("*********** verify subscribe ************\n"); - verify_subscribe(taos); - - printf("************ verify stream *************\n"); - // verify_stream(taos); - printf("done\n"); - taos_close(taos); - taos_cleanup(); -} diff --git a/tests/examples/c/asyncdemo.c b/tests/examples/c/asyncdemo.c deleted file mode 100644 index 78e41ddf5cad70ddb430dfdd5832e92d2800d030..0000000000000000000000000000000000000000 --- a/tests/examples/c/asyncdemo.c +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -// TAOS asynchronous API example -// this example opens multiple tables, insert/retrieve multiple tables -// it is used by TAOS internally for one performance testing -// to compiple: gcc -o asyncdemo asyncdemo.c -ltaos - -#include -#include -#include -#include -#include - -#include - -int points = 5; -int numOfTables = 3; -int tablesInsertProcessed = 0; -int tablesSelectProcessed = 0; -int64_t st, et; - -typedef struct { - int id; - TAOS * taos; - char name[16]; - time_t timeStamp; - int value; - int rowsInserted; - int rowsTried; - int rowsRetrieved; -} STable; - -void taos_insert_call_back(void *param, TAOS_RES *tres, int code); -void taos_select_call_back(void *param, TAOS_RES *tres, int code); -void taos_error(TAOS *taos); - -static void queryDB(TAOS *taos, char *command) { - int i; - TAOS_RES *pSql = NULL; - int32_t code = -1; - - for (i = 0; i < 5; i++) { - if (NULL != pSql) { - taos_free_result(pSql); - pSql = NULL; - } - - pSql = taos_query(taos, command); - code = taos_errno(pSql); - if (0 == code) { - break; - } - } - - if (code != 0) { - fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql)); - taos_free_result(pSql); - taos_close(taos); - taos_cleanup(); - exit(EXIT_FAILURE); - } - - taos_free_result(pSql); -} - -int main(int argc, char *argv[]) { - TAOS * taos; - struct timeval systemTime; - int i; - char sql[1024] = {0}; - char prefix[20] = {0}; - char db[128] = {0}; - STable * tableList; - - if (argc != 5) { - printf("usage: %s server-ip dbname rowsPerTable numOfTables\n", argv[0]); - exit(0); - } - - // a simple way to parse input parameters - if (argc >= 3) strcpy(db, argv[2]); - if (argc >= 4) points = atoi(argv[3]); - if (argc >= 5) numOfTables = atoi(argv[4]); - - size_t size = sizeof(STable) * (size_t)numOfTables; - tableList = (STable *)malloc(size); - memset(tableList, 0, size); - - taos = taos_connect(argv[1], "root", "taosdata", NULL, 0); - if (taos == NULL) taos_error(taos); - - printf("success to connect to server\n"); - - sprintf(sql, "drop database if exists %s", db); - queryDB(taos, sql); - - sprintf(sql, "create database %s", db); - queryDB(taos, sql); - - sprintf(sql, "use %s", db); - queryDB(taos, sql); - - strcpy(prefix, "asytbl_"); - for (i = 0; i < numOfTables; ++i) { - tableList[i].id = i; - tableList[i].taos = taos; - sprintf(tableList[i].name, "%s%d", prefix, i); - sprintf(sql, "create table %s%d (ts timestamp, volume bigint)", prefix, i); - queryDB(taos, sql); - } - - gettimeofday(&systemTime, NULL); - for (i = 0; i < numOfTables; ++i) - tableList[i].timeStamp = (time_t)(systemTime.tv_sec) * 1000 + systemTime.tv_usec / 1000; - - printf("success to create tables, press any key to insert\n"); - getchar(); - - printf("start to insert...\n"); - gettimeofday(&systemTime, NULL); - st = systemTime.tv_sec * 1000000 + systemTime.tv_usec; - - tablesInsertProcessed = 0; - tablesSelectProcessed = 0; - - for (i = 0; i < numOfTables; ++i) { - // insert records in asynchronous API - sprintf(sql, "insert into %s values(%ld, 0)", tableList[i].name, 1546300800000 + i); - taos_query_a(taos, sql, taos_insert_call_back, (void *)(tableList + i)); - } - - printf("once insert finished, presse any key to query\n"); - getchar(); - - while (1) { - if (tablesInsertProcessed < numOfTables) { - printf("wait for process finished\n"); - sleep(1); - continue; - } - - break; - } - - printf("start to query...\n"); - gettimeofday(&systemTime, NULL); - st = systemTime.tv_sec * 1000000 + systemTime.tv_usec; - - for (i = 0; i < numOfTables; ++i) { - // select records in asynchronous API - sprintf(sql, "select * from %s", tableList[i].name); - taos_query_a(taos, sql, taos_select_call_back, (void *)(tableList + i)); - } - - printf("\nonce finished, press any key to exit\n"); - getchar(); - - while (1) { - if (tablesSelectProcessed < numOfTables) { - printf("wait for process finished\n"); - sleep(1); - continue; - } - - break; - } - - for (i = 0; i < numOfTables; ++i) { - printf("%s inserted:%d retrieved:%d\n", tableList[i].name, tableList[i].rowsInserted, tableList[i].rowsRetrieved); - } - - taos_close(taos); - free(tableList); - - printf("==== async demo end====\n"); - printf("\n"); - return 0; -} - -void taos_error(TAOS *con) { - fprintf(stderr, "TDengine error: %s\n", taos_errstr(con)); - taos_close(con); - taos_cleanup(); - exit(1); -} - -void taos_insert_call_back(void *param, TAOS_RES *tres, int code) { - STable * pTable = (STable *)param; - struct timeval systemTime; - char sql[128]; - - pTable->rowsTried++; - - if (code < 0) { - printf("%s insert failed, code:%d, rows:%d\n", pTable->name, code, pTable->rowsTried); - } else if (code == 0) { - printf("%s not inserted\n", pTable->name); - } else { - pTable->rowsInserted++; - } - - if (pTable->rowsTried < points) { - // for this demo, insert another record - sprintf(sql, "insert into %s values(%ld, %d)", pTable->name, 1546300800000 + pTable->rowsTried * 1000, - pTable->rowsTried); - taos_query_a(pTable->taos, sql, taos_insert_call_back, (void *)pTable); - } else { - printf("%d rows data are inserted into %s\n", points, pTable->name); - tablesInsertProcessed++; - if (tablesInsertProcessed >= numOfTables) { - gettimeofday(&systemTime, NULL); - et = systemTime.tv_sec * 1000000 + systemTime.tv_usec; - printf("%lld mseconds to insert %d data points\n", (et - st) / 1000, points * numOfTables); - } - } - - taos_free_result(tres); -} - -void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows) { - STable * pTable = (STable *)param; - struct timeval systemTime; - - if (numOfRows > 0) { - for (int i = 0; i < numOfRows; ++i) { - // synchronous API to retrieve a row from batch of records - /*TAOS_ROW row = */ (void)taos_fetch_row(tres); - // process row - } - - pTable->rowsRetrieved += numOfRows; - - // retrieve next batch of rows - taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable); - - } else { - if (numOfRows < 0) printf("%s retrieve failed, code:%d\n", pTable->name, numOfRows); - - // taos_free_result(tres); - printf("%d rows data retrieved from %s\n", pTable->rowsRetrieved, pTable->name); - - tablesSelectProcessed++; - if (tablesSelectProcessed >= numOfTables) { - gettimeofday(&systemTime, NULL); - et = systemTime.tv_sec * 1000000 + systemTime.tv_usec; - printf("%lld mseconds to query %d data rows\n", (et - st) / 1000, points * numOfTables); - } - - taos_free_result(tres); - } -} - -void taos_select_call_back(void *param, TAOS_RES *tres, int code) { - STable *pTable = (STable *)param; - - if (code == 0 && tres) { - // asynchronous API to fetch a batch of records - taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable); - } else { - printf("%s select failed, code:%d\n", pTable->name, code); - taos_free_result(tres); - taos_cleanup(); - exit(1); - } -} diff --git a/tests/examples/c/clientcfgtest-taosd.c b/tests/examples/c/clientcfgtest-taosd.c deleted file mode 100644 index fbfbd8935a34481c23e806bbe461882ed9a10437..0000000000000000000000000000000000000000 --- a/tests/examples/c/clientcfgtest-taosd.c +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include -#include -#include -#include -#include "os.h" -#include "taosdef.h" -#include "taoserror.h" -#include "tconfig.h" -#include "tglobal.h" -#include "tulog.h" -#include "tsocket.h" -#include "tutil.h" -extern SGlobalCfg *taosGetConfigOption(const char *option) ; -int main( int argc, char *argv[]){ - - printf("start to test\n"); - - //case1: - //Test config to wrong type - const char config1[128] = "{\"cache\":\"4\"}";//input the parameter which want to be configured - taos_set_config(config1); //configure the parameter - - SGlobalCfg *cfg1 ; - - cfg1 = taosGetConfigOption("cache");//check the option result - if(cfg1->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config cache to '4'success!\n"); - else - printf("config cache failure!\n"); - return 0 ; - -} diff --git a/tests/examples/c/clientcfgtest-wrongjson.c b/tests/examples/c/clientcfgtest-wrongjson.c deleted file mode 100644 index eecb5dae6d27c213731afdea005af3fc265dd47f..0000000000000000000000000000000000000000 --- a/tests/examples/c/clientcfgtest-wrongjson.c +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include -#include -#include -#include -#include "os.h" -#include "taosdef.h" -#include "taoserror.h" -#include "tconfig.h" -#include "tglobal.h" -#include "tulog.h" -#include "tsocket.h" -#include "tutil.h" -extern SGlobalCfg *taosGetConfigOption(const char *option) ; -int main( int argc, char *argv[]){ - - printf("start to test\n"); - - //case1: - //Test config with wrong JSON - //The result is failure - const char config1[128] = "{\"firstEp\":\"BCC-2:6030\",\"debugFlag\":\135\"}";//input the parameter which want to be configured - taos_set_config(config1); //configure the parameter - - SGlobalCfg *cfg1 ; - cfg1 = taosGetConfigOption("firstEp");//check the option result - if(cfg1->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config firstEp 'BCC-2:6030'success!\n"); - else - printf("config firstEp failure!\n"); - SGlobalCfg *cfg2 ; - cfg2 = taosGetConfigOption("debugFlag");//check the option result - if(cfg1->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config debugFlag '135'success!\n"); - else - printf("config debugFlag failure!\n"); - - - //case2: - //repair the JSON and try again - //The result is success - const char config2[128] = "{\"firstEp\":\"BCC-2:6030\",\"debugFlag\":\"135\"}";//input the parameter which want to be configured - taos_set_config(config2); //configure the parameter - - SGlobalCfg *cfg3 ; - - cfg3 = taosGetConfigOption("firstEp");//check the option result - if(cfg3->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config firstEp 'BCC-2:6030'success!\n"); - else - printf("config firstEp failure!\n"); - - SGlobalCfg *cfg4 ; - - cfg4 = taosGetConfigOption("debugFlag");//check the option result - if(cfg4->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config debugFlag '135'success!\n"); - else - printf("config debugFlag failure!\n"); - return 0 ; - -} diff --git a/tests/examples/c/clientcfgtest-wrongtype.c b/tests/examples/c/clientcfgtest-wrongtype.c deleted file mode 100644 index d88cbeebe8e5114ed4836e77b9494de1cc54aba8..0000000000000000000000000000000000000000 --- a/tests/examples/c/clientcfgtest-wrongtype.c +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include -#include -#include -#include -#include "os.h" -#include "taosdef.h" -#include "taoserror.h" -#include "tconfig.h" -#include "tglobal.h" -#include "tulog.h" -#include "tsocket.h" -#include "tutil.h" -extern SGlobalCfg *taosGetConfigOption(const char *option) ; -int main( int argc, char *argv[]){ - - printf("start to test\n"); - - //case1: - //Test config to wrong type - //The result is failure - const char config1[128] = "{\"debugFlag\":\"9999999999999999999999999\"}";//input the parameter which want to be configured - taos_set_config(config1); //configure the parameter - - SGlobalCfg *cfg1 ; - - cfg1 = taosGetConfigOption("debugFlag");//check the option result - if(cfg1->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config debugFlag '9999999999999999999999999\n"); - else - printf("config debugFlag failure!\n"); - - //case2: - //Try again with right parameter - //The result is failure - const char config2[128] = "{\"debugFlag\":\"135\"}";//input the parameter which want to be configured - taos_set_config(config2); //configure the parameter - - SGlobalCfg *cfg2 ; - - cfg2 = taosGetConfigOption("debugFlag");//check the option result - if(cfg2->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config debugflag '135'success!\n"); - else - printf("config debugflag failure!\n"); - return 0 ; - -} diff --git a/tests/examples/c/clientcfgtest-wrongvalue.c b/tests/examples/c/clientcfgtest-wrongvalue.c deleted file mode 100644 index f0d44a47f62696d14844ea12276b74da7d0ff408..0000000000000000000000000000000000000000 --- a/tests/examples/c/clientcfgtest-wrongvalue.c +++ /dev/null @@ -1,46 +0,0 @@ -#include -#include -#include -#include -#include -#include "os.h" -#include "taosdef.h" -#include "taoserror.h" -#include "tconfig.h" -#include "tglobal.h" -#include "tulog.h" -#include "tsocket.h" -#include "tutil.h" -extern SGlobalCfg *taosGetConfigOption(const char *option) ; -int main( int argc, char *argv[]){ - - printf("start to test\n"); - - //case1: - //Test config to wrong type - const char config1[128] = "{\"rpcTimer\":\"0\"}";//input the parameter which want to be configured - taos_set_config(config1); //configure the parameter - - SGlobalCfg *cfg1 ; - - cfg1 = taosGetConfigOption("rpcTimer");//check the option result - if(cfg1->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config rpcTimer to '0'success!\n"); - else - printf("config rpcTimer failure!\n"); - - //case2: - //Try again with right parameter - const char config2[128] = "{\"rpcTimer\":\"400\"}";//input the parameter which want to be configured - taos_set_config(config2); //configure the parameter - - SGlobalCfg *cfg2 ; - - cfg2 = taosGetConfigOption("rpcTimer");//check the option result - if(cfg2->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config rpcTimer '400'success!\n"); - else - printf("config rpcTimer failure!\n"); - return 0 ; - -} diff --git a/tests/examples/c/clientcfgtest.c b/tests/examples/c/clientcfgtest.c deleted file mode 100644 index 5f8f51cdb1156a25544273fc6419f65b86ea4ecc..0000000000000000000000000000000000000000 --- a/tests/examples/c/clientcfgtest.c +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include -#include -#include -#include -#include "os.h" -#include "taosdef.h" -#include "taoserror.h" -#include "tconfig.h" -#include "tglobal.h" -#include "tulog.h" -#include "tsocket.h" -#include "tutil.h" -extern SGlobalCfg *taosGetConfigOption(const char *option) ; -int main( int argc, char *argv[]){ - - printf("start to test\n"); - - //case1: - //Test config firstEp success - const char config1[128] = "{\"firstEp\":\"BCC-2:6030\",\"debugFlag\":\"135\"}";//input the parameter which want to be configured - taos_set_config(config1); //configure the parameter - - SGlobalCfg *cfg1 ; - - cfg1 = taosGetConfigOption("firstEp");//check the option result - if(cfg1->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config firstEp 'BCC-2:6030'success!\n"); - else - printf("config firstEp failure!\n"); - - - SGlobalCfg *cfg2 ; - - cfg2 = taosGetConfigOption("debugFlag");//check the option result - if(cfg2->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config debugFlag '135' success!\n"); - else - printf("config debugFlag failure!\n"); - //case2: - //Test config only useful at the first time - //The result is failure - const char config2[128] = "{\"fqdn\":\"BCC-3\"}";//input the parameter which want to be configured - taos_set_config(config2); //configure the parameter - - SGlobalCfg *cfg3 ; - - cfg2 = taosGetConfigOption("fqdn");//check the option result - if(cfg2->cfgStatus == 3) //If cfgStatus is 3,it means configure is success - printf("config fqdn to 'BCC-3'success!\n"); - else - printf("config fqdn failure!\n"); - return 0 ; - -} diff --git a/tests/examples/c/connect_two_cluster.c b/tests/examples/c/connect_two_cluster.c deleted file mode 100644 index fa54dd437036f12915d62a60f96b90e6a7adc45f..0000000000000000000000000000000000000000 --- a/tests/examples/c/connect_two_cluster.c +++ /dev/null @@ -1,162 +0,0 @@ -#include -#include -#include -#include -#include "taos.h" -int numOfThreads = 1; - -void* connectClusterAndDeal(void *arg) { - int port = *(int *)arg; - const char *host = "127.0.0.1"; - const char *user = "root"; - const char *passwd = "taosdata"; - TAOS* taos1 = taos_connect(host, user, passwd, "", port); - TAOS* taos2 = taos_connect(host, user, passwd, "", port + 1000); - if (NULL == taos1 || NULL == taos2) { - printf("connect to (%d/%d) failed \n", port, port + 1000); - return NULL; - } - TAOS_RES *result = NULL; - result = taos_query(taos1, "drop database if exists db"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - - taos_query(taos2, "drop database if exists db"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - - taos_free_result(result); - // ========= build database - { - result = taos_query(taos1, "create database db"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - - taos_free_result(result); - } - { - result = taos_query(taos2, "create database db"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - } - - //======== create table - { - result = taos_query(taos1, "create stable db.stest (ts timestamp, port int) tags(tport int)"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - } - { - result = taos_query(taos2, "create stable db.stest (ts timestamp, port int) tags(tport int)"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - - } - //======== create table - { - result = taos_query(taos1, "use db"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - } - { - result = taos_query(taos2, "use db"); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - - } - { - char buf[1024] = {0}; - sprintf(buf, "insert into db.t1 using stest tags(%d) values(now, %d)", port, port); - for (int i = 0; i < 100000; i++) { - //printf("error here\t"); - result = taos_query(taos1, buf); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - //sleep(1); - } - } - - { - char buf[1024] = {0}; - sprintf(buf, "insert into db.t1 using stest tags(%d) values(now, %d)", port + 1000, port + 1000); - for (int i = 0; i < 100000; i++) { - result = taos_query(taos2, buf); - if (0 != taos_errno(result)) { - printf("failed %s\n", taos_errstr(result)); - } - taos_free_result(result); - //sleep(1); - } - } - // query result - { - result = taos_query(taos1, "select * from stest"); - if (result == NULL || taos_errno(result) != 0) { - printf("query failed %s\n", taos_errstr(result)); - taos_free_result(result); - } - TAOS_ROW row; - int rows = 0; - int num_fields = taos_field_count(result); - TAOS_FIELD *fields = taos_fetch_fields(result); - while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields , num_fields); - printf("%s\n", temp); - } - taos_free_result(result); - } - - // query result - { - result = taos_query(taos2, "select * from stest"); - if (result == NULL || taos_errno(result) != 0) { - printf("query failed %s\n", taos_errstr(result)); - taos_free_result(result); - } - TAOS_ROW row; - int rows = 0; - int num_fields = taos_field_count(result); - TAOS_FIELD *fields = taos_fetch_fields(result); - while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields , num_fields); - printf("%s\n", temp); - } - taos_free_result(result); - } - taos_close(taos1); - taos_close(taos2); - return NULL; -} -int main(int argc, char* argv[]) { - pthread_t *pthreads = malloc(sizeof(pthread_t) * numOfThreads); - - int *port = malloc(sizeof(int) * numOfThreads); - port[0] = 6030; - for (int i = 0; i < numOfThreads; i++) { - pthread_create(&pthreads[i], NULL, connectClusterAndDeal, (void *)&port[i]); - } - for (int i = 0; i < numOfThreads; i++) { - pthread_join(pthreads[i], NULL); - } - free(port); -} diff --git a/tests/examples/c/demo.c b/tests/examples/c/demo.c deleted file mode 100644 index 55d962888871c2ba175daef85f1084a1e28a0da1..0000000000000000000000000000000000000000 --- a/tests/examples/c/demo.c +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -// TAOS standard API example. The same syntax as MySQL, but only a subset -// to compile: gcc -o demo demo.c -ltaos - -#include -#include -#include -#include -#include // TAOS header file - -static void queryDB(TAOS *taos, char *command) { - int i; - TAOS_RES *pSql = NULL; - int32_t code = -1; - - for (i = 0; i < 5; i++) { - if (NULL != pSql) { - taos_free_result(pSql); - pSql = NULL; - } - - pSql = taos_query(taos, command); - code = taos_errno(pSql); - if (0 == code) { - break; - } - } - - if (code != 0) { - fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql)); - taos_free_result(pSql); - taos_close(taos); - exit(EXIT_FAILURE); - } - - taos_free_result(pSql); -} - -void Test(TAOS *taos, char *qstr, int i); - -int main(int argc, char *argv[]) { - char qstr[1024]; - - // connect to server - if (argc < 2) { - printf("please input server-ip \n"); - return 0; - } - - TAOS *taos = taos_connect(argv[1], "root", "taosdata", NULL, 0); - if (taos == NULL) { - printf("failed to connect to server, reason:%s\n", "null taos" /*taos_errstr(taos)*/); - exit(1); - } - for (int i = 0; i < 100; i++) { - Test(taos, qstr, i); - } - taos_close(taos); - taos_cleanup(); -} -void Test(TAOS *taos, char *qstr, int index) { - printf("==================test at %d\n================================", index); - queryDB(taos, "drop database if exists demo"); - queryDB(taos, "create database demo"); - TAOS_RES *result; - queryDB(taos, "use demo"); - - queryDB(taos, - "create table m1 (ts timestamp, ti tinyint, si smallint, i int, bi bigint, f float, d double, b binary(10))"); - printf("success to create table\n"); - - int i = 0; - for (i = 0; i < 10; ++i) { - sprintf(qstr, "insert into m1 values (%" PRId64 ", %d, %d, %d, %d, %f, %lf, '%s')", - (uint64_t)(1546300800000 + i * 1000), i, i, i, i * 10000000, i * 1.0, i * 2.0, "hello"); - printf("qstr: %s\n", qstr); - - // note: how do you wanna do if taos_query returns non-NULL - // if (taos_query(taos, qstr)) { - // printf("insert row: %i, reason:%s\n", i, taos_errstr(taos)); - // } - TAOS_RES *result1 = taos_query(taos, qstr); - if (result1 == NULL || taos_errno(result1) != 0) { - printf("failed to insert row, reason:%s\n", taos_errstr(result1)); - taos_free_result(result1); - exit(1); - } else { - printf("insert row: %i\n", i); - } - taos_free_result(result1); - } - printf("success to insert rows, total %d rows\n", i); - - // query the records - sprintf(qstr, "SELECT * FROM m1"); - result = taos_query(taos, qstr); - if (result == NULL || taos_errno(result) != 0) { - printf("failed to select, reason:%s\n", taos_errstr(result)); - taos_free_result(result); - exit(1); - } - - TAOS_ROW row; - int rows = 0; - int num_fields = taos_field_count(result); - TAOS_FIELD *fields = taos_fetch_fields(result); - - printf("num_fields = %d\n", num_fields); - printf("select * from table, result:\n"); - // fetch the records row by row - while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("%s\n", temp); - } - - taos_free_result(result); - printf("====demo end====\n\n"); -} diff --git a/tests/examples/c/epoll.c b/tests/examples/c/epoll.c deleted file mode 100644 index 05df33ffe6f0c08dd5608bb3ba30a21623f2ae45..0000000000000000000000000000000000000000 --- a/tests/examples/c/epoll.c +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -// how to use to do a pressure-test upon eok -// tester: cat /dev/urandom | nc -c -// testee: ./debug/build/bin/epoll -l > /dev/null -// compare against: nc -l > /dev/null -// monitor and compare : glances - -#ifdef __APPLE__ -#include "osEok.h" -#else // __APPLE__ -#include -#endif // __APPLE__ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define D(fmt, ...) fprintf(stderr, "%s[%d]%s(): " fmt "\n", basename(__FILE__), __LINE__, __func__, ##__VA_ARGS__) -#define A(statement, fmt, ...) \ - do { \ - if (statement) break; \ - fprintf(stderr, "%s[%d]%s(): assert [%s] failed: %d[%s]: " fmt "\n", basename(__FILE__), __LINE__, __func__, \ - #statement, errno, strerror(errno), ##__VA_ARGS__); \ - abort(); \ - } while (0) - -#define E(fmt, ...) \ - do { \ - fprintf(stderr, "%s[%d]%s(): %d[%s]: " fmt "\n", basename(__FILE__), __LINE__, __func__, errno, strerror(errno), \ - ##__VA_ARGS__); \ - } while (0) - -#include "os.h" - -typedef struct ep_s ep_t; -struct ep_s { - int ep; - - pthread_mutex_t lock; - int sv[2]; // 0 for read, 1 for write; - pthread_t thread; - - volatile unsigned int stopping : 1; - volatile unsigned int waiting : 1; - volatile unsigned int wakenup : 1; -}; - -static int ep_dummy = 0; - -static ep_t *ep_create(void); -static void ep_destroy(ep_t *ep); -static void *routine(void *arg); -static int open_listen(unsigned short port); - -typedef struct fde_s fde_t; -struct fde_s { - int skt; - void (*on_event)(ep_t *ep, struct epoll_event *events, fde_t *client); -}; - -static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client); -static void null_event(ep_t *ep, struct epoll_event *ev, fde_t *client); - -#define usage(arg0, fmt, ...) \ - do { \ - if (fmt[0]) { \ - fprintf(stderr, "" fmt "\n", ##__VA_ARGS__); \ - } \ - fprintf(stderr, "usage:\n"); \ - fprintf(stderr, " %s -l : specify listening port\n", arg0); \ - } while (0) - -int main(int argc, char *argv[]) { - char *prg = basename(argv[0]); - if (argc == 1) { - usage(prg, ""); - return 0; - } - ep_t *ep = ep_create(); - A(ep, "failed"); - for (int i = 1; i < argc; ++i) { - const char *arg = argv[i]; - if (0 == strcmp(arg, "-l")) { - ++i; - if (i >= argc) { - usage(prg, "expecting after -l, but got nothing"); - return 1; // confirmed potential leakage - } - arg = argv[i]; - int port = atoi(arg); - int skt = open_listen(port); - if (skt == -1) continue; - fde_t *client = (fde_t *)calloc(1, sizeof(*client)); - if (!client) { - E("out of memory"); - close(skt); - continue; - } - client->skt = skt; - client->on_event = listen_event; - struct epoll_event ev = {0}; - ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP; - ev.data.ptr = client; - A(0 == epoll_ctl(ep->ep, EPOLL_CTL_ADD, skt, &ev), ""); - continue; - } - usage(prg, "unknown argument: [%s]", arg); - return 1; - } - char * line = NULL; - size_t linecap = 0; - ssize_t linelen; - while ((linelen = getline(&line, &linecap, stdin)) > 0) { - line[strlen(line) - 1] = '\0'; - if (0 == strcmp(line, "exit")) break; - if (0 == strcmp(line, "quit")) break; - if (line == strstr(line, "close")) { - int fd = 0; - sscanf(line, "close %d", &fd); - if (fd <= 2) { - fprintf(stderr, "fd [%d] invalid\n", fd); - continue; - } - A(0 == epoll_ctl(ep->ep, EPOLL_CTL_DEL, fd, NULL), ""); - continue; - } - if (strlen(line) == 0) continue; - fprintf(stderr, "unknown cmd:[%s]\n", line); - } - ep_destroy(ep); - D(""); - return 0; -} - -ep_t *ep_create(void) { - ep_t *ep = (ep_t *)calloc(1, sizeof(*ep)); - A(ep, "out of memory"); - A(-1 != (ep->ep = epoll_create(1)), ""); - ep->sv[0] = -1; - ep->sv[1] = -1; - A(0 == socketpair(AF_LOCAL, SOCK_STREAM, 0, ep->sv), ""); - A(0 == pthread_mutex_init(&ep->lock, NULL), ""); - A(0 == pthread_mutex_lock(&ep->lock), ""); - struct epoll_event ev = {0}; - ev.events = EPOLLIN; - ev.data.ptr = &ep_dummy; - A(0 == epoll_ctl(ep->ep, EPOLL_CTL_ADD, ep->sv[0], &ev), ""); - A(0 == pthread_create(&ep->thread, NULL, routine, ep), ""); - A(0 == pthread_mutex_unlock(&ep->lock), ""); - return ep; -} - -static void ep_destroy(ep_t *ep) { - A(ep, "invalid argument"); - ep->stopping = 1; - A(1 == send(ep->sv[1], "1", 1, 0), ""); - A(0 == pthread_join(ep->thread, NULL), ""); - A(0 == pthread_mutex_destroy(&ep->lock), ""); - A(0 == close(ep->sv[0]), ""); - A(0 == close(ep->sv[1]), ""); - A(0 == close(ep->ep), ""); - free(ep); -} - -static void *routine(void *arg) { - A(arg, "invalid argument"); - ep_t *ep = (ep_t *)arg; - - while (!ep->stopping) { - struct epoll_event evs[10]; - memset(evs, 0, sizeof(evs)); - - A(0 == pthread_mutex_lock(&ep->lock), ""); - A(ep->waiting == 0, "internal logic error"); - ep->waiting = 1; - A(0 == pthread_mutex_unlock(&ep->lock), ""); - - int r = epoll_wait(ep->ep, evs, sizeof(evs) / sizeof(evs[0]), -1); - A(r > 0, "indefinite epoll_wait shall not timeout:[%d]", r); - - A(0 == pthread_mutex_lock(&ep->lock), ""); - A(ep->waiting == 1, "internal logic error"); - ep->waiting = 0; - A(0 == pthread_mutex_unlock(&ep->lock), ""); - - for (int i = 0; i < r; ++i) { - struct epoll_event *ev = evs + i; - if (ev->data.ptr == &ep_dummy) { - char c = '\0'; - A(1 == recv(ep->sv[0], &c, 1, 0), "internal logic error"); - A(0 == pthread_mutex_lock(&ep->lock), ""); - ep->wakenup = 0; - A(0 == pthread_mutex_unlock(&ep->lock), ""); - continue; - } - A(ev->data.ptr, "internal logic error"); - fde_t *client = (fde_t *)ev->data.ptr; - client->on_event(ep, ev, client); - continue; - } - } - return NULL; -} - -static int open_listen(unsigned short port) { - int r = 0; - int skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (skt == -1) { - E("socket() failed"); - return -1; - } - do { - struct sockaddr_in si = {0}; - si.sin_family = AF_INET; - si.sin_addr.s_addr = inet_addr("0.0.0.0"); - si.sin_port = htons(port); - r = bind(skt, (struct sockaddr *)&si, sizeof(si)); - if (r) { - E("bind(%u) failed", port); - break; - } - r = listen(skt, 100); - if (r) { - E("listen() failed"); - break; - } - memset(&si, 0, sizeof(si)); - socklen_t len = sizeof(si); - r = getsockname(skt, (struct sockaddr *)&si, &len); - if (r) { - E("getsockname() failed"); - } - A(len == sizeof(si), "internal logic error"); - D("listening at: %d", ntohs(si.sin_port)); - return skt; - } while (0); - close(skt); - return -1; -} - -static void listen_event(ep_t *ep, struct epoll_event *ev, fde_t *client) { - A(ev->events & EPOLLIN, "internal logic error"); - struct sockaddr_in si = {0}; - socklen_t silen = sizeof(si); - int skt = accept(client->skt, (struct sockaddr *)&si, &silen); - A(skt != -1, "internal logic error"); - fde_t *server = (fde_t *)calloc(1, sizeof(*server)); - if (!server) { - close(skt); - return; - } - server->skt = skt; - server->on_event = null_event; - struct epoll_event ee = {0}; - ee.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP; - ee.data.ptr = server; - A(0 == epoll_ctl(ep->ep, EPOLL_CTL_ADD, skt, &ee), ""); -} - -static void null_event(ep_t *ep, struct epoll_event *ev, fde_t *client) { - if (ev->events & EPOLLIN) { - char buf[8192]; - int n = recv(client->skt, buf, sizeof(buf), 0); - A(n >= 0 && n <= sizeof(buf), "internal logic error:[%d]", n); - A(n == fwrite(buf, 1, n, stdout), "internal logic error"); - } - if (ev->events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) { - A(0 == pthread_mutex_lock(&ep->lock), ""); - A(0 == epoll_ctl(ep->ep, EPOLL_CTL_DEL, client->skt, NULL), ""); - A(0 == pthread_mutex_unlock(&ep->lock), ""); - close(client->skt); - client->skt = -1; - client->on_event = NULL; - free(client); - } -} diff --git a/tests/examples/c/makefile b/tests/examples/c/makefile deleted file mode 100644 index 355d1a2d54c1293e909309dafe986daa716ac293..0000000000000000000000000000000000000000 --- a/tests/examples/c/makefile +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2017 by TAOS Technologies, Inc. -# todo: library dependency, header file dependency - -ROOT=./ -TARGET=exe -LFLAGS = '-Wl,-rpath,/usr/local/taos/driver/' -ltaos -lpthread -lm -lrt -CFLAGS = -O3 -g -Wall -Wno-deprecated -fPIC -Wno-unused-result -Wconversion \ - -Wno-char-subscripts -D_REENTRANT -Wno-format -D_REENTRANT -DLINUX \ - -Wno-unused-function -D_M_X64 -I/usr/local/taos/include -std=gnu99 \ - -I../../../deps/cJson/inc \ - -Wno-unused-function -D_M_X64 -I/usr/local/taos/include -std=gnu99 \ - -fsanitize=address -fsanitize=undefined -fno-sanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment - -all: $(TARGET) - -exe: - gcc $(CFLAGS) ./asyncdemo.c -o $(ROOT)asyncdemo $(LFLAGS) - gcc $(CFLAGS) ./demo.c -o $(ROOT)demo $(LFLAGS) - gcc $(CFLAGS) ./prepare.c -o $(ROOT)prepare $(LFLAGS) - gcc $(CFLAGS) ./stream.c -o $(ROOT)stream $(LFLAGS) - gcc $(CFLAGS) ./subscribe.c -o $(ROOT)subscribe $(LFLAGS) - gcc $(CFLAGS) ./apitest.c -o $(ROOT)apitest $(LFLAGS) - -clean: - rm $(ROOT)asyncdemo - rm $(ROOT)demo - rm $(ROOT)prepare - rm $(ROOT)stream - rm $(ROOT)subscribe - rm $(ROOT)apitest diff --git a/tests/examples/c/parameter-binding.c b/tests/examples/c/parameter-binding.c deleted file mode 100644 index 6034c66cbf21b1e3ae819d3f40ec032118a5b01c..0000000000000000000000000000000000000000 --- a/tests/examples/c/parameter-binding.c +++ /dev/null @@ -1,607 +0,0 @@ -#include -#include -#include -#include -#include - -bool isPrint = true; - -void one_batch_one_table_1(TAOS *conn, long totalRows, long batchRows); -void one_batch_one_table_2(TAOS *conn, long totalRows, long batchRows); -void one_batch_one_table_3(TAOS *conn, long totalRows, long batchRows); -void one_batch_one_table_4(TAOS *conn, long totalRows, long batchRows); -void one_batch_one_table_5(TAOS *conn, long totalRows, long batchRows); -void one_batch_one_table_6(TAOS *conn, long totalRows, long batchRows); -void one_batch_one_table_7(TAOS *conn, long totalRows, long batchRows); - -void one_batch_multi_table_1(TAOS *conn, long totalRows, long batchRows, int tables); -void one_batch_multi_table_2(TAOS *conn, long totalRows, long batchRows, int tables); -void one_batch_multi_table_3(TAOS *conn, long totalRows, long batchRows, int tables); - -void execute(TAOS *conn, char *sql); -void prepare_normal_table(TAOS *conn); -void prepare_super_and_sub_table(TAOS *conn, int subTables); -void prepare_super_table(TAOS *conn, int subTables); -int64_t getCurrentTimeMill(); - -TAOS_STMT *A(TAOS *); -void B(TAOS_STMT *stmt, char sql[]); -void C(TAOS_STMT *stmt, char sql[]); -void D(TAOS_STMT *stmt, char sql[], int tag); -void E(TAOS_STMT *stmt); -void F(TAOS_STMT *stmt, int64_t ts_start); -void G1(TAOS_STMT *stmt, int64_t ts_start, int rows); -void G2(TAOS_STMT *stmt, int rows); -void H(TAOS_STMT *stmt, int64_t ts_start, int rows); -void I(TAOS_STMT *stmt); -void J(TAOS_STMT *stmt); -void L(TAOS_STMT *stmt); - -int main() { - char host[] = "192.168.56.105"; - srand(time(NULL)); - - // connect - TAOS *conn = taos_connect(host, "root", "taosdata", NULL, 0); - if (conn == NULL) { - printf("failed to connect to:%s, reason:%s\n", host, "null taos"); - exit(-1); - } - execute(conn, "drop database if exists test"); - execute(conn, "create database if not exists test"); - execute(conn, "use test"); - - long totalRows = 1000000; - long batchRows = 32767; - int tables = 10; - - prepare_super_table(conn, 1); - // A -> B -> D -> [F -> I]... -> J -> L - // one_batch_one_table_1(conn, totalRows, batchRows); - // A -> B -> [D -> [F -> I]... -> J]... -> L - // one_batch_one_table_2(conn, totalRows, batchRows); - // A -> B -> D -> [F... -> I -> J]... -> L - // one_batch_one_table_3(conn, totalRows, batchRows); - // A -> B -> D -> [H -> I -> J]... -> L - // one_batch_one_table_4(conn, totalRows, batchRows); - // A -> B -> [D -> H -> I -> J]... -> L - // one_batch_one_table_5(conn, totalRows, batchRows); - // A -> B -> [D -> H -> I -> J]... -> L - // one_batch_one_table_6(conn, totalRows, batchRows); - // A -> B -> [D -> H -> I -> J]... -> L - // one_batch_one_table_7(conn, totalRows, batchRows); - - // A -> B -> [D -> [F -> I]... -> J]... -> L - // one_batch_multi_table_1(conn, totalRows, batchRows, tables); - // A -> B -> [D -> H -> I -> J]... -> L - // one_batch_multi_table_2(conn, totalRows, batchRows, tables); - // A -> B -> [D -> G1 -> G2 -> I -> J]... -> L - one_batch_multi_table_3(conn, totalRows, batchRows, tables); - - // close - taos_close(conn); - taos_cleanup(); - exit(0); -} - -// A -> B -> D -> [F -> I]... -> J -> L -void one_batch_one_table_1(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) (ts, f1) values(?, ?)"); - D(stmt, "t1", 1); - for (int i = 1; i <= totalRows; ++i) { - F(stmt, (current + i - 1) * 1000); - I(stmt); - if (i % batchRows == 0 || i == totalRows) { - J(stmt); - } - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -// A -> B -> D -> [F -> I]... -> J -> L -void one_batch_one_table_2(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) (ts, f1) values(?, ?)"); - for (int i = 1; i <= totalRows; ++i) { - if (i % batchRows == 1) { - D(stmt, "t1", 1); - } - - F(stmt, (current + i - 1) * 1000); - I(stmt); - if (i % batchRows == 0 || i == totalRows) { - J(stmt); - } - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -void one_batch_one_table_3(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) (ts, f1) values(?, ?)"); - D(stmt, "t1", 1); - for (int i = 1; i <= totalRows; ++i) { - F(stmt, (current + i - 1) * 1000); - if (i % batchRows == 0 || i == totalRows) { - I(stmt); - J(stmt); - } - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -void one_batch_one_table_4(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?,?)"); - D(stmt, "t1", 1); - for (int i = 1; i <= totalRows; i += batchRows) { - int rows = (i + batchRows) > totalRows ? (totalRows + 1 - i) : batchRows; - H(stmt, (current + i) * 1000, rows); - I(stmt); - J(stmt); - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -void one_batch_one_table_5(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?,?)"); - for (int i = 1; i <= totalRows; i += batchRows) { - D(stmt, "t1", 1); - int rows = (i + batchRows) > totalRows ? (totalRows + 1 - i) : batchRows; - H(stmt, (current + i) * 1000, rows); - I(stmt); - J(stmt); - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -void one_batch_one_table_6(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?,?)"); - D(stmt, "t1", 1); - for (int i = 1; i <= totalRows; i += batchRows) { - int rows = (i + batchRows) > totalRows ? (totalRows + 1 - i) : batchRows; - G1(stmt, (current + i) * 1000, rows); - G2(stmt, rows); - I(stmt); - J(stmt); - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -void one_batch_one_table_7(TAOS *conn, long totalRows, long batchRows) { - // given - time_t current; - time(¤t); - current -= totalRows; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?,?)"); - for (int i = 1; i <= totalRows; i += batchRows) { - if (i % batchRows == 1) { - D(stmt, "t1", 1); - } - int rows = (i + batchRows) > totalRows ? (totalRows + 1 - i) : batchRows; - G1(stmt, (current + i) * 1000, rows); - G2(stmt, rows); - I(stmt); - J(stmt); - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, time cost: %lld ms\n", totalRows, batchRows, (end - start)); -} - -void one_batch_multi_table_1(TAOS *conn, long totalRows, long batchRows, int tables) { - // given - time_t current; - time(¤t); - long eachTable = (totalRows - 1) / tables + 1; - current -= eachTable; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?, ?)"); - - for (int tbIndex = 0; tbIndex < tables; ++tbIndex) { - char tbname[10]; - sprintf(tbname, "t%d", tbIndex); - - eachTable = ((tbIndex + 1) * eachTable > totalRows) ? (totalRows - tbIndex * eachTable) : eachTable; - for (int rowIndex = 1; rowIndex <= eachTable; ++rowIndex) { - if (rowIndex % batchRows == 1) { - D(stmt, tbname, tbIndex); - if (isPrint) - printf("\ntbIndex: %d, table_rows: %ld, rowIndex: %d, batch_rows: %ld\n", tbIndex, eachTable, rowIndex, - batchRows); - } - F(stmt, (current + rowIndex - 1) * 1000); - I(stmt); - if (rowIndex % batchRows == 0 || rowIndex == eachTable) { - J(stmt); - } - } - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, table: %d, eachTableRows: %ld, time cost: %lld ms\n", totalRows, batchRows, - tables, eachTable, (end - start)); -} - -void one_batch_multi_table_2(TAOS *conn, long totalRows, long batchRows, int tables) { - // given - time_t current; - time(¤t); - long eachTable = (totalRows - 1) / tables + 1; - current -= eachTable; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?,?)"); - for (int tbIndex = 0; tbIndex < tables; ++tbIndex) { - char tbname[10]; - sprintf(tbname, "t%d", tbIndex); - - eachTable = ((tbIndex + 1) * eachTable > totalRows) ? (totalRows - tbIndex * eachTable) : eachTable; - for (int rowIndex = 1; rowIndex <= eachTable; rowIndex += batchRows) { - int rows = (rowIndex + batchRows) > eachTable ? (eachTable + 1 - rowIndex) : batchRows; - - if (rowIndex % batchRows == 1) { - D(stmt, tbname, tbIndex); - if (isPrint) - printf("\ntbIndex: %d, table_rows: %ld, rowIndex: %d, batch_rows: %d\n", tbIndex, eachTable, rowIndex, rows); - } - - H(stmt, (current + rowIndex) * 1000, rows); - I(stmt); - J(stmt); - } - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, table: %d, eachTableRows: %ld, time cost: %lld ms\n", totalRows, batchRows, - tables, eachTable, (end - start)); -} - -void one_batch_multi_table_3(TAOS *conn, long totalRows, long batchRows, int tables) { - // given - time_t current; - time(¤t); - long eachTable = (totalRows - 1) / tables + 1; - current -= eachTable; - - int64_t start = getCurrentTimeMill(); - // when - TAOS_STMT *stmt = A(conn); - B(stmt, "insert into ? using weather tags(?) values(?, ?)"); - for (int tbIndex = 0; tbIndex < tables; ++tbIndex) { - char tbname[10]; - sprintf(tbname, "t%d", tbIndex); - - eachTable = ((tbIndex + 1) * eachTable > totalRows) ? (totalRows - tbIndex * eachTable) : eachTable; - for (int rowIndex = 1; rowIndex <= eachTable; rowIndex += batchRows) { - int rows = (rowIndex + batchRows) > eachTable ? (eachTable + 1 - rowIndex) : batchRows; - - if (rowIndex % batchRows == 1) { - D(stmt, tbname, tbIndex); - if (isPrint) - printf("\ntbIndex: %d, table_rows: %ld, rowIndex: %d, batch_rows: %d\n", tbIndex, eachTable, rowIndex, rows); - } - G1(stmt, (current + rowIndex) * 1000, rows); - G2(stmt, rows); - I(stmt); - J(stmt); - } - } - L(stmt); - - int64_t end = getCurrentTimeMill(); - printf("totalRows: %ld, batchRows: %ld, table: %d, eachTableRows: %ld, time cost: %lld ms\n", totalRows, batchRows, - tables, eachTable, (end - start)); -} - -void execute(TAOS *conn, char *sql) { - TAOS_RES *psql = taos_query(conn, sql); - if (psql == NULL) { - printf("failed to execute: %s, reason: %s\n", sql, taos_errstr(psql)); - taos_free_result(psql); - taos_close(conn); - exit(-1); - } - taos_free_result(psql); -} - -TAOS_STMT *A(TAOS *conn) { - if (isPrint) printf("A -> "); - return taos_stmt_init(conn); -} - -void B(TAOS_STMT *stmt, char sql[]) { - if (isPrint) printf("B -> "); - - int code = taos_stmt_prepare(stmt, sql, 0); - if (code != 0) { - printf("failed to prepare stmt: %s, reason: %s\n", sql, taos_stmt_errstr(stmt)); - return; - } -} - -void C(TAOS_STMT *stmt, char tbname[]) { - if (isPrint) printf("C -> "); - - int code = taos_stmt_set_tbname(stmt, tbname); - if (code != 0) printf("failed to set_tbname_tags, reason: %s\n", taos_stmt_errstr(stmt)); -} - -void D(TAOS_STMT *stmt, char tbname[], int tag) { - if (isPrint) printf("D -> "); - - TAOS_BIND tags[1]; - tags[0].buffer_type = TSDB_DATA_TYPE_INT; - int tag_value = tag >= 0 ? tag : rand() % 100; - tags[0].buffer = &tag_value; - tags[0].buffer_length = sizeof(tag_value); - tags[0].length = &tags[0].buffer_length; - tags[0].is_null = NULL; - // set_tbname_tags - int code = taos_stmt_set_tbname_tags(stmt, tbname, tags); - if (code != 0) printf("failed to set_tbname_tags, reason: %s\n", taos_stmt_errstr(stmt)); -} - -void E(TAOS_STMT *stmt) { - // TODO -} - -void F(TAOS_STMT *stmt, int64_t ts) { - if (isPrint) printf("F -> "); - - TAOS_BIND params[2]; - // timestamp - params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - params[0].buffer = &ts; - params[0].buffer_length = sizeof(ts); - params[0].length = ¶ms[0].buffer_length; - params[0].is_null = NULL; - // int - int value = rand() % 100; - params[1].buffer_type = TSDB_DATA_TYPE_INT; - params[1].buffer = &value; - params[1].buffer_length = sizeof(value); - params[1].length = ¶ms[1].buffer_length; - params[1].is_null = NULL; - - // bind - int code = taos_stmt_bind_param(stmt, params); - if (0 != code) printf("failed to bind_param, reason: %s\n", taos_stmt_errstr(stmt)); -} - -void H(TAOS_STMT *stmt, int64_t ts_start, int rows) { - if (isPrint) printf("H -> "); - - TAOS_MULTI_BIND params[2]; - // timestamp - int64_t ts[rows]; - for (int i = 0; i < rows; ++i) { - ts[i] = ts_start + i * 1000; - } - params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - params[0].buffer = ts; - params[0].buffer_length = sizeof(ts[0]); - params[0].length = malloc(sizeof(int64_t) * rows); - char is_null[rows]; - for (int i = 0; i < rows; i++) { - is_null[i] = 0; - } - params[0].is_null = is_null; - params[0].num = rows; - // f1 - int32_t values[rows]; - for (int i = 0; i < rows; ++i) { - values[i] = rand() % 100; - } - params[1].buffer_type = TSDB_DATA_TYPE_INT; - params[1].buffer = values; - params[1].buffer_length = sizeof(int32_t); - params[1].length = malloc(sizeof(int32_t) * rows); - params[1].is_null = is_null; - params[1].num = rows; - - int code = taos_stmt_bind_param_batch(stmt, params); - if (code != 0) { - printf("failed to bind_param_batch, reason: %s\n", taos_stmt_errstr(stmt)); - return; - } -} - -void G1(TAOS_STMT *stmt, int64_t ts_start, int rows) { - if (isPrint) printf("G1 -> "); - - // timestamp - TAOS_MULTI_BIND param0[1]; - int64_t ts[rows]; - for (int i = 0; i < rows; ++i) { - ts[i] = ts_start + i * 1000; - } - param0[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - param0[0].buffer = ts; - param0[0].buffer_length = sizeof(ts[0]); - param0[0].length = malloc(sizeof(int64_t) * rows); - char is_null[rows]; - for (int i = 0; i < rows; i++) { - is_null[i] = 0; - } - param0[0].is_null = is_null; - param0[0].num = rows; - int code = taos_stmt_bind_single_param_batch(stmt, param0, 0); - if (code != 0) { - printf("failed to bind_single_param_batch, reason: %s\n", taos_stmt_errstr(stmt)); - return; - } -} - -void G2(TAOS_STMT *stmt, int rows) { - if (isPrint) printf("G2 -> "); - - // f1 - TAOS_MULTI_BIND param1[1]; - int32_t values[rows]; - for (int i = 0; i < rows; ++i) { - values[i] = rand() % 100; - } - param1[0].buffer_type = TSDB_DATA_TYPE_INT; - param1[0].buffer = values; - param1[0].buffer_length = sizeof(int32_t); - param1[0].length = malloc(sizeof(int32_t) * rows); - char is_null[rows]; - for (int i = 0; i < rows; i++) { - is_null[i] = 0; - } - param1[0].is_null = is_null; - param1[0].num = rows; - - int code = taos_stmt_bind_single_param_batch(stmt, param1, 1); - if (code != 0) { - printf("failed to bind_single_param_batch, reason: %s\n", taos_stmt_errstr(stmt)); - return; - } -} - -void I(TAOS_STMT *stmt) { - if (isPrint) printf("I -> "); - - int code = taos_stmt_add_batch(stmt); - if (code != 0) { - printf("failed to add_batch, reason: %s\n", taos_stmt_errstr(stmt)); - return; - } -} - -void J(TAOS_STMT *stmt) { - if (isPrint) printf("J -> "); - - int code = taos_stmt_execute(stmt); - if (code != 0) { - printf("failed to execute, reason: %s\n", taos_stmt_errstr(stmt)); - return; - } -} - -void L(TAOS_STMT *stmt) { - if (isPrint) printf("L\n"); - - taos_stmt_close(stmt); -} - -void prepare_super_table(TAOS *conn, int subTables) { - char sql[100] = "drop table weather"; - execute(conn, sql); - if (isPrint) printf("sql>>> %s\n", sql); - - sprintf(sql, "create table weather(ts timestamp, f1 int) tags(t1 int)"); - execute(conn, sql); - if (isPrint) printf("sql>>> %s\n", sql); - - for (int i = 0; i < subTables; i++) { - sprintf(sql, "drop table t%d", i); - if (isPrint) printf("sql>>> %s\n", sql); - execute(conn, sql); - } -} - -void prepare_normal_table(TAOS *conn) { - execute(conn, "drop table weather"); - execute(conn, "create table weather(ts timestamp, f1 int) tags(t1 int)"); -} - -void prepare_super_and_sub_table(TAOS *conn, int subTables) { - execute(conn, "drop table weather"); - execute(conn, "create table weather(ts timestamp, f1 int) tags(t1 int)"); - for (int i = 0; i < subTables; i++) { - char sql[100]; - sprintf(sql, "drop table t%d", i); - if (isPrint) printf("sql>>> %s\n", sql); - execute(conn, sql); - - sprintf(sql, "create table t%d using weather tags(%d)", i, i); - if (isPrint) printf("sql>>> %s\n", sql); - execute(conn, sql); - } -} - -int64_t getCurrentTimeMill() { - struct timeval tv; - gettimeofday(&tv, NULL); - return ((unsigned long long)tv.tv_sec * 1000 + (unsigned long long)tv.tv_usec / 1000); -} \ No newline at end of file diff --git a/tests/examples/c/prepare.c b/tests/examples/c/prepare.c deleted file mode 100644 index 14acba3b0d691b4d9bb61db3d8bf95e10e6c20fe..0000000000000000000000000000000000000000 --- a/tests/examples/c/prepare.c +++ /dev/null @@ -1,1422 +0,0 @@ -// TAOS standard API example. The same syntax as MySQL, but only a subet -// to compile: gcc -o prepare prepare.c -ltaos - -#include -#include -#include -#include -#include - -void taosMsleep(int mseconds); - -void verify_prepare(TAOS* taos) { - TAOS_RES* result = taos_query(taos, "drop database if exists test;"); - taos_free_result(result); - - usleep(100000); - result = taos_query(taos, "create database test;"); - - int code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create database, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - - taos_free_result(result); - - usleep(100000); - taos_select_db(taos, "test"); - - // create table - const char* sql = - "create table m1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin " - "binary(40), blob nchar(10), u1 tinyint unsigned, u2 smallint unsigned, u4 int unsigned, u8 bigint unsigned)"; - result = taos_query(taos, sql); - code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create table, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - // insert 10 records - struct { - int64_t ts; - int8_t b; - int8_t v1; - int16_t v2; - int32_t v4; - int64_t v8; - float f4; - double f8; - char bin[40]; - char blob[80]; - uint8_t u1; - uint16_t u2; - uint32_t u4; - uint64_t u8; - } v = {0}; - - TAOS_STMT* stmt = taos_stmt_init(taos); - TAOS_BIND params[14]; - params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - params[0].buffer_length = sizeof(v.ts); - params[0].buffer = &v.ts; - params[0].length = ¶ms[0].buffer_length; - params[0].is_null = NULL; - - params[1].buffer_type = TSDB_DATA_TYPE_BOOL; - params[1].buffer_length = sizeof(v.b); - params[1].buffer = &v.b; - params[1].length = ¶ms[1].buffer_length; - params[1].is_null = NULL; - - params[2].buffer_type = TSDB_DATA_TYPE_TINYINT; - params[2].buffer_length = sizeof(v.v1); - params[2].buffer = &v.v1; - params[2].length = ¶ms[2].buffer_length; - params[2].is_null = NULL; - - params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT; - params[3].buffer_length = sizeof(v.v2); - params[3].buffer = &v.v2; - params[3].length = ¶ms[3].buffer_length; - params[3].is_null = NULL; - - params[4].buffer_type = TSDB_DATA_TYPE_INT; - params[4].buffer_length = sizeof(v.v4); - params[4].buffer = &v.v4; - params[4].length = ¶ms[4].buffer_length; - params[4].is_null = NULL; - - params[5].buffer_type = TSDB_DATA_TYPE_BIGINT; - params[5].buffer_length = sizeof(v.v8); - params[5].buffer = &v.v8; - params[5].length = ¶ms[5].buffer_length; - params[5].is_null = NULL; - - params[6].buffer_type = TSDB_DATA_TYPE_FLOAT; - params[6].buffer_length = sizeof(v.f4); - params[6].buffer = &v.f4; - params[6].length = ¶ms[6].buffer_length; - params[6].is_null = NULL; - - params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE; - params[7].buffer_length = sizeof(v.f8); - params[7].buffer = &v.f8; - params[7].length = ¶ms[7].buffer_length; - params[7].is_null = NULL; - - params[8].buffer_type = TSDB_DATA_TYPE_BINARY; - params[8].buffer_length = sizeof(v.bin); - params[8].buffer = v.bin; - params[8].length = ¶ms[8].buffer_length; - params[8].is_null = NULL; - - strcpy(v.blob, "一二三四五六七八九十"); - params[9].buffer_type = TSDB_DATA_TYPE_NCHAR; - params[9].buffer_length = strlen(v.blob); - params[9].buffer = v.blob; - params[9].length = ¶ms[9].buffer_length; - params[9].is_null = NULL; - - params[10].buffer_type = TSDB_DATA_TYPE_UTINYINT; - params[10].buffer_length = sizeof(v.u1); - params[10].buffer = &v.u1; - params[10].length = ¶ms[10].buffer_length; - params[10].is_null = NULL; - - params[11].buffer_type = TSDB_DATA_TYPE_USMALLINT; - params[11].buffer_length = sizeof(v.u2); - params[11].buffer = &v.u2; - params[11].length = ¶ms[11].buffer_length; - params[11].is_null = NULL; - - params[12].buffer_type = TSDB_DATA_TYPE_UINT; - params[12].buffer_length = sizeof(v.u4); - params[12].buffer = &v.u4; - params[12].length = ¶ms[12].buffer_length; - params[12].is_null = NULL; - - params[13].buffer_type = TSDB_DATA_TYPE_UBIGINT; - params[13].buffer_length = sizeof(v.u8); - params[13].buffer = &v.u8; - params[13].length = ¶ms[13].buffer_length; - params[13].is_null = NULL; - - int is_null = 1; - - sql = "insert into m1 values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - code = taos_stmt_prepare(stmt, sql, 0); - if (code != 0) { - printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - v.ts = 1591060628000; - for (int i = 0; i < 10; ++i) { - v.ts += 1; - for (int j = 1; j < 10; ++j) { - params[j].is_null = ((i == j) ? &is_null : 0); - } - v.b = (int8_t)i % 2; - v.v1 = (int8_t)i; - v.v2 = (int16_t)(i * 2); - v.v4 = (int32_t)(i * 4); - v.v8 = (int64_t)(i * 8); - v.f4 = (float)(i * 40); - v.f8 = (double)(i * 80); - for (int j = 0; j < sizeof(v.bin); ++j) { - v.bin[j] = (char)(i + '0'); - } - v.u1 = (uint8_t)i; - v.u2 = (uint16_t)(i * 2); - v.u4 = (uint32_t)(i * 4); - v.u8 = (uint64_t)(i * 8); - - taos_stmt_bind_param(stmt, params); - taos_stmt_add_batch(stmt); - } - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31mfailed to execute insert statement.error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - int affectedRows = taos_stmt_affected_rows(stmt); - printf("sucessfully inserted %d rows\n", affectedRows); - - taos_stmt_close(stmt); - - // query the records - stmt = taos_stmt_init(taos); - taos_stmt_prepare(stmt, "SELECT * FROM m1 WHERE v1 > ? AND v2 < ?", 0); - v.v1 = 5; - v.v2 = 15; - taos_stmt_bind_param(stmt, params + 2); - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31mfailed to execute select statement.error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - result = taos_stmt_use_result(stmt); - - TAOS_ROW row; - int rows = 0; - int num_fields = taos_num_fields(result); - TAOS_FIELD* fields = taos_fetch_fields(result); - - // fetch the records row by row - while ((row = taos_fetch_row(result))) { - char temp[256] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("%s\n", temp); - } - - taos_free_result(result); - taos_stmt_close(stmt); -} - -void verify_prepare2(TAOS* taos) { - TAOS_RES* result = taos_query(taos, "drop database if exists test;"); - taos_free_result(result); - usleep(100000); - result = taos_query(taos, "create database test;"); - - int code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create database, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - usleep(100000); - taos_select_db(taos, "test"); - - // create table - const char* sql = - "create table m1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin " - "binary(40), blob nchar(10), u1 tinyint unsigned, u2 smallint unsigned, u4 int unsigned, u8 bigint unsigned)"; - result = taos_query(taos, sql); - code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create table, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - // insert 10 records - struct { - int64_t ts; - int8_t b; - int8_t v1; - int16_t v2; - int32_t v4; - int64_t v8; - float f4; - double f8; - char bin[40]; - char blob[80]; - uint8_t u1; - uint16_t u2; - uint32_t u4; - uint64_t u8; - } v = {0}; - - TAOS_STMT* stmt = taos_stmt_init(taos); - TAOS_BIND params[14]; - params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - params[0].buffer_length = sizeof(v.ts); - params[0].buffer = &v.ts; - params[0].length = ¶ms[0].buffer_length; - params[0].is_null = NULL; - - params[1].buffer_type = TSDB_DATA_TYPE_BOOL; - params[1].buffer_length = sizeof(v.b); - params[1].buffer = &v.b; - params[1].length = ¶ms[1].buffer_length; - params[1].is_null = NULL; - - params[2].buffer_type = TSDB_DATA_TYPE_TINYINT; - params[2].buffer_length = sizeof(v.v1); - params[2].buffer = &v.v1; - params[2].length = ¶ms[2].buffer_length; - params[2].is_null = NULL; - - params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT; - params[3].buffer_length = sizeof(v.v2); - params[3].buffer = &v.v2; - params[3].length = ¶ms[3].buffer_length; - params[3].is_null = NULL; - - params[4].buffer_type = TSDB_DATA_TYPE_INT; - params[4].buffer_length = sizeof(v.v4); - params[4].buffer = &v.v4; - params[4].length = ¶ms[4].buffer_length; - params[4].is_null = NULL; - - params[5].buffer_type = TSDB_DATA_TYPE_BIGINT; - params[5].buffer_length = sizeof(v.v8); - params[5].buffer = &v.v8; - params[5].length = ¶ms[5].buffer_length; - params[5].is_null = NULL; - - params[6].buffer_type = TSDB_DATA_TYPE_FLOAT; - params[6].buffer_length = sizeof(v.f4); - params[6].buffer = &v.f4; - params[6].length = ¶ms[6].buffer_length; - params[6].is_null = NULL; - - params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE; - params[7].buffer_length = sizeof(v.f8); - params[7].buffer = &v.f8; - params[7].length = ¶ms[7].buffer_length; - params[7].is_null = NULL; - - params[8].buffer_type = TSDB_DATA_TYPE_BINARY; - params[8].buffer_length = sizeof(v.bin); - params[8].buffer = v.bin; - params[8].length = ¶ms[8].buffer_length; - params[8].is_null = NULL; - - strcpy(v.blob, "一二三四五六七八九十"); - params[9].buffer_type = TSDB_DATA_TYPE_NCHAR; - params[9].buffer_length = strlen(v.blob); - params[9].buffer = v.blob; - params[9].length = ¶ms[9].buffer_length; - params[9].is_null = NULL; - - params[10].buffer_type = TSDB_DATA_TYPE_UTINYINT; - params[10].buffer_length = sizeof(v.u1); - params[10].buffer = &v.u1; - params[10].length = ¶ms[10].buffer_length; - params[10].is_null = NULL; - - params[11].buffer_type = TSDB_DATA_TYPE_USMALLINT; - params[11].buffer_length = sizeof(v.u2); - params[11].buffer = &v.u2; - params[11].length = ¶ms[11].buffer_length; - params[11].is_null = NULL; - - params[12].buffer_type = TSDB_DATA_TYPE_UINT; - params[12].buffer_length = sizeof(v.u4); - params[12].buffer = &v.u4; - params[12].length = ¶ms[12].buffer_length; - params[12].is_null = NULL; - - params[13].buffer_type = TSDB_DATA_TYPE_UBIGINT; - params[13].buffer_length = sizeof(v.u8); - params[13].buffer = &v.u8; - params[13].length = ¶ms[13].buffer_length; - params[13].is_null = NULL; - - sql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - code = taos_stmt_prepare(stmt, sql, 0); - if (code != 0) { - printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - code = taos_stmt_set_tbname(stmt, "m1"); - if (code != 0) { - printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - int is_null = 1; - - v.ts = 1591060628000; - for (int i = 0; i < 10; ++i) { - v.ts += 1; - for (int j = 1; j < 10; ++j) { - params[j].is_null = ((i == j) ? &is_null : 0); - } - v.b = (int8_t)i % 2; - v.v1 = (int8_t)i; - v.v2 = (int16_t)(i * 2); - v.v4 = (int32_t)(i * 4); - v.v8 = (int64_t)(i * 8); - v.f4 = (float)(i * 40); - v.f8 = (double)(i * 80); - for (int j = 0; j < sizeof(v.bin); ++j) { - v.bin[j] = (char)(i + '0'); - } - v.u1 = (uint8_t)i; - v.u2 = (uint16_t)(i * 2); - v.u4 = (uint32_t)(i * 4); - v.u8 = (uint64_t)(i * 8); - - taos_stmt_bind_param(stmt, params); - taos_stmt_add_batch(stmt); - } - - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31mfailed to execute insert statement.error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - int affectedRows = taos_stmt_affected_rows(stmt); - printf("sucessfully inserted %d rows\n", affectedRows); - - taos_stmt_close(stmt); - - // query the records - stmt = taos_stmt_init(taos); - taos_stmt_prepare(stmt, "SELECT * FROM m1 WHERE v1 > ? AND v2 < ?", 0); - TAOS_BIND qparams[2]; - - int8_t v1 = 5; - int16_t v2 = 15; - qparams[0].buffer_type = TSDB_DATA_TYPE_TINYINT; - qparams[0].buffer_length = sizeof(v1); - qparams[0].buffer = &v1; - qparams[0].length = &qparams[0].buffer_length; - qparams[0].is_null = NULL; - - qparams[1].buffer_type = TSDB_DATA_TYPE_SMALLINT; - qparams[1].buffer_length = sizeof(v2); - qparams[1].buffer = &v2; - qparams[1].length = &qparams[1].buffer_length; - qparams[1].is_null = NULL; - - taos_stmt_bind_param(stmt, qparams); - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31mfailed to execute select statement.error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - result = taos_stmt_use_result(stmt); - - TAOS_ROW row; - int rows = 0; - int num_fields = taos_num_fields(result); - TAOS_FIELD* fields = taos_fetch_fields(result); - - // fetch the records row by row - while ((row = taos_fetch_row(result))) { - char temp[256] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("%s\n", temp); - } - - taos_free_result(result); - taos_stmt_close(stmt); -} - -void verify_prepare3(TAOS* taos) { - TAOS_RES* result = taos_query(taos, "drop database if exists test;"); - taos_free_result(result); - usleep(100000); - result = taos_query(taos, "create database test;"); - - int code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create database, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - usleep(100000); - taos_select_db(taos, "test"); - - // create table - const char* sql = - "create stable st1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin " - "binary(40), blob nchar(10), u1 tinyint unsigned, u2 smallint unsigned, u4 int unsigned, u8 bigint unsigned) " - "tags " - "(b_tag bool, v1_tag tinyint, v2_tag smallint, v4_tag int, v8_tag bigint, f4_tag float, f8_tag double, bin_tag " - "binary(40), blob_tag nchar(10), u1_tag tinyint unsigned, u2_tag smallint unsigned, u4_tag int unsigned, u8_tag " - "bigint " - "unsigned)"; - result = taos_query(taos, sql); - code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create table, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - TAOS_BIND tags[13]; - - struct { - int8_t b; - int8_t v1; - int16_t v2; - int32_t v4; - int64_t v8; - float f4; - double f8; - char bin[40]; - char blob[80]; - uint8_t u1; - uint16_t u2; - uint32_t u4; - uint64_t u8; - } id = {0}; - - id.b = (int8_t)1; - id.v1 = (int8_t)1; - id.v2 = (int16_t)2; - id.v4 = (int32_t)4; - id.v8 = (int64_t)8; - id.f4 = (float)40; - id.f8 = (double)80; - for (int j = 0; j < sizeof(id.bin); ++j) { - id.bin[j] = (char)('1' + '0'); - } - strcpy(id.blob, "一二三四五六七八九十"); - id.u1 = (uint8_t)1; - id.u2 = (uint16_t)2; - id.u4 = (uint32_t)4; - id.u8 = (uint64_t)8; - - tags[0].buffer_type = TSDB_DATA_TYPE_BOOL; - tags[0].buffer_length = sizeof(id.b); - tags[0].buffer = &id.b; - tags[0].length = &tags[0].buffer_length; - tags[0].is_null = NULL; - - tags[1].buffer_type = TSDB_DATA_TYPE_TINYINT; - tags[1].buffer_length = sizeof(id.v1); - tags[1].buffer = &id.v1; - tags[1].length = &tags[1].buffer_length; - tags[1].is_null = NULL; - - tags[2].buffer_type = TSDB_DATA_TYPE_SMALLINT; - tags[2].buffer_length = sizeof(id.v2); - tags[2].buffer = &id.v2; - tags[2].length = &tags[2].buffer_length; - tags[2].is_null = NULL; - - tags[3].buffer_type = TSDB_DATA_TYPE_INT; - tags[3].buffer_length = sizeof(id.v4); - tags[3].buffer = &id.v4; - tags[3].length = &tags[3].buffer_length; - tags[3].is_null = NULL; - - tags[4].buffer_type = TSDB_DATA_TYPE_BIGINT; - tags[4].buffer_length = sizeof(id.v8); - tags[4].buffer = &id.v8; - tags[4].length = &tags[4].buffer_length; - tags[4].is_null = NULL; - - tags[5].buffer_type = TSDB_DATA_TYPE_FLOAT; - tags[5].buffer_length = sizeof(id.f4); - tags[5].buffer = &id.f4; - tags[5].length = &tags[5].buffer_length; - tags[5].is_null = NULL; - - tags[6].buffer_type = TSDB_DATA_TYPE_DOUBLE; - tags[6].buffer_length = sizeof(id.f8); - tags[6].buffer = &id.f8; - tags[6].length = &tags[6].buffer_length; - tags[6].is_null = NULL; - - tags[7].buffer_type = TSDB_DATA_TYPE_BINARY; - tags[7].buffer_length = sizeof(id.bin); - tags[7].buffer = &id.bin; - tags[7].length = &tags[7].buffer_length; - tags[7].is_null = NULL; - - tags[8].buffer_type = TSDB_DATA_TYPE_NCHAR; - tags[8].buffer_length = strlen(id.blob); - tags[8].buffer = &id.blob; - tags[8].length = &tags[8].buffer_length; - tags[8].is_null = NULL; - - tags[9].buffer_type = TSDB_DATA_TYPE_UTINYINT; - tags[9].buffer_length = sizeof(id.u1); - tags[9].buffer = &id.u1; - tags[9].length = &tags[9].buffer_length; - tags[9].is_null = NULL; - - tags[10].buffer_type = TSDB_DATA_TYPE_USMALLINT; - tags[10].buffer_length = sizeof(id.u2); - tags[10].buffer = &id.u2; - tags[10].length = &tags[10].buffer_length; - tags[10].is_null = NULL; - - tags[11].buffer_type = TSDB_DATA_TYPE_UINT; - tags[11].buffer_length = sizeof(id.u4); - tags[11].buffer = &id.u4; - tags[11].length = &tags[11].buffer_length; - tags[11].is_null = NULL; - - tags[12].buffer_type = TSDB_DATA_TYPE_UBIGINT; - tags[12].buffer_length = sizeof(id.u8); - tags[12].buffer = &id.u8; - tags[12].length = &tags[12].buffer_length; - tags[12].is_null = NULL; - // insert 10 records - struct { - int64_t ts[10]; - int8_t b[10]; - int8_t v1[10]; - int16_t v2[10]; - int32_t v4[10]; - int64_t v8[10]; - float f4[10]; - double f8[10]; - char bin[10][40]; - char blob[10][80]; - uint8_t u1[10]; - uint16_t u2[10]; - uint32_t u4[10]; - uint64_t u8[10]; - } v; - - int32_t* t8_len = malloc(sizeof(int32_t) * 10); - int32_t* t16_len = malloc(sizeof(int32_t) * 10); - int32_t* t32_len = malloc(sizeof(int32_t) * 10); - int32_t* t64_len = malloc(sizeof(int32_t) * 10); - int32_t* float_len = malloc(sizeof(int32_t) * 10); - int32_t* double_len = malloc(sizeof(int32_t) * 10); - int32_t* bin_len = malloc(sizeof(int32_t) * 10); - int32_t* blob_len = malloc(sizeof(int32_t) * 10); - int32_t* u8_len = malloc(sizeof(int32_t) * 10); - int32_t* u16_len = malloc(sizeof(int32_t) * 10); - int32_t* u32_len = malloc(sizeof(int32_t) * 10); - int32_t* u64_len = malloc(sizeof(int32_t) * 10); - - TAOS_STMT* stmt = taos_stmt_init(taos); - TAOS_MULTI_BIND params[14]; - char is_null[10] = {0}; - - params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - params[0].buffer_length = sizeof(v.ts[0]); - params[0].buffer = v.ts; - params[0].length = t64_len; - params[0].is_null = is_null; - params[0].num = 10; - - params[1].buffer_type = TSDB_DATA_TYPE_BOOL; - params[1].buffer_length = sizeof(v.b[0]); - params[1].buffer = v.b; - params[1].length = t8_len; - params[1].is_null = is_null; - params[1].num = 10; - - params[2].buffer_type = TSDB_DATA_TYPE_TINYINT; - params[2].buffer_length = sizeof(v.v1[0]); - params[2].buffer = v.v1; - params[2].length = t8_len; - params[2].is_null = is_null; - params[2].num = 10; - - params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT; - params[3].buffer_length = sizeof(v.v2[0]); - params[3].buffer = v.v2; - params[3].length = t16_len; - params[3].is_null = is_null; - params[3].num = 10; - - params[4].buffer_type = TSDB_DATA_TYPE_INT; - params[4].buffer_length = sizeof(v.v4[0]); - params[4].buffer = v.v4; - params[4].length = t32_len; - params[4].is_null = is_null; - params[4].num = 10; - - params[5].buffer_type = TSDB_DATA_TYPE_BIGINT; - params[5].buffer_length = sizeof(v.v8[0]); - params[5].buffer = v.v8; - params[5].length = t64_len; - params[5].is_null = is_null; - params[5].num = 10; - - params[6].buffer_type = TSDB_DATA_TYPE_FLOAT; - params[6].buffer_length = sizeof(v.f4[0]); - params[6].buffer = v.f4; - params[6].length = float_len; - params[6].is_null = is_null; - params[6].num = 10; - - params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE; - params[7].buffer_length = sizeof(v.f8[0]); - params[7].buffer = v.f8; - params[7].length = double_len; - params[7].is_null = is_null; - params[7].num = 10; - - params[8].buffer_type = TSDB_DATA_TYPE_BINARY; - params[8].buffer_length = sizeof(v.bin[0]); - params[8].buffer = v.bin; - params[8].length = bin_len; - params[8].is_null = is_null; - params[8].num = 10; - - params[9].buffer_type = TSDB_DATA_TYPE_NCHAR; - params[9].buffer_length = sizeof(v.blob[0]); - params[9].buffer = v.blob; - params[9].length = blob_len; - params[9].is_null = is_null; - params[9].num = 10; - - params[10].buffer_type = TSDB_DATA_TYPE_UTINYINT; - params[10].buffer_length = sizeof(v.u1[0]); - params[10].buffer = v.u1; - params[10].length = u8_len; - params[10].is_null = is_null; - params[10].num = 10; - - params[11].buffer_type = TSDB_DATA_TYPE_USMALLINT; - params[11].buffer_length = sizeof(v.u2[0]); - params[11].buffer = v.u2; - params[11].length = u16_len; - params[11].is_null = is_null; - params[11].num = 10; - - params[12].buffer_type = TSDB_DATA_TYPE_UINT; - params[12].buffer_length = sizeof(v.u4[0]); - params[12].buffer = v.u4; - params[12].length = u32_len; - params[12].is_null = is_null; - params[12].num = 10; - - params[13].buffer_type = TSDB_DATA_TYPE_UBIGINT; - params[13].buffer_length = sizeof(v.u8[0]); - params[13].buffer = v.u8; - params[13].length = u64_len; - params[13].is_null = is_null; - params[13].num = 10; - - sql = "insert into ? using st1 tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - code = taos_stmt_prepare(stmt, sql, 0); - if (code != 0) { - printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - code = taos_stmt_set_tbname_tags(stmt, "m1", tags); - if (code != 0) { - printf("\033[31mfailed to execute taos_stmt_set_tbname_tags. error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - int64_t ts = 1591060628000; - for (int i = 0; i < 10; ++i) { - v.ts[i] = ts++; - is_null[i] = 0; - - v.b[i] = (int8_t)i % 2; - v.v1[i] = (int8_t)i; - v.v2[i] = (int16_t)(i * 2); - v.v4[i] = (int32_t)(i * 4); - v.v8[i] = (int64_t)(i * 8); - v.f4[i] = (float)(i * 40); - v.f8[i] = (double)(i * 80); - for (int j = 0; j < sizeof(v.bin[0]); ++j) { - v.bin[i][j] = (char)(i + '0'); - } - strcpy(v.blob[i], "一二三四五六七八九十"); - v.u1[i] = (uint8_t)i; - v.u2[i] = (uint16_t)(i * 2); - v.u4[i] = (uint32_t)(i * 4); - v.u8[i] = (uint64_t)(i * 8); - - t8_len[i] = sizeof(int8_t); - t16_len[i] = sizeof(int16_t); - t32_len[i] = sizeof(int32_t); - t64_len[i] = sizeof(int64_t); - float_len[i] = sizeof(float); - double_len[i] = sizeof(double); - bin_len[i] = sizeof(v.bin[0]); - blob_len[i] = (int32_t)strlen(v.blob[i]); - u8_len[i] = sizeof(uint8_t); - u16_len[i] = sizeof(uint16_t); - u32_len[i] = sizeof(uint32_t); - u64_len[i] = sizeof(uint64_t); - } - - taos_stmt_bind_param_batch(stmt, params); - taos_stmt_add_batch(stmt); - - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31mfailed to execute insert statement.error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - int affectedRows = taos_stmt_affected_rows(stmt); - printf("successfully inserted %d rows\n", affectedRows); - - taos_stmt_close(stmt); - - // query the records - stmt = taos_stmt_init(taos); - taos_stmt_prepare(stmt, "SELECT * FROM m1 WHERE v1 > ? AND v2 < ?", 0); - - TAOS_BIND qparams[2]; - - int8_t v1 = 5; - int16_t v2 = 15; - qparams[0].buffer_type = TSDB_DATA_TYPE_TINYINT; - qparams[0].buffer_length = sizeof(v1); - qparams[0].buffer = &v1; - qparams[0].length = &qparams[0].buffer_length; - qparams[0].is_null = NULL; - - qparams[1].buffer_type = TSDB_DATA_TYPE_SMALLINT; - qparams[1].buffer_length = sizeof(v2); - qparams[1].buffer = &v2; - qparams[1].length = &qparams[1].buffer_length; - qparams[1].is_null = NULL; - - taos_stmt_bind_param(stmt, qparams); - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31mfailed to execute select statement.error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - result = taos_stmt_use_result(stmt); - - TAOS_ROW row; - int rows = 0; - int num_fields = taos_num_fields(result); - TAOS_FIELD* fields = taos_fetch_fields(result); - - // fetch the records row by row - while ((row = taos_fetch_row(result))) { - char temp[256] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("%s\n", temp); - } - - taos_free_result(result); - taos_stmt_close(stmt); - - free(t8_len); - free(t16_len); - free(t32_len); - free(t64_len); - free(float_len); - free(double_len); - free(bin_len); - free(blob_len); - free(u8_len); - free(u16_len); - free(u32_len); - free(u64_len); - -} - -/** - * @brief Verify the upper/lower case of tableName for create(by setTableName)/query/show/describe/drop. - * https://jira.taosdata.com:18080/browse/TS-904 - * https://jira.taosdata.com:18090/pages/viewpage.action?pageId=129140555 - * @param taos - */ -void verify_prepare4(TAOS* taos) { - printf("Verify the upper/lower case of tableName for create(by setTableName)/query/show/describe/drop etc.\n"); - - TAOS_RES* result = taos_query(taos, "drop database if exists test;"); - taos_free_result(result); - usleep(100000); - result = taos_query(taos, "create database test;"); - - int code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create database, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - usleep(100000); - taos_select_db(taos, "test"); - - // create table - const char* sql = - "create stable st1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin " - "binary(40), blob nchar(10), u1 tinyint unsigned, u2 smallint unsigned, u4 int unsigned, u8 bigint unsigned) " - "tags " - "(b_tag bool, v1_tag tinyint, v2_tag smallint, v4_tag int, v8_tag bigint, f4_tag float, f8_tag double, bin_tag " - "binary(40), blob_tag nchar(10), u1_tag tinyint unsigned, u2_tag smallint unsigned, u4_tag int unsigned, u8_tag " - "bigint " - "unsigned)"; - result = taos_query(taos, sql); - code = taos_errno(result); - if (code != 0) { - printf("\033[31mfailed to create table, reason:%s\033[0m\n", taos_errstr(result)); - taos_free_result(result); - exit(EXIT_FAILURE); - } - taos_free_result(result); - - TAOS_BIND tags[13]; - - struct { - int8_t b; - int8_t v1; - int16_t v2; - int32_t v4; - int64_t v8; - float f4; - double f8; - char bin[40]; - char blob[80]; - uint8_t u1; - uint16_t u2; - uint32_t u4; - uint64_t u8; - } id = {0}; - - id.b = (int8_t)1; - id.v1 = (int8_t)1; - id.v2 = (int16_t)2; - id.v4 = (int32_t)4; - id.v8 = (int64_t)8; - id.f4 = (float)40; - id.f8 = (double)80; - for (int j = 0; j < sizeof(id.bin); ++j) { - id.bin[j] = (char)('1' + '0'); - } - strcpy(id.blob, "一二三四五六七八九十"); - id.u1 = (uint8_t)1; - id.u2 = (uint16_t)2; - id.u4 = (uint32_t)4; - id.u8 = (uint64_t)8; - - tags[0].buffer_type = TSDB_DATA_TYPE_BOOL; - tags[0].buffer_length = sizeof(id.b); - tags[0].buffer = &id.b; - tags[0].length = &tags[0].buffer_length; - tags[0].is_null = NULL; - - tags[1].buffer_type = TSDB_DATA_TYPE_TINYINT; - tags[1].buffer_length = sizeof(id.v1); - tags[1].buffer = &id.v1; - tags[1].length = &tags[1].buffer_length; - tags[1].is_null = NULL; - - tags[2].buffer_type = TSDB_DATA_TYPE_SMALLINT; - tags[2].buffer_length = sizeof(id.v2); - tags[2].buffer = &id.v2; - tags[2].length = &tags[2].buffer_length; - tags[2].is_null = NULL; - - tags[3].buffer_type = TSDB_DATA_TYPE_INT; - tags[3].buffer_length = sizeof(id.v4); - tags[3].buffer = &id.v4; - tags[3].length = &tags[3].buffer_length; - tags[3].is_null = NULL; - - tags[4].buffer_type = TSDB_DATA_TYPE_BIGINT; - tags[4].buffer_length = sizeof(id.v8); - tags[4].buffer = &id.v8; - tags[4].length = &tags[4].buffer_length; - tags[4].is_null = NULL; - - tags[5].buffer_type = TSDB_DATA_TYPE_FLOAT; - tags[5].buffer_length = sizeof(id.f4); - tags[5].buffer = &id.f4; - tags[5].length = &tags[5].buffer_length; - tags[5].is_null = NULL; - - tags[6].buffer_type = TSDB_DATA_TYPE_DOUBLE; - tags[6].buffer_length = sizeof(id.f8); - tags[6].buffer = &id.f8; - tags[6].length = &tags[6].buffer_length; - tags[6].is_null = NULL; - - tags[7].buffer_type = TSDB_DATA_TYPE_BINARY; - tags[7].buffer_length = sizeof(id.bin); - tags[7].buffer = &id.bin; - tags[7].length = &tags[7].buffer_length; - tags[7].is_null = NULL; - - tags[8].buffer_type = TSDB_DATA_TYPE_NCHAR; - tags[8].buffer_length = strlen(id.blob); - tags[8].buffer = &id.blob; - tags[8].length = &tags[8].buffer_length; - tags[8].is_null = NULL; - - tags[9].buffer_type = TSDB_DATA_TYPE_UTINYINT; - tags[9].buffer_length = sizeof(id.u1); - tags[9].buffer = &id.u1; - tags[9].length = &tags[9].buffer_length; - tags[9].is_null = NULL; - - tags[10].buffer_type = TSDB_DATA_TYPE_USMALLINT; - tags[10].buffer_length = sizeof(id.u2); - tags[10].buffer = &id.u2; - tags[10].length = &tags[10].buffer_length; - tags[10].is_null = NULL; - - tags[11].buffer_type = TSDB_DATA_TYPE_UINT; - tags[11].buffer_length = sizeof(id.u4); - tags[11].buffer = &id.u4; - tags[11].length = &tags[11].buffer_length; - tags[11].is_null = NULL; - - tags[12].buffer_type = TSDB_DATA_TYPE_UBIGINT; - tags[12].buffer_length = sizeof(id.u8); - tags[12].buffer = &id.u8; - tags[12].length = &tags[12].buffer_length; - tags[12].is_null = NULL; - // insert 10 records - struct { - int64_t ts[10]; - int8_t b[10]; - int8_t v1[10]; - int16_t v2[10]; - int32_t v4[10]; - int64_t v8[10]; - float f4[10]; - double f8[10]; - char bin[10][40]; - char blob[10][80]; - uint8_t u1[10]; - uint16_t u2[10]; - uint32_t u4[10]; - uint64_t u8[10]; - } v; - - int32_t* t8_len = malloc(sizeof(int32_t) * 10); - int32_t* t16_len = malloc(sizeof(int32_t) * 10); - int32_t* t32_len = malloc(sizeof(int32_t) * 10); - int32_t* t64_len = malloc(sizeof(int32_t) * 10); - int32_t* float_len = malloc(sizeof(int32_t) * 10); - int32_t* double_len = malloc(sizeof(int32_t) * 10); - int32_t* bin_len = malloc(sizeof(int32_t) * 10); - int32_t* blob_len = malloc(sizeof(int32_t) * 10); - int32_t* u8_len = malloc(sizeof(int32_t) * 10); - int32_t* u16_len = malloc(sizeof(int32_t) * 10); - int32_t* u32_len = malloc(sizeof(int32_t) * 10); - int32_t* u64_len = malloc(sizeof(int32_t) * 10); - - TAOS_MULTI_BIND params[14]; - char is_null[10] = {0}; - params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; - params[0].buffer_length = sizeof(v.ts[0]); - params[0].buffer = v.ts; - params[0].length = t64_len; - params[0].is_null = is_null; - params[0].num = 10; - - params[1].buffer_type = TSDB_DATA_TYPE_BOOL; - params[1].buffer_length = sizeof(v.b[0]); - params[1].buffer = v.b; - params[1].length = t8_len; - params[1].is_null = is_null; - params[1].num = 10; - - params[2].buffer_type = TSDB_DATA_TYPE_TINYINT; - params[2].buffer_length = sizeof(v.v1[0]); - params[2].buffer = v.v1; - params[2].length = t8_len; - params[2].is_null = is_null; - params[2].num = 10; - - params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT; - params[3].buffer_length = sizeof(v.v2[0]); - params[3].buffer = v.v2; - params[3].length = t16_len; - params[3].is_null = is_null; - params[3].num = 10; - - params[4].buffer_type = TSDB_DATA_TYPE_INT; - params[4].buffer_length = sizeof(v.v4[0]); - params[4].buffer = v.v4; - params[4].length = t32_len; - params[4].is_null = is_null; - params[4].num = 10; - - params[5].buffer_type = TSDB_DATA_TYPE_BIGINT; - params[5].buffer_length = sizeof(v.v8[0]); - params[5].buffer = v.v8; - params[5].length = t64_len; - params[5].is_null = is_null; - params[5].num = 10; - - params[6].buffer_type = TSDB_DATA_TYPE_FLOAT; - params[6].buffer_length = sizeof(v.f4[0]); - params[6].buffer = v.f4; - params[6].length = float_len; - params[6].is_null = is_null; - params[6].num = 10; - - params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE; - params[7].buffer_length = sizeof(v.f8[0]); - params[7].buffer = v.f8; - params[7].length = double_len; - params[7].is_null = is_null; - params[7].num = 10; - - params[8].buffer_type = TSDB_DATA_TYPE_BINARY; - params[8].buffer_length = sizeof(v.bin[0]); - params[8].buffer = v.bin; - params[8].length = bin_len; - params[8].is_null = is_null; - params[8].num = 10; - - params[9].buffer_type = TSDB_DATA_TYPE_NCHAR; - params[9].buffer_length = sizeof(v.blob[0]); - params[9].buffer = v.blob; - params[9].length = blob_len; - params[9].is_null = is_null; - params[9].num = 10; - - params[10].buffer_type = TSDB_DATA_TYPE_UTINYINT; - params[10].buffer_length = sizeof(v.u1[0]); - params[10].buffer = v.u1; - params[10].length = u8_len; - params[10].is_null = is_null; - params[10].num = 10; - - params[11].buffer_type = TSDB_DATA_TYPE_USMALLINT; - params[11].buffer_length = sizeof(v.u2[0]); - params[11].buffer = v.u2; - params[11].length = u16_len; - params[11].is_null = is_null; - params[11].num = 10; - - params[12].buffer_type = TSDB_DATA_TYPE_UINT; - params[12].buffer_length = sizeof(v.u4[0]); - params[12].buffer = v.u4; - params[12].length = u32_len; - params[12].is_null = is_null; - params[12].num = 10; - - params[13].buffer_type = TSDB_DATA_TYPE_UBIGINT; - params[13].buffer_length = sizeof(v.u8[0]); - params[13].buffer = v.u8; - params[13].length = u64_len; - params[13].is_null = is_null; - params[13].num = 10; - -// verify table names for upper/lower case -#define VERIFY_CNT 5 - - typedef struct { - char setTbName[20]; - char showName[20]; - char describeName[20]; - char queryName[20]; - char dropName[20]; - } STbNames; - - /** - * @brief - * 0 - success expected - * NonZero - fail expected - */ - typedef struct { - int32_t setTbName; - int32_t showName; - int32_t describeName; - int32_t queryName; - int32_t dropName; - } STbNamesResult; - - STbNames tbName[VERIFY_CNT] = {0}; - STbNamesResult tbNameResult[VERIFY_CNT] = {0}; - - STbNames* pTbName = NULL; - STbNamesResult* pTbNameResult = NULL; - - pTbName = &tbName[0]; - pTbNameResult = &tbNameResult[0]; - strcpy(pTbName->setTbName, "Mn1"); - strcpy(pTbName->showName, "mn1"); - strcpy(pTbName->describeName, "mn1"); - strcpy(pTbName->queryName, "mn1"); - strcpy(pTbName->dropName, "mn1"); - - pTbName = &tbName[1]; - pTbNameResult = &tbNameResult[1]; - strcpy(pTbName->setTbName, "'Mn1'"); - strcpy(pTbName->showName, "'mn1'"); - strcpy(pTbName->describeName, "'mn1'"); - strcpy(pTbName->queryName, "'mn1'"); - strcpy(pTbName->dropName, "'mn1'"); - - pTbName = &tbName[2]; - pTbNameResult = &tbNameResult[2]; - strcpy(pTbName->setTbName, "\"Mn1\""); - strcpy(pTbName->showName, "\"mn1\""); - strcpy(pTbName->describeName, "\"mn1\""); - strcpy(pTbName->queryName, "\"mn1\""); - strcpy(pTbName->dropName, "\"mn1\""); - - pTbName = &tbName[3]; - pTbNameResult = &tbNameResult[3]; - strcpy(pTbName->setTbName, "\"Mn1\""); - strcpy(pTbName->showName, "'mn1'"); - strcpy(pTbName->describeName, "'mn1'"); - strcpy(pTbName->queryName, "mn1"); - strcpy(pTbName->dropName, "\"mn1\""); - - pTbName = &tbName[4]; - pTbNameResult = &tbNameResult[4]; - strcpy(pTbName->setTbName, "`Mn1`"); - strcpy(pTbName->showName, "Mn1"); // TODO support uniform of `` - strcpy(pTbName->describeName, "`Mn1`"); - strcpy(pTbName->queryName, "`Mn1`"); - strcpy(pTbName->dropName, "`Mn1`"); - - TAOS_STMT* stmt = NULL; - - for (int n = 0; n < VERIFY_CNT; ++n) { - printf("\033[31m[%d] ===================================\033[0m\n", n); - pTbName = &tbName[n]; - pTbNameResult = &tbNameResult[n]; - char tmpStr[256] = {0}; - - // set table name - stmt = taos_stmt_init(taos); - if (!stmt) { - printf("\033[31m[%d] failed to execute taos_stmt_init. error:%s\033[0m\n", n); - exit(EXIT_FAILURE); - } - - sql = "insert into ? using st1 tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - code = taos_stmt_prepare(stmt, sql, 0); - if (code != 0) { - printf("\033[31mfailed to execute taos_stmt_prepare. error:%s\033[0m\n", taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - printf("[%d] taos_stmt_set_tbname_tags, tbname=%s\n", n, pTbName->setTbName); - code = taos_stmt_set_tbname_tags(stmt, pTbName->setTbName, tags); - if ((!pTbNameResult->setTbName && (0 != code)) || (pTbNameResult->setTbName && (0 == code))) { - printf("\033[31m[%d] failed to execute taos_stmt_set_tbname_tags. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - if (code == 0) { - int64_t ts = 1591060628000 + 1000 * n; - for (int i = 0; i < 10; ++i) { - v.ts[i] = ts++; - is_null[i] = 0; - - v.b[i] = (int8_t)i % 2; - v.v1[i] = (int8_t)i; - v.v2[i] = (int16_t)(i * 2); - v.v4[i] = (int32_t)(i * 4); - v.v8[i] = (int64_t)(i * 8); - v.f4[i] = (float)(i * 40); - v.f8[i] = (double)(i * 80); - for (int j = 0; j < sizeof(v.bin[0]); ++j) { - v.bin[i][j] = (char)(i + '0'); - } - strcpy(v.blob[i], "一二三四五六七八九十"); - v.u1[i] = (uint8_t)i; - v.u2[i] = (uint16_t)(i * 2); - v.u4[i] = (uint32_t)(i * 4); - v.u8[i] = (uint64_t)(i * 8); - - t8_len[i] = sizeof(int8_t); - t16_len[i] = sizeof(int16_t); - t32_len[i] = sizeof(int32_t); - t64_len[i] = sizeof(int64_t); - float_len[i] = sizeof(float); - double_len[i] = sizeof(double); - bin_len[i] = sizeof(v.bin[0]); - blob_len[i] = (int32_t)strlen(v.blob[i]); - u8_len[i] = sizeof(uint8_t); - u16_len[i] = sizeof(uint16_t); - u32_len[i] = sizeof(uint32_t); - u64_len[i] = sizeof(uint64_t); - } - - taos_stmt_bind_param_batch(stmt, params); - taos_stmt_add_batch(stmt); - - if (taos_stmt_execute(stmt) != 0) { - printf("\033[31m[%d] failed to execute insert statement.error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - } - taos_stmt_close(stmt); - - // show the table - printf("[%d] show tables, tbName = %s\n", n, pTbName->showName); - stmt = taos_stmt_init(taos); - sprintf(tmpStr, "show tables like %s", pTbName->showName); - taos_stmt_prepare(stmt, tmpStr, 0); - code = taos_stmt_execute(stmt); - if ((!pTbNameResult->showName && (0 != code)) || (pTbNameResult->showName && (0 == code))) { - printf("\033[31m[%d] failed to execute show tables like. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - taos_stmt_close(stmt); - - // describe the table - printf("[%d] describe tables, tbName = %s\n", n, pTbName->describeName); - stmt = taos_stmt_init(taos); - sprintf(tmpStr, "describe %s", pTbName->describeName); - taos_stmt_prepare(stmt, tmpStr, 0); - code = taos_stmt_execute(stmt); - if ((!pTbNameResult->describeName && (0 != code)) || (pTbNameResult->describeName && (0 == code))) { - printf("\033[31m[%d] failed to execute describe tables. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - taos_stmt_close(stmt); - - // query the records - printf("[%d] select statement, tbName = %s\n", n, pTbName->queryName); - stmt = taos_stmt_init(taos); - sprintf(tmpStr, "SELECT * FROM %s", pTbName->queryName); - taos_stmt_prepare(stmt, tmpStr, 0); - - TAOS_BIND qparams[2]; - - int8_t v1 = 5; - int16_t v2 = 15; - qparams[0].buffer_type = TSDB_DATA_TYPE_TINYINT; - qparams[0].buffer_length = sizeof(v1); - qparams[0].buffer = &v1; - qparams[0].length = &qparams[0].buffer_length; - qparams[0].is_null = NULL; - - qparams[1].buffer_type = TSDB_DATA_TYPE_SMALLINT; - qparams[1].buffer_length = sizeof(v2); - qparams[1].buffer = &v2; - qparams[1].length = &qparams[1].buffer_length; - qparams[1].is_null = NULL; - - taos_stmt_bind_param(stmt, qparams); - - code = taos_stmt_execute(stmt); - if ((!pTbNameResult->queryName && (0 != code)) || (pTbNameResult->queryName && (0 == code))) { - printf("\033[31m[%d] failed to execute select statement.error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - - result = taos_stmt_use_result(stmt); - - TAOS_ROW row; - int rows = 0; - int num_fields = taos_num_fields(result); - TAOS_FIELD* fields = taos_fetch_fields(result); - - // fetch the records row by row - while ((row = taos_fetch_row(result))) { - char temp[256] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("[%d] row = %s\n", n, temp); - } - - taos_free_result(result); - taos_stmt_close(stmt); - - // drop table - printf("[%d] drop table, tbName = %s\n", n, pTbName->dropName); - stmt = taos_stmt_init(taos); - sprintf(tmpStr, "drop table %s", pTbName->dropName); - taos_stmt_prepare(stmt, tmpStr, 0); - code = taos_stmt_execute(stmt); - if ((!pTbNameResult->dropName && (0 != code)) || (pTbNameResult->dropName && (0 == code))) { - printf("\033[31m[%d] failed to drop table. error:%s\033[0m\n", n, taos_stmt_errstr(stmt)); - taos_stmt_close(stmt); - exit(EXIT_FAILURE); - } - taos_stmt_close(stmt); - } - - free(t8_len); - free(t16_len); - free(t32_len); - free(t64_len); - free(float_len); - free(double_len); - free(bin_len); - free(blob_len); - free(u8_len); - free(u16_len); - free(u32_len); - free(u64_len); -} - -int main(int argc, char* argv[]) { - const char* host = "127.0.0.1"; - const char* user = "root"; - const char* passwd = "taosdata"; - - taos_options(TSDB_OPTION_TIMEZONE, "GMT-8"); - TAOS* taos = taos_connect(host, user, passwd, "", 0); - if (taos == NULL) { - printf("\033[31mfailed to connect to db, reason:%s\033[0m\n", taos_errstr(taos)); - exit(1); - } - - char* info = taos_get_server_info(taos); - printf("server info: %s\n", info); - info = taos_get_client_info(taos); - printf("client info: %s\n", info); - printf("************ verify prepare *************\n"); - verify_prepare(taos); - printf("************ verify prepare2 *************\n"); - verify_prepare2(taos); - printf("************ verify prepare3 *************\n"); - verify_prepare3(taos); - printf("************ verify prepare4 *************\n"); - verify_prepare4(taos); - printf("************ verify end *************\n"); - exit(EXIT_SUCCESS); -} diff --git a/tests/examples/c/schemaless.c b/tests/examples/c/schemaless.c deleted file mode 100644 index e7f62ffdfe5628689a290730062f429d09170f6f..0000000000000000000000000000000000000000 --- a/tests/examples/c/schemaless.c +++ /dev/null @@ -1,315 +0,0 @@ -#include "os.h" -#include "taos.h" -#include "taoserror.h" - -#include -#include -#include -#include -#include - -bool verbose = false; - - -void printThreadId(pthread_t id, char* buf) -{ - size_t i; - for (i = sizeof(i); i; --i) - sprintf(buf + strlen(buf), "%02x", *(((unsigned char*) &id) + i - 1)); -} - -static int64_t getTimeInUs() { - struct timeval systemTime; - gettimeofday(&systemTime, NULL); - return (int64_t)systemTime.tv_sec * 1000000L + (int64_t)systemTime.tv_usec; -} - -typedef struct { - char** lines; - int numLines; -} SThreadLinesBatch; - -typedef struct { - TAOS* taos; - int protocol; - int numBatches; - SThreadLinesBatch *batches; - int64_t costTime; -} SThreadInsertArgs; - -static void* insertLines(void* args) { - SThreadInsertArgs* insertArgs = (SThreadInsertArgs*) args; - char tidBuf[32] = {0}; - printThreadId(pthread_self(), tidBuf); - for (int i = 0; i < insertArgs->numBatches; ++i) { - SThreadLinesBatch* batch = insertArgs->batches + i; - if (verbose) printf("%s, thread: 0x%s\n", "begin taos_insert_lines", tidBuf); - int64_t begin = getTimeInUs(); - //int32_t code = taos_insert_lines(insertArgs->taos, batch->lines, batch->numLines); - TAOS_RES * res = taos_schemaless_insert(insertArgs->taos, batch->lines, batch->numLines, insertArgs->protocol, TSDB_SML_TIMESTAMP_MILLI_SECONDS); - int32_t code = taos_errno(res); - int64_t end = getTimeInUs(); - insertArgs->costTime += end - begin; - if (verbose) printf("code: %d, %s. time used:%"PRId64", thread: 0x%s\n", code, tstrerror(code), end - begin, tidBuf); - } - return NULL; -} - -int32_t getTelenetTemplate(char* lineTemplate, int templateLen) { - char* sample = "sta%d %lld 44.3 t0=False t1=127i8 t2=32 t3=%di32 t4=9223372036854775807i64 t5=11.12345f32 t6=22.123456789f64 t7=\"hpxzrdiw\" t8=\"ncharTagValue\" t9=127i8"; - snprintf(lineTemplate, templateLen, "%s", sample); - return 0; -} - -int32_t getLineTemplate(char* lineTemplate, int templateLen, int numFields) { - if (numFields <= 4) { - char* sample = "sta%d,t3=%di32 c3=2147483647i32,c4=9223372036854775807i64,c9=11.12345f32,c10=22.123456789f64 %lld"; - snprintf(lineTemplate, templateLen, "%s", sample); - return 0; - } - - if (numFields <= 13) { - char* sample = "sta%d,t0=true,t1=127i8,t2=32767i16,t3=%di32,t4=9223372036854775807i64,t9=11.12345f32,t10=22.123456789f64,t11=\"binaryTagValue\",t12=L\"ncharTagValue\" c0=true,c1=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=254u8,c6=32770u16,c7=2147483699u32,c8=9223372036854775899u64,c9=11.12345f32,c10=22.123456789f64,c11=\"binaryValue\",c12=L\"ncharValue\" %lld"; - snprintf(lineTemplate, templateLen, "%s", sample); - return 0; - } - - char* lineFormatTable = "sta%d,t0=true,t1=127i8,t2=32767i16,t3=%di32 "; - snprintf(lineTemplate+strlen(lineTemplate), templateLen-strlen(lineTemplate), "%s", lineFormatTable); - - int offset[] = {numFields*2/5, numFields*4/5, numFields}; - - for (int i = 0; i < offset[0]; ++i) { - snprintf(lineTemplate+strlen(lineTemplate), templateLen-strlen(lineTemplate), "c%d=%di32,", i, i); - } - - for (int i=offset[0]+1; i < offset[1]; ++i) { - snprintf(lineTemplate+strlen(lineTemplate), templateLen-strlen(lineTemplate), "c%d=%d.43f64,", i, i); - } - - for (int i = offset[1]+1; i < offset[2]; ++i) { - snprintf(lineTemplate+strlen(lineTemplate), templateLen-strlen(lineTemplate), "c%d=\"%d\",", i, i); - } - char* lineFormatTs = " %lld"; - snprintf(lineTemplate+strlen(lineTemplate)-1, templateLen-strlen(lineTemplate)+1, "%s", lineFormatTs); - - return 0; -} - -int32_t generateLine(char* line, int lineLen, char* lineTemplate, int protocol, int superTable, int childTable, int64_t ts) { - if (protocol == TSDB_SML_LINE_PROTOCOL) { - snprintf(line, lineLen, lineTemplate, superTable, childTable, ts); - } else if (protocol == TSDB_SML_TELNET_PROTOCOL) { - snprintf(line, lineLen, lineTemplate, superTable, ts, childTable); - } - return TSDB_CODE_SUCCESS; -} - -int32_t setupSuperTables(TAOS* taos, char* lineTemplate, int protocol, - int numSuperTables, int numChildTables, int numRowsPerChildTable, - int maxBatchesPerThread, int64_t ts) { - printf("setup supertables..."); - { - char** linesStb = calloc(numSuperTables, sizeof(char*)); - for (int i = 0; i < numSuperTables; i++) { - char* lineStb = calloc(strlen(lineTemplate)+128, 1); - generateLine(lineStb, strlen(lineTemplate)+128, lineTemplate, protocol, i, - numSuperTables * numChildTables, - ts + numSuperTables * numChildTables * numRowsPerChildTable); - linesStb[i] = lineStb; - } - SThreadInsertArgs args = {0}; - args.protocol = protocol; - args.batches = calloc(maxBatchesPerThread, sizeof(maxBatchesPerThread)); - args.taos = taos; - args.batches[0].lines = linesStb; - args.batches[0].numLines = numSuperTables; - insertLines(&args); - free(args.batches); - for (int i = 0; i < numSuperTables; ++i) { - free(linesStb[i]); - } - free(linesStb); - } - return TSDB_CODE_SUCCESS; -} - -int main(int argc, char* argv[]) { - int numThreads = 8; - int maxBatchesPerThread = 1024; - - int numSuperTables = 1; - int numChildTables = 256; - int numRowsPerChildTable = 8192; - int numFields = 13; - - int maxLinesPerBatch = 16384; - - int protocol = TSDB_SML_TELNET_PROTOCOL; - int assembleSTables = 0; - - int opt; - while ((opt = getopt(argc, argv, "s:c:r:f:t:b:p:w:hv")) != -1) { - switch (opt) { - case 's': - numSuperTables = atoi(optarg); - break; - case 'c': - numChildTables = atoi(optarg); - break; - case 'r': - numRowsPerChildTable = atoi(optarg); - break; - case 'f': - numFields = atoi(optarg); - break; - case 't': - numThreads = atoi(optarg); - break; - case 'b': - maxLinesPerBatch = atoi(optarg); - break; - case 'v': - verbose = true; - break; - case 'a': - assembleSTables = atoi(optarg); - break; - case 'p': - if (optarg[0] == 't') { - protocol = TSDB_SML_TELNET_PROTOCOL; - } else if (optarg[0] == 'l') { - protocol = TSDB_SML_LINE_PROTOCOL; - } else if (optarg[0] == 'j') { - protocol = TSDB_SML_JSON_PROTOCOL; - } - break; - case 'h': - fprintf(stderr, "Usage: %s -s supertable -c childtable -r rows -f fields -t threads -b maxlines_per_batch -p [t|l|j] -a assemble-stables -v\n", - argv[0]); - exit(0); - default: /* '?' */ - fprintf(stderr, "Usage: %s -s supertable -c childtable -r rows -f fields -t threads -b maxlines_per_batch -p [t|l|j] -a assemble-stables -v\n", - argv[0]); - exit(-1); - } - } - - TAOS_RES* result; - //const char* host = "127.0.0.1"; - const char* host = NULL; - const char* user = "root"; - const char* passwd = "taosdata"; - - taos_options(TSDB_OPTION_TIMEZONE, "GMT-8"); - TAOS* taos = taos_connect(host, user, passwd, "", 0); - if (taos == NULL) { - printf("\033[31mfailed to connect to db, reason:%s\033[0m\n", taos_errstr(taos)); - exit(1); - } - - maxBatchesPerThread = (numSuperTables*numChildTables*numRowsPerChildTable)/(numThreads * maxLinesPerBatch) + 1; - - char* info = taos_get_server_info(taos); - printf("server info: %s\n", info); - info = taos_get_client_info(taos); - printf("client info: %s\n", info); - result = taos_query(taos, "drop database if exists db;"); - taos_free_result(result); - usleep(100000); - result = taos_query(taos, "create database db precision 'us';"); - taos_free_result(result); - usleep(100000); - - (void)taos_select_db(taos, "db"); - - time_t ct = time(0); - int64_t ts = ct * 1000 ; - - char* lineTemplate = calloc(65536, sizeof(char)); - if (protocol == TSDB_SML_LINE_PROTOCOL) { - getLineTemplate(lineTemplate, 65535, numFields); - } else if (protocol == TSDB_SML_TELNET_PROTOCOL ) { - getTelenetTemplate(lineTemplate, 65535); - } - - if (assembleSTables) { - setupSuperTables(taos, lineTemplate, protocol, - numSuperTables, numChildTables, numRowsPerChildTable, maxBatchesPerThread, ts); - } - - printf("generate lines...\n"); - pthread_t* tids = calloc(numThreads, sizeof(pthread_t)); - SThreadInsertArgs* argsThread = calloc(numThreads, sizeof(SThreadInsertArgs)); - for (int i = 0; i < numThreads; ++i) { - argsThread[i].batches = calloc(maxBatchesPerThread, sizeof(SThreadLinesBatch)); - argsThread[i].taos = taos; - argsThread[i].numBatches = 0; - argsThread[i].protocol = protocol; - } - - int64_t totalLines = numSuperTables * numChildTables * numRowsPerChildTable; - int totalBatches = (int) ((totalLines) / maxLinesPerBatch); - if (totalLines % maxLinesPerBatch != 0) { - totalBatches += 1; - } - - char*** allBatches = calloc(totalBatches, sizeof(char**)); - for (int i = 0; i < totalBatches; ++i) { - allBatches[i] = calloc(maxLinesPerBatch, sizeof(char*)); - int threadNo = i % numThreads; - int batchNo = i / numThreads; - argsThread[threadNo].batches[batchNo].lines = allBatches[i]; - argsThread[threadNo].numBatches = batchNo + 1; - } - - int l = 0; - for (int i = 0; i < numSuperTables; ++i) { - for (int j = 0; j < numChildTables; ++j) { - for (int k = 0; k < numRowsPerChildTable; ++k) { - int stIdx = i; - int ctIdx = numSuperTables*numChildTables + j; - char* line = calloc(strlen(lineTemplate)+128, 1); - generateLine(line, strlen(lineTemplate)+128, lineTemplate, protocol, stIdx, ctIdx, ts + l); - int batchNo = l / maxLinesPerBatch; - int lineNo = l % maxLinesPerBatch; - allBatches[batchNo][lineNo] = line; - argsThread[batchNo % numThreads].batches[batchNo/numThreads].numLines = lineNo + 1; - ++l; - } - } - } - - printf("begin multi-thread insertion...\n"); - int64_t begin = taosGetTimestampUs(); - - for (int i=0; i < numThreads; ++i) { - pthread_create(tids+i, NULL, insertLines, argsThread+i); - } - for (int i = 0; i < numThreads; ++i) { - pthread_join(tids[i], NULL); - } - int64_t end = taosGetTimestampUs(); - - size_t linesNum = numSuperTables*numChildTables*numRowsPerChildTable; - printf("TOTAL LINES: %zu\n", linesNum); - printf("THREADS: %d\n", numThreads); - printf("TIME: %d(ms)\n", (int)(end-begin)/1000); - double throughput = (double)(totalLines)/(double)(end-begin) * 1000000; - printf("THROUGHPUT:%d/s\n", (int)throughput); - - for (int i = 0; i < totalBatches; ++i) { - free(allBatches[i]); - } - free(allBatches); - - for (int i = 0; i < numThreads; i++) { - free(argsThread[i].batches); - } - free(argsThread); - free(tids); - - free(lineTemplate); - taos_close(taos); - return 0; -} diff --git a/tests/examples/c/sqlperf.c b/tests/examples/c/sqlperf.c deleted file mode 100644 index bde69149651f2b2afffc9c4dffca6f42604f4f2c..0000000000000000000000000000000000000000 --- a/tests/examples/c/sqlperf.c +++ /dev/null @@ -1,141 +0,0 @@ -#include -#include -#include -#include -#include "taos.h" // TAOS header file -#include "taoserror.h" -#include "os.h" - -bool verbose = false; -bool describeTableFirst = false; - -typedef struct{ - TAOS* taos; - int numThreads; - int threadId; - int numSTables; -} SThreadArgs; - -static int executeSql(TAOS *taos, char *command) { - if (verbose) { - printf("sql: %s\n", command); - } - TAOS_RES *pSql = NULL; - int32_t code = TSDB_CODE_SUCCESS; - - pSql = taos_query(taos, command); - code = taos_errno(pSql); - - if (code != 0) { - if (verbose) fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql)); - taos_free_result(pSql); - return code; - } - - taos_free_result(pSql); - return 0; -} - -void* threadFunc(void* args) { - char* sqlDescribeSTable = "describe st%d"; - char* sqlCreateSTable = "create table st%d (ts timestamp, value double) " - "tags(t0 nchar(20), t1 nchar(20), t2 nchar(20), t3 nchar(20), t4 nchar(20), " - "t5 nchar(20), t6 nchar(20), t7 nchar(20), t8 nchar(20), t9 nchar(20))"; - - char* sqlInsertData = "insert into t%d using st%d tags('t%d', 't%d', 't%d', 't%d', 't%d', 't%d', 't%d', 't%d', 't%d', 't%d') values(%lld, %d.%d)"; - - SThreadArgs* param = args; - - int interval = param->numSTables/param->numThreads; - if (param->numSTables % param->numThreads != 0) { - ++interval; - } - int start = param->threadId*interval; - int end = (param->threadId+1)*interval > param->numSTables ? param->numSTables : (param->threadId+1)*interval; - int r = rand(); - - for (int i = start; i < end; ++i) { - int tableId = i; - char sql0[1024] = {0}; - char sql1[1024] = {0}; - char sql2[1024] = {0}; - sprintf(sql0, sqlDescribeSTable, tableId); - sprintf(sql1, sqlCreateSTable, tableId); - time_t ct = time(0); - int64_t ts = ct * 1000; - sprintf(sql2, sqlInsertData, tableId, tableId, r, r, r, r, r, r, r, r, r, r, ts + tableId, r, r); - - if (describeTableFirst) { - executeSql(param->taos, sql0); - } - - executeSql(param->taos, sql1); - - executeSql(param->taos, sql2); - } - return NULL; -} - - -int main(int argc, char *argv[]) { - int numSTables = 20000; - int numThreads = 32; - - int opt; - while ((opt = getopt(argc, argv, "s:t:fvh")) != -1) { - switch (opt) { - case 's': - numSTables = atoi(optarg); - break; - case 't': - numThreads = atoi(optarg); - break; - case 'f': - describeTableFirst = true; - break; - case 'v': - verbose = true; - break; - case 'h': - fprintf(stderr, "Usage: %s -s supertable -t thread -FirstDescribeSTable -Verbose\n", argv[0]); - exit(0); - default: - fprintf(stderr, "Usage: %s -s supertable -t thread -FirstDescribeSTable -Verbose\n", argv[0]); - exit(-1); - } - } - - - // connect to server - TAOS *taos = taos_connect(NULL, "root", "taosdata", NULL, 0); - if (taos == NULL) { - printf("failed to connect to server, reason:%s\n", "null taos" /*taos_errstr(taos)*/); - exit(1); - } - executeSql(taos, "drop database if exists sqlsml"); - executeSql(taos, "create database sqlsml"); - executeSql(taos, "use sqlsml"); - pthread_t* tids = calloc(numThreads, sizeof(pthread_t)); - SThreadArgs* threadArgs = calloc(numThreads, sizeof(SThreadArgs)); - for (int i = 0; i < numThreads; ++i) { - threadArgs[i].numSTables = numSTables; - threadArgs[i].numThreads = numThreads; - threadArgs[i].threadId = i; - threadArgs[i].taos = taos; - } - - int64_t begin = taosGetTimestampUs(); - for (int i = 0; i < numThreads; ++i) { - pthread_create(tids+i, NULL, threadFunc, threadArgs+i); - } - for (int i = 0; i < numThreads; ++i) { - pthread_join(tids[i], NULL); - } - int64_t end = taosGetTimestampUs(); - printf("TIME: %d(ms)\n", (int)((end-begin)/1000)); - printf("THROUGHPUT: %d\n", (int)((numSTables * 1e6) / (end-begin))); - free(threadArgs); - free(tids); - taos_close(taos); - taos_cleanup(); -} diff --git a/tests/examples/c/stream.c b/tests/examples/c/stream.c deleted file mode 100644 index f759da4283bfca69d921f4bbfbb2e78e2123a70c..0000000000000000000000000000000000000000 --- a/tests/examples/c/stream.c +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ - -#include -#include -#include -#include -#include // include TDengine header file -#include - -typedef struct { - char server_ip[64]; - char db_name[64]; - char tbl_name[64]; -} param; - -int g_thread_exit_flag = 0; -void *insert_rows(void *sarg); - -void streamCallBack(void *param, TAOS_RES *res, TAOS_ROW row) { - // in this simple demo, it just print out the result - char temp[128]; - - TAOS_FIELD *fields = taos_fetch_fields(res); - int numFields = taos_num_fields(res); - - taos_print_row(temp, row, fields, numFields); - - printf("\n%s\n", temp); -} - -int main(int argc, char *argv[]) { - TAOS *taos; - char db_name[64]; - char tbl_name[64]; - char sql[1024] = {0}; - - if (argc != 4) { - printf("usage: %s server-ip dbname tblname\n", argv[0]); - exit(0); - } - - strcpy(db_name, argv[2]); - strcpy(tbl_name, argv[3]); - - // create pthread to insert into row per second for stream calc - param *t_param = (param *)malloc(sizeof(param)); - if (NULL == t_param) { - printf("failed to malloc\n"); - exit(1); - } - memset(t_param, 0, sizeof(param)); - strcpy(t_param->server_ip, argv[1]); - strcpy(t_param->db_name, db_name); - strcpy(t_param->tbl_name, tbl_name); - - pthread_t pid; - pthread_create(&pid, NULL, (void *(*)(void *))insert_rows, t_param); - - sleep(3); // waiting for database is created. - // open connection to database - taos = taos_connect(argv[1], "root", "taosdata", db_name, 0); - if (taos == NULL) { - printf("failed to connet to server:%s\n", argv[1]); - free(t_param); - exit(1); - } - - // starting stream calc, - printf("please input stream SQL:[e.g., select count(*) from tblname interval(5s) sliding(2s);]\n"); - fgets(sql, sizeof(sql), stdin); - if (sql[0] == 0) { - printf("input NULL stream SQL, so exit!\n"); - free(t_param); - exit(1); - } - - // param is set to NULL in this demo, it shall be set to the pointer to app context - TAOS_STREAM *pStream = taos_open_stream(taos, sql, streamCallBack, 0, NULL, NULL); - if (NULL == pStream) { - printf("failed to create stream\n"); - free(t_param); - exit(1); - } - - printf("press any key to exit\n"); - getchar(); - - taos_close_stream(pStream); - - g_thread_exit_flag = 1; - pthread_join(pid, NULL); - - taos_close(taos); - free(t_param); - - return 0; -} - -void *insert_rows(void *sarg) { - TAOS * taos; - char command[1024] = {0}; - param *winfo = (param *)sarg; - - if (NULL == winfo) { - printf("para is null!\n"); - exit(1); - } - - taos = taos_connect(winfo->server_ip, "root", "taosdata", NULL, 0); - if (taos == NULL) { - printf("failed to connet to server:%s\n", winfo->server_ip); - exit(1); - } - - // drop database - sprintf(command, "drop database %s;", winfo->db_name); - if (taos_query(taos, command) != 0) { - printf("failed to drop database, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // create database - sprintf(command, "create database %s;", winfo->db_name); - if (taos_query(taos, command) != 0) { - printf("failed to create database, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // use database - sprintf(command, "use %s;", winfo->db_name); - if (taos_query(taos, command) != 0) { - printf("failed to use database, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // create table - sprintf(command, "create table %s (ts timestamp, speed int);", winfo->tbl_name); - if (taos_query(taos, command) != 0) { - printf("failed to create table, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - // insert data - int64_t begin = (int64_t)time(NULL); - int index = 0; - while (1) { - if (g_thread_exit_flag) break; - - index++; - sprintf(command, "insert into %s values (%ld, %d)", winfo->tbl_name, (begin + index) * 1000, index); - if (taos_query(taos, command)) { - printf("failed to insert row [%s], reason:%s\n", command, taos_errstr(taos)); - } - sleep(1); - } - - taos_close(taos); - return 0; -} diff --git a/tests/examples/c/subscribe.c b/tests/examples/c/subscribe.c deleted file mode 100644 index d8b76c008f24a4ff1e7827e5b1cb167f013c81c5..0000000000000000000000000000000000000000 --- a/tests/examples/c/subscribe.c +++ /dev/null @@ -1,257 +0,0 @@ -// sample code for TDengine subscribe/consume API -// to compile: gcc -o subscribe subscribe.c -ltaos - -#include -#include -#include -#include // include TDengine header file -#include - -int nTotalRows; - -void print_result(TAOS_RES* res, int blockFetch) { - TAOS_ROW row = NULL; - int num_fields = taos_num_fields(res); - TAOS_FIELD* fields = taos_fetch_fields(res); - int nRows = 0; - - if (blockFetch) { - nRows = taos_fetch_block(res, &row); - // for (int i = 0; i < nRows; i++) { - // taos_print_row(buf, row + i, fields, num_fields); - // puts(buf); - //} - } else { - while ((row = taos_fetch_row(res))) { - char buf[4096] = {0}; - taos_print_row(buf, row, fields, num_fields); - puts(buf); - nRows++; - } - } - - nTotalRows += nRows; - printf("%d rows consumed.\n", nRows); -} - -void subscribe_callback(TAOS_SUB* tsub, TAOS_RES* res, void* param, int code) { print_result(res, *(int*)param); } - -void check_row_count(int line, TAOS_RES* res, int expected) { - int actual = 0; - TAOS_ROW row; - while ((row = taos_fetch_row(res))) { - actual++; - } - if (actual != expected) { - printf("line %d: row count mismatch, expected: %d, actual: %d\n", line, expected, actual); - } else { - printf("line %d: %d rows consumed as expected\n", line, actual); - } -} - -void do_query(TAOS* taos, const char* sql) { - TAOS_RES* res = taos_query(taos, sql); - taos_free_result(res); -} - -void run_test(TAOS* taos) { - do_query(taos, "drop database if exists test;"); - - usleep(100000); - do_query(taos, "create database test;"); - usleep(100000); - do_query(taos, "use test;"); - - usleep(100000); - do_query(taos, "create table meters(ts timestamp, a int) tags(area int);"); - - do_query(taos, "create table t0 using meters tags(0);"); - do_query(taos, "create table t1 using meters tags(1);"); - do_query(taos, "create table t2 using meters tags(2);"); - do_query(taos, "create table t3 using meters tags(3);"); - do_query(taos, "create table t4 using meters tags(4);"); - do_query(taos, "create table t5 using meters tags(5);"); - do_query(taos, "create table t6 using meters tags(6);"); - do_query(taos, "create table t7 using meters tags(7);"); - do_query(taos, "create table t8 using meters tags(8);"); - do_query(taos, "create table t9 using meters tags(9);"); - - do_query(taos, "insert into t0 values('2020-01-01 00:00:00.000', 0);"); - do_query(taos, "insert into t0 values('2020-01-01 00:01:00.000', 0);"); - do_query(taos, "insert into t0 values('2020-01-01 00:02:00.000', 0);"); - do_query(taos, "insert into t1 values('2020-01-01 00:00:00.000', 0);"); - do_query(taos, "insert into t1 values('2020-01-01 00:01:00.000', 0);"); - do_query(taos, "insert into t1 values('2020-01-01 00:02:00.000', 0);"); - do_query(taos, "insert into t1 values('2020-01-01 00:03:00.000', 0);"); - do_query(taos, "insert into t2 values('2020-01-01 00:00:00.000', 0);"); - do_query(taos, "insert into t2 values('2020-01-01 00:01:00.000', 0);"); - do_query(taos, "insert into t2 values('2020-01-01 00:01:01.000', 0);"); - do_query(taos, "insert into t2 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t3 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t4 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t5 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t6 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t7 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t8 values('2020-01-01 00:01:02.000', 0);"); - do_query(taos, "insert into t9 values('2020-01-01 00:01:02.000', 0);"); - - // super tables subscription - usleep(1000000); - - TAOS_SUB* tsub = taos_subscribe(taos, 0, "test", "select * from meters;", NULL, NULL, 0); - TAOS_RES* res = taos_consume(tsub); - check_row_count(__LINE__, res, 18); - - res = taos_consume(tsub); - check_row_count(__LINE__, res, 0); - - do_query(taos, "insert into t0 values('2020-01-01 00:02:00.001', 0);"); - do_query(taos, "insert into t8 values('2020-01-01 00:01:03.000', 0);"); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 2); - - do_query(taos, "insert into t2 values('2020-01-01 00:01:02.001', 0);"); - do_query(taos, "insert into t1 values('2020-01-01 00:03:00.001', 0);"); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 2); - - do_query(taos, "insert into t1 values('2020-01-01 00:03:00.002', 0);"); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 1); - - // keep progress information and restart subscription - taos_unsubscribe(tsub, 1); - do_query(taos, "insert into t0 values('2020-01-01 00:04:00.000', 0);"); - tsub = taos_subscribe(taos, 1, "test", "select * from meters;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 24); - - // keep progress information and continue previous subscription - taos_unsubscribe(tsub, 1); - tsub = taos_subscribe(taos, 0, "test", "select * from meters;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 0); - - // don't keep progress information and continue previous subscription - taos_unsubscribe(tsub, 0); - tsub = taos_subscribe(taos, 0, "test", "select * from meters;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 24); - - // single meter subscription - - taos_unsubscribe(tsub, 0); - tsub = taos_subscribe(taos, 0, "test", "select * from t0;", NULL, NULL, 0); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 5); - - res = taos_consume(tsub); - check_row_count(__LINE__, res, 0); - - do_query(taos, "insert into t0 values('2020-01-01 00:04:00.001', 0);"); - res = taos_consume(tsub); - check_row_count(__LINE__, res, 1); - - taos_unsubscribe(tsub, 0); -} - -int main(int argc, char* argv[]) { - const char* host = "127.0.0.1"; - const char* user = "root"; - const char* passwd = "taosdata"; - const char* sql = "select * from meters;"; - const char* topic = "test-multiple"; - int async = 1, restart = 0, keep = 1, test = 0, blockFetch = 0; - - for (int i = 1; i < argc; i++) { - if (strncmp(argv[i], "-h=", 3) == 0) { - host = argv[i] + 3; - continue; - } - if (strncmp(argv[i], "-u=", 3) == 0) { - user = argv[i] + 3; - continue; - } - if (strncmp(argv[i], "-p=", 3) == 0) { - passwd = argv[i] + 3; - continue; - } - if (strcmp(argv[i], "-sync") == 0) { - async = 0; - continue; - } - if (strcmp(argv[i], "-restart") == 0) { - restart = 1; - continue; - } - if (strcmp(argv[i], "-single") == 0) { - sql = "select * from t0;"; - topic = "test-single"; - continue; - } - if (strcmp(argv[i], "-nokeep") == 0) { - keep = 0; - continue; - } - if (strncmp(argv[i], "-sql=", 5) == 0) { - sql = argv[i] + 5; - topic = "test-custom"; - continue; - } - if (strcmp(argv[i], "-test") == 0) { - test = 1; - continue; - } - if (strcmp(argv[i], "-block-fetch") == 0) { - blockFetch = 1; - continue; - } - } - - TAOS* taos = taos_connect(host, user, passwd, "", 0); - if (taos == NULL) { - printf("failed to connect to db, reason:%s\n", taos_errstr(taos)); - exit(1); - } - - if (test) { - run_test(taos); - taos_close(taos); - exit(0); - } - - taos_select_db(taos, "test"); - TAOS_SUB* tsub = NULL; - if (async) { - // create an asynchronized subscription, the callback function will be called every 1s - tsub = taos_subscribe(taos, restart, topic, sql, subscribe_callback, &blockFetch, 1000); - } else { - // create an synchronized subscription, need to call 'taos_consume' manually - tsub = taos_subscribe(taos, restart, topic, sql, NULL, NULL, 0); - } - - if (tsub == NULL) { - printf("failed to create subscription.\n"); - exit(0); - } - - if (async) { - getchar(); - } else - while (1) { - TAOS_RES* res = taos_consume(tsub); - if (res == NULL) { - printf("failed to consume data."); - break; - } else { - print_result(res, blockFetch); - getchar(); - } - } - - printf("total rows consumed: %d\n", nTotalRows); - taos_unsubscribe(tsub, keep); - taos_close(taos); - - return 0; -} diff --git a/tests/examples/go/taosdemo.go b/tests/examples/go/taosdemo.go deleted file mode 100644 index 543cfcc0f65aad154cc411891a76ae2fdb4e0e02..0000000000000000000000000000000000000000 --- a/tests/examples/go/taosdemo.go +++ /dev/null @@ -1,561 +0,0 @@ -/* - * Copyright (c) 2019 TAOS Data, Inc. - * - * 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 . - */ -package main - -import ( - "database/sql" - "flag" - "fmt" - "log" - "math/rand" - "os" - "runtime" - "strconv" - "sync" - "time" - - _ "github.com/taosdata/driver-go/taosSql" -) - -const ( - maxLocationSize = 32 - //maxSqlBufSize = 65480 -) - -var locations = [maxLocationSize]string{ - "Beijing", "Shanghai", "Guangzhou", "Shenzhen", - "HangZhou", "Tianjin", "Wuhan", "Changsha", - "Nanjing", "Xian"} - -type config struct { - hostName string - serverPort int - user string - password string - dbName string - supTblName string - tablePrefix string - mode string - numOftables int - numOfRecordsPerTable int - numOfRecordsPerReq int - numOfThreads int - startTimestamp string - startTs int64 - - keep int - days int -} - -var configPara config -var taosDriverName = "taosSql" -var url string - -func init() { - flag.StringVar(&configPara.hostName, "h", "127.0.0.1", "The host to connect to TDengine server.") - flag.IntVar(&configPara.serverPort, "p", 6030, "The TCP/IP port number to use for the connection to TDengine server.") - flag.StringVar(&configPara.user, "u", "root", "The TDengine user name to use when connecting to the server.") - flag.StringVar(&configPara.password, "P", "taosdata", "The password to use when connecting to the server.") - flag.StringVar(&configPara.dbName, "d", "test", "Destination database.") - flag.StringVar(&configPara.tablePrefix, "m", "d", "Table prefix name.") - flag.StringVar(&configPara.mode, "M", "r", "mode,r:raw,s:stmt") - flag.IntVar(&configPara.numOftables, "t", 2, "The number of tables.") - flag.IntVar(&configPara.numOfRecordsPerTable, "n", 10, "The number of records per table.") - flag.IntVar(&configPara.numOfRecordsPerReq, "r", 3, "The number of records per request.") - flag.IntVar(&configPara.numOfThreads, "T", 1, "The number of threads.") - flag.StringVar(&configPara.startTimestamp, "s", "2020-10-01 08:00:00", "The start timestamp for one table.") - flag.Parse() - - configPara.keep = 365 * 20 - configPara.days = 30 - configPara.supTblName = "meters" - - startTs, err := time.ParseInLocation("2006-01-02 15:04:05", configPara.startTimestamp, time.Local) - if err == nil { - configPara.startTs = startTs.UnixNano() / 1e6 - } -} - -func printAllArgs() { - fmt.Printf("\n============= args parse result: =============\n") - fmt.Printf("hostName: %v\n", configPara.hostName) - fmt.Printf("serverPort: %v\n", configPara.serverPort) - fmt.Printf("usr: %v\n", configPara.user) - fmt.Printf("password: %v\n", configPara.password) - fmt.Printf("dbName: %v\n", configPara.dbName) - fmt.Printf("mode: %v\n", configPara.mode) - fmt.Printf("tablePrefix: %v\n", configPara.tablePrefix) - fmt.Printf("numOftables: %v\n", configPara.numOftables) - fmt.Printf("numOfRecordsPerTable: %v\n", configPara.numOfRecordsPerTable) - fmt.Printf("numOfRecordsPerReq: %v\n", configPara.numOfRecordsPerReq) - fmt.Printf("numOfThreads: %v\n", configPara.numOfThreads) - fmt.Printf("startTimestamp: %v[%v]\n", configPara.startTimestamp, configPara.startTs) - fmt.Printf("================================================\n") -} - -func main() { - printAllArgs() - fmt.Printf("Please press enter key to continue....\n") - _, _ = fmt.Scanln() - - url = "root:taosdata@/tcp(" + configPara.hostName + ":" + strconv.Itoa(configPara.serverPort) + ")/" - //url = fmt.Sprintf("%s:%s@/tcp(%s:%d)/%s?interpolateParams=true", configPara.user, configPara.password, configPara.hostName, configPara.serverPort, configPara.dbName) - // open connect to taos server - //db, err := sql.Open(taosDriverName, url) - //if err != nil { - // fmt.Println("Open database error: %s\n", err) - // os.Exit(1) - //} - //defer db.Close() - rand.Seed(time.Now().Unix()) - - if configPara.mode == "s" { - fmt.Printf("\n======== start stmt mode test ========\n") - db, err := sql.Open("taosSql", url) - if err != nil { - log.Fatalf("Open database error: %s\n", err) - } - defer db.Close() - demodbStmt := configPara.dbName - demotStmt := "demotStmt" - drop_database_stmt(db, demodbStmt) - create_database_stmt(db, demodbStmt) - use_database_stmt(db, demodbStmt) - create_table_stmt(db, demotStmt) - insert_data_stmt(db, demotStmt) - select_data_stmt(db, demotStmt) - return - } - - createDatabase(configPara.dbName, configPara.supTblName) - fmt.Printf("======== create database success! ========\n\n") - - //create_table(db, stblName) - multiThreadCreateTable(configPara.numOfThreads, configPara.numOftables, configPara.dbName, configPara.tablePrefix) - fmt.Printf("======== create super table and child tables success! ========\n\n") - - //insert_data(db, demot) - multiThreadInsertData(configPara.numOfThreads, configPara.numOftables, configPara.dbName, configPara.tablePrefix) - fmt.Printf("======== insert data into child tables success! ========\n\n") - - //select_data(db, demot) - selectTest(configPara.dbName, configPara.tablePrefix, configPara.supTblName) - fmt.Printf("======== select data success! ========\n\n") - - fmt.Printf("======== end demo ========\n") -} - -func createDatabase(dbName string, supTblName string) { - db, err := sql.Open(taosDriverName, url) - if err != nil { - fmt.Printf("Open database error: %s\n", err) - os.Exit(1) - } - defer db.Close() - - // drop database if exists - sqlStr := "drop database if exists " + dbName - _, err = db.Exec(sqlStr) - checkErr(err, sqlStr) - - time.Sleep(time.Second) - - // create database - sqlStr = "create database " + dbName + " keep " + strconv.Itoa(configPara.keep) + " days " + strconv.Itoa(configPara.days) - _, err = db.Exec(sqlStr) - checkErr(err, sqlStr) - - // use database - //sqlStr = "use " + dbName - //_, err = db.Exec(sqlStr) - //checkErr(err, sqlStr) - - sqlStr = "create table if not exists " + dbName + "." + supTblName + " (ts timestamp, current float, voltage int, phase float) tags(location binary(64), groupId int);" - _, err = db.Exec(sqlStr) - checkErr(err, sqlStr) -} - -func multiThreadCreateTable(threads int, nTables int, dbName string, tablePrefix string) { - st := time.Now().UnixNano() - - if threads < 1 { - threads = 1 - } - - a := nTables / threads - if a < 1 { - threads = nTables - a = 1 - } - - b := nTables % threads - - last := 0 - endTblId := 0 - wg := sync.WaitGroup{} - for i := 0; i < threads; i++ { - startTblId := last - if i < b { - endTblId = last + a - } else { - endTblId = last + a - 1 - } - last = endTblId + 1 - wg.Add(1) - go createTable(dbName, tablePrefix, startTblId, endTblId, &wg) - } - wg.Wait() - - et := time.Now().UnixNano() - fmt.Printf("create tables spent duration: %6.6fs\n", (float32(et-st))/1e9) -} - -func createTable(dbName string, childTblPrefix string, startTblId int, endTblId int, wg *sync.WaitGroup) { - //fmt.Printf("subThread[%d]: create table from %d to %d \n", unix.Gettid(), startTblId, endTblId) - // windows.GetCurrentThreadId() - - db, err := sql.Open(taosDriverName, url) - if err != nil { - fmt.Printf("Open database error: %s\n", err) - os.Exit(1) - } - defer db.Close() - - for i := startTblId; i <= endTblId; i++ { - sqlStr := "create table if not exists " + dbName + "." + childTblPrefix + strconv.Itoa(i) + " using " + dbName + ".meters tags('" + locations[i%maxLocationSize] + "', " + strconv.Itoa(i) + ");" - //fmt.Printf("sqlStr: %v\n", sqlStr) - _, err = db.Exec(sqlStr) - checkErr(err, sqlStr) - } - wg.Done() - runtime.Goexit() -} - -func generateRowData(ts int64) string { - voltage := rand.Int() % 1000 - current := 200 + rand.Float32() - phase := rand.Float32() - values := "( " + strconv.FormatInt(ts, 10) + ", " + strconv.FormatFloat(float64(current), 'f', 6, 64) + ", " + strconv.Itoa(voltage) + ", " + strconv.FormatFloat(float64(phase), 'f', 6, 64) + " ) " - return values -} - -func insertData(dbName string, childTblPrefix string, startTblId int, endTblId int, wg *sync.WaitGroup) { - //fmt.Printf("subThread[%d]: insert data to table from %d to %d \n", unix.Gettid(), startTblId, endTblId) - // windows.GetCurrentThreadId() - - db, err := sql.Open(taosDriverName, url) - if err != nil { - fmt.Printf("Open database error: %s\n", err) - os.Exit(1) - } - defer db.Close() - - tmpTs := configPara.startTs - //rand.New(rand.NewSource(time.Now().UnixNano())) - for tID := startTblId; tID <= endTblId; tID++ { - totalNum := 0 - for { - sqlStr := "insert into " + dbName + "." + childTblPrefix + strconv.Itoa(tID) + " values " - currRowNum := 0 - for { - tmpTs += 1000 - valuesOfRow := generateRowData(tmpTs) - currRowNum += 1 - totalNum += 1 - - sqlStr = fmt.Sprintf("%s %s", sqlStr, valuesOfRow) - - if currRowNum >= configPara.numOfRecordsPerReq || totalNum >= configPara.numOfRecordsPerTable { - break - } - } - - res, err := db.Exec(sqlStr) - checkErr(err, sqlStr) - - count, err := res.RowsAffected() - checkErr(err, "rows affected") - - if count != int64(currRowNum) { - fmt.Printf("insert data, expect affected:%d, actual:%d\n", currRowNum, count) - os.Exit(1) - } - - if totalNum >= configPara.numOfRecordsPerTable { - break - } - } - } - - wg.Done() - runtime.Goexit() -} - -func multiThreadInsertData(threads int, nTables int, dbName string, tablePrefix string) { - st := time.Now().UnixNano() - - if threads < 1 { - threads = 1 - } - - a := nTables / threads - if a < 1 { - threads = nTables - a = 1 - } - - b := nTables % threads - - last := 0 - endTblId := 0 - wg := sync.WaitGroup{} - for i := 0; i < threads; i++ { - startTblId := last - if i < b { - endTblId = last + a - } else { - endTblId = last + a - 1 - } - last = endTblId + 1 - wg.Add(1) - go insertData(dbName, tablePrefix, startTblId, endTblId, &wg) - } - wg.Wait() - - et := time.Now().UnixNano() - fmt.Printf("insert data spent duration: %6.6fs\n", (float32(et-st))/1e9) -} - -func selectTest(dbName string, tbPrefix string, supTblName string) { - db, err := sql.Open(taosDriverName, url) - if err != nil { - fmt.Printf("Open database error: %s\n", err) - os.Exit(1) - } - defer db.Close() - - // select sql 1 - limit := 3 - offset := 0 - sqlStr := "select * from " + dbName + "." + supTblName + " limit " + strconv.Itoa(limit) + " offset " + strconv.Itoa(offset) - rows, err := db.Query(sqlStr) - checkErr(err, sqlStr) - - defer rows.Close() - fmt.Printf("query sql: %s\n", sqlStr) - for rows.Next() { - var ( - ts string - current float32 - voltage int - phase float32 - location string - groupid int - ) - err := rows.Scan(&ts, ¤t, &voltage, &phase, &location, &groupid) - if err != nil { - checkErr(err, "rows scan fail") - } - - fmt.Printf("ts:%s\t current:%f\t voltage:%d\t phase:%f\t location:%s\t groupid:%d\n", ts, current, voltage, phase, location, groupid) - } - // check iteration error - if rows.Err() != nil { - checkErr(err, "rows next iteration error") - } - - // select sql 2 - sqlStr = "select avg(voltage), min(voltage), max(voltage) from " + dbName + "." + tbPrefix + strconv.Itoa(rand.Int()%configPara.numOftables) - rows, err = db.Query(sqlStr) - checkErr(err, sqlStr) - - defer rows.Close() - fmt.Printf("\nquery sql: %s\n", sqlStr) - for rows.Next() { - var ( - voltageAvg float32 - voltageMin int - voltageMax int - ) - err := rows.Scan(&voltageAvg, &voltageMin, &voltageMax) - if err != nil { - checkErr(err, "rows scan fail") - } - - fmt.Printf("avg(voltage):%f\t min(voltage):%d\t max(voltage):%d\n", voltageAvg, voltageMin, voltageMax) - } - // check iteration error - if rows.Err() != nil { - checkErr(err, "rows next iteration error") - } - - // select sql 3 - sqlStr = "select last(*) from " + dbName + "." + supTblName - rows, err = db.Query(sqlStr) - checkErr(err, sqlStr) - - defer rows.Close() - fmt.Printf("\nquery sql: %s\n", sqlStr) - for rows.Next() { - var ( - lastTs string - lastCurrent float32 - lastVoltage int - lastPhase float32 - ) - err := rows.Scan(&lastTs, &lastCurrent, &lastVoltage, &lastPhase) - if err != nil { - checkErr(err, "rows scan fail") - } - - fmt.Printf("last(ts):%s\t last(current):%f\t last(voltage):%d\t last(phase):%f\n", lastTs, lastCurrent, lastVoltage, lastPhase) - } - // check iteration error - if rows.Err() != nil { - checkErr(err, "rows next iteration error") - } -} -func drop_database_stmt(db *sql.DB, demodb string) { - st := time.Now().Nanosecond() - // drop test db - res, err := db.Exec("drop database if exists " + demodb) - checkErr(err, "drop database "+demodb) - - affectd, err := res.RowsAffected() - checkErr(err, "drop db, res.RowsAffected") - - et := time.Now().Nanosecond() - fmt.Printf("drop database result:\n %d row(s) affectd (%6.6fs)\n\n", affectd, (float32(et-st))/1e9) -} - -func create_database_stmt(db *sql.DB, demodb string) { - st := time.Now().Nanosecond() - // create database - //var stmt interface{} - stmt, err := db.Prepare("create database ?") - checkErr(err, "create db, db.Prepare") - - //var res driver.Result - res, err := stmt.Exec(demodb) - checkErr(err, "create db, stmt.Exec") - - //fmt.Printf("Query OK, %d row(s) affected()", res.RowsAffected()) - affectd, err := res.RowsAffected() - checkErr(err, "create db, res.RowsAffected") - - et := time.Now().Nanosecond() - fmt.Printf("create database result:\n %d row(s) affectd (%6.6fs)\n\n", affectd, (float32(et-st))/1e9) -} - -func use_database_stmt(db *sql.DB, demodb string) { - st := time.Now().Nanosecond() - // create database - //var stmt interface{} - stmt, err := db.Prepare("use " + demodb) - checkErr(err, "use db, db.Prepare") - - res, err := stmt.Exec() - checkErr(err, "use db, stmt.Exec") - - affectd, err := res.RowsAffected() - checkErr(err, "use db, res.RowsAffected") - - et := time.Now().Nanosecond() - fmt.Printf("use database result:\n %d row(s) affectd (%6.6fs)\n\n", affectd, (float32(et-st))/1e9) -} - -func create_table_stmt(db *sql.DB, demot string) { - st := time.Now().Nanosecond() - // create table - // (ts timestamp, id int, name binary(8), len tinyint, flag bool, notes binary(8), fv float, dv double) - stmt, err := db.Prepare("create table ? (? timestamp, ? int, ? binary(10), ? tinyint, ? bool, ? binary(8), ? float, ? double)") - checkErr(err, "create table db.Prepare") - - res, err := stmt.Exec(demot, "ts", "id", "name", "len", "flag", "notes", "fv", "dv") - checkErr(err, "create table stmt.Exec") - - affectd, err := res.RowsAffected() - checkErr(err, "create table res.RowsAffected") - - et := time.Now().Nanosecond() - fmt.Printf("create table result:\n %d row(s) affectd (%6.6fs)\n\n", affectd, (float32(et-st))/1e9) -} - -func insert_data_stmt(db *sql.DB, demot string) { - st := time.Now().Nanosecond() - // insert data into table - stmt, err := db.Prepare("insert into ? values(?, ?, ?, ?, ?, ?, ?, ?) (?, ?, ?, ?, ?, ?, ?, ?) (?, ?, ?, ?, ?, ?, ?, ?)") - checkErr(err, "insert db.Prepare") - - res, err := stmt.Exec(demot, "now", 1000, "'haidian'", 6, true, "'AI world'", 6987.654, 321.987, - "now+1s", 1001, "'changyang'", 7, false, "'DeepMode'", 12356.456, 128634.456, - "now+2s", 1002, "'chuangping'", 8, true, "'database'", 3879.456, 65433478.456) - checkErr(err, "insert data, stmt.Exec") - - affectd, err := res.RowsAffected() - checkErr(err, "res.RowsAffected") - - et := time.Now().Nanosecond() - fmt.Printf("insert data result:\n %d row(s) affectd (%6.6fs)\n\n", affectd, (float32(et-st))/1e9) -} - -func select_data_stmt(db *sql.DB, demot string) { - st := time.Now().Nanosecond() - - stmt, err := db.Prepare("select ?, ?, ?, ?, ?, ?, ?, ? from ?") // go binary mode - checkErr(err, "db.Prepare") - - rows, err := stmt.Query("ts", "id", "name", "len", "flag", "notes", "fv", "dv", demot) - checkErr(err, "stmt.Query") - - fmt.Printf("%10s%s%8s %5s %8s%s %s %10s%s %7s%s %8s%s %11s%s %14s%s\n", " ", "ts", " ", "id", " ", "name", " ", "len", " ", "flag", " ", "notes", " ", "fv", " ", " ", "dv") - var affectd int - for rows.Next() { - var ts string - var name string - var id int - var len int8 - var flag bool - var notes string - var fv float32 - var dv float64 - - err = rows.Scan(&ts, &id, &name, &len, &flag, ¬es, &fv, &dv) - //fmt.Println("start scan fields from row.rs, &fv:", &fv) - //err = rows.Scan(&fv) - checkErr(err, "rows.Scan") - - fmt.Printf("%s\t", ts) - fmt.Printf("%d\t", id) - fmt.Printf("%10s\t", name) - fmt.Printf("%d\t", len) - fmt.Printf("%t\t", flag) - fmt.Printf("%s\t", notes) - fmt.Printf("%06.3f\t", fv) - fmt.Printf("%09.6f\n", dv) - - affectd++ - - } - - et := time.Now().Nanosecond() - fmt.Printf("insert data result:\n %d row(s) affectd (%6.6fs)\n\n", affectd, (float32(et-st))/1e9) -} -func checkErr(err error, prompt string) { - if err != nil { - fmt.Printf("%s\n", prompt) - panic(err) - } -} diff --git a/tests/examples/lua/OpenResty/conf/nginx.conf b/tests/examples/lua/OpenResty/conf/nginx.conf deleted file mode 100644 index 960cac606a49e5964a900f815eb76e7f228078eb..0000000000000000000000000000000000000000 --- a/tests/examples/lua/OpenResty/conf/nginx.conf +++ /dev/null @@ -1,21 +0,0 @@ -worker_processes 1; -user root; -error_log logs/error.log; -events { - worker_connections 1024; -} - -http { - lua_package_path '$prefix/lua/?.lua;$prefix/rest/?.lua;$prefix/rest/?/init.lua;;'; - lua_package_cpath "$prefix/so/?.so;;"; - lua_code_cache on; - server { - listen 7000; - server_name restapi; - charset utf-8; - lua_need_request_body on; - location ~ ^/api/([-_a-zA-Z0-9/]+) { - content_by_lua_file rest/$1.lua; - } - } -} diff --git a/tests/examples/lua/OpenResty/logs/.gitignore b/tests/examples/lua/OpenResty/logs/.gitignore deleted file mode 100644 index ad8530e1c3e3c88fcce3b50abf7cc006333f5522..0000000000000000000000000000000000000000 --- a/tests/examples/lua/OpenResty/logs/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Ignore everything in this directory -* -# Except this file -!.gitignore diff --git a/tests/examples/lua/OpenResty/rest/config.lua b/tests/examples/lua/OpenResty/rest/config.lua deleted file mode 100644 index 72a4fd8ec687430e5f3d0a798dc4fb3b2d95a942..0000000000000000000000000000000000000000 --- a/tests/examples/lua/OpenResty/rest/config.lua +++ /dev/null @@ -1,10 +0,0 @@ -local config = { - host = "127.0.0.1", - port = 6030, - database = "", - user = "root", - password = "taosdata", - max_packet_size = 1024 * 1024 , - connection_pool_size = 64 -} -return config diff --git a/tests/examples/lua/OpenResty/rest/tdpool/init.lua b/tests/examples/lua/OpenResty/rest/tdpool/init.lua deleted file mode 100644 index ebf8e91756539cc8af5db38232a40bf42aeaa245..0000000000000000000000000000000000000000 --- a/tests/examples/lua/OpenResty/rest/tdpool/init.lua +++ /dev/null @@ -1,72 +0,0 @@ -local _M = {} -local driver = require "luaconnector51" -local water_mark = 0 -local occupied = 0 -local connection_pool = {} - -function _M.new(o,config) - o = o or {} - o.connection_pool = connection_pool - o.water_mark = water_mark - o.occupied = occupied - if #connection_pool == 0 then - - for i = 1, config.connection_pool_size do - local res = driver.connect(config) - if res.code ~= 0 then - ngx.log(ngx.ERR, "connect--- failed:"..res.error) - return nil - else - local object = {obj = res.conn, state = 0} - table.insert(o.connection_pool,i, object) - ngx.log(ngx.INFO, "add connection, now pool size:"..#(o.connection_pool)) - end - end - - end - - return setmetatable(o, { __index = _M }) -end - -function _M:get_connection() - - local connection_obj - - for i = 1, #connection_pool do - connection_obj = connection_pool[i] - if connection_obj.state == 0 then - connection_obj.state = 1 - occupied = occupied +1 - if occupied > water_mark then - water_mark = occupied - end - return connection_obj["obj"] - end - end - - ngx.log(ngx.ERR,"ALERT! NO FREE CONNECTION.") - - return nil -end - -function _M:get_water_mark() - - return water_mark -end - -function _M:release_connection(conn) - - local connection_obj - - for i = 1, #connection_pool do - connection_obj = connection_pool[i] - - if connection_obj["obj"] == conn then - connection_obj["state"] = 0 - occupied = occupied -1 - return - end - end -end - -return _M diff --git a/tests/examples/lua/OpenResty/rest/test.lua b/tests/examples/lua/OpenResty/rest/test.lua deleted file mode 100644 index 9b2169a2da656ea34f60e99c8904b5f224da3dd4..0000000000000000000000000000000000000000 --- a/tests/examples/lua/OpenResty/rest/test.lua +++ /dev/null @@ -1,91 +0,0 @@ -local driver = require "luaconnector51" -local cjson = require "cjson" -local Pool = require "tdpool" -local config = require "config" -ngx.say("start time:"..os.time()) - -local pool = Pool.new(Pool,config) -local conn = pool:get_connection() - -local res = driver.query(conn,"drop database if exists nginx") -if res.code ~=0 then - ngx.say("drop db--- failed: "..res.error) -else - ngx.say("drop db--- pass.") -end -res = driver.query(conn,"create database nginx") -if res.code ~=0 then - ngx.say("create db--- failed: "..res.error) - -else - ngx.say("create db--- pass.") -end - -res = driver.query(conn,"use nginx") -if res.code ~=0 then - ngx.say("select db--- failed: "..res.error) -else - ngx.say("select db--- pass.") -end - -res = driver.query(conn,"create table m1 (ts timestamp, speed int, owner binary(20), mark nchar(30))") -if res.code ~=0 then - ngx.say("create table---failed: "..res.error) - -else - ngx.say("create table--- pass.") -end - -res = driver.query(conn,"insert into m1 values ('2019-09-01 00:00:00.001', 0, 'robotspace', '世界人民大团结万岁'), ('2019-09-01 00:00:00.002',1,'Hilink','⾾⾿⿀⿁⿂⿃⿄⿅⿆⿇⿈⿉⿊⿋⿌⿍⿎⿏⿐⿑⿒⿓⿔⿕'),('2019-09-01 00:00:00.003',2,'Harmony', '₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵')") -if res.code ~=0 then - ngx.say("insert records failed: "..res.error) - return -else - if(res.affected == 3) then - ngx.say("insert records--- pass") - else - ngx.say("insert records---failed: expect 3 affected records, actually affected "..res.affected) - end -end - -res = driver.query(conn,"select * from m1") - -if res.code ~=0 then - ngx.say("select failed: "..res.error) - return -else - ngx.say(cjson.encode(res)) - if (#(res.item) == 3) then - ngx.say("select--- pass") - else - ngx.say("select--- failed: expect 3 affected records, actually received "..#(res.item)) - end - -end ---[[ -local flag = false -function query_callback(res) - if res.code ~=0 then - ngx.say("async_query_callback--- failed:"..res.error) - else - if(res.affected == 3) then - ngx.say("async_query_callback, insert records--- pass") - else - ngx.say("async_query_callback, insert records---failed: expect 3 affected records, actually affected "..res.affected) - end - end - flag = true -end - -driver.query_a(conn,"insert into m1 values ('2019-09-01 00:00:00.001', 3, 'robotspace'),('2019-09-01 00:00:00.006', 4, 'Hilink'),('2019-09-01 00:00:00.007', 6, 'Harmony')", query_callback) - -while not flag do - ngx.say("i am here once...") - ngx.sleep(0.001) -- time unit is second -end ---]] - -ngx.say("pool water_mark:"..pool:get_water_mark()) - -pool:release_connection(conn) -ngx.say("end time:"..os.time()) diff --git a/tests/examples/lua/OpenResty/so/luaconnector51.so b/tests/examples/lua/OpenResty/so/luaconnector51.so deleted file mode 100755 index a17c0318bd1e9196311ca97b20a8dde4fc1835a6..0000000000000000000000000000000000000000 Binary files a/tests/examples/lua/OpenResty/so/luaconnector51.so and /dev/null differ diff --git a/tests/examples/lua/README.md b/tests/examples/lua/README.md deleted file mode 100644 index bdc88edbd7b5d6798a8df6530ea82d24eb22915b..0000000000000000000000000000000000000000 --- a/tests/examples/lua/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# TDengine driver connector for Lua - -It's a Lua implementation for [TDengine](https://github.com/taosdata/TDengine), an open-sourced big data platform designed and optimized for the Internet of Things (IoT), Connected Cars, Industrial IoT, and IT Infrastructure and Application Monitoring. You may need to install Lua5.3 . -As TDengine is built with lua-enable, the built-in lua module conflicts with external lua. The following commands require TDengine built with lua-disable. -To disable built-in lua: -mkdir debug && cd debug -cmake .. -DBUILD_LUA=false && cmake --build . -## Lua Dependencies -- Lua: -``` -https://www.lua.org/ -``` - -## Run with Lua Sample - -Build driver lib: -``` -./build.sh -``` -Run lua sample: -``` -lua test.lua -``` - -## Run performance test: -``` -time lua benchmark.lua -``` -## OpenResty Dependencies -- OpenResty: -``` -http://openresty.org -``` -## Run with OpenResty Sample -**This section demonstrates how to get binary file for connector. To be convenient for trial, an connector has been put into OpenResty work directory. -Because of difference on C API between Lua5.3 and Lua5.1, the files needed by connector for OpenResty are stored in local source directory and configured in script build.sh.** - -Build driver lib: -``` -cd lua51 -./build.sh -``` -Run OpenResty sample: -``` -cd .. -cd OpenResty -sudo openresty -p . -curl http://127.0.0.1:7000/api/test -``` - diff --git a/tests/examples/lua/benchmark.lua b/tests/examples/lua/benchmark.lua deleted file mode 100644 index 900e7891d81d5de2d723a9ebd9accf3317b2413a..0000000000000000000000000000000000000000 --- a/tests/examples/lua/benchmark.lua +++ /dev/null @@ -1,67 +0,0 @@ -local driver = require "luaconnector" - -local config = { - password = "taosdata", - host = "127.0.0.1", - port = 6030, - database = "", - user = "root", - - max_packet_size = 1024 * 1024 -} - -local conn -local res = driver.connect(config) -if res.code ~=0 then - print("connect--- failed: "..res.error) - return -else - conn = res.conn - print("connect--- pass.") -end - -local res = driver.query(conn,"drop database if exists demo") - -res = driver.query(conn,"create database demo") -if res.code ~=0 then - print("create db--- failed: "..res.error) - return -else - print("create db--- pass.") -end - -res = driver.query(conn,"use demo") -if res.code ~=0 then - print("select db--- failed: "..res.error) - return -else - print("select db--- pass.") -end - -res = driver.query(conn,"create table m1 (ts timestamp, speed int,owner binary(20))") -if res.code ~=0 then - print("create table---failed: "..res.error) - return -else - print("create table--- pass.") -end - -local base = 1617330000000 -local index =0 -local count = 100000 -local t -while( index < count ) -do - t = base + index - local q=string.format([[insert into m1 values (%d,0,'robotspace')]],t) -res = driver.query(conn,q) -if res.code ~=0 then - print("insert records failed: "..res.error) - return -else - -end - index = index+1 -end -print(string.format([["Done. %d records has been stored."]],count)) -driver.close(conn) diff --git a/tests/examples/lua/build.sh b/tests/examples/lua/build.sh deleted file mode 100755 index 9d00c6842515415034ce0b5dc71d5d6af9ffc881..0000000000000000000000000000000000000000 --- a/tests/examples/lua/build.sh +++ /dev/null @@ -1,8 +0,0 @@ -lua_header_installed=`apt-cache policy liblua5.3-dev|grep Installed|grep none > /dev/null; echo $?` -if [ "$lua_header_installed" = "0" ]; then - echo "If need, please input root password to install liblua5.3-dev for build the connector.." - sudo apt install -y liblua5.3-dev -fi - -gcc -std=c99 lua_connector.c -fPIC -shared -o luaconnector.so -Wall -ltaos -I/usr/include/lua5.3 - diff --git a/tests/examples/lua/lua51/build.sh b/tests/examples/lua/lua51/build.sh deleted file mode 100755 index 3b52ed14489a636fe7a867ed086199647fa650df..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/build.sh +++ /dev/null @@ -1,2 +0,0 @@ -gcc -std=c99 lua_connector51.c -fPIC -shared -o luaconnector51.so -Wall -ltaos - diff --git a/tests/examples/lua/lua51/lauxlib.h b/tests/examples/lua/lua51/lauxlib.h deleted file mode 100644 index a44f0272b3ab0745b0ce798d377b40d2cce113cd..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/lauxlib.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -** $Id: lauxlib.h,v 1.88.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - -/* extra error code for `luaL_load' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - -LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, - const luaL_Reg *l, int nup); -LUALIB_API void (luaL_register) (lua_State *L, const char *libname, - const luaL_Reg *l); -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname); -LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, - lua_Integer def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int narg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, - const char *const lst[]); - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); -LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, - const char *name); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - - -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, - const char *r); - -LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, - const char *fname, int szhint); - -/* From Lua 5.2. */ -LUALIB_API int luaL_fileresult(lua_State *L, int stat, const char *fname); -LUALIB_API int luaL_execresult(lua_State *L, int stat); -LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, - const char *mode); -LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, - const char *name, const char *mode); -LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, - int level); -LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); -LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, - int sizehint); -LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); -LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define luaL_argcheck(L, cond,numarg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -/* From Lua 5.2. */ -#define luaL_newlibtable(L, l) \ - lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) -#define luaL_newlib(L, l) (luaL_newlibtable(L, l), luaL_setfuncs(L, l, 0)) - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - - - -typedef struct luaL_Buffer { - char *p; /* current position in buffer */ - int lvl; /* number of strings in the stack (level) */ - lua_State *L; - char buffer[LUAL_BUFFERSIZE]; -} luaL_Buffer; - -#define luaL_addchar(B,c) \ - ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ - (*(B)->p++ = (char)(c))) - -/* compatibility only */ -#define luaL_putchar(B,c) luaL_addchar(B,c) - -#define luaL_addsize(B,n) ((B)->p += (n)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); - - -/* }====================================================== */ - -#endif diff --git a/tests/examples/lua/lua51/lua.h b/tests/examples/lua/lua51/lua.h deleted file mode 100644 index 9dcafd690655868115ce53dff26599f5845b12c5..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/lua.h +++ /dev/null @@ -1,404 +0,0 @@ -/* -** $Id: lua.h,v 1.218.1.5 2008/08/06 13:30:12 roberto Exp $ -** Lua - An Extensible Extension Language -** Lua.org, PUC-Rio, Brazil (http://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION "Lua 5.1" -#define LUA_RELEASE "Lua 5.1.4" -#define LUA_VERSION_NUM 501 -#define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" - - -/* mark for precompiled code (`Lua') */ -#define LUA_SIGNATURE "\033Lua" - -/* option for multiple returns in `lua_pcall' and `lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** pseudo-indices -*/ -#define LUA_REGISTRYINDEX (-10000) -#define LUA_ENVIRONINDEX (-10001) -#define LUA_GLOBALSINDEX (-10002) -#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) - - -/* thread status */ -#define LUA_OK 0 -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRERR 5 - - -typedef struct lua_State lua_State; - -typedef int (*lua_CFunction) (lua_State *L); - - -/* -** functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); - - -/* -** prototype for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void (lua_close) (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_remove) (lua_State *L, int idx); -LUA_API void (lua_insert) (lua_State *L, int idx); -LUA_API void (lua_replace) (lua_State *L, int idx); -LUA_API int (lua_checkstack) (lua_State *L, int sz); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); - -LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); -LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API size_t (lua_objlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l); -LUA_API void (lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API void (lua_gettable) (lua_State *L, int idx); -LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawget) (lua_State *L, int idx); -LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API void (lua_getfenv) (lua_State *L, int idx); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API int (lua_setfenv) (lua_State *L, int idx); - - -/* -** `load' and `call' functions (load and run Lua code) -*/ -LUA_API void (lua_call) (lua_State *L, int nargs, int nresults); -LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); -LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yield) (lua_State *L, int nresults); -LUA_API int (lua_resume) (lua_State *L, int narg); -LUA_API int (lua_status) (lua_State *L); - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 -#define LUA_GCISRUNNING 9 - -LUA_API int (lua_gc) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); - -LUA_API void lua_setexdata(lua_State *L, void *exdata); -LUA_API void *lua_getexdata(lua_State *L); - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_strlen(L,i) lua_objlen(L, (i)) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) \ - lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) - -#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) -#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - - -/* -** compatibility macros and functions -*/ - -#define lua_open() luaL_newstate() - -#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) - -#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) - -#define lua_Chunkreader lua_Reader -#define lua_Chunkwriter lua_Writer - - -/* hack */ -LUA_API void lua_setlevel (lua_State *from, lua_State *to); - - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILRET 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debuger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); -LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); -LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); -LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook lua_gethook (lua_State *L); -LUA_API int lua_gethookmask (lua_State *L); -LUA_API int lua_gethookcount (lua_State *L); - -/* From Lua 5.2. */ -LUA_API void *lua_upvalueid (lua_State *L, int idx, int n); -LUA_API void lua_upvaluejoin (lua_State *L, int idx1, int n1, int idx2, int n2); -LUA_API int lua_loadx (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname, const char *mode); -LUA_API const lua_Number *lua_version (lua_State *L); -LUA_API void lua_copy (lua_State *L, int fromidx, int toidx); -LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum); -LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum); - -/* From Lua 5.3. */ -LUA_API int lua_isyieldable (lua_State *L); - - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) `global', `local', `field', `method' */ - const char *what; /* (S) `Lua', `C', `main', `tail' */ - const char *source; /* (S) */ - int currentline; /* (l) */ - int nups; /* (u) number of upvalues */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - int i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved. -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - - -#endif diff --git a/tests/examples/lua/lua51/lua_connector51.c b/tests/examples/lua/lua51/lua_connector51.c deleted file mode 100644 index 7aad42f29343306516c6d8973b76060f3e1e6dfe..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/lua_connector51.c +++ /dev/null @@ -1,387 +0,0 @@ -#include -#include -#include -#include -#include "lua.h" -#include "lauxlib.h" -#include "lualib.h" -#include - -struct cb_param{ - lua_State* state; - int callback; - void * stream; -}; - -struct async_query_callback_param{ - lua_State* state; - int callback; -}; - -static int l_connect(lua_State *L){ - TAOS * taos=NULL; - const char* host; - const char* database; - const char* user; - const char* password; - int port; - - luaL_checktype(L, 1, LUA_TTABLE); - - lua_getfield(L, 1,"host"); - if (lua_isstring(L,-1)){ - host = lua_tostring(L, -1); - // printf("host = %s\n", host); - } - - lua_getfield(L, 1, "port"); - if (lua_isnumber(L, -1)){ - port = lua_tonumber(L, -1); - //printf("port = %d\n", port); - } - - lua_getfield(L, 1, "database"); - if (lua_isstring(L, -1)){ - database = lua_tostring(L, -1); - //printf("database = %s\n", database); - } - - lua_getfield(L, 1, "user"); - if (lua_isstring(L, -1)){ - user = lua_tostring(L, -1); - //printf("user = %s\n", user); - } - - lua_getfield(L, 1, "password"); - if (lua_isstring(L, -1)){ - password = lua_tostring(L, -1); - //printf("password = %s\n", password); - } - - lua_settop(L,0); - - taos_init(); - - lua_newtable(L); - int table_index = lua_gettop(L); - - taos = taos_connect(host, user,password,database, port); - if (taos == NULL) { - printf("failed to connect server, reason:%s\n", taos_errstr(taos)); - - lua_pushinteger(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - lua_pushlightuserdata(L,NULL); - lua_setfield(L, table_index, "conn"); - }else{ - // printf("success to connect server\n"); - lua_pushinteger(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - lua_pushlightuserdata(L,taos); - lua_setfield(L, table_index, "conn"); - } - - return 1; -} - -static int l_query(lua_State *L){ - TAOS *taos= (TAOS*)lua_topointer(L,1); - const char* s = lua_tostring(L, 2); - TAOS_RES *result; - lua_newtable(L); - int table_index = lua_gettop(L); - - // printf("receive command:%s\r\n",s); - result = taos_query(taos, s); - int32_t code = taos_errno(result); - if( code != 0){ - printf("failed, reason:%s\n", taos_errstr(result)); - lua_pushinteger(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(result)); - lua_setfield(L, table_index, "error"); - - return 1; - - }else{ - //printf("success to query.\n"); - TAOS_ROW row; - int rows = 0; - int num_fields = taos_field_count(result); - const TAOS_FIELD *fields = taos_fetch_fields(result); - - const int affectRows = taos_affected_rows(result); - // printf(" affect rows:%d\r\n", affectRows); - lua_pushinteger(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushinteger(L, affectRows); - lua_setfield(L, table_index, "affected"); - lua_newtable(L); - - while ((row = taos_fetch_row(result))) { - //printf("row index:%d\n",rows); - rows++; - - lua_pushnumber(L,rows); - lua_newtable(L); - - for (int i = 0; i < num_fields; ++i) { - if (row[i] == NULL) { - continue; - } - - lua_pushstring(L,fields[i].name); - int32_t* length = taos_fetch_lengths(result); - switch (fields[i].type) { - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_TINYINT: - lua_pushinteger(L,*((char *)row[i])); - break; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_SMALLINT: - lua_pushinteger(L,*((short *)row[i])); - break; - case TSDB_DATA_TYPE_UINT: - case TSDB_DATA_TYPE_INT: - lua_pushinteger(L,*((int *)row[i])); - break; - case TSDB_DATA_TYPE_UBIGINT: - case TSDB_DATA_TYPE_BIGINT: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_FLOAT: - lua_pushnumber(L,*((float *)row[i])); - break; - case TSDB_DATA_TYPE_DOUBLE: - lua_pushnumber(L,*((double *)row[i])); - break; - case TSDB_DATA_TYPE_JSON: - case TSDB_DATA_TYPE_BINARY: - case TSDB_DATA_TYPE_NCHAR: - //printf("type:%d, max len:%d, current len:%d\n",fields[i].type, fields[i].bytes, length[i]); - lua_pushlstring(L,(char *)row[i], length[i]); - break; - case TSDB_DATA_TYPE_TIMESTAMP: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_BOOL: - lua_pushinteger(L,*((char *)row[i])); - break; - case TSDB_DATA_TYPE_NULL: - default: - lua_pushnil(L); - break; - } - - lua_settable(L,-3); - } - - lua_settable(L,-3); - } - taos_free_result(result); - } - - lua_setfield(L, table_index, "item"); - return 1; -} - -void async_query_callback(void *param, TAOS_RES *result, int code){ - struct async_query_callback_param* p = (struct async_query_callback_param*) param; - - //printf("\nin c,numfields:%d\n", numFields); - //printf("\nin c, code:%d\n", code); - - lua_State *L = p->state; - lua_rawgeti(L, LUA_REGISTRYINDEX, p->callback); - lua_newtable(L); - int table_index = lua_gettop(L); - if( code < 0){ - printf("failed, reason:%s\n", taos_errstr(result)); - lua_pushinteger(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L,"something is wrong");// taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - }else{ - //printf("success to async query.\n"); - const int affectRows = taos_affected_rows(result); - //printf(" affect rows:%d\r\n", affectRows); - lua_pushinteger(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushinteger(L, affectRows); - lua_setfield(L, table_index, "affected"); - } - - lua_call(L, 1, 0); -} - -static int l_async_query(lua_State *L){ - int r = luaL_ref(L, LUA_REGISTRYINDEX); - TAOS * taos = (TAOS*)lua_topointer(L,1); - const char * sqlstr = lua_tostring(L,2); - // int stime = luaL_checknumber(L,3); - - lua_newtable(L); - int table_index = lua_gettop(L); - - struct async_query_callback_param *p = malloc(sizeof(struct async_query_callback_param)); - p->state = L; - p->callback=r; - // printf("r:%d, L:%d\n",r,L); - taos_query_a(taos,sqlstr,async_query_callback,p); - - lua_pushnumber(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, "ok"); - lua_setfield(L, table_index, "error"); - - return 1; -} - -void stream_cb(void *param, TAOS_RES *result, TAOS_ROW row){ - struct cb_param* p = (struct cb_param*) param; - TAOS_FIELD *fields = taos_fetch_fields(result); - int numFields = taos_num_fields(result); - - // printf("\nnumfields:%d\n", numFields); - //printf("\n\r-----------------------------------------------------------------------------------\n"); - - lua_State *L = p->state; - lua_rawgeti(L, LUA_REGISTRYINDEX, p->callback); - - lua_newtable(L); - - for (int i = 0; i < numFields; ++i) { - if (row[i] == NULL) { - continue; - } - - lua_pushstring(L,fields[i].name); - - switch (fields[i].type) { - case TSDB_DATA_TYPE_TINYINT: - lua_pushinteger(L,*((char *)row[i])); - break; - case TSDB_DATA_TYPE_SMALLINT: - lua_pushinteger(L,*((short *)row[i])); - break; - case TSDB_DATA_TYPE_INT: - lua_pushinteger(L,*((int *)row[i])); - break; - case TSDB_DATA_TYPE_BIGINT: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_FLOAT: - lua_pushnumber(L,*((float *)row[i])); - break; - case TSDB_DATA_TYPE_DOUBLE: - lua_pushnumber(L,*((double *)row[i])); - break; - case TSDB_DATA_TYPE_BINARY: - case TSDB_DATA_TYPE_NCHAR: - lua_pushstring(L,(char *)row[i]); - break; - case TSDB_DATA_TYPE_TIMESTAMP: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_BOOL: - lua_pushinteger(L,*((char *)row[i])); - break; - default: - lua_pushnil(L); - break; - } - - lua_settable(L, -3); - } - - lua_call(L, 1, 0); - - // printf("-----------------------------------------------------------------------------------\n\r"); -} - -static int l_open_stream(lua_State *L){ - int r = luaL_ref(L, LUA_REGISTRYINDEX); - TAOS * taos = (TAOS*)lua_topointer(L,1); - const char * sqlstr = lua_tostring(L,2); - int stime = luaL_checknumber(L,3); - - lua_newtable(L); - int table_index = lua_gettop(L); - - struct cb_param *p = malloc(sizeof(struct cb_param)); - p->state = L; - p->callback=r; - // printf("r:%d, L:%d\n",r,L); - void * s = taos_open_stream(taos,sqlstr,stream_cb,stime,p,NULL); - if (s == NULL) { - printf("failed to open stream, reason:%s\n", taos_errstr(taos)); - free(p); - lua_pushnumber(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - lua_pushlightuserdata(L,NULL); - lua_setfield(L, table_index, "stream"); - }else{ - // printf("success to open stream\n"); - lua_pushnumber(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - p->stream = s; - lua_pushlightuserdata(L,p); - lua_setfield(L, table_index, "stream");//stream has different content in lua and c. - } - - return 1; -} - -static int l_close_stream(lua_State *L){ - //TODO:get stream and free cb_param - struct cb_param *p = lua_touserdata(L,1); - taos_close_stream(p->stream); - free(p); - return 0; -} - -static int l_close(lua_State *L){ - TAOS *taos= (TAOS*)lua_topointer(L,1); - lua_newtable(L); - int table_index = lua_gettop(L); - - if(taos == NULL){ - lua_pushnumber(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, "null pointer."); - lua_setfield(L, table_index, "error"); - }else{ - taos_close(taos); - lua_pushnumber(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, "done."); - lua_setfield(L, table_index, "error"); - } - return 1; -} - -static const struct luaL_Reg lib[] = { - {"connect", l_connect}, - {"query", l_query}, - {"query_a",l_async_query}, - {"close", l_close}, - {"open_stream", l_open_stream}, - {"close_stream", l_close_stream}, - {NULL, NULL} -}; - -extern int luaopen_luaconnector51(lua_State* L) -{ - // luaL_register(L, "luaconnector51", lib); - lua_newtable (L); - luaL_setfuncs(L,lib,0); - return 1; -} diff --git a/tests/examples/lua/lua51/luaconf.h b/tests/examples/lua/lua51/luaconf.h deleted file mode 100644 index c72893fd152e23c2a413c2da1d31be7b860b2a39..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/luaconf.h +++ /dev/null @@ -1,152 +0,0 @@ -/* -** Configuration header. -** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef luaconf_h -#define luaconf_h - -#ifndef WINVER -#define WINVER 0x0501 -#endif -#include -#include - -/* Default path for loading Lua and C modules with require(). */ -#if defined(_WIN32) -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_PATH_DEFAULT \ - ".\\?.lua;" "!\\lualib\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" -#define LUA_CPATH_DEFAULT \ - ".\\?.dll;" "!\\lualib\\?.so;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" -#else -/* -** Note to distribution maintainers: do NOT patch the following lines! -** Please read ../doc/install.html#distro and pass PREFIX=/usr instead. -*/ -#ifndef LUA_MULTILIB -#define LUA_MULTILIB "lib" -#endif -#ifndef LUA_LMULTILIB -#define LUA_LMULTILIB "lib" -#endif -#define LUA_LROOT "/usr/local" -#define LUA_LUADIR "/lua/5.1/" -#define LUA_LJDIR "/luajit-2.1.0-beta3/" - -#ifdef LUA_ROOT -#define LUA_JROOT LUA_ROOT -#define LUA_RLDIR LUA_ROOT "/share" LUA_LUADIR -#define LUA_RCDIR LUA_ROOT "/" LUA_MULTILIB LUA_LUADIR -#define LUA_RLPATH ";" LUA_RLDIR "?.lua;" LUA_RLDIR "?/init.lua" -#define LUA_RCPATH ";" LUA_RCDIR "?.so" -#else -#define LUA_JROOT LUA_LROOT -#define LUA_RLPATH -#define LUA_RCPATH -#endif - -#define LUA_JPATH ";" LUA_JROOT "/share" LUA_LJDIR "?.lua" -#define LUA_LLDIR LUA_LROOT "/share" LUA_LUADIR -#define LUA_LCDIR LUA_LROOT "/" LUA_LMULTILIB LUA_LUADIR -#define LUA_LLPATH ";" LUA_LLDIR "?.lua;" LUA_LLDIR "?/init.lua" -#define LUA_LCPATH1 ";" LUA_LCDIR "?.so" -#define LUA_LCPATH2 ";" LUA_LCDIR "loadall.so" - -#define LUA_PATH_DEFAULT "./?.lua" LUA_JPATH LUA_LLPATH LUA_RLPATH -#define LUA_CPATH_DEFAULT "./?.so" LUA_LCPATH1 LUA_RCPATH LUA_LCPATH2 -#endif - -/* Environment variable names for path overrides and initialization code. */ -#define LUA_PATH "LUA_PATH" -#define LUA_CPATH "LUA_CPATH" -#define LUA_INIT "LUA_INIT" - -/* Special file system characters. */ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif -#define LUA_PATHSEP ";" -#define LUA_PATH_MARK "?" -#define LUA_EXECDIR "!" -#define LUA_IGMARK "-" -#define LUA_PATH_CONFIG \ - LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" \ - LUA_EXECDIR "\n" LUA_IGMARK "\n" - -/* Quoting in error messages. */ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - -/* Various tunables. */ -#define LUAI_MAXSTACK 65500 /* Max. # of stack slots for a thread (<64K). */ -#define LUAI_MAXCSTACK 8000 /* Max. # of stack slots for a C func (<10K). */ -#define LUAI_GCPAUSE 200 /* Pause GC until memory is at 200%. */ -#define LUAI_GCMUL 200 /* Run GC at 200% of allocation speed. */ -#define LUA_MAXCAPTURES 32 /* Max. pattern captures. */ - -/* Configuration for the frontend (the luajit executable). */ -#if defined(luajit_c) -#define LUA_PROGNAME "luajit" /* Fallback frontend name. */ -#define LUA_PROMPT "> " /* Interactive prompt. */ -#define LUA_PROMPT2 ">> " /* Continuation prompt. */ -#define LUA_MAXINPUT 512 /* Max. input line length. */ -#endif - -/* Note: changing the following defines breaks the Lua 5.1 ABI. */ -#define LUA_INTEGER ptrdiff_t -#define LUA_IDSIZE 60 /* Size of lua_Debug.short_src. */ -/* -** Size of lauxlib and io.* on-stack buffers. Weird workaround to avoid using -** unreasonable amounts of stack space, but still retain ABI compatibility. -** Blame Lua for depending on BUFSIZ in the ABI, blame **** for wrecking it. -*/ -#define LUAL_BUFFERSIZE (BUFSIZ > 16384 ? 8192 : BUFSIZ) - -/* The following defines are here only for compatibility with luaconf.h -** from the standard Lua distribution. They must not be changed for LuaJIT. -*/ -#define LUA_NUMBER_DOUBLE -#define LUA_NUMBER double -#define LUAI_UACNUMBER double -#define LUA_NUMBER_SCAN "%lf" -#define LUA_NUMBER_FMT "%.14g" -#define lua_number2str(s, n) sprintf((s), LUA_NUMBER_FMT, (n)) -#define LUAI_MAXNUMBER2STR 32 -#define LUA_INTFRMLEN "l" -#define LUA_INTFRM_T long - -/* Linkage of public API functions. */ -#if defined(LUA_BUILD_AS_DLL) -#if defined(LUA_CORE) || defined(LUA_LIB) -#define LUA_API __declspec(dllexport) -#else -#define LUA_API __declspec(dllimport) -#endif -#else -#define LUA_API extern -#endif - -#define LUALIB_API LUA_API - -/* Support for internal assertions. */ -#if defined(LUA_USE_ASSERT) || defined(LUA_USE_APICHECK) -#include -#endif -#ifdef LUA_USE_ASSERT -#define lua_assert(x) assert(x) -#endif -#ifdef LUA_USE_APICHECK -#define luai_apicheck(L, o) { (void)L; assert(o); } -#else -#define luai_apicheck(L, o) { (void)L; } -#endif - -#endif diff --git a/tests/examples/lua/lua51/luajit.h b/tests/examples/lua/lua51/luajit.h deleted file mode 100644 index ae14c4ffebdff746b22b2274abf33b5c9d601b26..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/luajit.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** LuaJIT -- a Just-In-Time Compiler for Lua. http://luajit.org/ -** -** Copyright (C) 2005-2017 Mike Pall. All rights reserved. -** -** Permission is hereby granted, free of charge, to any person obtaining -** a copy of this software and associated documentation files (the -** "Software"), to deal in the Software without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Software, and to -** permit persons to whom the Software is furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be -** included in all copies or substantial portions of the Software. -** -** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -** -** [ MIT license: http://www.opensource.org/licenses/mit-license.php ] -*/ - -#ifndef _LUAJIT_H -#define _LUAJIT_H - -#include "lua.h" - -#define OPENRESTY_LUAJIT - -#define LUAJIT_VERSION "LuaJIT 2.1.0-beta3" -#define LUAJIT_VERSION_NUM 20100 /* Version 2.1.0 = 02.01.00. */ -#define LUAJIT_VERSION_SYM luaJIT_version_2_1_0_beta3 -#define LUAJIT_COPYRIGHT "Copyright (C) 2005-2017 Mike Pall" -#define LUAJIT_URL "http://luajit.org/" - -/* Modes for luaJIT_setmode. */ -#define LUAJIT_MODE_MASK 0x00ff - -enum { - LUAJIT_MODE_ENGINE, /* Set mode for whole JIT engine. */ - LUAJIT_MODE_DEBUG, /* Set debug mode (idx = level). */ - - LUAJIT_MODE_FUNC, /* Change mode for a function. */ - LUAJIT_MODE_ALLFUNC, /* Recurse into subroutine protos. */ - LUAJIT_MODE_ALLSUBFUNC, /* Change only the subroutines. */ - - LUAJIT_MODE_TRACE, /* Flush a compiled trace. */ - - LUAJIT_MODE_WRAPCFUNC = 0x10, /* Set wrapper mode for C function calls. */ - - LUAJIT_MODE_MAX -}; - -/* Flags or'ed in to the mode. */ -#define LUAJIT_MODE_OFF 0x0000 /* Turn feature off. */ -#define LUAJIT_MODE_ON 0x0100 /* Turn feature on. */ -#define LUAJIT_MODE_FLUSH 0x0200 /* Flush JIT-compiled code. */ - -/* LuaJIT public C API. */ - -/* Control the JIT engine. */ -LUA_API int luaJIT_setmode(lua_State *L, int idx, int mode); - -/* Low-overhead profiling API. */ -typedef void (*luaJIT_profile_callback)(void *data, lua_State *L, - int samples, int vmstate); -LUA_API void luaJIT_profile_start(lua_State *L, const char *mode, - luaJIT_profile_callback cb, void *data); -LUA_API void luaJIT_profile_stop(lua_State *L); -LUA_API const char *luaJIT_profile_dumpstack(lua_State *L, const char *fmt, - int depth, size_t *len); - -/* Enforce (dynamic) linker error for version mismatches. Call from main. */ -LUA_API void LUAJIT_VERSION_SYM(void); - -#endif diff --git a/tests/examples/lua/lua51/lualib.h b/tests/examples/lua/lua51/lualib.h deleted file mode 100644 index 6aceabe59218d1863e6493bb77b9bed18bc18bdc..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua51/lualib.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -** Standard library header. -** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LUALIB_H -#define _LUALIB_H - -#include "lua.h" - -#define LUA_FILEHANDLE "FILE*" - -#define LUA_COLIBNAME "coroutine" -#define LUA_MATHLIBNAME "math" -#define LUA_STRLIBNAME "string" -#define LUA_TABLIBNAME "table" -#define LUA_IOLIBNAME "io" -#define LUA_OSLIBNAME "os" -#define LUA_LOADLIBNAME "package" -#define LUA_DBLIBNAME "debug" -#define LUA_BITLIBNAME "bit" -#define LUA_JITLIBNAME "jit" -#define LUA_FFILIBNAME "ffi" -#define LUA_THRLIBNAME "thread" - -LUALIB_API int luaopen_base(lua_State *L); -LUALIB_API int luaopen_math(lua_State *L); -LUALIB_API int luaopen_string(lua_State *L); -LUALIB_API int luaopen_table(lua_State *L); -LUALIB_API int luaopen_io(lua_State *L); -LUALIB_API int luaopen_os(lua_State *L); -LUALIB_API int luaopen_package(lua_State *L); -LUALIB_API int luaopen_debug(lua_State *L); -LUALIB_API int luaopen_bit(lua_State *L); -LUALIB_API int luaopen_jit(lua_State *L); -LUALIB_API int luaopen_ffi(lua_State *L); - -LUALIB_API void luaL_openlibs(lua_State *L); - -#ifndef lua_assert -#define lua_assert(x) ((void)0) -#endif - -#endif diff --git a/tests/examples/lua/lua_connector.c b/tests/examples/lua/lua_connector.c deleted file mode 100644 index 035b17eb2a729c5267996fe7e3b7d3e1cf122d3e..0000000000000000000000000000000000000000 --- a/tests/examples/lua/lua_connector.c +++ /dev/null @@ -1,386 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -struct cb_param{ - lua_State* state; - int callback; - void * stream; -}; - -struct async_query_callback_param{ - lua_State* state; - int callback; -}; - -static int l_connect(lua_State *L){ - TAOS * taos=NULL; - const char* host; - const char* database; - const char* user; - const char* password; - int port; - - luaL_checktype(L, 1, LUA_TTABLE); - - lua_getfield(L, 1,"host"); - if (lua_isstring(L,-1)){ - host = lua_tostring(L, -1); - // printf("host = %s\n", host); - } - - lua_getfield(L, 1, "port"); - if (lua_isinteger(L, -1)){ - port = lua_tointeger(L, -1); - //printf("port = %d\n", port); - } - - lua_getfield(L, 1, "database"); - if (lua_isstring(L, -1)){ - database = lua_tostring(L, -1); - //printf("database = %s\n", database); - } - - lua_getfield(L, 1, "user"); - if (lua_isstring(L, -1)){ - user = lua_tostring(L, -1); - //printf("user = %s\n", user); - } - - lua_getfield(L, 1, "password"); - if (lua_isstring(L, -1)){ - password = lua_tostring(L, -1); - //printf("password = %s\n", password); - } - - lua_settop(L,0); - - taos_init(); - - lua_newtable(L); - int table_index = lua_gettop(L); - - taos = taos_connect(host, user,password,database, port); - if (taos == NULL) { - printf("failed to connect server, reason:%s\n", taos_errstr(taos)); - - lua_pushinteger(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - lua_pushlightuserdata(L,NULL); - lua_setfield(L, table_index, "conn"); - }else{ - // printf("success to connect server\n"); - lua_pushinteger(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - lua_pushlightuserdata(L,taos); - lua_setfield(L, table_index, "conn"); - } - - return 1; -} - -static int l_query(lua_State *L){ - TAOS *taos= (TAOS*)lua_topointer(L,1); - const char* s = lua_tostring(L, 2); - TAOS_RES *result; - lua_newtable(L); - int table_index = lua_gettop(L); - - // printf("receive command:%s\r\n",s); - result = taos_query(taos, s); - int32_t code = taos_errno(result); - if( code != 0){ - printf("failed, reason:%s\n", taos_errstr(result)); - lua_pushinteger(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(result)); - lua_setfield(L, table_index, "error"); - - return 1; - - }else{ - //printf("success to query.\n"); - TAOS_ROW row; - int rows = 0; - int num_fields = taos_field_count(result); - const TAOS_FIELD *fields = taos_fetch_fields(result); - - const int affectRows = taos_affected_rows(result); - // printf(" affect rows:%d\r\n", affectRows); - lua_pushinteger(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushinteger(L, affectRows); - lua_setfield(L, table_index, "affected"); - lua_newtable(L); - - while ((row = taos_fetch_row(result))) { - //printf("row index:%d\n",rows); - rows++; - - lua_pushnumber(L,rows); - lua_newtable(L); - - for (int i = 0; i < num_fields; ++i) { - if (row[i] == NULL) { - continue; - } - - lua_pushstring(L,fields[i].name); - int32_t* length = taos_fetch_lengths(result); - switch (fields[i].type) { - case TSDB_DATA_TYPE_UTINYINT: - case TSDB_DATA_TYPE_TINYINT: - lua_pushinteger(L,*((char *)row[i])); - break; - case TSDB_DATA_TYPE_USMALLINT: - case TSDB_DATA_TYPE_SMALLINT: - lua_pushinteger(L,*((short *)row[i])); - break; - case TSDB_DATA_TYPE_UINT: - case TSDB_DATA_TYPE_INT: - lua_pushinteger(L,*((int *)row[i])); - break; - case TSDB_DATA_TYPE_UBIGINT: - case TSDB_DATA_TYPE_BIGINT: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_FLOAT: - lua_pushnumber(L,*((float *)row[i])); - break; - case TSDB_DATA_TYPE_DOUBLE: - lua_pushnumber(L,*((double *)row[i])); - break; - case TSDB_DATA_TYPE_JSON: - case TSDB_DATA_TYPE_BINARY: - case TSDB_DATA_TYPE_NCHAR: - //printf("type:%d, max len:%d, current len:%d\n",fields[i].type, fields[i].bytes, length[i]); - lua_pushlstring(L,(char *)row[i], length[i]); - break; - case TSDB_DATA_TYPE_TIMESTAMP: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_BOOL: - lua_pushinteger(L,*((char *)row[i])); - break; - case TSDB_DATA_TYPE_NULL: - default: - lua_pushnil(L); - break; - } - - lua_settable(L,-3); - } - - lua_settable(L,-3); - } - taos_free_result(result); - } - - lua_setfield(L, table_index, "item"); - return 1; -} - -void async_query_callback(void *param, TAOS_RES *result, int code){ - struct async_query_callback_param* p = (struct async_query_callback_param*) param; - - //printf("\nin c,numfields:%d\n", numFields); - //printf("\nin c, code:%d\n", code); - - lua_State *L = p->state; - lua_rawgeti(L, LUA_REGISTRYINDEX, p->callback); - lua_newtable(L); - int table_index = lua_gettop(L); - if( code < 0){ - printf("failed, reason:%s\n", taos_errstr(result)); - lua_pushinteger(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L,"something is wrong");// taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - }else{ - //printf("success to async query.\n"); - const int affectRows = taos_affected_rows(result); - //printf(" affect rows:%d\r\n", affectRows); - lua_pushinteger(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushinteger(L, affectRows); - lua_setfield(L, table_index, "affected"); - } - - lua_call(L, 1, 0); -} - -static int l_async_query(lua_State *L){ - int r = luaL_ref(L, LUA_REGISTRYINDEX); - TAOS * taos = (TAOS*)lua_topointer(L,1); - const char * sqlstr = lua_tostring(L,2); - // int stime = luaL_checknumber(L,3); - - lua_newtable(L); - int table_index = lua_gettop(L); - - struct async_query_callback_param *p = malloc(sizeof(struct async_query_callback_param)); - p->state = L; - p->callback=r; - // printf("r:%d, L:%d\n",r,L); - taos_query_a(taos,sqlstr,async_query_callback,p); - - lua_pushnumber(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, "ok"); - lua_setfield(L, table_index, "error"); - - return 1; -} - -void stream_cb(void *param, TAOS_RES *result, TAOS_ROW row){ - struct cb_param* p = (struct cb_param*) param; - TAOS_FIELD *fields = taos_fetch_fields(result); - int numFields = taos_num_fields(result); - - // printf("\nnumfields:%d\n", numFields); - //printf("\n\r-----------------------------------------------------------------------------------\n"); - - lua_State *L = p->state; - lua_rawgeti(L, LUA_REGISTRYINDEX, p->callback); - - lua_newtable(L); - - for (int i = 0; i < numFields; ++i) { - if (row[i] == NULL) { - continue; - } - - lua_pushstring(L,fields[i].name); - - switch (fields[i].type) { - case TSDB_DATA_TYPE_TINYINT: - lua_pushinteger(L,*((char *)row[i])); - break; - case TSDB_DATA_TYPE_SMALLINT: - lua_pushinteger(L,*((short *)row[i])); - break; - case TSDB_DATA_TYPE_INT: - lua_pushinteger(L,*((int *)row[i])); - break; - case TSDB_DATA_TYPE_BIGINT: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_FLOAT: - lua_pushnumber(L,*((float *)row[i])); - break; - case TSDB_DATA_TYPE_DOUBLE: - lua_pushnumber(L,*((double *)row[i])); - break; - case TSDB_DATA_TYPE_BINARY: - case TSDB_DATA_TYPE_NCHAR: - lua_pushstring(L,(char *)row[i]); - break; - case TSDB_DATA_TYPE_TIMESTAMP: - lua_pushinteger(L,*((int64_t *)row[i])); - break; - case TSDB_DATA_TYPE_BOOL: - lua_pushinteger(L,*((char *)row[i])); - break; - default: - lua_pushnil(L); - break; - } - - lua_settable(L, -3); - } - - lua_call(L, 1, 0); - - // printf("-----------------------------------------------------------------------------------\n\r"); -} - -static int l_open_stream(lua_State *L){ - int r = luaL_ref(L, LUA_REGISTRYINDEX); - TAOS * taos = (TAOS*)lua_topointer(L,1); - const char * sqlstr = lua_tostring(L,2); - int stime = luaL_checknumber(L,3); - - lua_newtable(L); - int table_index = lua_gettop(L); - - struct cb_param *p = malloc(sizeof(struct cb_param)); - p->state = L; - p->callback=r; - // printf("r:%d, L:%d\n",r,L); - void * s = taos_open_stream(taos,sqlstr,stream_cb,stime,p,NULL); - if (s == NULL) { - printf("failed to open stream, reason:%s\n", taos_errstr(taos)); - free(p); - lua_pushnumber(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - lua_pushlightuserdata(L,NULL); - lua_setfield(L, table_index, "stream"); - }else{ - // printf("success to open stream\n"); - lua_pushnumber(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, taos_errstr(taos)); - lua_setfield(L, table_index, "error"); - p->stream = s; - lua_pushlightuserdata(L,p); - lua_setfield(L, table_index, "stream");//stream has different content in lua and c. - } - - return 1; -} - -static int l_close_stream(lua_State *L){ - //TODO:get stream and free cb_param - struct cb_param *p = lua_touserdata(L,1); - taos_close_stream(p->stream); - free(p); - return 0; -} - -static int l_close(lua_State *L){ - TAOS *taos= (TAOS*)lua_topointer(L,1); - lua_newtable(L); - int table_index = lua_gettop(L); - - if(taos == NULL){ - lua_pushnumber(L, -1); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, "null pointer."); - lua_setfield(L, table_index, "error"); - }else{ - taos_close(taos); - lua_pushnumber(L, 0); - lua_setfield(L, table_index, "code"); - lua_pushstring(L, "done."); - lua_setfield(L, table_index, "error"); - } - return 1; -} - -static const struct luaL_Reg lib[] = { - {"connect", l_connect}, - {"query", l_query}, - {"query_a",l_async_query}, - {"close", l_close}, - {"open_stream", l_open_stream}, - {"close_stream", l_close_stream}, - {NULL, NULL} -}; - -extern int luaopen_luaconnector(lua_State* L) -{ - luaL_newlib(L, lib); - - return 1; -} diff --git a/tests/examples/lua/test.lua b/tests/examples/lua/test.lua deleted file mode 100644 index c124b50a4dbd954ab47098e527bd2d35ee44384e..0000000000000000000000000000000000000000 --- a/tests/examples/lua/test.lua +++ /dev/null @@ -1,172 +0,0 @@ -local driver = require "luaconnector" - -local config = { - host = "127.0.0.1", - port = 6030, - database = "", - user = "root", - password = "taosdata", - max_packet_size = 1024 * 1024 -} - -local conn -local res = driver.connect(config) -if res.code ~=0 then - print("connect--- failed: "..res.error) - return -else - conn = res.conn - print("connect--- pass.") -end - -local res = driver.query(conn,"drop database if exists demo") - -res = driver.query(conn,"create database demo") -if res.code ~=0 then - print("create db--- failed: "..res.error) - return -else - print("create db--- pass.") -end - -res = driver.query(conn,"use demo") -if res.code ~=0 then - print("select db--- failed: "..res.error) - return -else - print("select db--- pass.") -end - -res = driver.query(conn,"create table m1 (ts timestamp, speed int, owner binary(20), mark nchar(30))") -if res.code ~=0 then - print("create table---failed: "..res.error) - return -else - print("create table--- pass.") -end - -res = driver.query(conn,"insert into m1 values ('2019-09-01 00:00:00.001', 0, 'robotspace', '世界人民大团结万岁'), ('2019-09-01 00:00:00.002', 1, 'Hilink', '⾾⾿⿀⿁⿂⿃⿄⿅⿆⿇⿈⿉⿊⿋⿌⿍⿎⿏⿐⿑⿒⿓⿔⿕'),('2019-09-01 00:00:00.003', 2, 'Harmony', '₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵')") -if res.code ~=0 then - print("insert records failed: "..res.error) - return -else - if(res.affected == 3) then - print("insert records--- pass") - else - print("insert records---failed: expect 3 affected records, actually affected "..res.affected) - end -end - -res = driver.query(conn,"select * from m1") - -if res.code ~=0 then - print("select failed: "..res.error) - return -else - if (#(res.item) == 3) then - print("select--- pass") - print(res.item[1].mark) - print(res.item[2].mark) - print(res.item[3].mark) - - else - print("select--- failed: expect 3 affected records, actually received "..#(res.item)) - end - -end - -res = driver.query(conn,"CREATE TABLE thermometer (ts timestamp, degree double) TAGS(location binary(20), type int)") -if res.code ~=0 then - print(res.error) - return -else - print("create super table--- pass") -end -res = driver.query(conn,"CREATE TABLE therm1 USING thermometer TAGS ('beijing', 1)") -if res.code ~=0 then - print(res.error) - return -else - print("create table--- pass") -end - -res = driver.query(conn,"INSERT INTO therm1 VALUES ('2019-09-01 00:00:00.001', 20),('2019-09-01 00:00:00.002', 21)") - -if res.code ~=0 then - print(res.error) - return -else - if(res.affected == 2) then - print("insert records--- pass") - else - print("insert records---failed: expect 2 affected records, actually affected "..res.affected) - end -end - -res = driver.query(conn,"SELECT COUNT(*) count, AVG(degree) AS av, MAX(degree), MIN(degree) FROM thermometer WHERE location='beijing' or location='tianjin' GROUP BY location, type") -if res.code ~=0 then - print("select from super table--- failed:"..res.error) - return -else - print("select from super table--- pass") - for i = 1, #(res.item) do - print("res:"..res.item[i].count) - end -end - -function async_query_callback(res) - if res.code ~=0 then - print("async_query_callback--- failed:"..res.error) - return - else - - if(res.affected == 3) then - print("async_query_callback, insert records--- pass") - else - print("async_query_callback, insert records---failed: expect 3 affected records, actually affected "..res.affected) - end - - end -end - -driver.query_a(conn,"INSERT INTO therm1 VALUES ('2019-09-01 00:00:00.005', 100),('2019-09-01 00:00:00.006', 101),('2019-09-01 00:00:00.007', 102)", async_query_callback) - - -function stream_callback(t) - print("------------------------") - print("continuous query result:") - for key, value in pairs(t) do - print("key:"..key..", value:"..value) - end -end - -local stream -res = driver.open_stream(conn,"SELECT COUNT(*) as count, AVG(degree) as avg, MAX(degree) as max, MIN(degree) as min FROM thermometer interval(2s) sliding(2s);)",0, stream_callback) -if res.code ~=0 then - print("open stream--- failed:"..res.error) - return -else - print("open stream--- pass") - stream = res.stream -end - -print("From now on we start continous insert in an definite (infinite if you want) loop.") -local loop_index = 0 -while loop_index < 30 do - local t = os.time()*1000 - local v = loop_index - res = driver.query(conn,string.format("INSERT INTO therm1 VALUES (%d, %d)",t,v)) - - if res.code ~=0 then - print("continous insertion--- failed:" .. res.error) - return - else - --print("insert successfully, affected:"..res.affected) - end - os.execute("sleep " .. 1) - loop_index = loop_index + 1 -end - -driver.close_stream(stream) - -driver.close(conn) diff --git a/tests/examples/matlab/TDengineDemo.m b/tests/examples/matlab/TDengineDemo.m deleted file mode 100644 index b44777512bb20d6231d92dd19645d39b77ac80ca..0000000000000000000000000000000000000000 --- a/tests/examples/matlab/TDengineDemo.m +++ /dev/null @@ -1,128 +0,0 @@ -%% Connect to TDengine -clear; -fprintf("Connecting to TDengine..."); -dbName = 'tsdb'; -user = 'root'; -password = 'taosdata'; -jdbcDriverName = 'com.taosdata.jdbc.TSDBDriver'; -jdbcUrl = 'jdbc:TSDB://192.168.1.113:0/'; -conn = database(dbName, user, password, jdbcDriverName, jdbcUrl) -if isempty(conn.Message) - fprintf("Connection is successfully established!\n"); -else - fprintf("Failed to connect to server: %s\n", conn.Message); -end - -%% Query a table in TDengine, and store the results in a MATLAB table object 'tb1' -% Please note that the select() function retrieves all rows in a table/supertale into MATLAB -sql = "select ts, distance1 from device1 limit 5"; -fprintf("Execute query: %s\n", sql); -tic -tb1 = select(conn, sql); -timeused = toc; -fprintf("\tQuery completed!\n\tNumber of rows retrieved: %d\n\tNumber of columns in each row: %d\n\tTime used: %g\n", height(tb1), width(tb1), timeused); - -% To go a bit further, we can convert the MATLAB table object to a MATLAB matrix object -data = table2array(tb1) - -%% Query table names in a TDengine supertable, and store the results in a MATLAB table object 'stbmeta' -sql = "select tbname from devices limit 10"; -fprintf("Execute query: %s\n", sql); -tic; -stbmeta = select(conn, sql); -timeused = toc; -fprintf("\tTables in supertable 'devices': %t", stbmeta); -fprintf("\tQuery completed!\n\tNumber of rows retrieved: %d\n\tNumber of columns in each row: %d\n\tTime used: %g\n", height(stbmeta), width(stbmeta), timeused); - -%% Query a TDengine supertable, and stores the results in a MATLAB table object 'stb' -sql = "select ts, distance1 from devices"; -fprintf("Execute query: %s\n", sql); -tic; -stb = select(conn, sql); -timeused = toc; -fprintf("\tQuery completed!\n\tNumber of rows retrieved: %d\n\tNumber of columns in each row: %d\n\tTime used: %g\n", height(stb), width(stb), timeused); - -%% Query TDengine using cursors and specify the number of rows to fetch -sql = 'select * from device1'; -rowLimit = 5; -fprintf("Execute query: %s with row limit set to %d\n", sql, rowLimit); -tic; -% Get cursor -cur = exec(conn, sql); -% Fetch data -cur = fetch(cur, rowLimit); -data = cur.Data -timeused = toc; -fprintf("\tQuery completed!\n\tNumber of rows retrieved: %d\n\tNumber of columns in each row: %d\n\tTime used: %g\n", size(data, 1), size(data, 2), timeused); - -%% Query specific columns in a TDenigine table 'device1', and stores the results directly in a MATLAB cell array 'data' -sql = 'SELECT * FROM device1 order by ts asc'; -fprintf("Execute query: %s\n", sql); -tic; -data = fetch(conn, sql); -timeused = toc; -fprintf("\tQuery completed!\n\tNumber of rows retrieved: %d\n\tNumber of columns in each row: %d\n\tTime used: %g\n", size(data, 1), size(data, 2), timeused); -% Let's now convert the cell array 'data' into some matrices, and make a plot of column 'c1' again the timestamp 'ts' -ts = cell2mat(data(:,1)); -c1 = cell2mat(data(:,2)); - -%% Query aggregation results from a table -% TDengine is so powerful at aggregated computations. Let's calculate the max, mean, standard deviation and min values for every 10 minutes in the -% tb1's timeline, and then plot them together with all the data points in tb1 -sql = sprintf('SELECT max(measure1), avg(measure1), stddev(measure1), min(measure1) FROM device1 WHERE ts >= %d and ts <= %d interval(10m)', ts(1), ts(end)); -fprintf("Execute query: %s\n", sql); -tic; -c1_stats = fetch(conn, sql); -timeused = toc; -fprintf("\tQuery completed!\n\tNumber of rows retrieved: %d\n\tNumber of columns in each row: %d\n\tTime used: %g\n", size(c1_stats, 1), size(c1_stats, 2), timeused); -% Prepare data for plotting. -tsAsDate = datestr(ts/86400000 + datenum(1970,1,1), 'mm-dd HH:MM'); -c1_stats = cell2mat(c1_stats); -c1_stats_ts = c1_stats(:, 1); -c1_stats_max = c1_stats(:, 2); -c1_stats_mean = c1_stats(:, 3); -c1_stats_stddev = c1_stats(:, 4); -c1_stats_min = c1_stats(:, 5); -c1_stats_tsAsDate = datestr(c1_stats(:,1)/86400000 + datenum(1970,1,1), 'mm-dd HH:MM'); - -%% Now let's plot the data and associated statistical aggregation calculation in a figure. -fh = figure(1); -set(fh,'position',[50 50 1300 700]); -h1 = scatter(ts, c1, 5, 'c'); -hold on; -h2 = plot(c1_stats_ts + 300000, c1_stats_max, '-or', 'linewidth', 1); -hold on; -h3 = plot(c1_stats_ts + 300000, c1_stats_mean, '-xg', 'linewidth', 1); -hold on; -h4 = plot(c1_stats_ts + 300000, c1_stats_stddev, '-*y', 'linewidth', 1); -hold on; -h5 = plot(c1_stats_ts + 300000, c1_stats_min, '-+k', 'linewidth', 1); -xlabel('time'); -ylabel('measurement1'); -set(gca, 'xtick',[ts(1),ts(end/4),ts(2*end/4),ts(3*end/4),ts(end)]); -set(gca, 'xticklabel',{tsAsDate(1,:), tsAsDate(end/4,:),tsAsDate(2*end/4,:),tsAsDate(3*end/4,:),tsAsDate(end,:)}); -xlim([ts(1), ts(end)]); -legend([h1, h2, h3, h4, h5], 'data points', 'max per 10 mins', 'mean per 10 mins', 'stddev per 10 mins', 'min per 10 mins'); -title('Device Measurement Monitoring Demo'); -grid on; - -%% Insert data into TDengine using exec() -sql = 'insert into device1 (ts, distance1) values (now, -1)'; -fprintf("Execute query: %s\n", sql); -cur = exec(conn, sql) -sql = 'select * from device1 limit 1'; -fprintf("Execute query: %s\n", sql); -data = select(conn, sql) -conn.close; - -%% Insert data into TDengine using datainsert() -% this is currently not supported - -% colnames = {'ts','c1','c2','c3'}; -% dat = {'now' 99 99 99}; -% tbname = 'plane1'; -% datainsert(conn, tbname, colnames, dat); -% cur = exec(conn, 'select * from ' + tbname); -% cur = fetch(cur, 5); -% data = cur.Data - diff --git a/tests/examples/nodejs/README-win.md b/tests/examples/nodejs/README-win.md deleted file mode 100644 index 75fec69413af2bb49498118ec7235c9947e2f89e..0000000000000000000000000000000000000000 --- a/tests/examples/nodejs/README-win.md +++ /dev/null @@ -1,200 +0,0 @@ -# 如何在windows上使用nodejs进行TDengine应用开发 - -## 环境准备 - -(1)安装nodejs-10.22.0 - -下载链接:https://nodejs.org/dist/v10.22.0/node-v10.22.0-win-x64.zip -解压安装,把node配置到环境变量里 - -cmd启动命令行,查看node的版本 - -```shell -> node.exe --version -v10.22.0 - -> npm --version -6.14.6 -``` - - - -(2)安装python2.7 - -下载链接:https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi - -查看python版本 - -```shell ->python --version -Python 2.7.18 -``` - - -(3)安装TDengine-client - -下载地址:https://www.taosdata.com/cn/all-downloads/,选择一个合适的windows-client下载(client应该尽量与server端的版本保持一致) - -使用client的taos shell连接server - -```shell ->taos -h node5 - -Welcome to the TDengine shell from Linux, Client Version:2.0.6.0 -Copyright (c) 2017 by TAOS Data, Inc. All rights reserved. - -taos> show dnodes; - id | end_point | vnodes | cores | status | role | create_time | offline reason | -============================================================================================================================================ - 1 | node5:6030 | 7 | 1 | ready | any | 2020-10-26 09:45:26.308 | | -Query OK, 1 row(s) in set (0.036000s) -``` - -注意: -* 检查能否在client的机器上ping通server的fqdn -* 如果你的dns server并没有提供到server的域名解析,可以将server的hostname配置到client的hosts文件中 - - -## 应用开发 - -(1)建立nodejs项目 - -``` -npm init -``` - -(2)安装windows-build-tools -``` -npm install --global --production windows-build-tools -``` - -(3)安装td2.0-connector驱动 - -``` tdshell -npm install td2.0-connector -``` - -(4)nodejs访问tdengine的示例程序 - -```javascript -const taos = require('td2.0-connector'); - -var host = null; -var port = 6030; -for (var i = 2; i < global.process.argv.length; i++) { - var key = global.process.argv[i].split("=")[0]; - var value = global.process.argv[i].split("=")[1]; - - if ("host" == key) { - host = value; - } - if ("port" == key) { - port = value; - } -} - -if (host == null) { - console.log("Usage: node nodejsChecker.js host= port="); - process.exit(0); -} - -// establish connection -var conn = taos.connect({host: host, user: "root", password: "taosdata", port: port}); -var cursor = conn.cursor(); -// create database -executeSql("create database if not exists testnodejs", 0); -// use db -executeSql("use testnodejs", 0); -// drop table -executeSql("drop table if exists testnodejs.weather", 0); -// create table -executeSql("create table if not exists testnodejs.weather(ts timestamp, temperature float, humidity int)", 0); -// insert -executeSql("insert into testnodejs.weather (ts, temperature, humidity) values(now, 20.5, 34)", 1); -// select -executeQuery("select * from testnodejs.weather"); -// close connection -conn.close(); - -function executeQuery(sql) { - var start = new Date().getTime(); - var promise = cursor.query(sql, true); - var end = new Date().getTime(); - promise.then(function (result) { - printSql(sql, result != null, (end - start)); - result.pretty(); - }); -} - -function executeSql(sql, affectRows) { - var start = new Date().getTime(); - var promise = cursor.execute(sql); - var end = new Date().getTime(); - printSql(sql, promise == affectRows, (end - start)); -} - -function printSql(sql, succeed, cost) { - console.log("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql); -} -``` - -(5)测试nodejs程序 - -```shell ->node nodejsChecker.js -Usage: node nodejsChecker.js host= port= -# 提示指定host - ->node nodejsChecker.js host=node5 -Successfully connected to TDengine -Query OK, 0 row(s) affected (0.00997610s) -[ OK ] time cost: 14 ms, execute statement ====> create database if not exists testnodejs -Query OK, 0 row(s) affected (0.00235920s) -[ OK ] time cost: 4 ms, execute statement ====> use testnodejs -Query OK, 0 row(s) affected (0.06604280s) -[ OK ] time cost: 67 ms, execute statement ====> drop table if exists testnodejs.weather -Query OK, 0 row(s) affected (0.59403290s) -[ OK ] time cost: 595 ms, execute statement ====> create table if not exists testnodejs.weather(ts timestamp, temperature float, humidity int) -Query OK, 1 row(s) affected (0.01058950s) -[ OK ] time cost: 12 ms, execute statement ====> insert into testnodejs.weather (ts, temperature, humidity) values(now, 20.5, 34) -Query OK, 1 row(s) in set (0.00401490s) -[ OK ] time cost: 10 ms, execute statement ====> select * from testnodejs.weather -Connection is closed - - ts | temperature | humidity | -===================================================================== -2020-10-27 18:49:15.547 | 20.5 | 34 | -``` - -## 指南 - -### 如何设置主机名和hosts - -在server上查看hostname和fqdn -```shell -查看hostname -# hostname -taos-server - -查看fqdn -# hostname -f -taos-server -``` - -windows下hosts文件位于: -C:\\Windows\System32\drivers\etc\hosts -修改hosts文件,添加server的ip和hostname - -``` -192.168.56.101 node5 -``` - -> 什么是FQDN? -> -> FQDN(Full qualified domain name)全限定域名,fqdn由2部分组成:hostname+domainname。 -> -> 例如,一个邮件服务器的fqdn可能是:mymail.somecollege.edu,其中mymail是hostname(主机名),somcollege.edu是domainname(域名)。本例中,.edu是顶级域名,.somecollege是二级域名。 -> -> 当连接服务器时,必须指定fqdn,然后,dns服务器通过查看dns表,将hostname解析为相应的ip地址。如果只指定hostname(不指定domainname),应用程序可能服务解析主机名。因为如果你试图访问不在本地的远程服务器时,本地的dns服务器和可能没有远程服务器的hostname列表。 -> -> 参考:https://kb.iu.edu/d/aiuv diff --git a/tests/examples/nodejs/node-example-raw.js b/tests/examples/nodejs/node-example-raw.js deleted file mode 100644 index 80d5cd1bdea23370f1ac03756541eaa96937a6d6..0000000000000000000000000000000000000000 --- a/tests/examples/nodejs/node-example-raw.js +++ /dev/null @@ -1,123 +0,0 @@ -/* This example is to show how to use the td-connector through the cursor only and is a bit more raw. - * No promises, object wrappers around data, functions that prettify the data, or anything. - * The cursor will generally use callback functions over promises, and return and store the raw data from the C Interface. - * It is advised to use the td-connector through the cursor and the TaosQuery class amongst other higher level APIs. -*/ - -// Get the td-connector package -const taos = require('td2.0-connector'); - -/* We will connect to TDengine by passing an object comprised of connection options to taos.connect and store the - * connection to the variable conn - */ -/* - * Connection Options - * host: the host to connect to - * user: the use to login as - * password: the password for the above user to login - * config: the location of the taos.cfg file, by default it is in /etc/taos - * port: the port we connect through - */ -var conn = taos.connect({host:"127.0.0.1", user:"root", password:"taosdata", config:"/etc/taos",port:0}); - -// Initialize our TDengineCursor, which we use to interact with TDengine -var c1 = conn.cursor(); - -//execute the sql -function execute(sql){ - try { - c1.execute(sql); - } - catch(err) { - conn.close(); - throw err; - } -} - -// c1.execute(query) will execute the query -// Let's create a database named db -execute('create database if not exists db;') - -// Now we will use database db -execute('use db;') - - -// Let's create a table called weather -// which stores some weather data like humidity, AQI (air quality index), temperature, and some notes as text -execute('create table if not exists weather (ts timestamp, humidity smallint, aqi int, temperature float, notes binary(30));'); - -// Let's get the description of the table weather -execute('describe db.weather'); - -// To get results, we run the function c1.fetchall() -// It only returns the query results as an array of result rows, but also stores the latest results in c1.data -try { - var tableDesc = c1.fetchall(); // The description variable here is equal to c1.data; - console.log(tableDesc); -} -catch (err) { - conn.close(); - throw err; -} - -// Let's try to insert some random generated data to test with - -let stime = new Date(); -let interval = 1000; - -// Timestamps must be in the form of "YYYY-MM-DD HH:MM:SS.MMM" if they are in milliseconds -// "YYYY-MM-DD HH:MM:SS.MMMMMM" if they are in microseconds -// Thus, we create the following function to convert a javascript Date object to the correct formatting -function convertDateToTS(date) { - let tsArr = date.toISOString().split("T") - return "\"" + tsArr[0] + " " + tsArr[1].substring(0, tsArr[1].length-1) + "\""; -} - -try { - for (let i = 0; i < 10000; i++) { - stime.setMilliseconds(stime.getMilliseconds() + interval); - let insertData = [convertDateToTS(stime), - parseInt(Math.random()*100), - parseInt(Math.random()*300), - parseFloat(Math.random()*10 + 30), - "\"random note!\""]; - c1.execute('insert into db.weather values(' + insertData.join(',') + ' );'); - } -} -catch (err) { - conn.close(); - throw err; -} - -// Now let's look at our newly inserted data -var retrievedData; -try { - c1.execute('select * from db.weather;') - retrievedData = c1.fetchall(); - - // c1.fields stores the names of each column retrieved - console.log(c1.fields); - console.log(retrievedData); - // timestamps retrieved are always JS Date Objects - // Numbers are numbers, big ints are big ints, and strings are strings -} -catch (err) { - conn.close(); - throw err; -} - -// Let's try running some basic functions -try { - c1.execute('select count(*), avg(temperature), max(temperature), min(temperature), stddev(temperature) from db.weather;') - c1.fetchall(); - console.log(c1.fields); - console.log(c1.data); -} -catch(err) { - conn.close(); - throw err; -} - -conn.close(); - -// Feel free to fork this repository or copy this code and start developing your own apps and backends with NodeJS and TDengine! diff --git a/tests/examples/nodejs/node-example.js b/tests/examples/nodejs/node-example.js deleted file mode 100644 index bfdd9e49a08fc1d6c20f3bdafbb84a500986b9fd..0000000000000000000000000000000000000000 --- a/tests/examples/nodejs/node-example.js +++ /dev/null @@ -1,153 +0,0 @@ -/* This example is to show the preferred way to use the td-connector */ -/* To run, enter node path/to/node-example.js */ -// Get the td-connector package -const taos = require('td2.0-connector'); - -/* We will connect to TDengine by passing an object comprised of connection options to taos.connect and store the - * connection to the variable conn - */ -/* - * Connection Options - * host: the host to connect to - * user: the use to login as - * password: the password for the above user to login - * config: the location of the taos.cfg file, by default it is in /etc/taos - * port: the port we connect through - */ -var conn = taos.connect({host:"127.0.0.1", user:"root", password:"taosdata", config:"/etc/taos",port:0}); - -// Initialize our TDengineCursor, which we use to interact with TDengine -var c1 = conn.cursor(); - -// c1.query(query) will return a TaosQuery object, of which then we can execute. The execute function then returns a promise -// Let's create a database named db -try { - c1.execute('create database if not exists db;'); - //var query = c1.query('create database if not exists db;'); - //query.execute(); -} -catch(err) { - conn.close(); - throw err; -} - -// Now we will use database db. As this query won't return any results, -// we can simplify the code and directly use the c1.execute() function. No need for a TaosQuery object to wrap around the query -try { - c1.execute('use db;'); -} -catch (err) { - conn.close(); - throw err; -} - -// Let's create a table called weather -// which stores some weather data like humidity, AQI (air quality index), temperature, and some notes as text -// We can also immedietely execute a TaosQuery object by passing true as the secodn argument -// This will then return a promise that we can then attach a callback function to -try { - var promise = c1.query('create table if not exists weather (ts timestamp, humidity smallint, aqi int, temperature float, notes binary(30));', true); - promise.then(function(){ - console.log("Table created!"); - }).catch(function() { - console.log("Table couldn't be created.") - }); -} -catch (err) { - conn.close(); - throw err; -} - -// Let's get the description of the table weather -// When using a TaosQuery object and then executing it, upon success it returns a TaosResult object, which is a wrapper around the -// retrieved data and allows us to easily access data and manipulate or display it. -try { - c1.query('describe db.weather;').execute().then(function(result){ - // Result is an instance of TaosResult and has the function pretty() which instantly logs a prettified version to the console - result.pretty(); - }); -} -catch (err) { - conn.close(); - throw err; -} - - -Date.prototype.Format = function(fmt){ - var o = { - 'M+': this.getMonth() + 1, - 'd+': this.getDate(), - 'H+': this.getHours(), - 'm+': this.getMinutes(), - 's+': this.getSeconds(), - 'S+': this.getMilliseconds() - }; - if (/(y+)/.test(fmt)) { - fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)); - } - for (var k in o) { - if (new RegExp('(' + k + ')').test(fmt)) { - fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(String(o[k]).length))); - } - } - return fmt; -} - - -// Let's try to insert some random generated data to test with -// We will use the bind function of the TaosQuery object to easily bind values to question marks in the query -// For Timestamps, a normal Datetime object or TaosTimestamp or milliseconds can be passed in through the bind function -let stime = new Date(); -let interval = 1000; -try { - for (let i = 0; i < 1000; i++) { - stime.setMilliseconds(stime.getMilliseconds() + interval); - - //console.log(stime.Format('yyyy-MM-dd HH:mm:ss.SSS')); - - let insertData = [stime, - parseInt(Math.random()*100), - parseInt(Math.random()*300), - parseFloat(Math.random()*10 + 30), - "Note"]; - //c1.execute('insert into db.weather values(' + insertData.join(',') + ' );'); - - //var query = c1.query('insert into db.weather values(?, ?, ?, ?, ?);').bind(insertData); - //query.execute(); - c1.execute('insert into db.weather values(\"'+stime.Format('yyyy-MM-dd HH:mm:ss.SSS')+'\",'+parseInt(Math.random() * 100)+','+parseInt(Math.random() * 300)+','+parseFloat(Math.random()*10 + 30)+',"Note");'); - } -}catch (err) { - conn.close(); - throw err; -} - -// Now let's look at our newly inserted data -var retrievedData; -try { - c1.query('select * from db.weather limit 5 offset 100;', true).then(function(result){ - //result.pretty(); - console.log('=========>'+JSON.stringify(result)); - // Neat! - }); - -} -catch (err) { - conn.close(); - throw err; -} - -// Let's try running some basic functions -try { - c1.query('select count(*), avg(temperature), max(temperature), min(temperature), stddev(temperature) from db.weather;', true) - .then(function(result) { - result.pretty(); - }) -} -catch(err) { - conn.close(); - throw err; -} - -conn.close(); - -// Feel free to fork this repository or copy this code and start developing your own apps and backends with NodeJS and TDengine! diff --git a/tests/examples/nodejs/nodejsChecker.js b/tests/examples/nodejs/nodejsChecker.js deleted file mode 100644 index 1b391e55a07b1e86a9c7dc92f6bfba23b147c822..0000000000000000000000000000000000000000 --- a/tests/examples/nodejs/nodejsChecker.js +++ /dev/null @@ -1,61 +0,0 @@ -//const taos = require('td2.0-connector'); -const taos = require('../../../src/connector/nodejs/'); - - -var host = null; -var port = 6030; -for(var i = 2; i < global.process.argv.length; i++){ - var key = global.process.argv[i].split("=")[0]; - var value = global.process.argv[i].split("=")[1]; - - if("host" == key){ - host = value; - } - if("port" == key){ - port = value; - } -} - -if(host == null){ - console.log("Usage: node nodejsChecker.js host= port="); - process.exit(0); -} - -// establish connection -var conn = taos.connect({host:host, user:"root", password:"taosdata",port:port}); -var cursor = conn.cursor(); -// create database -executeSql("create database if not exists test", 0); -// use db -executeSql("use test", 0); -// drop table -executeSql("drop table if exists test.weather", 0); -// create table -executeSql("create table if not exists test.weather(ts timestamp, temperature float, humidity int)", 0); -// insert -executeSql("insert into test.weather (ts, temperature, humidity) values(now, 20.5, 34)", 1); -// select -executeQuery("select * from test.weather"); -// close connection -conn.close(); - -function executeQuery(sql){ - var start = new Date().getTime(); - var promise = cursor.query(sql, true); - var end = new Date().getTime(); - promise.then(function(result){ - printSql(sql, result != null,(end - start)); - result.pretty(); - }); -} - -function executeSql(sql, affectRows){ - var start = new Date().getTime(); - var promise = cursor.execute(sql); - var end = new Date().getTime(); - printSql(sql, promise == affectRows, (end - start)); -} - -function printSql(sql, succeed, cost){ - console.log("[ "+(succeed ? "OK" : "ERROR!")+" ] time cost: " + cost + " ms, execute statement ====> " + sql); -} diff --git a/tests/examples/nodejs/test1970.js b/tests/examples/nodejs/test1970.js deleted file mode 100644 index 5177a7371e9a07fa7b548936ff038c1f2a29bc1f..0000000000000000000000000000000000000000 --- a/tests/examples/nodejs/test1970.js +++ /dev/null @@ -1,125 +0,0 @@ -const taos = require('td2.0-connector'); -var conn = taos.connect({host:"127.0.0.1", user:"root", password:"taosdata", config:"/etc/taos",port:0}) -var c1 = conn.cursor(); // Initializing a new cursor - -let stime = new Date(); -let interval = 1000; - -function convertDateToTS(date) { - let tsArr = date.toISOString().split("T") - return "\"" + tsArr[0] + " " + tsArr[1].substring(0, tsArr[1].length - 1) + "\""; -} - -function R(l, r) { - return Math.random() * (r - l) - r; -} - -function randomBool() { - if (Math.random() < 0.5) { - return true; - } - return false; -} - -// Initialize -const dbname = "nodejs_1970_db"; -const tbname = "t1"; - -let dropDB = "drop database if exists " + dbname -console.log(dropDB);//asdasdasd -c1.execute(dropDB);///asdasd - -let createDB = "create database " + dbname + " keep 36500" -console.log(createDB); -c1.execute(createDB); - -let useTbl = "use " + dbname -console.log(useTbl) -c1.execute(useTbl); - -let createTbl = "create table if not exists " + tbname + "(ts timestamp,id int)" -console.log(createTbl); -c1.execute(createTbl); - -//1969-12-31 23:59:59.999 -//1970-01-01 00:00:00.000 -//1970-01-01 07:59:59.999 -//1970-01-01 08:00:00.000a -//1628928479484 2021-08-14 08:07:59.484 -let sql1 = "insert into " + dbname + "." + tbname + " values('1969-12-31 23:59:59.999',1)" -console.log(sql1); -c1.execute(sql1); - -let sql2 = "insert into " + dbname + "." + tbname + " values('1970-01-01 00:00:00.000',2)" -console.log(sql2); -c1.execute(sql2); - -let sql3 = "insert into " + dbname + "." + tbname + " values('1970-01-01 07:59:59.999',3)" -console.log(sql3); -c1.execute(sql3); - -let sql4 = "insert into " + dbname + "." + tbname + " values('1970-01-01 08:00:00.000',4)" -console.log(sql4); -c1.execute(sql4); - -let sql5 = "insert into " + dbname + "." + tbname + " values('2021-08-14 08:07:59.484',5)" -console.log(sql5); -c1.execute(sql5); - -// Select -let query1 = "select * from " + dbname + "." + tbname -console.log(query1); -c1.execute(query1); - -var d = c1.fetchall(); -console.log(c1.fields); -for (let i = 0; i < d.length; i++) - console.log(d[i][0].valueOf()); - -//initialize -let initSql1 = "drop table if exists " + tbname -console.log(initSql1); -c1.execute(initSql1); - -console.log(createTbl); -c1.execute(createTbl); -c1.execute(useTbl) - -//-28800001 1969-12-31 23:59:59.999 -//-28800000 1970-01-01 00:00:00.000 -//-1 1970-01-01 07:59:59.999 -//0 1970-01-01 08:00:00.00 -//1628928479484 2021-08-14 08:07:59.484 -let sql11 = "insert into " + dbname + "." + tbname + " values(-28800001,11)"; -console.log(sql11); -c1.execute(sql11); - -let sql12 = "insert into " + dbname + "." + tbname + " values(-28800000,12)" -console.log(sql12); -c1.execute(sql12); - -let sql13 = "insert into " + dbname + "." + tbname + " values(-1,13)" -console.log(sql13); -c1.execute(sql13); - -let sql14 = "insert into " + dbname + "." + tbname + " values(0,14)" -console.log(sql14); -c1.execute(sql14); - -let sql15 = "insert into " + dbname + "." + tbname + " values(1628928479484,15)" -console.log(sql15); -c1.execute(sql15); - -// Select -console.log(query1); -c1.execute(query1); - -var d = c1.fetchall(); -console.log(c1.fields); -for (let i = 0; i < d.length; i++) - console.log(d[i][0].valueOf()); - -setTimeout(function () { - conn.close(); -}, 2000); - diff --git a/tests/examples/python/PYTHONConnectorChecker/PythonChecker.py b/tests/examples/python/PYTHONConnectorChecker/PythonChecker.py deleted file mode 100644 index d74f021ffcf3aa33c551cc265243b5139c23b757..0000000000000000000000000000000000000000 --- a/tests/examples/python/PYTHONConnectorChecker/PythonChecker.py +++ /dev/null @@ -1,114 +0,0 @@ -import taos -import time -import sys -import getopt -class ConnectorChecker: - def init(self): - self.host = "127.0.0.1" - self.dbName = "test" - self.tbName = "weather" - self.user = "root" - self.password = "taosdata" - - - def sethdt(self,FQDN,dbname,tbname): - if(FQDN): - self.host=FQDN - if(dbname): - self.dbname=dbname - if(tbname): - self.tbName - def printSql(self,sql,elapsed): - print("[ "+"OK"+" ]"+" time cost: %s ms, execute statement ====> %s" - %(elapsed,sql)) - def executeQuery(self,sql): - try: - start=time.time() - execute = self.cl.execute(sql) - elapsed = (time.time()-start)*1000 - self.printSql(sql,elapsed) - data = self.cl.fetchall() - numOfRows = self.cl.rowcount - numOfCols = len(self.cl.description) - for irow in range(numOfRows): - print("Row%d: ts=%s, temperature=%d, humidity=%f" %(irow, data[irow][0], data[irow][1],data[irow][2])) - except Exception as e: - print("Failure sql: %s,exception: %s" %sql,str(e)) - def execute(self,sql): - try: - start=time.time() - execute = self.cl.execute(sql) - elapsed = (time.time()-start)*1000 - self.printSql(sql,elapsed) - - except Exception as e: - print("Failure sql: %s,exception: %s" % - sql,str(e)) - def close(self): - print("connetion closed.") - self.cl.close() - self.conn.close() - def createDatabase(self): - sql="create database if not exists %s" % self.dbName - self.execute(sql) - def useDatabase(self): - sql="use %s" % self.dbName - self.execute(sql) - def createTable(self): - sql="create table if not exists %s.%s (ts timestamp, temperature float, humidity int)"%(self.dbName,self.tbName) - self.execute(sql) - def checkDropTable(self): - sql="drop table if exists " + self.dbName + "." + self.tbName + "" - self.execute(sql) - def checkInsert(self): - sql="insert into test.weather (ts, temperature, humidity) values(now, 20.5, 34)" - self.execute(sql) - def checkSelect(self): - sql = "select * from test.weather" - self.executeQuery(sql) - def srun(self): - try: - self.conn = taos.connect(host=self.host,user=self.user,password=self.password) - #self.conn = taos.connect(self.host,self.user,self.password) - except Exception as e: - print("connection failed: %s"%self.host) - exit(1) - print("[ OK ] Connection established.") - self.cl = self.conn.cursor() - -def main(argv): - FQDN='' - dbname='' - tbname='' - try: - opts, args = getopt.getopt(argv,"h:d:t:",["FQDN=","ifile=","ofile="]) - except getopt.GetoptError: - print ('PYTHONConnectorChecker.py -h ') - sys.exit(2) - for opt, arg in opts: - if opt in ("-h", "--FQDN"): - FQDN=arg - elif opt in ("-d", "--dbname"): - dbname = arg - elif opt in ("-t", "--tbname"): - tbname = arg - - checker = ConnectorChecker() - checker.init() - checker.sethdt(FQDN,dbname,tbname) - checker.srun() - checker.createDatabase() - checker.useDatabase() - checker.checkDropTable() - checker.createTable() - checker.checkInsert() - checker.checkSelect() - checker.checkDropTable() - checker.close() - - - -if __name__ == "__main__": - main(sys.argv[1:]) - - diff --git a/tests/examples/python/read_example.py b/tests/examples/python/read_example.py deleted file mode 100644 index 73052ab2df54fcee8fb01573e23eb7b29ed11712..0000000000000000000000000000000000000000 --- a/tests/examples/python/read_example.py +++ /dev/null @@ -1,93 +0,0 @@ -""" -This is the sample code for TDengine python2 client. -""" -import taos -import sys -import datetime -import random - -def exitProgram(conn): - conn.close() - sys.exit() - -if __name__ == '__main__': - start_time = datetime.datetime(2019, 7, 1) - time_interval = datetime.timedelta(seconds=60) - - # Connect to TDengine server. - # - # parameters: - # @host : TDengine server IP address - # @user : Username used to connect to TDengine server - # @password : Password - # @database : Database to use when connecting to TDengine server - # @config : Configuration directory - if len(sys.argv)>1: - hostname=sys.argv[1] - conn = taos.connect(host=hostname, user="root", password="taosdata", config="/etc/taos") - else: - conn = taos.connect(host="127.0.0.1", user="root", password="taosdata", config="/etc/taos") - - # Generate a cursor object to run SQL commands - c1 = conn.cursor() - # Create a database named db - try: - c1.execute('create database if not exists db ') - except Exception as err: - conn.close() - raise(err) - - # use database - try: - c1.execute('use db') - except Exception as err: - conn.close() - raise(err) - - - # create table - try: - c1.execute('create table if not exists t (ts timestamp, a int, b float, c binary(20))') - except Exception as err: - conn.close() - raise(err) - - # insert data - for i in range(10): - try: - value = c1.execute("insert into t values ('%s', %d, %f, '%s')" % (start_time, random.randint(1,10), random.randint(1,10)/10.0, 'hello')) - #if insert, value is the affected rows - print(value) - except Exception as err: - conn.close() - raise(err) - start_time += time_interval - - # query data and return data in the form of list - try: - c1.execute('select * from db.t') - except Exception as err: - conn.close() - raise(err) - - # Column names are in c1.description list - cols = c1.description - # Use fetchall to fetch data in a list - data = c1.fetchall() - - for col in data: - print(col) - - print('Another query method ') - - try: - c1.execute('select * from db.t') - except Exception as err: - conn.close() - raise(err) - - # Use iterator to go through the retreived data - for col in c1: - print(col) - - conn.close() diff --git a/tests/examples/python/taosdemo/README.md b/tests/examples/python/taosdemo/README.md deleted file mode 100644 index d48fffe8ff44fb68a1a147a2c97ca057fb360092..0000000000000000000000000000000000000000 --- a/tests/examples/python/taosdemo/README.md +++ /dev/null @@ -1,38 +0,0 @@ -install build environment -=== -/usr/bin/python3 -m pip install -r requirements.txt - -run python version taosdemo -=== -Usage: ./taosdemo.py [OPTION...] - -Author: Shuduo Sang - - -H, --help Show usage. - - -N, --native flag, Use native interface if set. Default is using RESTful interface. - -h, --host host, The host to connect to TDengine. Default is localhost. - -p, --port port, The TCP/IP port number to use for the connection. Default is 0. - -u, --user user, The user name to use when connecting to the server. Default is 'root'. - -P, --password password, The password to use when connecting to the server. Default is 'taosdata'. - -l, --colsPerRec num_of_columns_per_record, The number of columns per record. Default is 3. - -d, --dbname database, Destination database. Default is 'test'. - -a, --replica replica, Set the replica parameters of the database, Default 1, min: 1, max: 5. - -m, --tbname
table_prefix, Table prefix name. Default is 't'. - -M, --stable flag, Use super table. Default is no - -s, --stbname stable_prefix, STable prefix name. Default is 'st' - -Q, --query query, Execute query command. set 'DEFAULT' means select * from each table - -T, --threads num_of_threads, The number of threads. Default is 1. - -C, --processes num_of_processes, The number of threads. Default is 1. - -r, --batch num_of_records_per_req, The number of records per request. Default is 1000. - -t, --numOfTb num_of_tables, The number of tables. Default is 1. - -n, --numOfRec num_of_records_per_table, The number of records per table. Default is 1. - -c, --config config_directory, Configuration directory. Default is '/etc/taos/'. - -x, --inserOnly flag, Insert only flag. - -O, --outOfOrder out of order data insert, 0: In order, 1: Out of order. Default is in order. - -R, --rateOOOO rate, Out of order data's rate--if order=1 Default 10, min: 0, max: 50. - -D, --deleteMethod Delete data methods 0: don't delete, 1: delete by table, 2: delete by stable, 3: delete by database. - -v, --verbose Print verbose output - -g, --debug Print debug output - -y, --skipPrompt Skip read key for continous test, default is not skip - diff --git a/tests/examples/python/taosdemo/requirements.txt b/tests/examples/python/taosdemo/requirements.txt deleted file mode 100644 index 977e8e3726a446e85635764fe9243a3c5416ea0f..0000000000000000000000000000000000000000 --- a/tests/examples/python/taosdemo/requirements.txt +++ /dev/null @@ -1,28 +0,0 @@ -## -######## example-requirements.txt ####### -## -####### Requirements without Version Specifiers ###### -requests -multipledispatch -#beautifulsoup4 -## -####### Requirements with Version Specifiers ###### -## See https://www.python.org/dev/peps/pep-0440/#version-specifiers -#docopt == 0.6.1 # Version Matching. Must be version 0.6.1 -#keyring >= 4.1.1 # Minimum version 4.1.1 -#coverage != 3.5 # Version Exclusion. Anything except version 3.5 -#Mopidy-Dirble ~= 1.1 # Compatible release. Same as >= 1.1, == 1.* -## -####### Refer to other requirements files ###### -#-r other-requirements.txt -## -## -####### A particular file ###### -#./downloads/numpy-1.9.2-cp34-none-win32.whl -#http://wxpython.org/Phoenix/snapshot-builds/wxPython_Phoenix-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl -## -####### Additional Requirements without Version Specifiers ###### -## Same as 1st section, just here to show that you can put things in any order. -#rejected -#green -## diff --git a/tests/examples/python/taosdemo/taosdemo.py b/tests/examples/python/taosdemo/taosdemo.py deleted file mode 100755 index 4aaf00157c5fe5bbeec27b001f663a94c1d89439..0000000000000000000000000000000000000000 --- a/tests/examples/python/taosdemo/taosdemo.py +++ /dev/null @@ -1,817 +0,0 @@ -#!/usr/bin/python3 -# * Copyright (c) 2019 TAOS Data, Inc. -# * -# * 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 . - -# -*- coding: utf-8 -*- - -import sys -import getopt -import requests -import json -import random -import time -import datetime -import multiprocessing -from multiprocessing import Manager, Pool, Lock -from multipledispatch import dispatch -from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED - - -@dispatch(str, str) -def v_print(msg, arg): - # type: (str, str) -> None - if verbose: - print(msg % arg) - - -@dispatch(str, str, str) -def v_print(msg, arg1, arg2): - # type: (str, str, str) -> None - if verbose: - print(msg % (arg1, arg2)) - - -@dispatch(str, str, str, str) -def v_print(msg, arg1, arg2, arg3): - # type: (str, str, str, str) -> None - if verbose: - print(msg % (arg1, arg2, arg3)) - - -@dispatch(str, str, str, str, str) -def v_print(msg, arg1, arg2, arg3, arg4): - # type: (str, str, str, str, str) -> None - if verbose: - print(msg % (arg1, arg2, arg3, arg4)) - - -@dispatch(str, int) -def v_print(msg, arg): - # type: (str, int) -> None - if verbose: - print(msg % int(arg)) - - -@dispatch(str, int, str) -def v_print(msg, arg1, arg2): - # type: (str, int, str) -> None - if verbose: - print(msg % (int(arg1), str(arg2))) - - -@dispatch(str, str, int) -def v_print(msg, arg1, arg2): - # type: (str, str, int) -> None - if verbose: - print(msg % (arg1, int(arg2))) - - -@dispatch(str, int, int) -def v_print(msg, arg1, arg2): - # type: (str, int, int) -> None - if verbose: - print(msg % (int(arg1), int(arg2))) - - -@dispatch(str, int, int, str) -def v_print(msg, arg1, arg2, arg3): - # type: (str, int, int, str) -> None - if verbose: - print(msg % (int(arg1), int(arg2), str(arg3))) - - -@dispatch(str, int, int, int) -def v_print(msg, arg1, arg2, arg3): - # type: (str, int, int, int) -> None - if verbose: - print(msg % (int(arg1), int(arg2), int(arg3))) - - -@dispatch(str, int, int, int, int) -def v_print(msg, arg1, arg2, arg3, arg4): - # type: (str, int, int, int, int) -> None - if verbose: - print(msg % (int(arg1), int(arg2), int(arg3), int(arg4))) - - -def restful_execute(host, port, user, password, cmd): - # type: (str, int, str, str, str) -> None - url = "http://%s:%d/rest/sql" % (host, restPort) - - v_print("restful_execute - cmd: %s", cmd) - - resp = requests.post(url, cmd, auth=(user, password)) - - v_print("resp status: %d", resp.status_code) - - if debug: - v_print( - "resp text: %s", - json.dumps( - resp.json(), - sort_keys=True, - indent=2)) - else: - print("resp: %s" % json.dumps(resp.json())) - - -def query_func(process, thread, cmd): - # type: (int, int, str) -> None - v_print("%d process %d thread cmd: %s", process, thread, cmd) - - if oneMoreHost != "NotSupported" and random.randint( - 0, 1) == 1: - v_print("%s", "Send to second host") - if native: - cursor2.execute(cmd) - else: - restful_execute( - oneMoreHost, port, user, password, cmd) - else: - v_print("%s%s%s", "Send ", cmd, " to the host") - if native: - pass -# cursor.execute(cmd) - else: - restful_execute( - host, port, user, password, cmd) - - -def query_data_process(cmd): - # type: (str) -> None - # establish connection if native - if native: - v_print("host:%s, user:%s passwd:%s configDir:%s ", host, user, password, configDir) - try: - conn = taos.connect( - host=host, - user=user, - password=password, - config=configDir) - v_print("conn: %s", str(conn.__class__)) - except Exception as e: - print("Error: %s" % e.args[0]) - sys.exit(1) - - try: - cursor = conn.cursor() - v_print("cursor:%d %s", id(cursor), str(cursor.__class__)) - except Exception as e: - print("Error: %s" % e.args[0]) - conn.close() - sys.exit(1) - - if native: - try: - cursor.execute(cmd) - cols = cursor.description - data = cursor.fetchall() - - for col in data: - print(col) - except Exception as e: - conn.close() - print("Error: %s" % e.args[0]) - sys.exit(1) - - else: - restful_execute( - host, - port, - user, - password, - cmd) - - if native: - cursor.close() - conn.close() - - -def create_stb(): - for i in range(0, numOfStb): - if native: - cursor.execute( - "CREATE TABLE IF NOT EXISTS %s%d (ts timestamp, value float) TAGS (uuid binary(50))" % - (stbName, i)) - else: - restful_execute( - host, - port, - user, - password, - "CREATE TABLE IF NOT EXISTS %s%d (ts timestamp, value float) TAGS (uuid binary(50))" % - (stbName, i) - ) - - -def use_database(): - - if native: - cursor.execute("USE %s" % current_db) - else: - restful_execute(host, port, user, password, "USE %s" % current_db) - - -def create_databases(): - for i in range(0, numOfDb): - v_print("will create database db%d", int(i)) - - if native: - cursor.execute( - "CREATE DATABASE IF NOT EXISTS %s%d" % (dbName, i)) - else: - restful_execute( - host, - port, - user, - password, - "CREATE DATABASE IF NOT EXISTS %s%d" % (dbName, i)) - - -def drop_tables(): - # TODO - v_print("TODO: drop tables total %d", numOfTb) - pass - - -def drop_stable(): - # TODO - v_print("TODO: drop stables total %d", numOfStb) - pass - - -def drop_databases(): - v_print("drop databases total %d", numOfDb) - - # drop exist databases first - for i in range(0, numOfDb): - v_print("will drop database db%d", int(i)) - - if native: - cursor.execute( - "DROP DATABASE IF EXISTS %s%d" % - (dbName, i)) - else: - restful_execute( - host, - port, - user, - password, - "DROP DATABASE IF EXISTS %s%d" % - (dbName, i)) - - -def insert_func(process, thread): - # type: (int, int) -> None - v_print("%d process %d thread, insert_func ", process, thread) - - # generate uuid - uuid_int = random.randint(0, numOfTb + 1) - uuid = "%s" % uuid_int - v_print("uuid is: %s", uuid) - - # establish connection if native - if native: - v_print("host:%s, user:%s passwd:%s configDir:%s ", host, user, password, configDir) - try: - conn = taos.connect( - host=host, - user=user, - password=password, - config=configDir) - v_print("conn: %s", str(conn.__class__)) - except Exception as e: - print("Error: %s" % e.args[0]) - sys.exit(1) - - try: - cursor = conn.cursor() - v_print("cursor:%d %s", id(cursor), str(cursor.__class__)) - except Exception as e: - print("Error: %s" % e.args[0]) - conn.close() - sys.exit(1) - - v_print("numOfRec %d:", numOfRec) - - row = 0 - while row < numOfRec: - v_print("row: %d", row) - sqlCmd = ['INSERT INTO '] - try: - sqlCmd.append( - "%s.%s%d " % (current_db, tbName, thread)) - - if (numOfStb > 0 and autosubtable): - sqlCmd.append("USING %s.%s%d TAGS('%s') " % - (current_db, stbName, numOfStb - 1, uuid)) - - start_time = datetime.datetime( - 2021, 1, 25) + datetime.timedelta(seconds=row) - - sqlCmd.append("VALUES ") - for batchIter in range(0, batch): - sqlCmd.append("('%s', %f) " % - ( - start_time + - datetime.timedelta( - milliseconds=batchIter), - random.random())) - row = row + 1 - if row >= numOfRec: - v_print("BREAK, row: %d numOfRec:%d", row, numOfRec) - break - - except Exception as e: - print("Error: %s" % e.args[0]) - - cmd = ' '.join(sqlCmd) - - if measure: - exec_start_time = datetime.datetime.now() - - if native: - affectedRows = cursor.execute(cmd) - else: - restful_execute( - host, port, user, password, cmd) - - if measure: - exec_end_time = datetime.datetime.now() - exec_delta = exec_end_time - exec_start_time - v_print( - "consume %d microseconds", - exec_delta.microseconds) - - v_print("cmd: %s, length:%d", cmd, len(cmd)) - - if native: - cursor.close() - conn.close() - - -def create_tb_using_stb(): - # TODO: - pass - - -def create_tb(): - v_print("create_tb() numOfTb: %d", numOfTb) - for i in range(0, numOfDb): - if native: - cursor.execute("USE %s%d" % (dbName, i)) - else: - restful_execute( - host, port, user, password, "USE %s%d" % - (dbName, i)) - - for j in range(0, numOfTb): - if native: - cursor.execute( - "CREATE TABLE %s%d (ts timestamp, value float)" % - (tbName, j)) - else: - restful_execute( - host, - port, - user, - password, - "CREATE TABLE %s%d (ts timestamp, value float)" % - (tbName, j)) - - -def insert_data_process(lock, i, begin, end): - # type: (multiprocessing._LockType, int, int, int) -> None - lock.acquire() - tasks = end - begin - v_print("insert_data_process:%d table from %d to %d, tasks %d", i, begin, end, tasks) - - if (threads < (end - begin)): - for j in range(begin, end, threads): - with ThreadPoolExecutor(max_workers=threads) as executor: - k = end if ((j + threads) > end) else (j + threads) - workers = [ - executor.submit( - insert_func, - i, - n) for n in range( - j, - k)] - wait(workers, return_when=ALL_COMPLETED) - else: - with ThreadPoolExecutor(max_workers=threads) as executor: - workers = [ - executor.submit( - insert_func, - i, - j) for j in range( - begin, - end)] - wait(workers, return_when=ALL_COMPLETED) - - lock.release() - - -def query_db(i): - if native: - cursor.execute("USE %s%d" % (dbName, i)) - else: - restful_execute( - host, port, user, password, "USE %s%d" % - (dbName, i)) - - for j in range(0, numOfTb): - if native: - cursor.execute( - "SELECT COUNT(*) FROM %s%d" % (tbName, j)) - else: - restful_execute( - host, port, user, password, "SELECT COUNT(*) FROM %s%d" % - (tbName, j)) - - -def printConfig(): - - print("###################################################################") - print("# Use native interface: %s" % native) - print("# Server IP: %s" % host) - if native: - print("# Server port: %s" % port) - else: - print("# Server port: %s" % restPort) - - print("# Configuration Dir: %s" % configDir) - print("# User: %s" % user) - print("# Password: %s" % password) - print("# Number of Columns per record: %s" % colsPerRecord) - print("# Number of Threads: %s" % threads) - print("# Number of Processes: %s" % processes) - print("# Number of Tables: %s" % numOfTb) - print("# Number of records per Table: %s" % numOfRec) - print("# Records/Request: %s" % batch) - print("# Database name: %s" % dbName) - print("# Replica: %s" % replica) - print("# Use STable: %s" % useStable) - print("# Table prefix: %s" % tbName) - if useStable: - print("# STable prefix: %s" % stbName) - - print("# Data order: %s" % outOfOrder) - print("# Data out of order rate: %s" % rateOOOO) - print("# Delete method: %s" % deleteMethod) - print("# Query command: %s" % queryCmd) - print("# Insert Only: %s" % insertOnly) - print("# Verbose output %s" % verbose) - print("# Test time: %s" % - datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")) - print("###################################################################") - - -if __name__ == "__main__": - - native = False - verbose = False - debug = False - measure = True - dropDbOnly = False - colsPerRecord = 3 - numOfDb = 1 - dbName = "test" - replica = 1 - batch = 1 - numOfTb = 1 - tbName = "tb" - useStable = False - numOfStb = 0 - stbName = "stb" - numOfRec = 10 - ieration = 1 - host = "127.0.0.1" - configDir = "/etc/taos" - oneMoreHost = "NotSupported" - port = 6030 - restPort = 6041 - user = "root" - defaultPass = "taosdata" - processes = 1 - threads = 1 - insertOnly = False - autosubtable = False - queryCmd = "NO" - outOfOrder = 0 - rateOOOO = 0 - deleteMethod = 0 - skipPrompt = False - - try: - opts, args = getopt.gnu_getopt(sys.argv[1:], - 'Nh:p:u:P:d:a:m:Ms:Q:T:C:r:l:t:n:c:xOR:D:vgyH', - [ - 'native', 'host', 'port', 'user', 'password', 'dbname', 'replica', 'tbname', - 'stable', 'stbname', 'query', 'threads', 'processes', - 'recPerReq', 'colsPerRecord', 'numOfTb', 'numOfRec', 'config', - 'insertOnly', 'outOfOrder', 'rateOOOO', 'deleteMethod', - 'verbose', 'debug', 'skipPrompt', 'help' - ]) - except getopt.GetoptError as err: - print('ERROR:', err) - print('Try `taosdemo.py --help` for more options.') - sys.exit(1) - - if bool(opts) is False: - print('Try `taosdemo.py --help` for more options.') - sys.exit(1) - - for key, value in opts: - if key in ['-H', '--help']: - print('') - print( - 'taosdemo.py for TDengine') - print('') - print('Author: Shuduo Sang ') - print('') - - print('\t-H, --help Show usage.') - print('') - - print('\t-N, --native flag, Use native interface if set. Default is using RESTful interface.') - print('\t-h, --host host, The host to connect to TDengine. Default is localhost.') - print('\t-p, --port port, The TCP/IP port number to use for the connection. Default is 0.') - print('\t-u, --user user, The user name to use when connecting to the server. Default is \'root\'.') - print('\t-P, --password password, The password to use when connecting to the server. Default is \'taosdata\'.') - print('\t-l, --colsPerRec num_of_columns_per_record, The number of columns per record. Default is 3.') - print( - '\t-d, --dbname database, Destination database. Default is \'test\'.') - print('\t-a, --replica replica, Set the replica parameters of the database, Default 1, min: 1, max: 5.') - print( - '\t-m, --tbname
table_prefix, Table prefix name. Default is \'t\'.') - print( - '\t-M, --stable flag, Use super table. Default is no') - print( - '\t-s, --stbname stable_prefix, STable prefix name. Default is \'st\'') - print('\t-Q, --query [NO|EACHTB|command] query, Execute query command. set \'EACHTB\' means select * from each table') - print( - '\t-T, --threads num_of_threads, The number of threads. Default is 1.') - print( - '\t-C, --processes num_of_processes, The number of threads. Default is 1.') - print('\t-r, --batch num_of_records_per_req, The number of records per request. Default is 1000.') - print( - '\t-t, --numOfTb num_of_tables, The number of tables. Default is 1.') - print('\t-n, --numOfRec num_of_records_per_table, The number of records per table. Default is 1.') - print('\t-c, --config config_directory, Configuration directory. Default is \'/etc/taos/\'.') - print('\t-x, --inserOnly flag, Insert only flag.') - print('\t-O, --outOfOrder out of order data insert, 0: In order, 1: Out of order. Default is in order.') - print('\t-R, --rateOOOO rate, Out of order data\'s rate--if order=1 Default 10, min: 0, max: 50.') - print('\t-D, --deleteMethod Delete data methods 0: don\'t delete, 1: delete by table, 2: delete by stable, 3: delete by database.') - print('\t-v, --verbose Print verbose output') - print('\t-g, --debug Print debug output') - print( - '\t-y, --skipPrompt Skip read key for continous test, default is not skip') - print('') - sys.exit(0) - - if key in ['-N', '--native']: - try: - import taos - except Exception as e: - print("Error: %s" % e.args[0]) - sys.exit(1) - native = True - - if key in ['-h', '--host']: - host = value - - if key in ['-p', '--port']: - port = int(value) - - if key in ['-u', '--user']: - user = value - - if key in ['-P', '--password']: - password = value - else: - password = defaultPass - - if key in ['-d', '--dbname']: - dbName = value - - if key in ['-a', '--replica']: - replica = int(value) - if replica < 1: - print("FATAL: number of replica need > 0") - sys.exit(1) - - if key in ['-m', '--tbname']: - tbName = value - - if key in ['-M', '--stable']: - useStable = True - numOfStb = 1 - - if key in ['-s', '--stbname']: - stbName = value - - if key in ['-Q', '--query']: - queryCmd = str(value) - - if key in ['-T', '--threads']: - threads = int(value) - if threads < 1: - print("FATAL: number of threads must be larger than 0") - sys.exit(1) - - if key in ['-C', '--processes']: - processes = int(value) - if processes < 1: - print("FATAL: number of processes must be larger than 0") - sys.exit(1) - - if key in ['-r', '--batch']: - batch = int(value) - - if key in ['-l', '--colsPerRec']: - colsPerRec = int(value) - - if key in ['-t', '--numOfTb']: - numOfTb = int(value) - v_print("numOfTb is %d", numOfTb) - - if key in ['-n', '--numOfRec']: - numOfRec = int(value) - v_print("numOfRec is %d", numOfRec) - if numOfRec < 1: - print("FATAL: number of records must be larger than 0") - sys.exit(1) - - - if key in ['-c', '--config']: - configDir = value - v_print("config dir: %s", configDir) - - if key in ['-x', '--insertOnly']: - insertOnly = True - v_print("insert only: %d", insertOnly) - - if key in ['-O', '--outOfOrder']: - outOfOrder = int(value) - v_print("out of order is %d", outOfOrder) - - if key in ['-R', '--rateOOOO']: - rateOOOO = int(value) - v_print("the rate of out of order is %d", rateOOOO) - - if key in ['-D', '--deleteMethod']: - deleteMethod = int(value) - if (deleteMethod < 0) or (deleteMethod > 3): - print( - "inputed delete method is %d, valid value is 0~3, set to default 0" % - deleteMethod) - deleteMethod = 0 - v_print("the delete method is %d", deleteMethod) - - if key in ['-v', '--verbose']: - verbose = True - - if key in ['-g', '--debug']: - debug = True - - if key in ['-y', '--skipPrompt']: - skipPrompt = True - - if verbose: - printConfig() - - if not skipPrompt: - try: - input("Press any key to continue..") - except SyntaxError: - pass - - # establish connection first if native - if native: - v_print("host:%s, user:%s passwd:%s configDir:%s ", host, user, password, configDir) - try: - conn = taos.connect( - host=host, - user=user, - password=password, - config=configDir) - v_print("conn: %s", str(conn.__class__)) - except Exception as e: - print("Error: %s" % e.args[0]) - sys.exit(1) - - try: - cursor = conn.cursor() - v_print("cursor:%d %s", id(cursor), str(cursor.__class__)) - except Exception as e: - print("Error: %s" % e.args[0]) - conn.close() - sys.exit(1) - - # drop data only if delete method be set - if deleteMethod > 0: - if deleteMethod == 1: - drop_tables() - print("Drop tables done.") - elif deleteMethod == 2: - drop_stables() - print("Drop super tables done.") - elif deleteMethod == 3: - drop_databases() - print("Drop Database done.") - sys.exit(0) - - # create databases - drop_databases() - create_databases() - - # use last database - current_db = "%s%d" % (dbName, (numOfDb - 1)) - use_database() - - if measure: - start_time_begin = time.time() - - if numOfStb > 0: - create_stb() - if (autosubtable == False): - create_tb_using_stb() - else: - create_tb() - - if measure: - end_time = time.time() - print( - "Total time consumed {} seconds for create table.".format( - (end_time - start_time_begin))) - - if native: - cursor.close() - conn.close() - - # start insert data - if measure: - start_time = time.time() - - manager = Manager() - lock = manager.Lock() - pool = Pool(processes) - - begin = 0 - end = 0 - - quotient = numOfTb // processes - if quotient < 1: - processes = numOfTb - quotient = 1 - - remainder = numOfTb % processes - v_print( - "num of tables: %d, quotient: %d, remainder: %d", - numOfTb, - quotient, - remainder) - - for i in range(processes): - begin = end - - if i < remainder: - end = begin + quotient + 1 - else: - end = begin + quotient - pool.apply_async(insert_data_process, args=(lock, i, begin, end,)) - - pool.close() - pool.join() - time.sleep(1) - - if measure: - end_time = time.time() - print( - "Total time consumed {} seconds for insert data.".format( - (end_time - start_time))) - - - # query data - if queryCmd != "NO": - print("queryCmd: %s" % queryCmd) - query_data_process(queryCmd) - - if measure: - end_time = time.time() - print( - "Total time consumed {} seconds.".format( - (end_time - start_time_begin))) - - print("done") diff --git a/tests/parallel_test/cases.task b/tests/parallel_test/cases.task index 303378d6945d1dc0b518140abe49972cc89b25c1..3b3ed8505b2f31e661e29059838af6b159422b14 100644 --- a/tests/parallel_test/cases.task +++ b/tests/parallel_test/cases.task @@ -36,7 +36,7 @@ 83,,script,./test.sh -f general/parser/limit1_tblocks100.sim 82,,script,./test.sh -f general/parser/limit1.sim 82,,pytest,python3 test.py -f query/last_row_cache.py -81,,develop-test,timeout 180 bash 3-connectors/c#/test.sh +81,,develop-test,timeout 180 bash 3-connectors/c#/test.sh 80,,develop-test,timeout 180 bash 3-connectors/nodejs/test.sh 79,,script,./test.sh -f general/db/alter_tables_v4.sim 79,,pytest,python3 test.py -f insert/verifyMemToDiskCrash.py @@ -234,6 +234,7 @@ 30,,script,./test.sh -f unique/account/account_delete.sim 30,,script,./test.sh -f general/import/commit.sim 30,,script,./test.sh -f general/compute/diff2.sim +30,,develop-test,bash 3-connectors/R/test.sh 29,,system-test,python3 ./test.py -f 0-others/create_col_tag.py 29,,script,./test.sh -f unique/arbitrator/dn3_mn1_full_createTableFail.sim 29,,script,./test.sh -f general/wal/maxtables.sim @@ -303,17 +304,19 @@ 20,,script,./test.sh -f general/parser/auto_create_tb_drop_tb.sim 20,,script,./test.sh -f general/import/basic.sim 20,2,script,./test.sh -f general/alter/dnode.sim -20,,script,./test.sh -f general/compute/cast.sim +20,,script,eval sh -c \"if [ `uname -m` != aarch64 ]; then ./test.sh -f general/compute/cast.sim; fi\" 20,,script,./test.sh -f general/compute/string_funcs.sim 20,,develop-test,python3 test.py -f 2-query/lower_func.py 20,,develop-test,python3 test.py -f 2-query/upper_func.py 20,,develop-test,python3 test.py -f 2-query/ltrim_func.py 20,,develop-test,python3 test.py -f 2-query/rtrim_func.py 20,,develop-test,python3 test.py -f 2-query/substr_func.py +20,,develop-test,bash 3-connectors/TypeScript-REST/test.sh 20,,pytest,python3 test.py -f query/query.py 20,,pytest,python3 test.py -f import_merge/importLastTO.py 20,,pytest,python3 test.py -f import_merge/importDataSub.py 20,,pytest,python3 test.py -f import_merge/importDataLastSub.py +20,,pytest,python3 test.py -f table/create.py 19,,script,./test.sh -f unique/stable/dnode2.sim 19,,script,./test.sh -f general/db/vnodes.sim 19,,pytest,python3 test.py -f tools/taosdumpTest3.py @@ -560,11 +563,11 @@ 10,,script,./test.sh -f unique/stable/replica2_vnode3.sim 10,,pytest,python3 testCompress.py 10,,pytest,python3 test.py -f client/client.py -10,,script,./test.sh -f general/parser/scalar_expression.sim 10,,script,./test.sh -f general/compute/scalar_pow.sim 9,,script,./test.sh -f general/parser/alter1.sim 9,,script,./test.sh -f general/db/delete.sim -9,,pytest,python3 test.py -f tools/taosdemoTestLimitOffset.py +9,,pytest,python3 test.py -f tools/taosdemoTestLimitOffset.py +9,,develop-test,python3 ./test.py -f 5-taos-tools/taosbenchmark/custom_col_tag.py 9,,pytest,python3 test.py -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoInsert.py 9,,pytest,python3 test.py -f stream/showStreamExecTimeisNull.py 9,,pytest,python3 test.py -f query/bug1876.py @@ -583,6 +586,7 @@ 8,,develop-test,python3 ./test.py -f 5-taos-tools/taosdump/taosdumpTestTypeTinyInt.py 8,,develop-test,python3 ./test.py -f 5-taos-tools/taosdump/taosdumpTestTypeInt.py 8,,develop-test,python3 ./test.py -f 5-taos-tools/taosdump/taosdumpTestTypeDouble.py +8,,pytest,python3 test.py -f update/update2.py 7,,system-test,python3 ./test.py -f 5-taos-tools/taosbenchmark/taosdemoTestInsertWithJsonSml-otherPara.py 7,,pytest,python3 test.py -f tools/taosdumpTest2.py 7,,pytest,python3 test.py -f tools/taosdemoTestdatatype.py @@ -711,6 +715,11 @@ 5,,develop-test,python3 ./test.py -f 2-query/function_timezone.py 5,,develop-test,python3 ./test.py -f 2-query/function_to_iso8601.py 5,,develop-test,python3 ./test.py -f 2-query/function_to_unixtimestamp.py +5,,develop-test,python3 ./test.py -f 2-query/time_window_keywords.py +5,,develop-test,python3 ./test.py -f 2-query/TD-13946.py +5,,develop-test,python3 ./test.py -f 2-query/query_window_keywords.py +5,,develop-test,python3 ./test.py -f 2-query/scalar_triangle.py +5,,develop-test,python3 ./test.py -f 2-query/scalar_expression.py 4,,system-test,python3 test.py -f 4-taosAdapter/TD-12163.py 4,,system-test,python3 ./test.py -f 3-connectors/restful/restful_binddbname.py 4,,system-test,python3 ./test.py -f 2-query/TD-12614.py @@ -783,11 +792,18 @@ 4,,pytest,python3 test.py -f alter/alterTabAddTagWithNULL.py 4,,pytest,python3 test.py -f alter/alter_debugFlag.py 4,,pytest,python3 test.py -f alter/alter_create_exception.py +4,,pytest,python3 test.py -f insert/line_insert.py 3,,pytest,python3 test.py -f tag_lite/binary.py 3,,pytest,python3 test.py -f query/filterAllIntTypes.py 3,,develop-test,python3 ./test.py -f 2-query/ts_hidden_column.py -3,,script,./test.sh -f general/compute/scalar_triangle.sim +3,,develop-test,python3 ./test.py -f 2-query/ts_shortcut.py +3,,develop-test,python3 ./test.py -f 2-query/nchar_funcs.py +3,,develop-test,python3 ./test.py -f 2-query/TD-5902.py +1,,develop-test,python3 ./test.py -f 2-query/TD-14196.py 3,,script,./test.sh -f general/compute/scalar_str_concat_len.sim +3,,develop-test,python3 ./test.py -f 2-query/TD-13414.py 3,,develop-test,python3 ./test.py -f 2-query/function_tail.py 2,,develop-test,python3 ./test.py -f 2-query/function_unique.py +2,,develop-test,python3 ./test.py -f 2-query/function_hll.py +1,,develop-test,python3 ./test.py -f 2-query/function_state.py 1,,develop-test,python3 ./test.py -f 5-taos-tools/taosbenchmark/demo.py diff --git a/tests/parallel_test/run.sh b/tests/parallel_test/run.sh index a9263929f4a2d5abd6048d2d93114ebecd45c9a9..221b70b22a7b17586be9ed04895e716b391f3b0e 100755 --- a/tests/parallel_test/run.sh +++ b/tests/parallel_test/run.sh @@ -272,10 +272,11 @@ function run_thread() { flock -x $lock_file -c "echo \"${hosts[index]} ret:${ret} ${line}\" >>$log_dir/failed.log" mkdir -p $log_dir/${case_file}.coredump local remote_coredump_dir="${workdirs[index]}/tmp/thread_volume/$thread_no/coredump" - cmd="sshpass -p ${passwords[index]} scp -o StrictHostKeyChecking=no ${usernames[index]}@${hosts[index]}:${remote_coredump_dir}/* $log_dir/${case_file}.coredump/" + local scpcmd="sshpass -p ${passwords[index]} scp -o StrictHostKeyChecking=no -r ${usernames[index]}@${hosts[index]}" if [ -z ${passwords[index]} ]; then - cmd="scp -o StrictHostKeyChecking=no ${usernames[index]}@${hosts[index]}:${remote_coredump_dir}/* $log_dir/${case_file}.coredump/" + scpcmd="scp -o StrictHostKeyChecking=no -r ${usernames[index]}@${hosts[index]}" fi + cmd="$scpcmd:${remote_coredump_dir}/* $log_dir/${case_file}.coredump/" $cmd # 2>/dev/null local case_info=`echo "$line"|cut -d, -f 3,4` local corefile=`ls $log_dir/${case_file}.coredump/` @@ -287,6 +288,15 @@ function run_thread() { echo -e "\e[34m log file: $log_dir/$case_file.log \e[0m" if [ ! -z "$corefile" ]; then echo -e "\e[34m corefiles: $corefile \e[0m" + local build_dir=$log_dir/build_${hosts[index]} + local remote_build_dir="${workdirs[index]}/TDinternal/debug/build" + mkdir $build_dir 2>/dev/null + if [ $? -eq 0 ]; then + # scp build binary + cmd="$scpcmd:${remote_build_dir}/* ${build_dir}/" + echo "$cmd" + $cmd >/dev/null + fi fi fi done diff --git a/tests/pytest/crash_gen/crash_gen_main.py b/tests/pytest/crash_gen/crash_gen_main.py index 252b343a068e84589776c9e6c59c5fd5a0384944..1e6304ed5aa4c2f23689610460ae0b09bbe1334e 100755 --- a/tests/pytest/crash_gen/crash_gen_main.py +++ b/tests/pytest/crash_gen/crash_gen_main.py @@ -84,10 +84,10 @@ class WorkerThread: # self._thread = threading.Thread(target=runThread, args=(self,)) self._thread = threading.Thread(target=self.run) self._stepGate = threading.Event() - # Let us have a DB connection of our own if (Config.getConfig().per_thread_db_connection): # type: ignore - # print("connector_type = {}".format(gConfig.connector_type)) + # print("connector_type = {}".format(Config.getConfig().connector_type)) + tInst = gContainer.defTdeInstance if Config.getConfig().connector_type == 'native': self._dbConn = DbConn.createNative(tInst.getDbTarget()) @@ -963,7 +963,7 @@ class StateMechine: # did not do this when openning connection, and this is NOT the worker # thread, which does this on their own dbc.use(dbName) - if not dbc.hasTables(): # no tables + if not dbc.hasTables(dbName): # no tables Logging.debug("[STT] DB_ONLY found, between {} and {}".format(ts, time.time())) return StateDbOnly() @@ -1434,6 +1434,7 @@ class Task(): # TODO: refactor away, just provide the dbConn def execWtSql(self, wt: WorkerThread, sql): # execute an SQL on the worker thread """ Haha """ + # print("thread %d runing sql is : %s " %(wt._tid , sql) ) return wt.execSql(sql) def queryWtSql(self, wt: WorkerThread, sql): # execute an SQL on the worker thread @@ -1690,6 +1691,9 @@ class TdSuperTable: def getName(self): return self._stName + def getFullTableName(self): + return self._dbName + '.' + self._stName + def drop(self, dbc, skipCheck = False): dbName = self._dbName if self.exists(dbc) : # if myself exists @@ -1701,7 +1705,7 @@ class TdSuperTable: def exists(self, dbc): dbc.execute("USE " + self._dbName) - return dbc.existsSuperTable(self._stName) + return dbc.existsSuperTable(self._dbName, self._stName) # TODO: odd semantic, create() method is usually static? def create(self, dbc, cols: TdColumns, tags: TdTags, dropIfExists = False): @@ -1710,7 +1714,7 @@ class TdSuperTable: dbName = self._dbName dbc.execute("USE " + dbName) fullTableName = dbName + '.' + self._stName - if dbc.existsSuperTable(self._stName): + if dbc.existsSuperTable(dbName, self._stName): if dropIfExists: dbc.execute("DROP TAbLE {}".format(fullTableName)) else: # error @@ -2491,7 +2495,7 @@ class MainExec: action='store', default='native', type=str, - help='Connector type to use: native, rest, or mixed (default: 10)') + help='Connector type to use: native, rest, or mixed (default: native)') parser.add_argument( '-d', '--debug', @@ -2552,7 +2556,7 @@ class MainExec: '-r', '--record-ops', action='store_true', - help='Use a pair of always-fsynced fils to record operations performing + performed, for power-off tests (default: false)') + help='Use a pair of always-fsynced files to record operations performing + performed, for power-off tests (default: false)') parser.add_argument( '-s', '--max-steps', diff --git a/tests/pytest/crash_gen/service_manager.py b/tests/pytest/crash_gen/service_manager.py index 3aa0d00a49844fefbb808ddce4b89b67f37ac10a..780ee7cc607a5da12e0d03c63e0584f9c9ff2bf1 100644 --- a/tests/pytest/crash_gen/service_manager.py +++ b/tests/pytest/crash_gen/service_manager.py @@ -164,6 +164,9 @@ quorum 2 def getExecFile(self): # .../taosd return self._buildDir + "/build/bin/taosd" + + def getAdapterFile(self): # .../taosadapter for restful + return self._buildDir + "/build/bin/taosadapter" def getRunDir(self) -> DirPath : # TODO: rename to "root dir" ?! if Config.getConfig().set_path =='': # use default path @@ -187,6 +190,31 @@ quorum 2 else: # TODO: move "exec -c" into Popen(), we can both "use shell" and NOT fork so ask to lose kill control return ["exec " + self.getExecFile(), '-c', self.getCfgDir()] # used in subproce.Popen() + + def getAdapterCmdLine(self): + REST_PORT_INCREMENT = 11 + Adapter_ports =str(self._port + REST_PORT_INCREMENT) + AdapterCmds = [self.getAdapterFile() + ' --port='+ Adapter_ports + + ' --log.path='+ self.getLogDir() + ' --taosConfigDir='+self.getCfgDir()+ + ' --collectd.enable=false' + + ' --influxdb.enable=false --node_exporter.enable=false' + + ' --opentsdb.enable=false --statsd.enable=false' + + ' --prometheus.enable=false --opentsdb_telnet.enable=false'] # get adapter cmd string + return AdapterCmds + + def start_Adapter(self,cmdLine): + # print('nohup '+' '.join(cmdLine)+ '>>taosadapter.log 2>&1 &') + cmds = 'nohup '+' '.join(cmdLine)+ '>>taosadapter.log 2>&1 &' + ret = Popen( + cmds, + shell=True, + stdout=PIPE, + stderr=PIPE, + ) + time.sleep(0.1) # very brief wait, then let's check if sub process started successfully. + if ret.poll(): + raise CrashGenError("Sub process failed to start with command line: {}".format(cmdLine)) + return ret def _getDnodes(self, dbc): dbc.query("show dnodes") @@ -230,6 +258,10 @@ quorum 2 # self._smThread.start(self.getServiceCmdLine(), self.getLogDir()) # May raise exceptions self._subProcess = TdeSubProcess(self.getServiceCmdLine(), self.getLogDir()) + # run taosadapter by subprocess ,taosadapter is stateless with TDengine ,so it don't need monitor + self.start_Adapter(self.getAdapterCmdLine()) + print(' '.join(self.getAdapterCmdLine())) + def stop(self): self._subProcess.stop() self._subProcess = None diff --git a/tests/pytest/crash_gen/shared/db.py b/tests/pytest/crash_gen/shared/db.py index 75931ace48ed65708c7dfa97d01a426a0baa8203..3effb80ee9045f89943444c57a30be3ba56fc775 100644 --- a/tests/pytest/crash_gen/shared/db.py +++ b/tests/pytest/crash_gen/shared/db.py @@ -100,13 +100,13 @@ class DbConn: # print("dbs = {}, str = {}, ret2={}, type2={}".format(dbs, dbName,ret2, type(dbName))) return dbName in dbs # TODO: super weird type mangling seen, once here - def existsSuperTable(self, stName): - self.query("show stables") + def existsSuperTable(self, dbName, stName): + self.query("show {}.stables".format(dbName)) sts = [v[0] for v in self.getQueryResult()] return stName in sts - def hasTables(self): - return self.query("show tables") > 0 + def hasTables(self, dbName): + return self.query("show {}.tables".format(dbName)) > 0 def execute(self, sql): ''' Return the number of rows affected''' diff --git a/tests/pytest/functions/function_stddev.py b/tests/pytest/functions/function_stddev.py index b9eadeb3443127c927b29fbb16bda4c12378e71a..65aec6ddac4ddd2be86381bad9523897c579301c 100644 --- a/tests/pytest/functions/function_stddev.py +++ b/tests/pytest/functions/function_stddev.py @@ -135,9 +135,9 @@ class TDTestCase: tdSql.execute("insert into std3 values(now + 5s, 4);") tdSql.execute("insert into std3 values(now + 6s, 8);") tdSql.query("select stddev(col1) from stdtable group by loc;") - tdSql.checkData(0, 0, 2.0) + tdSql.checkData(2, 0, 2.0) tdSql.checkData(1, 0, 0.5) - tdSql.checkData(2, 0, 0.5) + tdSql.checkData(0, 0, 0.5) tdSql.execute("create table stdtableint(ts timestamp, col1 int) tags(num int)") tdSql.execute("create table stdint1 using stdtableint tags(1)") diff --git a/tests/pytest/insert/line_insert.py b/tests/pytest/insert/line_insert.py index d95df3a8491f73f7279e583afd446a7182adf823..4c873ec4a4efa6d1877a83d5b3942f5eb990a714 100644 --- a/tests/pytest/insert/line_insert.py +++ b/tests/pytest/insert/line_insert.py @@ -32,9 +32,9 @@ class TDTestCase: tdSql.execute('create stable ste(ts timestamp, f int) tags(t1 bigint)') - lines = [ "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"\"\"a pa,\"s si,t \"\"\",c2=false,c4=4f64 1626006833639000000", + lines = [ "st,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"\\\"\\\"a pa,\\\"s si,t \\\"\\\"\",c2=false,c4=4f64 1626006833639000000", "st,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833640000000", - "ste,t2=5f64,t3=L\"ste\" c1=true,c2=4i64,c3=\" i,\"a \"m,\"\"\" 1626056811823316532", + "ste,t2=5f64,t3=L\"ste\" c1=true,c2=4i64,c3=\" i,\\\"a \\\"m,\\\"\\\"\" 1626056811823316532", "stf,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64,c6=7u64 1626006933640000000", "st,t1=4i64,t2=5f64,t3=\"t4\" c1=3i64,c3=L\"passitagain\",c2=true,c4=5f64 1626006833642000000", "ste,t2=5f64,t3=L\"ste2\" c3=\"iamszhou\",c4=false 1626056811843316532", @@ -147,7 +147,7 @@ class TDTestCase: tdSql.query('select tbname from str') tdSql.checkRows(3) - ###Special Character and keyss + ###Special Character and keys self._conn.schemaless_insert([ "1234,id=3456,abc=4i64,def=3i64 123=3i64,int=2i64,bool=false,into=5f64,column=7u64,!@#$.%^&*()=false 1626006933641", "int,id=and,123=4i64,smallint=5f64,double=5f64,of=3i64,key=L\"passitagin_stf\",!@#$.%^&*()=false abc=false 1626006933654", @@ -193,6 +193,15 @@ class TDTestCase: #tdSql.query('select * from `create`') #tdSql.checkRows(1) + + self._conn.schemaless_insert([ + "sts,t1=abc,t2=ab\"c,t3=ab\\,c,t4=ab\\=c,t5=ab\\ c c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64,c6=\"abc\" 1626006833640000000", + "sts,t1=abc c1=3i64,c2=false,c3=L\"{\\\"date\\\":\\\"2020-01-01 08:00:00.000\\\",\\\"temperature\\\":20}\",c6=\"ab\\\\c\" 1626006833640000000" + ], TDSmlProtocolType.LINE.value, TDSmlTimestampType.NANO_SECOND.value) + + tdSql.query('select tbname from sts') + tdSql.checkRows(2) + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/pytest/query/bug2117.py b/tests/pytest/query/bug2117.py index f637558d79fd49d49380c273ee649865d9d3ec4a..4c910c0d9e2aa33f4ccfa0bc73bf575c35a50e53 100644 --- a/tests/pytest/query/bug2117.py +++ b/tests/pytest/query/bug2117.py @@ -49,13 +49,13 @@ class TDTestCase: tdSql.query('select last(*) from mt0 group by c8') tdSql.checkData(0,3,5) tdSql.checkData(0,4,20) - tdSql.checkData(3,1,92) - tdSql.checkData(3,9,'涛思8') + tdSql.checkData(3,1,57) + tdSql.checkData(3,9,'涛思14') tdSql.query('select last(*) from mt0 group by c9') tdSql.checkData(0,3,0) tdSql.checkData(0,8,'taos38') - tdSql.checkData(40,1,83) - tdSql.checkData(40,3,40) + tdSql.checkData(35,1,83) + tdSql.checkData(35,3,40) def stop(self): tdSql.close() diff --git a/tests/pytest/query/bug2143.py b/tests/pytest/query/bug2143.py index c28abba53503cbd8c35531c44ca2bd698b2c2d03..48ac5c82698b33103845872f431162216ec16ee3 100644 --- a/tests/pytest/query/bug2143.py +++ b/tests/pytest/query/bug2143.py @@ -51,19 +51,19 @@ class TDTestCase: tdSql.checkRows(0) tdSql.query('select max(c1),min(c1),first(c1),last(c1) from mt0 group by c3 limit 70 offset 3') tdSql.checkRows(38) - tdSql.query('select max(c1),min(c1),first(c1),last(c1) from mt0 group by c8 limit 3 offset 2') + tdSql.query('select max(c1),min(c1),first(c1),last(c1) from mt0 group by c8 limit 3 offset 12') tdSql.checkData(0,0,91) tdSql.checkData(0,1,2) tdSql.checkData(0,2,2) tdSql.checkData(0,3,91) - tdSql.checkData(1,0,92) - tdSql.checkData(2,1,4) - tdSql.query('select max(c1),min(c1),first(c1),last(c1) from mt0 group by c9 limit 2 offset 9') - tdSql.checkData(0,0,96) - tdSql.checkData(0,1,1) - tdSql.checkData(0,2,9) - tdSql.checkData(0,3,93) - tdSql.checkData(1,0,97) + tdSql.checkData(1,0,94) + tdSql.checkData(2,1,7) + tdSql.query('select max(c1),min(c1),first(c1),last(c1) from mt0 group by c9 limit 2 offset 39') + tdSql.checkData(1,0,96) + tdSql.checkData(1,1,1) + tdSql.checkData(1,2,9) + tdSql.checkData(0,3,92) + tdSql.checkData(0,0,95) def stop(self): tdSql.close() diff --git a/tests/pytest/query/filterOtherTypes.py b/tests/pytest/query/filterOtherTypes.py index 7d62f2502eaf7ef5e2591adadb1628a618233628..eb7539b874a5e7a523d44068a016d305baccad3b 100644 --- a/tests/pytest/query/filterOtherTypes.py +++ b/tests/pytest/query/filterOtherTypes.py @@ -303,11 +303,11 @@ class TDTestCase: tdSql.checkRows(10) # > for binary type on tag - tdSql.query("select * from st where tagcol3 > '表'") + tdSql.query("select * from st where tagcol3 < '表'") tdSql.checkRows(10) # >= for binary type on tag - tdSql.query("select * from st where tagcol3 >= '表'") + tdSql.query("select * from st where tagcol3 <= '表'") tdSql.checkRows(10) # = for binary type on tag diff --git a/tests/pytest/query/nestedQuery/nestedQuery_datacheck.py b/tests/pytest/query/nestedQuery/nestedQuery_datacheck.py index 311133b8c8911c1d9d8fe90fd5e556571f8e9548..20452cd886932169836964f6e816e66cdb9daf0c 100755 --- a/tests/pytest/query/nestedQuery/nestedQuery_datacheck.py +++ b/tests/pytest/query/nestedQuery/nestedQuery_datacheck.py @@ -619,8 +619,11 @@ class TDTestCase: sql += "%s )" % random.choice(t_join_where) datacheck = self.stable_join_checkall_0(sql) tdSql.checkRows(100) - datacheck = self.stable_join_checkall_100(sql) - + datacheck = self.stable_join_checkall_100(sql) + + # for TD-14342 + sql = "select * from ( select * from stable_1 ) where t_nchar like 'nchar%' or t_nchar = '0'" + datacheck = self.stable1_checkall_0(sql) endTime = time.time() print("total time %ds" % (endTime - startTime)) diff --git a/tests/pytest/query/query.py b/tests/pytest/query/query.py index 31831cca9facea6aba1a6fc88a84a33a66583a5e..b581f30c245a87f9b845f7f0b01f034729da3ab7 100644 --- a/tests/pytest/query/query.py +++ b/tests/pytest/query/query.py @@ -198,6 +198,28 @@ class TDTestCase: tdLog.info("case for TS-636") self.escape_ascii() + # TS-1304 + tdLog.info("case for JIRA TS-1304") + tdSql.execute("create stable devices (ts timestamp,tempature int,humity float,`1name` int ) tags (`1devid` int,devname binary(20))") + tdSql.execute("insert into devices_001 using devices tags (111,'zzm') values (now,10001,1,1)") + tdSql.execute("insert into devices_001 using devices tags (222,'cxd') values (now + 1s,10002,2,2)") + tdSql.execute("insert into devices_001 using devices tags (333,'cyt') values (now + 2s,10002,2,2)") + + tdSql.error("select 1name from devices") + tdSql.error("select 1name from devices_001") + tdSql.error("select 1devid from devices") + tdSql.error("select 1devid from devices_001") + + tdSql.query("select `1name` from devices_001") + tdSql.checkRows(3) + tdSql.checkData(0, 0, 1) + tdSql.checkData(1, 0, 2) + tdSql.checkData(2, 0, 2) + + tdSql.query("select `1devid` from devices_001") + tdSql.checkRows(1) + tdSql.checkData(0, 0, 111) + def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/pytest/query/querySort.py b/tests/pytest/query/querySort.py index a50b9cbf8afd7052a78e1f6ef85b8c464e816e71..8abec6cea1e405d519b197f6021cd4dec6b3ca50 100644 --- a/tests/pytest/query/querySort.py +++ b/tests/pytest/query/querySort.py @@ -18,6 +18,8 @@ from util.cases import * from util.sql import * import numpy as np +# constant define +WAITS = 5 # wait seconds class TDTestCase: def init(self, conn, logSql): @@ -67,9 +69,7 @@ class TDTestCase: "%s failed: sql:%s, the order provided for col:%d is not correct" % (callerFilename, tdSql.sql, col)) - def run(self): - tdSql.prepare() - + def test_base(self): print("======= step 1: create table and insert data =========") tdLog.debug( ''' create table st(ts timestamp, tbcol1 tinyint, tbcol2 smallint, tbcol3 int, tbcol4 bigint, tbcol5 float, tbcol6 double, @@ -183,6 +183,44 @@ class TDTestCase: tdSql.close() tdLog.success("%s successfully executed" % __file__) + def create_insert_data(self): + sql = "create table sb(ts timestamp, i1 int) tags(t_b1 binary(32), t_n1 nchar(64));" + tdSql.execute(sql) + for i in range(20): + value = "%s%s%s" % (chr(64+i),chr(64+i),chr(65+i)) + if i%10 == 5: + value += "_%s" % (chr(66+i)) + if i%10 == 0: + value += "_%s" % (chr(67+i)) + sql = "insert into b%d using sb tags('A%s', 'B%s') values(now, %d);"%(i, value, value, i+1000) + tdSql.execute(sql) + + def test_groupby_order(self): + # create and insert data + print("======= group order step 1: create table and insert data =========") + self.create_insert_data() + + # do query + print("======= group order step 2: do query =========") + # ASC + sql = "select count(*) from sb group by t_b1 order by t_b1 asc;" + tdSql.execute(sql) + tdSql.waitedQuery(sql, 20, WAITS) + tdSql.checkData(0, 1, "A@@A_C") + tdSql.checkData(5, 1, "AEEF_G") + tdSql.checkData(19, 1, "ASST") + #DESC + sql = "select count(*) from sb group by t_b1 order by t_b1 desc;" + tdSql.execute(sql) + tdSql.waitedQuery(sql, 20, WAITS) + tdSql.checkData(19, 1, "A@@A_C") + tdSql.checkData(4, 1, "AOOP_Q") + tdSql.checkData(0, 1, "ASST") + + def run(self): + tdSql.prepare() + self.test_base() + self.test_groupby_order() tdCases.addWindows(__file__, TDTestCase()) tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/table/create.py b/tests/pytest/table/create.py index a1eee6be63980504742b35d22b0035d56ad077fb..4bd630f4c00d70df857d81bfe97d6aab85398ec3 100644 --- a/tests/pytest/table/create.py +++ b/tests/pytest/table/create.py @@ -106,9 +106,9 @@ class TDTestCase: tdSql.query("select _block_dist() from db.`%s` ; " %self.stb1) tdSql.checkRows(0) - tdSql.query("show create stable db.`%s` ; " %self.stb1) + tdSql.query("show create table db.`%s` ; " %self.stb1) tdSql.checkData(0, 0, self.stb1) - tdSql.checkData(0, 1, "create table `%s` (ts TIMESTAMP,i INT) TAGS (j INT)" %self.stb1) + tdSql.checkData(0, 1, "CREATE TABLE `%s` (`ts` TIMESTAMP,`i` INT) TAGS (`j` INT)" %self.stb1) tdSql.execute("create table db.`table!1` using db.`%s` tags(1)" %self.stb1) tdSql.query("describe db.`table!1` ; ") @@ -221,7 +221,7 @@ class TDTestCase: tdSql.query("show create stable `%s` ; " %self.stb2) tdSql.checkData(0, 0, self.stb2) - tdSql.checkData(0, 1, "create table `%s` (ts TIMESTAMP,i INT) TAGS (j INT)" %self.stb2) + tdSql.checkData(0, 1, "CREATE TABLE `%s` (`ts` TIMESTAMP,`i` INT) TAGS (`j` INT)" %self.stb2) tdSql.execute("create table `table!2` using `%s` tags(1)" %self.stb2) tdSql.query("describe `table!2` ; ") @@ -310,7 +310,7 @@ class TDTestCase: tdSql.query("show create table `%s` ; " %self.regular_table) tdSql.checkData(0, 0, self.regular_table) - tdSql.checkData(0, 1, "CREATE TABLE `%s` (ts TIMESTAMP,i INT)" %self.regular_table) + tdSql.checkData(0, 1, "CREATE TABLE `%s` (`ts` TIMESTAMP,`i` INT)" %self.regular_table) tdSql.execute("insert into `%s` values(now, 1)" %self.regular_table) tdSql.query("select * from `%s` ; " %self.regular_table) @@ -341,7 +341,12 @@ class TDTestCase: tdSql.error("select * from `%s`" %self.regular_table) - + # TS-1366 + tdSql.execute("create table meters(ts timestamp, c1 int) tags(t1 int, t2 tinyint unsigned, t3 smallint unsigned, t4 int unsigned, t5 bigint unsigned, t6 int)") + tdSql.execute("create table meter1 using meters tags(1, 2, 3, 4, 5, 6)") + + tdSql.query("show create table meter1") + tdSql.checkData(0, 1, "CREATE TABLE `meter1` USING `meters` TAGS (1,2,3,4,5,6)") def stop(self): diff --git a/tests/pytest/test.py b/tests/pytest/test.py index 1c6022fe2bbd847c95d561e1258a2f0f9b7533e8..a65d58edd4d6635471b311b35046328fd9c1dbf1 100644 --- a/tests/pytest/test.py +++ b/tests/pytest/test.py @@ -150,15 +150,22 @@ if __name__ == "__main__": numOfNodes = ucase.updatecfgDict.get('numOfNodes') cluster.init(numOfNodes, dataDir) cluster.prepardBuild() - + + startArbitrator = False + arbitratorHost = "tdnode1" for i in range(numOfNodes): if ucase.updatecfgDict.get('%d' % (i + 1)) != None: config = dict (ucase.updatecfgDict.get('%d' % (i + 1))) print(config) for key, value in config.items(): - print(key, value, i + 1) - cluster.cfg(key, value, i + 1) + if key == "arbitrator": + startArbitrator = True + arbitratorHost = value + cluster.cfg(key, value, i + 1) cluster.run() + if startArbitrator: + hostname=value.split(":")[0] + cluster.startArbitrator(hostname) conn = cluster.conn except Exception as e: print(e.args) diff --git a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestInsertTime_step.py b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestInsertTime_step.py index 36221e4b7ff21b82ccf72451cfea8472952b622d..61ed052c6b33e1e4400136374c92d9f6a5109c00 100644 --- a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestInsertTime_step.py +++ b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestInsertTime_step.py @@ -24,7 +24,7 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -32,26 +32,29 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath() + if (binPath == "taosBenchmark"): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) + + # insert: create one or mutiple tables per sql and insert multiple + # rows per sql - # insert: create one or mutiple tables per sql and insert multiple rows per sql - # check the params of taosdemo about time_step is nano - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoInsertNanoDB.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoInsertNanoDB.json -y " % + binPath) tdSql.execute("use testdb1") tdSql.query("show stables") tdSql.checkData(0, 4, 100) @@ -63,12 +66,14 @@ class TDTestCase: tdSql.checkData(0, 0, 10000) tdSql.query("describe stb0") tdSql.getData(9, 1) - tdSql.checkDataType(9, 1,"TIMESTAMP") + tdSql.checkDataType(9, 1, "TIMESTAMP") tdSql.query("select last(ts) from stb0") - tdSql.checkData(0, 0,"2021-07-01 00:00:00.000099000") + tdSql.checkData(0, 0, "2021-07-01 00:00:00.000099000") # check the params of taosdemo about time_step is us - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoInsertUSDB.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoInsertUSDB.json -y " % + binPath) tdSql.execute("use testdb2") tdSql.query("show stables") tdSql.checkData(0, 4, 100) @@ -80,12 +85,14 @@ class TDTestCase: tdSql.checkData(0, 0, 10000) tdSql.query("describe stb0") tdSql.getData(9, 1) - tdSql.checkDataType(9, 1,"TIMESTAMP") + tdSql.checkDataType(9, 1, "TIMESTAMP") tdSql.query("select last(ts) from stb0") - tdSql.checkData(0, 0,"2021-07-01 00:00:00.099000") + tdSql.checkData(0, 0, "2021-07-01 00:00:00.099000") # check the params of taosdemo about time_step is ms - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoInsertMSDB.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoInsertMSDB.json -y " % + binPath) tdSql.execute("use testdb3") tdSql.query("show stables") tdSql.checkData(0, 4, 100) @@ -96,15 +103,12 @@ class TDTestCase: tdSql.query("select count(*) from stb0") tdSql.checkData(0, 0, 10000) tdSql.query("describe stb0") - tdSql.checkDataType(9, 1,"TIMESTAMP") + tdSql.checkDataType(9, 1, "TIMESTAMP") tdSql.query("select last(ts) from stb0") - tdSql.checkData(0, 0,"2021-07-01 00:01:39.000") + tdSql.checkData(0, 0, "2021-07-01 00:01:39.000") - os.system("rm -rf ./res.txt") os.system("rm -rf ./*.py.sql") - - def stop(self): tdSql.close() diff --git a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoInsert.py b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoInsert.py index f6928dffefde2420969492c2160456297d99e8bf..8329b82076b598a6d35d6d65edce60fd38a4d72b 100644 --- a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoInsert.py +++ b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoInsert.py @@ -12,7 +12,8 @@ # -*- coding: utf-8 -*- import sys -import os, time +import os +import time from util.log import * from util.cases import * from util.sql import * @@ -24,7 +25,7 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -32,28 +33,28 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) # insert: create one or mutiple tables per sql and insert multiple rows per sql # insert data from a special timestamp # check stable stb0 os.system( - "%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabase.json -y " % + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabase.json -y " % binPath) tdSql.execute("use nsdb") tdSql.query("show stables") @@ -88,7 +89,7 @@ class TDTestCase: # check stable stb0 os.system( - "%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseNow.json -y " % + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseNow.json -y " % binPath) tdSql.execute("use nsdb2") @@ -107,9 +108,8 @@ class TDTestCase: # insert by csv files and timetamp is long int , strings in ts and # cols - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabasecsv.json -y " % + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabasecsv.json -y " % binPath) tdSql.execute("use nsdbcsv") tdSql.query("show stables") @@ -133,7 +133,7 @@ class TDTestCase: # taosdemo test insert with command and parameter , detals show # taosdemo --help os.system( - "%staosBenchmark -u root -ptaosdata -P 6030 -a 1 -m pre -n 10 -T 20 -t 60 -o res.txt -y " % + "%s -u root -ptaosdata -P 6030 -a 1 -m pre -n 10 -T 20 -t 60 -o res.txt -y " % binPath) tdSql.query("select count(*) from test.meters") tdSql.checkData(0, 0, 600) diff --git a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuery.py b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuery.py index 137cbe724310260254591c874e7bc0362f1e7f2f..19e8e9263f654ffe9006052a7e28fb137db94e34 100644 --- a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuery.py +++ b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuery.py @@ -1,4 +1,4 @@ -''################################################################### +'' # Copyright (c) 2016 by TAOS Technologies, Inc. # All rights reserved. # @@ -24,7 +24,7 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -32,70 +32,77 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) - # query: query test for nanoSecond with where and max min groupby order - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabase.json -y " % binPath) + # query: query test for nanoSecond with where and max min groupby order + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabase.json -y " % + binPath) tdSql.execute("use nsdb") - # use where to filter - - tdSql.query("select count(*) from stb0 where ts>\"2021-07-01 00:00:00.590000000 \" ") + # use where to filter + + tdSql.query( + "select count(*) from stb0 where ts>\"2021-07-01 00:00:00.590000000 \" ") tdSql.checkData(0, 0, 4000) - tdSql.query("select count(*) from stb0 where ts>\"2021-07-01 00:00:00.000000000\" and ts <=\"2021-07-01 00:00:00.590000000\" ") + tdSql.query( + "select count(*) from stb0 where ts>\"2021-07-01 00:00:00.000000000\" and ts <=\"2021-07-01 00:00:00.590000000\" ") tdSql.checkData(0, 0, 5900) - tdSql.query("select count(*) from tb0_0 where ts>\"2021-07-01 00:00:00.590000000 \" ;") + tdSql.query( + "select count(*) from tb0_0 where ts>\"2021-07-01 00:00:00.590000000 \" ;") tdSql.checkData(0, 0, 40) - tdSql.query("select count(*) from tb0_0 where ts>\"2021-07-01 00:00:00.000000000\" and ts <=\"2021-07-01 00:00:00.590000000\" ") + tdSql.query( + "select count(*) from tb0_0 where ts>\"2021-07-01 00:00:00.000000000\" and ts <=\"2021-07-01 00:00:00.590000000\" ") tdSql.checkData(0, 0, 59) - # select max min avg from special col tdSql.query("select max(c10) from stb0;") - print("select max(c10) from stb0 : " , tdSql.getData(0, 0)) + print("select max(c10) from stb0 : ", tdSql.getData(0, 0)) tdSql.query("select max(c10) from tb0_0;") - print("select max(c10) from tb0_0 : " , tdSql.getData(0, 0)) - + print("select max(c10) from tb0_0 : ", tdSql.getData(0, 0)) tdSql.query("select min(c1) from stb0;") - print( "select min(c1) from stb0 : " , tdSql.getData(0, 0)) + print("select min(c1) from stb0 : ", tdSql.getData(0, 0)) tdSql.query("select min(c1) from tb0_0;") - print( "select min(c1) from tb0_0 : " , tdSql.getData(0, 0)) + print("select min(c1) from tb0_0 : ", tdSql.getData(0, 0)) tdSql.query("select avg(c1) from stb0;") - print( "select avg(c1) from stb0 : " , tdSql.getData(0, 0)) + print("select avg(c1) from stb0 : ", tdSql.getData(0, 0)) tdSql.query("select avg(c1) from tb0_0;") - print( "select avg(c1) from tb0_0 : " , tdSql.getData(0, 0)) + print("select avg(c1) from tb0_0 : ", tdSql.getData(0, 0)) tdSql.query("select count(*) from stb0 group by tbname;") tdSql.checkData(0, 0, 100) tdSql.checkData(10, 0, 100) - # query : query above sqls by taosdemo and continuously - - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuery.json -y " % binPath) + # query : query above sqls by taosdemo and continuously + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuery.json -y " % + binPath) - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabasecsv.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabasecsv.json -y " % + binPath) tdSql.execute("use nsdbcsv") tdSql.query("show stables") tdSql.checkData(0, 4, 100) @@ -103,24 +110,37 @@ class TDTestCase: tdSql.checkData(0, 0, 10000) tdSql.query("describe stb0") tdSql.checkDataType(3, 1, "TIMESTAMP") - tdSql.query("select count(*) from stb0 where ts >\"2021-07-01 00:00:00.490000000\"") + tdSql.query( + "select count(*) from stb0 where ts >\"2021-07-01 00:00:00.490000000\"") tdSql.checkData(0, 0, 5000) tdSql.query("select count(*) from stb0 where ts 162687012800000000') - tdSql.execute('select count(*) from stb0 where c2 < 162687012800000000') - tdSql.execute('select count(*) from stb0 where c2 = 162687012800000000') - tdSql.execute('select count(*) from stb0 where c2 != 162687012800000000') - tdSql.execute('select count(*) from stb0 where c2 <> 162687012800000000') - tdSql.execute('select count(*) from stb0 where c2 > "2021-07-21 20:22:08.248246976"') - tdSql.execute('select count(*) from stb0 where c2 < "2021-07-21 20:22:08.248246976"') - tdSql.execute('select count(*) from stb0 where c2 = "2021-07-21 20:22:08.248246976"') - tdSql.execute('select count(*) from stb0 where c2 != "2021-07-21 20:22:08.248246976"') - tdSql.execute('select count(*) from stb0 where c2 <> "2021-07-21 20:22:08.248246976"') - tdSql.execute('select count(*) from stb0 where ts between "2021-07-01 00:00:00.000000000" and "2021-07-01 00:00:00.990000000"') - tdSql.execute('select count(*) from stb0 where ts between 1625068800000000000 and 1625068801000000000') + tdSql.execute( + 'select count(*) from stb0 where c2 > 162687012800000000') + tdSql.execute( + 'select count(*) from stb0 where c2 < 162687012800000000') + tdSql.execute( + 'select count(*) from stb0 where c2 = 162687012800000000') + tdSql.execute( + 'select count(*) from stb0 where c2 != 162687012800000000') + tdSql.execute( + 'select count(*) from stb0 where c2 <> 162687012800000000') + tdSql.execute( + 'select count(*) from stb0 where c2 > "2021-07-21 20:22:08.248246976"') + tdSql.execute( + 'select count(*) from stb0 where c2 < "2021-07-21 20:22:08.248246976"') + tdSql.execute( + 'select count(*) from stb0 where c2 = "2021-07-21 20:22:08.248246976"') + tdSql.execute( + 'select count(*) from stb0 where c2 != "2021-07-21 20:22:08.248246976"') + tdSql.execute( + 'select count(*) from stb0 where c2 <> "2021-07-21 20:22:08.248246976"') + tdSql.execute( + 'select count(*) from stb0 where ts between "2021-07-01 00:00:00.000000000" and "2021-07-01 00:00:00.990000000"') + tdSql.execute( + 'select count(*) from stb0 where ts between 1625068800000000000 and 1625068801000000000') tdSql.query('select avg(c0) from stb0 interval(5000000000b)') tdSql.checkRows(1) @@ -136,17 +156,17 @@ class TDTestCase: tdSql.query('select avg(c0) from stb0 interval(1u)') tdSql.checkRows(100) - tdSql.query('select avg(c0) from stb0 interval(100000000b) sliding (100000000b)') + tdSql.query( + 'select avg(c0) from stb0 interval(100000000b) sliding (100000000b)') tdSql.checkRows(10) # query : query above sqls by taosdemo and continuously - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuerycsv.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoQuerycsv.json -y " % + binPath) os.system("rm -rf ./query_res*.txt*") os.system("rm -rf tools/taosdemoAllTest/NanoTestCase/*.py.sql") - - - def stop(self): tdSql.close() diff --git a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanosubscribe.py b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanosubscribe.py index f3cd4fb8333b37c55d5f1cf7a74adcabdfcde686..aa1f98edc104b4c829b9682420aba6ca7e7d095e 100644 --- a/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanosubscribe.py +++ b/tests/pytest/tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanosubscribe.py @@ -26,8 +26,8 @@ class TDTestCase: def init(self, conn, logSql): tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): + + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -35,96 +35,104 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] # get the number of subscriptions - def subTimes(self,filename): + def subTimes(self, filename): self.filename = filename - command = 'cat %s |wc -l'% filename - times = int(subprocess.getstatusoutput(command)[1]) + command = 'cat %s |wc -l' % filename + times = int(subprocess.getstatusoutput(command)[1]) return times - + # assert results - def assertCheck(self,filename,subResult,expectResult): + def assertCheck(self, filename, subResult, expectResult): self.filename = filename self.subResult = subResult self.expectResult = expectResult args0 = (filename, subResult, expectResult) print("Queryfile:%s ,result is %s != expect: %s" % args0) - assert subResult == expectResult , "Queryfile:%s ,result is %s != expect: %s" % args0 + assert subResult == expectResult, "Queryfile:%s ,result is %s != expect: %s" % args0 def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) # clear envs - os.system("ps -aux |grep 'taosdemoAllTest/taosdemoTestSupportNanoSubscribe.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") - os.system("ps -aux |grep 'tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseInsertForSub.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") - os.system("rm -rf ./subscribe_res*") - os.system("rm -rf ./all_subscribe_res*") + os.system( + "ps -aux |grep 'taosdemoAllTest/taosdemoTestSupportNanoSubscribe.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") + os.system( + "ps -aux |grep 'tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseInsertForSub.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") + os.system("rm -rf ./subscribe_res*") + os.system("rm -rf ./all_subscribe_res*") # insert data - os.system("%staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseInsertForSub.json" % binPath) + os.system( + "%s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseInsertForSub.json" % + binPath) tdSql.query("select count(*) from subnsdb.stb0") - tdSql.checkData(0,0,100) - - os.system(" nohup %staosBenchmark -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoSubscribe.json & >/dev/null 2>&1" % binPath) + tdSql.checkData(0, 0, 100) + + os.system( + " nohup %s -f tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoSubscribe.json & >/dev/null 2>&1" % + binPath) sleep(3) print('taosBenchmark query done!') - + # merge result files - + os.system("cat subscribe_res0.txt* > all_subscribe_res0.txt") os.system("cat subscribe_res1.txt* > all_subscribe_res1.txt") os.system("cat subscribe_res2.txt* > all_subscribe_res2.txt") sleep(5) - + # check subscribeTimes testcase subTimes0 = self.subTimes("all_subscribe_res0.txt") - self.assertCheck("all_subscribe_res0.txt",subTimes0 ,200) + self.assertCheck("all_subscribe_res0.txt", subTimes0, 200) subTimes1 = self.subTimes("all_subscribe_res1.txt") - self.assertCheck("all_subscribe_res1.txt",subTimes1 ,200) + self.assertCheck("all_subscribe_res1.txt", subTimes1, 200) subTimes2 = self.subTimes("all_subscribe_res2.txt") - self.assertCheck("all_subscribe_res2.txt",subTimes2 ,200) - + self.assertCheck("all_subscribe_res2.txt", subTimes2, 200) - # insert extral data + # insert extral data tdSql.execute("use subnsdb") - tdSql.execute("insert into tb0_0 values(now,100.1000,'subtest1',now-1s)") - sleep(5) + tdSql.execute( + "insert into tb0_0 values(now,100.1000,'subtest1',now-1s)") + sleep(5) os.system("cat subscribe_res0.txt* > all_subscribe_res0.txt") subTimes0 = self.subTimes("all_subscribe_res0.txt") - self.assertCheck("all_subscribe_res0.txt",subTimes0 ,202) + self.assertCheck("all_subscribe_res0.txt", subTimes0, 202) sleep(3) - os.system("rm -rf ./subscribe_res*") + os.system("rm -rf ./subscribe_res*") os.system("rm -rf ./all_subscribe*") os.system("rm -rf ./*.py.sql") os.system("rm -rf ./nohup*") - os.system("ps -aux |grep 'taosdemoAllTest/taosdemoTestSupportNanoSubscribe.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") - os.system("ps -aux |grep 'tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoSubscribe.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") - os.system("ps -aux |grep 'tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseInsertForSub.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") - + os.system( + "ps -aux |grep 'taosdemoAllTest/taosdemoTestSupportNanoSubscribe.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") + os.system( + "ps -aux |grep 'tools/taosdemoAllTest/NanoTestCase/taosdemoTestSupportNanoSubscribe.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") + os.system( + "ps -aux |grep 'tools/taosdemoAllTest/NanoTestCase/taosdemoTestNanoDatabaseInsertForSub.json' |awk '{print $2}'|xargs kill -9 >/dev/null 2>&1") def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) + tdCases.addWindows(__file__, TDTestCase()) tdCases.addLinux(__file__, TDTestCase()) - diff --git a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo.py b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo.py deleted file mode 100644 index 8f28f214090dd4ac528e3408ae133da3ed67c545..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo.py +++ /dev/null @@ -1,185 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import taos -import time -import os -from util.log import tdLog -from util.cases import tdCases -from util.sql import tdSql - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - os.system("rm -rf tools/taosdemoAllTest/TD-10539/create_taosdemo.py.sql") - tdSql.prepare() - - #print("==============taosdemo,#create stable,table; insert table; show table; select table; drop table") - self.tsdemo = "tsdemo~!.@#$%^*[]-_=+{,?.}" - #this escape character is not support in shell . include & () <> | / - os.system("%staosBenchmark -d test -E -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) - tdSql.execute("use test ;" ) - tdSql.query("select count(*) from meters") - tdSql.checkData(0, 0, 1000) - tdSql.query("show test.tables like 'tsdemo%'" ) - tdSql.checkRows(10) - tdSql.query("show test.tables like '%s_'" %self.tsdemo) - tdSql.checkRows(10) - tdSql.query("select _block_dist() from `%s1`" %self.tsdemo) - tdSql.checkRows(1) - tdSql.query("describe test.`%s1` ; " %self.tsdemo) - tdSql.checkRows(13) - tdSql.query("show create table test.`%s1` ; " %self.tsdemo) - tdSql.checkData(0, 0, self.tsdemo+str(1)) - tdSql.checkData(0, 1, "CREATE TABLE `%s1` USING `meters` TAGS (1,\"beijing\")" %self.tsdemo) - - print("==============drop table\stable") - try: - tdSql.execute("drop table test.`%s1` ; " %self.tsdemo) - except Exception as e: - tdLog.exit(e) - - tdSql.error("select * from test.`%s1` ; " %self.tsdemo) - tdSql.query("show test.tables like '%s_'" %self.tsdemo) - tdSql.checkRows(9) - - try: - tdSql.execute("drop table test.meters ") - except Exception as e: - tdLog.exit(e) - - tdSql.error("select * from test.meters ") - tdSql.error("select * from test.`%s2` ; " %self.tsdemo) - - # Exception - os.system("%staosBenchmark -d test -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) - tdSql.query("show test.tables ") - tdSql.checkRows(0) - - #print("==============taosdemo,#create regular table; insert table; show table; select table; drop table") - self.tsdemo = "tsdemo~!.@#$%^*[]-_=+{,?.}" - #this escape character is not support in shell . include & () <> | / - os.system("%staosBenchmark -N -E -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) - tdSql.execute("use test ;" ) - tdSql.query("select count(*) from `%s1`" %self.tsdemo) - tdSql.checkData(0, 0, 100) - tdSql.query("show test.tables like 'tsdemo%'" ) - tdSql.checkRows(10) - tdSql.query("show test.tables like '%s_'" %self.tsdemo) - tdSql.checkRows(10) - tdSql.query("select _block_dist() from `%s1`" %self.tsdemo) - tdSql.checkRows(1) - tdSql.query("describe test.`%s1` ; " %self.tsdemo) - tdSql.checkRows(11) - tdSql.query("show create table test.`%s1` ; " %self.tsdemo) - tdSql.checkData(0, 0, self.tsdemo+str(1)) - tdSql.checkData(0, 1, "CREATE TABLE `%s1` (ts TIMESTAMP,c0 FLOAT,c1 INT,c2 FLOAT,c3 INT,c4 INT,c5 INT,c6 INT,c7 INT,c8 INT,c9 INT)" %self.tsdemo) - - print("==============drop table\stable") - try: - tdSql.execute("drop table test.`%s1` ; " %self.tsdemo) - except Exception as e: - tdLog.exit(e) - - tdSql.error("select * from test.`%s1` ; " %self.tsdemo) - tdSql.query("show test.tables like '%s_'" %self.tsdemo) - tdSql.checkRows(9) - - # Exception - os.system("%staosBenchmark -N -m %s -t 10 -n 100 -l 10 -y " % (binPath,self.tsdemo)) - tdSql.query("show test.tables ") - tdSql.checkRows(0) - - - #print("==============taosdemo——json_yes,#create stable,table; insert table; show table; select table; drop table") - os.system("%staosBenchmark -f tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json -y " % binPath) - tdSql.execute("use dbyes") - - self.tsdemo_stable = "tsdemo_stable~!.@#$%^*[]-_=+{,?.}" - self.tsdemo = "tsdemo~!.@#$%^*[]-_=+{,?.}" - - tdSql.query("select count(*) from dbyes.`%s`" %self.tsdemo_stable) - tdSql.checkData(0, 0, 1000) - tdSql.query("show dbyes.tables like 'tsdemo%'" ) - tdSql.checkRows(10) - tdSql.query("show dbyes.tables like '%s_'" %self.tsdemo) - tdSql.checkRows(10) - tdSql.query("select _block_dist() from `%s1`" %self.tsdemo) - tdSql.checkRows(1) - tdSql.query("describe dbyes.`%s1` ; " %self.tsdemo) - tdSql.checkRows(13) - tdSql.query("show create table dbyes.`%s1` ; " %self.tsdemo) - tdSql.checkData(0, 0, self.tsdemo+str(1)) - tdSql.checkData(0, 1, "CREATE TABLE `%s1` USING `%s` TAGS (1,1)" %(self.tsdemo,self.tsdemo_stable)) - - print("==============drop table\stable") - try: - tdSql.execute("drop table dbyes.`%s1` ; " %self.tsdemo) - except Exception as e: - tdLog.exit(e) - - tdSql.error("select * from dbyes.`%s1` ; " %self.tsdemo) - tdSql.query("show dbyes.tables like '%s_'" %self.tsdemo) - tdSql.checkRows(9) - - try: - tdSql.execute("drop table dbyes.`%s` ; " %self.tsdemo_stable) - except Exception as e: - tdLog.exit(e) - - tdSql.error("select * from dbyes.`%s` ; " %self.tsdemo_stable) - tdSql.error("select * from dbyes.`%s2` ; " %self.tsdemo) - - #print("==============taosdemo——json_no,#create stable,table; insert table; show table; select table; drop table") - - os.system("%staosBenchmark -f tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json -y " % binPath) - tdSql.query("show dbno.tables;") - tdSql.checkRows(0) - - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json deleted file mode 100644 index 759a437b448c8c65bf252e859345dd9557cc51c5..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_no.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "filetype": "insert", - "cfgdir": "/etc/taos", - "host": "127.0.0.1", - "port": 6030, - "user": "root", - "password": "taosdata", - "thread_count": 10, - "thread_count_create_tbl": 10, - "result_file": "./insert_res.txt", - "confirm_parameter_prompt": "no", - "insert_interval": 0, - "interlace_rows": 10, - "num_of_records_per_req": 1, - "max_sql_len": 1024000, - "databases": [{ - "dbinfo": { - "name": "dbno", - "drop": "yes", - "replica": 1, - "days": 10, - "cache": 50, - "blocks": 8, - "precision": "ms", - "keep": 36500, - "minRows": 100, - "maxRows": 4096, - "comp":2, - "walLevel":1, - "cachelast":0, - "quorum":1, - "fsync":3000, - "update": 0 - }, - "super_tables": [{ - "name": "meters", - "child_table_exists":"no", - "childtable_count": 10, - "childtable_prefix": "tsdemo~!.@#$%^*[]-_=+{,?.}", - "escape_character": "no", - "auto_create_table": "no", - "batch_create_tbl_num": 1, - "data_source": "rand", - "insert_mode": "taosc", - "insert_rows": 100, - "childtable_limit": 0, - "childtable_offset":0, - "multi_thread_write_one_tbl": "no", - "interlace_rows": 0, - "insert_interval":0, - "max_sql_len": 1024000, - "disorder_ratio": 0, - "disorder_range": 1000, - "timestamp_step": 1, - "start_timestamp": "2020-10-01 00:00:00.000", - "sample_format": "csv", - "sample_file": "", - "tags_file": "", - "columns": [{"type": "INT","count":9}, {"type": "BINARY", "len": 16, "count":1}], - "tags": [{"type": "INT", "count":2}] - }] - }] -} diff --git a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json b/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json deleted file mode 100644 index aafc79215fc0b94d037da3a9b229a2f967b51613..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/TD-10539/create_taosdemo_yes.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "filetype": "insert", - "cfgdir": "/etc/taos", - "host": "127.0.0.1", - "port": 6030, - "user": "root", - "password": "taosdata", - "thread_count": 5, - "thread_count_create_tbl": 10, - "result_file": "./insert_res.txt", - "confirm_parameter_prompt": "no", - "insert_interval": 0, - "interlace_rows": 10, - "num_of_records_per_req": 1, - "max_sql_len": 1024000, - "databases": [{ - "dbinfo": { - "name": "dbyes", - "drop": "yes", - "replica": 1, - "days": 10, - "cache": 50, - "blocks": 8, - "precision": "ms", - "keep": 36500, - "minRows": 100, - "maxRows": 4096, - "comp":2, - "walLevel":1, - "cachelast":0, - "quorum":1, - "fsync":3000, - "update": 0 - }, - "super_tables": [{ - "name": "tsdemo_stable~!.@#$%^*[]-_=+{,?.}", - "child_table_exists":"no", - "childtable_count": 10, - "childtable_prefix": "tsdemo~!.@#$%^*[]-_=+{,?.}", - "escape_character": "yes", - "auto_create_table": "no", - "batch_create_tbl_num": 1, - "data_source": "rand", - "insert_mode": "taosc", - "insert_rows": 100, - "childtable_limit": 0, - "childtable_offset":0, - "multi_thread_write_one_tbl": "no", - "interlace_rows": 0, - "insert_interval":0, - "max_sql_len": 1024000, - "disorder_ratio": 0, - "disorder_range": 1000, - "timestamp_step": 1, - "start_timestamp": "2020-10-01 00:00:00.000", - "sample_format": "csv", - "sample_file": "", - "tags_file": "", - "columns": [{"type": "INT","count":9}, {"type": "BINARY", "len": 16, "count":1}], - "tags": [{"type": "INT", "count":2}] - }] - }] -} diff --git a/tests/pytest/tools/taosdemoAllTest/TD-3453/query-interrupt.json b/tests/pytest/tools/taosdemoAllTest/TD-3453/query-interrupt.json deleted file mode 100644 index c2e4920097cd1b3581c9893c9677c3cf1f14b7ed..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/TD-3453/query-interrupt.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "filetype": "insert", - "cfgdir": "/etc/taos", - "host": "127.0.0.1", - "port": 6030, - "user": "root", - "password": "taosdata", - "thread_count": 4, - "thread_count_create_tbl": 4, - "result_file": "./insert_res.txt", - "confirm_parameter_prompt": "no", - "insert_interval": 0, - "interlace_rows": 100, - "num_of_records_per_req": 1000, - "max_sql_len": 1024000, - "databases": [{ - "dbinfo": { - "name": "db", - "drop": "yes", - "replica": 1, - "days": 10, - "cache": 50, - "blocks": 8, - "precision": "ms", - "keep": 36500, - "minRows": 100, - "maxRows": 4096, - "comp":2, - "walLevel":1, - "cachelast":0, - "quorum":1, - "fsync":3000, - "update": 0 - }, - "super_tables": [{ - "name": "stb0", - "child_table_exists":"no", - "childtable_count": 60, - "childtable_prefix": "stb00_", - "auto_create_table": "no", - "batch_create_tbl_num": 20, - "data_source": "rand", - "insert_mode": "taosc", - "insert_rows": 100000, - "childtable_limit": -1, - "childtable_offset":0, - "multi_thread_write_one_tbl": "no", - "interlace_rows": 1000, - "insert_interval":0, - "max_sql_len": 1024000, - "disorder_ratio": 0, - "disorder_range": 1000, - "timestamp_step": 1, - "start_timestamp": "2020-10-01 00:00:00.000", - "sample_format": "csv", - "sample_file": "./sample.csv", - "tags_file": "", - "columns": [{"type": "INT"}, {"type": "DOUBLE", "count":10}, {"type": "BINARY", "len": 16, "count":3}, {"type": "BINARY", "len": 32, "count":6}], - "tags": [{"type": "TINYINT", "count":2}, {"type": "BINARY", "len": 16, "count":5}] - }] - }] -} diff --git a/tests/pytest/tools/taosdemoAllTest/TD-3453/query-interrupt.py b/tests/pytest/tools/taosdemoAllTest/TD-3453/query-interrupt.py deleted file mode 100644 index e8e65b68b89c35f33e239b4121f4d99b84c796a0..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/TD-3453/query-interrupt.py +++ /dev/null @@ -1,89 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -import subprocess -import time -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # # insert 1000w rows in stb0 - os.system("%staosBenchmark -f tools/taosdemoAllTest/TD-3453/query-interrupt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0,60) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 6000000) - os.system('%staosBenchmark -f tools/taosdemoAllTest/TD-3453/queryall.json -y & ' % binPath) - time.sleep(2) - query_pid = int(subprocess.getstatusoutput('ps aux|grep "TD-3453/queryall.json" |grep -v "grep"|awk \'{print $2}\'')[1]) - taosd_cpu_load_1 = float(subprocess.getstatusoutput('top -n 1 -b -p $(ps aux|grep "bin/taosd -c"|grep -v "grep" |awk \'{print $2}\')|awk \'END{print}\' |awk \'{print $9}\'')[1]) - if taosd_cpu_load_1 > 10.0 : - os.system("kill -9 %d" % query_pid) - time.sleep(5) - taosd_cpu_load_2 = float(subprocess.getstatusoutput('top -n 1 -b -p $(ps aux|grep "bin/taosd -c"|grep -v "grep" |awk \'{print $2}\')|awk \'END{print}\' |awk \'{print $9}\'')[1]) - if taosd_cpu_load_2 < 10.0 : - suc_kill = 60 - else: - suc_kill = 10 - print("taosd_cpu_load is higher than 10%") - else: - suc_kill = 20 - print("taosd_cpu_load is still less than 10%") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, "%d" % suc_kill) - os.system("rm -rf querySystemInfo*") - os.system("rm -rf insert_res.txt") - os.system("rm -rf query_res.txt") - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/TD-3453/queryall.json b/tests/pytest/tools/taosdemoAllTest/TD-3453/queryall.json deleted file mode 100644 index 97697feb9dd4e123a86543f0dc9198dacca1bc19..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/TD-3453/queryall.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "filetype":"query", - "cfgdir": "/etc/taos", - "host": "127.0.0.1", - "port": 6030, - "user": "root", - "password": "taosdata", - "confirm_parameter_prompt": "no", - "databases": "db", - "specified_table_query":{ - "query_interval":1, - "threads":1, - "sqls":[ - { - "sql": "select * from stb0", - "result": "./query_res.txt" - } - ] - } -} \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/TD-4985/query-limit-offset.py b/tests/pytest/tools/taosdemoAllTest/TD-4985/query-limit-offset.py index 987dd1bfa4771b505023bdeab78994ba488d671a..0b45b42dca5c9e51b0c03fde9d092fdb338811d5 100644 --- a/tests/pytest/tools/taosdemoAllTest/TD-4985/query-limit-offset.py +++ b/tests/pytest/tools/taosdemoAllTest/TD-4985/query-limit-offset.py @@ -28,7 +28,7 @@ class TDTestCase: now = time.time() self.ts = int(round(now * 1000)) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -36,153 +36,184 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) # insert: create one or mutiple tables per sql and insert multiple rows per sql # test case for https://jira.taosdata.com:18080/browse/TD-4985 os.system("rm -rf tools/taosdemoAllTest/TD-4985/query-limit-offset.py.sql") - os.system("%staosBenchmark -f tools/taosdemoAllTest/TD-4985/query-limit-offset.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/TD-4985/query-limit-offset.json -y " % + binPath) tdSql.execute("use db") tdSql.query("select count (tbname) from stb0") tdSql.checkData(0, 0, 10000) for i in range(1000): - tdSql.execute('''insert into stb00_9999 values(%d, %d, %d,'test99.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_8888 values(%d, %d, %d,'test98.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_7777 values(%d, %d, %d,'test97.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_6666 values(%d, %d, %d,'test96.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_5555 values(%d, %d, %d,'test95.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_4444 values(%d, %d, %d,'test94.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_3333 values(%d, %d, %d,'test93.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_2222 values(%d, %d, %d,'test92.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_1111 values(%d, %d, %d,'test91.%s')''' - % (self.ts + i, i, -10000+i, i)) - tdSql.execute('''insert into stb00_100 values(%d, %d, %d,'test90.%s')''' - % (self.ts + i, i, -10000+i, i)) + tdSql.execute( + '''insert into stb00_9999 values(%d, %d, %d,'test99.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_8888 values(%d, %d, %d,'test98.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_7777 values(%d, %d, %d,'test97.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_6666 values(%d, %d, %d,'test96.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_5555 values(%d, %d, %d,'test95.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_4444 values(%d, %d, %d,'test94.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_3333 values(%d, %d, %d,'test93.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_2222 values(%d, %d, %d,'test92.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_1111 values(%d, %d, %d,'test91.%s')''' % + (self.ts + i, i, -10000 + i, i)) + tdSql.execute( + '''insert into stb00_100 values(%d, %d, %d,'test90.%s')''' % + (self.ts + i, i, -10000 + i, i)) tdSql.query("select * from stb0 where c2 like 'test99%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_9999' limit 10" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_9999' limit 10") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_9999' limit 10 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_9999' limit 10 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test98%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_8888' limit 10" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_8888' limit 10") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_8888' limit 10 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_8888' limit 10 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test97%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_7777' limit 10" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_7777' limit 10") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_7777' limit 10 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_7777' limit 10 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test96%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_6666' limit 10" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_6666' limit 10") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_6666' limit 10 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_6666' limit 10 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test95%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_5555' limit 10" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_5555' limit 10") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_5555' limit 10 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_5555' limit 10 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test94%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_4444' limit 10" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_4444' limit 10") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_4444' limit 10 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_4444' limit 10 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test93%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_3333' limit 100" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_3333' limit 100") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_3333' limit 100 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_3333' limit 100 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test92%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_2222' limit 100" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_2222' limit 100") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_2222' limit 100 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_2222' limit 100 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test91%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_1111' limit 100" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_1111' limit 100") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_1111' limit 100 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_1111' limit 100 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) tdSql.query("select * from stb0 where c2 like 'test90%' ") tdSql.checkRows(1000) - tdSql.query("select * from stb0 where tbname like 'stb00_100' limit 100" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_100' limit 100") tdSql.checkData(0, 1, 0) tdSql.checkData(1, 1, 1) tdSql.checkData(2, 1, 2) - tdSql.query("select * from stb0 where tbname like 'stb00_100' limit 100 offset 5" ) + tdSql.query( + "select * from stb0 where tbname like 'stb00_100' limit 100 offset 5") tdSql.checkData(0, 1, 5) tdSql.checkData(1, 1, 6) tdSql.checkData(2, 1, 7) - def stop(self): tdSql.close() diff --git a/tests/pytest/tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py b/tests/pytest/tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py index 56b51f5498aed0a540a86bf03625266ad3599b58..c047e4b0aadcc27e0014420c2d350f106125109c 100755 --- a/tests/pytest/tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py +++ b/tests/pytest/tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py @@ -24,8 +24,8 @@ class TDTestCase: def init(self, conn, logSql): tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): + + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -33,26 +33,26 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath - + return paths[0] + def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) #-N:regular table -d:database name -t:table num -n:rows num per table -l:col num -y:force - #regular old && new + # regular old && new startTime = time.time() - os.system("%staosBenchmark -N -d regular_old -t 1 -n 10 -l 1023 -y" % binPath) + os.system("%s -N -d regular_old -t 1 -n 10 -l 1023 -y" % binPath) tdSql.execute("use regular_old") tdSql.query("show tables;") tdSql.checkRows(1) @@ -61,7 +61,7 @@ class TDTestCase: tdSql.query("describe d0;") tdSql.checkRows(1024) - os.system("%staosBenchmark -N -d regular_new -t 1 -n 10 -l 4095 -y" % binPath) + os.system("%s -N -d regular_new -t 1 -n 10 -l 4095 -y" % binPath) tdSql.execute("use regular_new") tdSql.query("show tables;") tdSql.checkRows(1) @@ -70,8 +70,9 @@ class TDTestCase: tdSql.query("describe d0;") tdSql.checkRows(4096) - #super table -d:database name -t:table num -n:rows num per table -l:col num -y:force - os.system("%staosBenchmark -d super_old -t 1 -n 10 -l 1021 -y" % binPath) + # super table -d:database name -t:table num -n:rows num per table + # -l:col num -y:force + os.system("%s -d super_old -t 1 -n 10 -l 1021 -y" % binPath) tdSql.execute("use super_old") tdSql.query("show tables;") tdSql.checkRows(1) @@ -84,7 +85,7 @@ class TDTestCase: tdSql.query("describe d0;") tdSql.checkRows(1024) - os.system("%staosBenchmark -d super_new -t 1 -n 10 -l 4093 -y" % binPath) + os.system("%s -d super_new -t 1 -n 10 -l 4093 -y" % binPath) tdSql.execute("use super_new") tdSql.query("show tables;") tdSql.checkRows(1) @@ -102,9 +103,11 @@ class TDTestCase: tdSql.query("describe stb_new1_1;") tdSql.checkRows(4096) - # insert: create one or mutiple tables per sql and insert multiple rows per sql + # insert: create one or mutiple tables per sql and insert multiple rows per sql # test case for https://jira.taosdata.com:18080/browse/TD-5213 - os.system("%staosBenchmark -f tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.json -y " % + binPath) tdSql.execute("use json_test") tdSql.query("select count (tbname) from stb_old") tdSql.checkData(0, 0, 1) @@ -112,7 +115,7 @@ class TDTestCase: tdSql.query("select * from stb_old") tdSql.checkRows(10) tdSql.checkCols(1024) - + tdSql.query("select count (tbname) from stb_new") tdSql.checkData(0, 0, 1) @@ -160,13 +163,11 @@ class TDTestCase: tdSql.query("describe stb_excel_0;") tdSql.checkRows(4096) endTime = time.time() - print("total time %ds" % (endTime - startTime)) + print("total time %ds" % (endTime - startTime)) + os.system( + "rm -rf tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py.sql") - os.system("rm -rf tools/taosdemoAllTest/TD-5213/insertSigcolumnsNum4096.py.sql") - - - def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) diff --git a/tests/pytest/tools/taosdemoAllTest/query-interrupt.py b/tests/pytest/tools/taosdemoAllTest/query-interrupt.py deleted file mode 100644 index df021cbe3be5da9a0a28b78bbafef548c24697fa..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/query-interrupt.py +++ /dev/null @@ -1,88 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -import subprocess -import time -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # # insert 1000w rows in stb0 - os.system("%staosBenchmark -f tools/taosdemoAllTest/query-interrupt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0,60) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 6000000) - os.system('%staosBenchmark -f tools/taosdemoAllTest/queryall.json -y & ' % binPath) - time.sleep(2) - query_pid = int(subprocess.getstatusoutput('ps aux|grep "taosdemoAllTest/queryall.json" |grep -v "grep"|awk \'{print $2}\'')[1]) - taosd_cpu_load_1 = float(subprocess.getstatusoutput('top -n 1 -b -p $(ps aux|grep "bin/taosd -c"|grep -v "grep" |awk \'{print $2}\')|awk \'END{print}\' |awk \'{print $9}\'')[1]) - if taosd_cpu_load_1 > 10.0 : - os.system("kill -9 %d" % query_pid) - time.sleep(5) - taosd_cpu_load_2 = float(subprocess.getstatusoutput('top -n 1 -b -p $(ps aux|grep "bin/taosd -c"|grep -v "grep" |awk \'{print $2}\')|awk \'END{print}\' |awk \'{print $9}\'')[1]) - if taosd_cpu_load_2 < 10.0 : - suc_kill = 60 - else: - suc_kill = 10 - print("taosd_cpu_load is higher than 10%") - else: - suc_kill = 20 - print("taosd_cpu_load is still less than 10%") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, "%d" % suc_kill) - os.system("rm -rf querySystemInfo*") - os.system("rm -rf insert_res.txt") - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/subscribeNoResult.py b/tests/pytest/tools/taosdemoAllTest/subscribeNoResult.py deleted file mode 100644 index e1a9f647fa2b5d1f561e50a06b9755d78bebfa79..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/subscribeNoResult.py +++ /dev/null @@ -1,82 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -import time -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * -import _thread - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - self.ts = 1601481600000 - self.numberOfRecords = 1100000 - - def execCmdAndGetOutput(self, cmd): - r = os.popen(cmd) - text = r.read() - r.close() - return text - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - buildPath = self.getBuildPath() - tdSql.prepare() - tdSql.execute("create table st(ts timestamp, c1 timestamp, c2 int, c3 bigint, c4 float, c5 double, c6 binary(8), c7 smallint, c8 tinyint, c9 bool, c10 nchar(8)) tags(t1 int)") - tdSql.execute("create table t1 using st tags(0)") - currts = self.ts - finish = 0 - while(finish < self.numberOfRecords): - sql = "insert into t1 values" - for i in range(finish, self.numberOfRecords): - sql += "(%d, 1019774612, 29931, 1442173978, 165092.468750, 1128.643179, 'MOCq1pTu', 18405, 82, 0, 'g0A6S0Fu')" % (currts + i) - finish = i + 1 - if (1048576 - len(sql)) < 16384: - break - tdSql.execute(sql) - - binPath = buildPath+ "/build/bin/" - - os.system("%staosBenchmark -f tools/taosdemoAllTest/sub_no_result.json -g 2>&1 | tee sub_no_result.log" % binPath) - test_line = int(self.execCmdAndGetOutput("cat sub_no_result.log | wc -l")) - if(test_line < 1100024): - tdLog.exit("failed test subscribeNoResult: %d != expected(1100024)" % test_line) - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertAllType.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertAllType.py index 3bc2495f626e28017d55fc6d01f487ef239cd8b5..914231878a61d48bbbca3883e21db18eaf8761ad 100644 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertAllType.py +++ b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertAllType.py @@ -24,7 +24,7 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -32,24 +32,26 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) - # taosc interface - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-allDataType.json -y " % binPath) + # taosc interface + os.system( + "%s -f tools/taosdemoAllTest/insert-allDataType.json -y " % + binPath) tdSql.execute("use db") tdSql.query("select count (tbname) from stb0") tdSql.checkData(0, 0, 1000) @@ -64,8 +66,10 @@ class TDTestCase: tdSql.query("select count(*) from stb1") tdSql.checkData(0, 0, 200000) - # stmt interface - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-allDataType-stmt.json -y " % binPath) + # stmt interface + os.system( + "%s -f tools/taosdemoAllTest/stmt/insert-allDataType-stmt.json -y " % + binPath) tdSql.execute("use db") tdSql.query("select count (tbname) from stb0") tdSql.checkData(0, 0, 1000) @@ -80,53 +84,60 @@ class TDTestCase: tdSql.query("select count(*) from stb1") tdSql.checkData(0, 0, 200000) - # insert-interface: sml - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-allDataType-sml.json -y " % binPath) + # insert-interface: sml + os.system( + "%s -f tools/taosdemoAllTest/sml/insert-allDataType-sml.json -y " % + binPath) tdSql.execute("use db") tdSql.query("select count (tbname) from stb0") tdSql.checkData(0, 0, 10) tdSql.query("select count (tbname) from stb1") tdSql.checkData(0, 0, 20) # tdSql.query("select last(ts) from db.stb00_0") - # tdSql.checkData(0, 0, "2020-10-01 00:00:00.019000") + # tdSql.checkData(0, 0, "2020-10-01 00:00:00.019000") tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 1000) + tdSql.checkData(0, 0, 1000) # tdSql.query("select last(ts) from db.stb01_0") - # tdSql.checkData(0, 0, "2020-11-01 00:00:00.190000") + # tdSql.checkData(0, 0, "2020-11-01 00:00:00.190000") tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 4000) - + tdSql.checkData(0, 0, 4000) - # insert-interface: sml-json - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-sml-json-alltype.json -y " % binPath) + # insert-interface: sml-json + os.system( + "%s -f tools/taosdemoAllTest/sml/insert-sml-json-alltype.json -y " % + binPath) tdSql.execute("use db") tdSql.query("show stables") for i in range(13): - for j in range(13): - if tdSql.queryResult[i][0] == 'stb%d'%j: + for j in range(13): + if tdSql.queryResult[i][0] == 'stb%d' % j: # print(i,"stb%d"%j) - tdSql.checkData(i, 4, j+1) - + tdSql.checkData(i, 4, j + 1) # insert-interface: sml-telnet - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-sml-telnet-alltype.json -y " % binPath) + os.system( + "%s -f tools/taosdemoAllTest/sml/insert-sml-telnet-alltype.json -y " % + binPath) tdSql.execute("use db") tdSql.query("show stables") for i in range(13): - for j in range(13): - if tdSql.queryResult[i][0] == 'stb%d'%j: + for j in range(13): + if tdSql.queryResult[i][0] == 'stb%d' % j: # print(i,"stb%d"%j) - tdSql.checkData(i, 4, j+1) + tdSql.checkData(i, 4, j + 1) for i in range(13): - tdSql.query("select count(*) from stb%d"%i) - tdSql.checkData(0, 0, (i+1)*10) + tdSql.query("select count(*) from stb%d" % i) + tdSql.checkData(0, 0, (i + 1) * 10) # insert-interface: sml-telnet - assert os.system("%staosdemo -f tools/taosdemoAllTest/sml/insert-sml-timestamp.json -y " % binPath) !=0 - + assert os.system( + "%s -f tools/taosdemoAllTest/sml/insert-sml-timestamp.json -y " % + binPath) != 0 # taosdemo command line - os.system("%staosBenchmark -t 1000 -n 100 -T 10 -b INT,TIMESTAMP,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,NCHAR,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY -y " % binPath) + os.system( + "%s -t 1000 -n 100 -T 10 -b INT,TIMESTAMP,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,NCHAR,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY -y " % + binPath) tdSql.execute("use test") tdSql.query("select count (tbname) from meters") tdSql.checkData(0, 0, 1000) @@ -137,10 +148,7 @@ class TDTestCase: testcaseFilename = os.path.split(__file__)[-1] os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename ) - - - + os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename) def stop(self): tdSql.close() diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertShell.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertShell.py index a872d8566fa83a95c1c47519fd391a69c34b78d5..7403ad60a4a5ee2b257d44bcbaf5a849cdff581d 100644 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertShell.py +++ b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertShell.py @@ -24,40 +24,41 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) global cfgPath if ("community" in selfPath): projPath = selfPath[:selfPath.find("community")] cfgPath = projPath + "/community/sim/dnode1/cfg" - else: projPath = selfPath[:selfPath.find("tests")] cfgPath = projPath + "/sim/dnode1/cfg" + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] # def checkGerData(): def run(self): - buildPath = self.getBuildPath() - print("%s" % cfgPath ) - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + print("%s" % cfgPath) + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) tdLog.info("create super table") - # create super table - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % (binPath,cfgPath)) + # create super table + os.system( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % + (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("describe meters;") tdSql.checkRows(13) @@ -68,12 +69,13 @@ class TDTestCase: tdSql.query("select count(*) from `test.0`") tdSql.checkData(0, 0, 100) - tdLog.info("create general table -N ") tdSql.execute("drop database db1;") - # create general table -N - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -N " % (binPath,cfgPath)) + # create general table -N + os.system( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -N " % + (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("describe `test.0`;") tdSql.checkRows(11) @@ -85,8 +87,10 @@ class TDTestCase: tdLog.info("use diffrent interface stmt") tdSql.execute("drop database db1;") # use diffrent interface-stmt - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,BINARY\(4000\) -w 40 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I stmt " % (binPath,cfgPath)) + os.system( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,BINARY\(4000\) -w 40 \ + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I stmt " % + (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -98,8 +102,10 @@ class TDTestCase: tdLog.info("use diffrent interface rest") tdSql.execute("drop database db1;") # use diffrent interface -rest - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4097 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I rest " % (binPath,cfgPath)) + os.system( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4097 \ + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I rest " % + (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -111,8 +117,10 @@ class TDTestCase: tdLog.info("use diffrent interface sml") tdSql.execute("drop database db1;") # use diffrent interface-sml - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 1024 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I sml " % (binPath,cfgPath)) + os.system( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 1024 \ + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I sml " % + (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -122,9 +130,9 @@ class TDTestCase: tdLog.info("all data type") tdSql.execute("drop database db1;") # all data type-taosc - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ + os.system("%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ -b INT,TIMESTAMP,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY\(15\),NCHAR\(15\) -w 4096 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % (binPath,cfgPath)) + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -135,9 +143,9 @@ class TDTestCase: tdLog.info("all data type") tdSql.execute("drop database db1;") # all data type-stmt - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ + os.system("%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ -b INT,TIMESTAMP,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY\(15\),NCHAR\(15\) -w 4096 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I stmt " % (binPath,cfgPath)) + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I stmt " % (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -147,9 +155,9 @@ class TDTestCase: tdSql.checkData(0, 0, 100) # all data type-rest - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ + os.system("%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ -b INT,TIMESTAMP,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY\(15\),NCHAR\(15\) -w 4096 \ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I rest " % (binPath,cfgPath)) + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I rest " % (binPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -159,7 +167,7 @@ class TDTestCase: tdSql.checkData(0, 0, 100) # # all data type-rest - # os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ + # os.system("%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 \ # -b INT,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY\(15\),NCHAR\(15\) -w 4096 \ # -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I sml " % (binPath,cfgPath)) # tdSql.execute("use db1") @@ -172,10 +180,10 @@ class TDTestCase: tdLog.info("all data type and interlace rows") tdSql.execute("drop database db1;") - # all data type - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db3 -a 1 -l 10\ + # all data type + os.system("%s -u root -c %s -h localhost -P 6030 -d db3 -a 1 -l 10\ -b INT,TIMESTAMP,BIGINT,FLOAT,DOUBLE,SMALLINT,TINYINT,BOOL,UINT,UBIGINT,UTINYINT,USMALLINT,BINARY\(15\),NCHAR\(15\) -w 4096\ - -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -B 1000 -M -x -y -O 10 -R 100 -E -m test. " % (binPath,cfgPath)) + -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -B 1000 -M -x -y -O 10 -R 100 -E -m test. " % (binPath, cfgPath)) tdSql.execute("use db3") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -185,14 +193,18 @@ class TDTestCase: tdSql.checkData(0, 0, 100) tdLog.info("all data type and too much para") - tdLog.info("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ + tdLog.info( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test.taosdemo -u root -c %s -h \ - localhost -P 6030 -d db1 -a 1 -l 100 -b float,int,NCHAR\(15\) -w 4096 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % (binPath,cfgPath,cfgPath)) + localhost -P 6030 -d db1 -a 1 -l 100 -b float,int,NCHAR\(15\) -w 4096 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % + (binPath, cfgPath, cfgPath)) tdSql.execute("drop database db3;") - # repeate parameters - os.system("%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ + # repeate parameters + os.system( + "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(15\) -w 4096 \ -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test.taosdemo -u root -c %s -h \ - localhost -P 6030 -d db1 -a 1 -l 100 -b float,int,NCHAR\(15\) -w 4096 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % (binPath,cfgPath,cfgPath)) + localhost -P 6030 -d db1 -a 1 -l 100 -b float,int,NCHAR\(15\) -w 4096 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. " % + (binPath, cfgPath, cfgPath)) tdSql.execute("use db1") tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, 1000) @@ -203,21 +215,22 @@ class TDTestCase: # taosdemo error # too max length - sql = "%staosBenchmark -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(4096\) \ - -w 40 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I taosc" % (binPath,cfgPath) - tdLog.info("%s" % sql ) - assert os.system("%s" % sql ) != 0 - - # error password - sql = "%staosBenchmark -u root -c %s -h localhost -P 6030 -p123 -d db1 -a 1 -l 10 -b float,int,NCHAR\(40\) \ - -w 40 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I stmt" % (binPath,cfgPath) - tdLog.info("%s" % sql ) - assert os.system("%s" % sql ) != 0 + sql = "%s -u root -c %s -h localhost -P 6030 -d db1 -a 1 -l 10 -b float,int,NCHAR\(4096\) \ + -w 40 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I taosc" % (binPath, + cfgPath) + tdLog.info("%s" % sql) + assert os.system("%s" % sql) != 0 + + # error password + sql = "%s -u root -c %s -h localhost -P 6030 -p123 -d db1 -a 1 -l 10 -b float,int,NCHAR\(40\) \ + -w 40 -T 8 -i 10 -S 1000 -r 1000000 -t 10 -n 100 -M -x -y -O 10 -R 100 -E -m test. -I stmt" % (binPath, + cfgPath) + tdLog.info("%s" % sql) + assert os.system("%s" % sql) != 0 testcaseFilename = os.path.split(__file__)[-1] os.system("rm -rf ./insert_res*.txt*") - os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename ) - + os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename) def stop(self): tdSql.close() diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py deleted file mode 100644 index 8b0f55b5bfbb2706a470d55f0be6c62c804611da..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJson.py +++ /dev/null @@ -1,390 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - testcaseFilename = os.path.split(__file__)[-1] - os.system("rm -rf ./insert*_res.txt*") - os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename ) - - # insert: create one or mutiple tables per sql and insert multiple rows per sql - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-1s1tnt1r.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 11) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 10) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 1100) - tdSql.query("select count(*) from stb01_1") - tdSql.checkData(0, 0, 200) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 2000) - - # restful connector insert data - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertRestful.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 10) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count(*) from stb01_1") - tdSql.checkData(0, 0, 20) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 200) - - # default values json files - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-default.json -y " % binPath) - tdSql.query("show databases;") - for i in range(tdSql.queryRows): - if tdSql.queryResult[i][0] == 'db': - tdSql.checkData(i, 2, 100) - tdSql.checkData(i, 4, 1) - tdSql.checkData(i, 6, 10) - tdSql.checkData(i, 16, 'ms') - - # insert: create mutiple tables per sql and insert one rows per sql . - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-1s1tntmr.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 20) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 1000) - tdSql.query("select count(*) from stb01_0") - tdSql.checkData(0, 0, 200) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 4000) - - # insert: using parament "insert_interval to controls spped of insert. - # but We need to have accurate methods to control the speed, such as getting the speed value, checking the count and so on。 - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-interval-speed.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("show stables") - tdSql.checkData(0, 4, 10) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 200) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 2000) - tdSql.query("show stables") - tdSql.checkData(1, 4, 20) - tdSql.query("select count(*) from stb01_0") - tdSql.checkData(0, 0, 200) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 4000) - - # spend 2min30s for 3 testcases. - # insert: drop and child_table_exists combination test - # insert: using parament "childtable_offset and childtable_limit" to control table'offset point and offset - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-nodbnodrop.json -y" % binPath) - tdSql.error("show dbno.stables") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-newdb.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 5) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 6) - tdSql.query("select count (tbname) from stb2") - tdSql.checkData(0, 0, 7) - tdSql.query("select count (tbname) from stb3") - tdSql.checkData(0, 0, 8) - tdSql.query("select count (tbname) from stb4") - tdSql.checkData(0, 0, 8) - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-offset.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 50) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 240) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 220) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 180) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 160) - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-newtable.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 150) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 360) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 360) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 340) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 400) - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-renewdb.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 50) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 120) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 140) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 160) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 160) - - - # insert: let parament in json file is illegal, it'll expect error. - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertColumnsAndTagNumLarge4096.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertSigcolumnsNum4096.json -y " % binPath) - tdSql.error("select * from db.stb0") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertColumnsAndTagNum4096.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkData(0, 0, 10000) - - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertInterlaceRowsLarge1M.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkRows(0) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertColumnsNum0.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("show stables like 'stb0%' ") - tdSql.checkData(0, 2, 11) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertTagsNumLarge128.json -y " % binPath) - tdSql.error("use db1") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertBinaryLenLarge16374AllcolLar49151.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkRows(1) - tdSql.query("select count(*) from db.stb1") - tdSql.checkRows(1) - tdSql.error("select * from db.stb4") - tdSql.error("select * from db.stb2") - tdSql.query("select count(*) from db.stb3") - tdSql.checkRows(1) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertBinaryLenLarge16374AllcolLar49151-error.json -y " % binPath) - tdSql.error("select * from db.stb4") - tdSql.error("select * from db.stb2") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertNumOfrecordPerReq0.json -y " % binPath) - tdSql.error("select count(*) from db.stb0") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertNumOfrecordPerReqless0.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertChildTab0.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertChildTabLess0.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists blf") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertTimestepMulRowsLargeint16.json -y " % binPath) - tdSql.execute("use blf") - tdSql.query("select ts from blf.p_0_topics_7 limit 262800,1") - tdSql.checkData(0, 0, "2020-03-31 12:00:00.000") - tdSql.query("select first(ts) from blf.p_0_topics_2") - tdSql.checkData(0, 0, "2019-10-01 00:00:00") - tdSql.query("select last(ts) from blf.p_0_topics_6 ") - tdSql.checkData(0, 0, "2020-09-29 23:59:00") - os.system("%staosBenchmark -f tools/taosdemoAllTest/insertMaxNumPerReq.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 5000000) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 5000000) - - - - # insert: timestamp and step - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-timestep.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("show stables") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 20) - tdSql.query("select last(ts) from db.stb00_0") - tdSql.checkData(0, 0, "2020-10-01 00:00:00.019000") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 200) - tdSql.query("select last(ts) from db.stb01_0") - tdSql.checkData(0, 0, "2020-11-01 00:00:00.190000") - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 400) - - # # insert: disorder_ratio - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-disorder.json -g 2>&1 -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 1) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 1) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 10) - - # insert: sample json - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-sample-ts.json -y " % binPath) - tdSql.execute("use dbtest123") - tdSql.query("select c2 from stb0") - tdSql.checkData(0, 0, 2147483647) - tdSql.query("select c0 from stb0_0 order by ts") - tdSql.checkData(3, 0, 4) - tdSql.query("select count(*) from stb0 order by ts") - tdSql.checkData(0, 0, 40) - tdSql.query("select * from stb0_1 order by ts") - tdSql.checkData(0, 0, '2021-10-28 15:34:44.735') - tdSql.checkData(3, 0, '2021-10-31 15:34:44.735') - tdSql.query("select * from stb1 where t1=-127") - tdSql.checkRows(20) - tdSql.query("select * from stb1 where t2=127") - tdSql.checkRows(10) - tdSql.query("select * from stb1 where t2=126") - tdSql.checkRows(10) - - # insert: sample json - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-sample.json -y " % binPath) - tdSql.execute("use dbtest123") - tdSql.query("select c2 from stb0") - tdSql.checkData(0, 0, 2147483647) - tdSql.query("select * from stb1 where t1=-127") - tdSql.checkRows(20) - tdSql.query("select * from stb1 where t2=127") - tdSql.checkRows(10) - tdSql.query("select * from stb1 where t2=126") - tdSql.checkRows(10) - - - # insert: test interlace parament - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-interlace-row.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count (*) from stb0") - tdSql.checkData(0, 0, 15000) - - - # # insert: auto_create - - tdSql.execute('drop database if exists db') - tdSql.execute('create database db') - tdSql.execute('use db') - os.system("%staosBenchmark -y -f tools/taosdemoAllTest/insert-drop-exist-auto-N00.json " % binPath) # drop = no, child_table_exists, auto_create_table varies - tdSql.execute('use db') - tdSql.query('show tables like \'NN123%\'') #child_table_exists = no, auto_create_table varies = 123 - tdSql.checkRows(20) - tdSql.query('show tables like \'NNN%\'') #child_table_exists = no, auto_create_table varies = no - tdSql.checkRows(20) - tdSql.query('show tables like \'NNY%\'') #child_table_exists = no, auto_create_table varies = yes - tdSql.checkRows(20) - tdSql.query('show tables like \'NYN%\'') #child_table_exists = yes, auto_create_table varies = no - tdSql.checkRows(0) - tdSql.query('show tables like \'NY123%\'') #child_table_exists = yes, auto_create_table varies = 123 - tdSql.checkRows(0) - tdSql.query('show tables like \'NYY%\'') #child_table_exists = yes, auto_create_table varies = yes - tdSql.checkRows(0) - - tdSql.execute('drop database if exists db') - os.system("%staosBenchmark -y -f tools/taosdemoAllTest/insert-drop-exist-auto-Y00.json " % binPath) # drop = yes, child_table_exists, auto_create_table varies - tdSql.execute('use db') - tdSql.query('show tables like \'YN123%\'') #child_table_exists = no, auto_create_table varies = 123 - tdSql.checkRows(20) - tdSql.query('show tables like \'YNN%\'') #child_table_exists = no, auto_create_table varies = no - tdSql.checkRows(20) - tdSql.query('show tables like \'YNY%\'') #child_table_exists = no, auto_create_table varies = yes - tdSql.checkRows(20) - tdSql.query('show tables like \'YYN%\'') #child_table_exists = yes, auto_create_table varies = no - tdSql.checkRows(20) - tdSql.query('show tables like \'YY123%\'') #child_table_exists = yes, auto_create_table varies = 123 - tdSql.checkRows(20) - tdSql.query('show tables like \'YYY%\'') #child_table_exists = yes, auto_create_table varies = yes - tdSql.checkRows(20) - - - # insert: test chinese encoding - # TD-11399、TD-10819 - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-chinese.json -y " % binPath) - os.system("%staosBenchmark -f tools/taosdemoAllTest/insert-chinese-sml.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("show stables") - for i in range(6): - for j in range(6): - if tdSql.queryResult[i][0] == 'stb%d'%j: - # print(i,"stb%d"%j) - tdSql.checkData(i, 4, (j+1)*10) - for i in range(6): - tdSql.query("select count(*) from stb%d"%i) - tdSql.checkData(0, 0, (i+1)*1000) - - # rm useless files - os.system("rm -rf ./insert*_res.txt*") - - - - - - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonSml.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonSml.py deleted file mode 100644 index ee86fefda4397bba4470a1dd9c32b78a0866b45c..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonSml.py +++ /dev/null @@ -1,266 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # insert: create one or mutiple tables per sql and insert multiple rows per sql - # line_protocol——telnet and json - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-1s1tnt1r-sml.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 20) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 1000) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 4000) - - - # insert: create mutiple tables per sql and insert one rows per sql . - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-1s1tntmr-sml.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 15) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 1500) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 3000) - - # insert: using parament "insert_interval to controls spped of insert. - # but We need to have accurate methods to control the speed, such as getting the speed value, checking the count and so on。 - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-interval-speed-sml.json -y" % binPath) - tdSql.execute("use db") - # tdSql.query("select count (tbname) from stb0") - tdSql.query("select tbname from db.stb0") - tdSql.checkRows(100 ) - # tdSql.query("select count(*) from stb00_0") - # tdSql.checkData(0, 0, 20) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 2000) - tdSql.query("show stables") - tdSql.checkData(1, 4, 20) - # tdSql.query("select count(*) from stb01_0") - # tdSql.checkData(0, 0, 35) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 700) - - # spend 2min30s for 3 testcases. - # insert: drop and child_table_exists combination test - # insert: sml can't support parament "childtable_offset and childtable_limit" \ drop=no or child_table_exists = yes - - # os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-nodbnodrop-sml.json -y" % binPath) - # tdSql.error("show dbno.stables") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-newdb-sml.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 5) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 6) - tdSql.query("select count (tbname) from stb2") - tdSql.checkData(0, 0, 7) - tdSql.query("select count (tbname) from stb3") - tdSql.checkData(0, 0, 8) - tdSql.query("select count (tbname) from stb4") - tdSql.checkData(0, 0, 8) - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-renewdb-sml.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 50) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 120) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 140) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 160) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 160) - - - # insert: let parament in json file is illegal, it'll expect error. - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertColumnsAndTagNumLarge4096-sml.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertSigcolumnsNum4096-sml.json -y " % binPath) - tdSql.error("select * from db.stb0") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertColumnsAndTagNum4096-sml.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkData(0, 0, 10000) - - # there is no limit of 4096 columns,so cancels this case - # tdSql.execute("drop database if exists db") - # os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertInterlaceRowsLarge1M-sml.json -y " % binPath) - # tdSql.query("select count(*) from db.stb0") - # tdSql.checkRows(0) - - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertColumnsNum0-sml.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("show stables like 'stb0%' ") - tdSql.checkData(0, 2, 11) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertTagsNumLarge128-sml.json -y " % binPath) - tdSql.error("use db1") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertBinaryLenLarge16374AllcolLar49151-sml.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkRows(1) - tdSql.query("select count(*) from db.stb1") - tdSql.checkRows(1) - tdSql.query("select count(*) from db.stb3") - tdSql.checkRows(1) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertBinaryLenLarge16374AllcolLar49151-error-sml.json -y " % binPath) - tdSql.error("select * from db.stb4") - tdSql.error("select * from db.stb2") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertNumOfrecordPerReq0-sml.json -y " % binPath) - tdSql.error("select count(*) from db.stb0") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertNumOfrecordPerReqless0-sml.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertChildTab0-sml.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertChildTabLess0-sml.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists blf") - - # child table name is invalid reading,so - # os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertTimestepMulRowsLargeint16-sml.json -y " % binPath) - # tdSql.execute("use blf") - # tdSql.query("select ts from blf.p_0_topics_7 limit 262800,1") - # tdSql.checkData(0, 0, "2020-03-31 12:00:00.000") - # tdSql.query("select first(ts) from blf.p_0_topics_2") - # tdSql.checkData(0, 0, "2019-10-01 00:00:00") - # tdSql.query("select last(ts) from blf.p_0_topics_6 ") - # tdSql.checkData(0, 0, "2020-09-29 23:59:00") - - # it will be commented in ci because it spend too much time to insert data, but when you can excute it when you want to test this case. - # os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertMaxNumPerReq-sml.json -y " % binPath) - # tdSql.execute("use db") - # tdSql.query("select count(*) from stb0") - # tdSql.checkData(0, 0, 5000000) - # tdSql.query("select count(*) from stb1") - # tdSql.checkData(0, 0, 5000000) - # os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insertMaxNumPerReq-sml-telnet.json -y " % binPath) - # tdSql.execute("use db") - # tdSql.query("select count(*) from stb0") - # tdSql.checkData(0, 0, 5000000) - # tdSql.query("select count(*) from stb1") - # tdSql.checkData(0, 0, 5000000) - - - - # insert: timestamp and step - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-timestep-sml.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 20) - # tdSql.query("select last(ts) from db.stb00_0") - # tdSql.checkData(0, 0, "2020-10-01 00:00:00.019000") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 200) - # tdSql.query("select last(ts) from db.stb01_0") - # tdSql.checkData(0, 0, "2020-11-01 00:00:00.190000") - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 400) - - # # insert: disorder_ratio - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-disorder-sml.json 2>&1 -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 1) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 1) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 10) - - # insert: doesn‘t currently supported sample json - assert os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-sample-sml.json -y " % binPath) != 0 - # tdSql.execute("use dbtest123") - # tdSql.query("select c2 from stb0") - # tdSql.checkData(0, 0, 2147483647) - # tdSql.query("select * from stb1 where t1=-127") - # tdSql.checkRows(20) - # tdSql.query("select * from stb1 where t2=127") - # tdSql.checkRows(10) - # tdSql.query("select * from stb1 where t2=126") - # tdSql.checkRows(10) - - # insert: test interlace parament - os.system("%staosBenchmark -f tools/taosdemoAllTest/sml/insert-interlace-row-sml.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count (*) from stb0") - tdSql.checkData(0, 0, 15000) - - - testcaseFilename = os.path.split(__file__)[-1] - os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename ) - - - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonStmt.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonStmt.py deleted file mode 100644 index 6a5a3f767f1c5787680d75ee8cb98ee284a44741..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonStmt.py +++ /dev/null @@ -1,339 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # insert: create one or mutiple tables per sql and insert multiple rows per sql - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-1s1tnt1r-stmt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 1000) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 1000) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 100000) - tdSql.query("select count(*) from stb01_1") - tdSql.checkData(0, 0, 200) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 200000) - - - # insert: create mutiple tables per sql and insert one rows per sql . - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-1s1tntmr-stmt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 20) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 10000) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 100000) - tdSql.query("select count(*) from stb01_0") - tdSql.checkData(0, 0, 20000) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 400000) - - # insert: using parament "insert_interval to controls spped of insert. - # but We need to have accurate methods to control the speed, such as getting the speed value, checking the count and so on。 - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-interval-speed-stmt.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("show stables") - tdSql.checkData(0, 4, 100) - tdSql.query("select count(*) from stb00_0") - tdSql.checkData(0, 0, 20000) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 2000000) - tdSql.query("show stables") - tdSql.checkData(1, 4, 100) - tdSql.query("select count(*) from stb01_0") - tdSql.checkData(0, 0, 20000) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 2000000) - - # spend 2min30s for 3 testcases. - # insert: drop and child_table_exists combination test - # insert: using parament "childtable_offset and childtable_limit" to control table'offset point and offset - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-nodbnodrop-stmt.json -y" % binPath) - tdSql.error("show dbno.stables") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-newdb-stmt.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 5) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 6) - tdSql.query("select count (tbname) from stb2") - tdSql.checkData(0, 0, 7) - tdSql.query("select count (tbname) from stb3") - tdSql.checkData(0, 0, 8) - tdSql.query("select count (tbname) from stb4") - tdSql.checkData(0, 0, 8) - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-offset-stmt.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 50) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 240) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 220) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 180) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 160) - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-newtable-stmt.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 150) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 360) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 360) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 340) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 400) - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-renewdb-stmt.json -y" % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 50) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 120) - tdSql.query("select count(*) from stb2") - tdSql.checkData(0, 0, 140) - tdSql.query("select count(*) from stb3") - tdSql.checkData(0, 0, 160) - tdSql.query("select count(*) from stb4") - tdSql.checkData(0, 0, 160) - - - # insert: let parament in json file is illegal, it'll expect error. - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertColumnsAndTagNumLarge4096-stmt.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertSigcolumnsNum4096-stmt.json -y " % binPath) - tdSql.error("select * from db.stb0") - # tdSql.execute("drop database if exists db") - # os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertColumnsAndTagNum4096-stmt.json -y " % binPath) - # tdSql.query("select count(*) from db.stb0") - # tdSql.checkData(0, 0, 10000) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertInterlaceRowsLarge1M-stmt.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkRows(0) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertColumnsNum0-stmt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("show stables like 'stb0%' ") - tdSql.checkData(0, 2, 11) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertTagsNumLarge128-stmt.json -y " % binPath) - tdSql.error("use db1") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertBinaryLenLarge16374AllcolLar49151-stmt.json -y " % binPath) - tdSql.query("select count(*) from db.stb0") - tdSql.checkRows(1) - tdSql.query("select count(*) from db.stb1") - tdSql.checkRows(1) - tdSql.error("select * from db.stb4") - tdSql.error("select * from db.stb2") - tdSql.query("select count(*) from db.stb3") - tdSql.checkRows(1) - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertBinaryLenLarge16374AllcolLar49151-error-stmt.json -y " % binPath) - tdSql.error("select * from db.stb4") - tdSql.error("select * from db.stb2") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertNumOfrecordPerReq0-stmt.json -y " % binPath) - tdSql.error("select count(*) from db.stb0") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertNumOfrecordPerReqless0-stmt.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertChildTab0-stmt.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists db") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertChildTabLess0-stmt.json -y " % binPath) - tdSql.error("use db") - tdSql.execute("drop database if exists blf") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertTimestepMulRowsLargeint16-stmt.json -y " % binPath) - tdSql.execute("use blf") - tdSql.query("select ts from blf.p_0_topics_7 limit 262800,1") - tdSql.checkData(0, 0, "2020-03-31 12:00:00.000") - tdSql.query("select first(ts) from blf.p_0_topics_2") - tdSql.checkData(0, 0, "2019-10-01 00:00:00") - tdSql.query("select last(ts) from blf.p_0_topics_6 ") - tdSql.checkData(0, 0, "2020-09-29 23:59:00") - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insertMaxNumPerReq-stmt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 5000000) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 5000000) - - - # insert: sample json - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-sample-ts-stmt.json -y " % binPath) - tdSql.execute("use dbtest123") - tdSql.query("select c2 from stb0") - tdSql.checkData(0, 0, 2147483647) - tdSql.query("select c0 from stb0_0 order by ts") - tdSql.checkData(3, 0, 4) - tdSql.query("select count(*) from stb0 order by ts") - tdSql.checkData(0, 0, 40) - tdSql.query("select * from stb0_1 order by ts") - tdSql.checkData(0, 0, '2021-10-28 15:34:44.735') - tdSql.checkData(3, 0, '2021-10-31 15:34:44.735') - tdSql.query("select * from stb1 where t1=-127") - tdSql.checkRows(20) - tdSql.query("select * from stb1 where t2=127") - tdSql.checkRows(10) - tdSql.query("select * from stb1 where t2=126") - tdSql.checkRows(10) - - # insert: timestamp and step - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-timestep-stmt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("show stables") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 20) - tdSql.query("select last(ts) from db.stb00_0") - tdSql.checkData(0, 0, "2020-10-01 00:00:00.019000") - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 200) - tdSql.query("select last(ts) from db.stb01_0") - tdSql.checkData(0, 0, "2020-11-01 00:00:00.190000") - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 400) - - # # insert: disorder_ratio - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-disorder-stmt.json 2>&1 -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 1) - tdSql.query("select count (tbname) from stb1") - tdSql.checkData(0, 0, 1) - tdSql.query("select count(*) from stb0") - tdSql.checkData(0, 0, 10) - tdSql.query("select count(*) from stb1") - tdSql.checkData(0, 0, 10) - - # insert: sample json - #os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-sample-stmt.json -y " % binPath) - #tdSql.execute("use dbtest123") - #tdSql.query("select c2 from stb0") - #tdSql.checkData(0, 0, 2147483647) - #tdSql.query("select * from stb1 where t1=-127") - #tdSql.checkRows(20) - #tdSql.query("select * from stb1 where t2=127") - #tdSql.checkRows(10) - #tdSql.query("select * from stb1 where t2=126") - #tdSql.checkRows(10) - - # insert: test interlace parament - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/insert-interlace-row-stmt.json -y " % binPath) - tdSql.execute("use db") - tdSql.query("select count (tbname) from stb0") - tdSql.checkData(0, 0, 100) - tdSql.query("select count (*) from stb0") - tdSql.checkData(0, 0, 15000) - - - # insert: auto_create - - tdSql.execute('drop database if exists db') - tdSql.execute('create database db') - tdSql.execute('use db') - os.system("%staosBenchmark -y -f tools/taosdemoAllTest/stmt/insert-drop-exist-auto-N00-stmt.json " % binPath) # drop = no, child_table_exists, auto_create_table varies - tdSql.execute('use db') - tdSql.query('show tables like \'NN123%\'') #child_table_exists = no, auto_create_table varies = 123 - tdSql.checkRows(20) - tdSql.query('show tables like \'NNN%\'') #child_table_exists = no, auto_create_table varies = no - tdSql.checkRows(20) - tdSql.query('show tables like \'NNY%\'') #child_table_exists = no, auto_create_table varies = yes - tdSql.checkRows(20) - tdSql.query('show tables like \'NYN%\'') #child_table_exists = yes, auto_create_table varies = no - tdSql.checkRows(0) - tdSql.query('show tables like \'NY123%\'') #child_table_exists = yes, auto_create_table varies = 123 - tdSql.checkRows(0) - tdSql.query('show tables like \'NYY%\'') #child_table_exists = yes, auto_create_table varies = yes - tdSql.checkRows(0) - - tdSql.execute('drop database if exists db') - os.system("%staosBenchmark -y -f tools/taosdemoAllTest/stmt/insert-drop-exist-auto-Y00-stmt.json " % binPath) # drop = yes, child_table_exists, auto_create_table varies - tdSql.execute('use db') - tdSql.query('show tables like \'YN123%\'') #child_table_exists = no, auto_create_table varies = 123 - tdSql.checkRows(20) - tdSql.query('show tables like \'YNN%\'') #child_table_exists = no, auto_create_table varies = no - tdSql.checkRows(20) - tdSql.query('show tables like \'YNY%\'') #child_table_exists = no, auto_create_table varies = yes - tdSql.checkRows(20) - tdSql.query('show tables like \'YYN%\'') #child_table_exists = yes, auto_create_table varies = no - tdSql.checkRows(20) - tdSql.query('show tables like \'YY123%\'') #child_table_exists = yes, auto_create_table varies = 123 - tdSql.checkRows(20) - tdSql.query('show tables like \'YYY%\'') #child_table_exists = yes, auto_create_table varies = yes - tdSql.checkRows(20) - - testcaseFilename = os.path.split(__file__)[-1] - os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename ) - - - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonStmtPerformance.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonStmtPerformance.py deleted file mode 100644 index ff22ffe5a56bf69559d77bc202f289d4349e1e38..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestInsertWithJsonStmtPerformance.py +++ /dev/null @@ -1,92 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - # tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # insert: create one or mutiple tables per sql and insert multiple rows per sql - os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/1174-small-stmt-random.json -y " % binPath) - # sleep(60) - - # os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/1174-small-taosc.json -y " % binPath) - # sleep(60) - # os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/1174-small-stmt.json -y " % binPath) - # sleep(60) - # os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/1174-large-taosc.json -y " % binPath) - # sleep(60) - # os.system("%staosBenchmark -f tools/taosdemoAllTest/stmt/1174-large-stmt.json -y " % binPath) - - # tdSql.execute("use db") - # tdSql.query("select count (tbname) from stb0") - # tdSql.checkData(0, 0, 1000) - # tdSql.query("select count (tbname) from stb1") - # tdSql.checkData(0, 0, 1000) - # tdSql.query("select count(*) from stb00_0") - # tdSql.checkData(0, 0, 100) - # tdSql.query("select count(*) from stb0") - # tdSql.checkData(0, 0, 100000) - # tdSql.query("select count(*) from stb01_1") - # tdSql.checkData(0, 0, 200) - # tdSql.query("select count(*) from stb1") - # tdSql.checkData(0, 0, 200000) - - - - - testcaseFilename = os.path.split(__file__)[-1] - os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/%s.sql" % testcaseFilename ) - - - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py deleted file mode 100644 index 06dcda48064913d69b18cfa004a8218958e35413..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestQueryWithJson.py +++ /dev/null @@ -1,244 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * -import time -from datetime import datetime -import ast -import re -# from assertpy import assert_that -import subprocess - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] - break - return buildPath - - # 获取taosc接口查询的结果文件中的内容,返回每行数据,并断言数据的第一列内容。 - def assertfileDataTaosc(self, filename, expectResult): - self.filename = filename - self.expectResult = expectResult - with open("%s" % filename, 'r+') as f1: - for line in f1.readlines(): - queryResultTaosc = line.strip().split()[0] - self.assertCheck(filename, queryResultTaosc, expectResult) - - # 获取restful接口查询的结果文件中的关键内容,目前的关键内容找到第一个key就跳出循,所以就只有一个数据。后续再修改多个结果文件。 - def getfileDataRestful(self, filename): - self.filename = filename - with open("%s" % filename, 'r+') as f1: - for line in f1.readlines(): - contents = line.strip() - if contents.find("data") != -1: - pattern = re.compile("{.*}") - contents = pattern.search(contents).group() - contentsDict = ast.literal_eval(contents) # 字符串转换为字典 - queryResultRest = contentsDict['data'][0][0] - break - else : - queryResultRest = "" - return queryResultRest - - - # 获取taosc接口查询次数 - def queryTimesTaosc(self, filename): - self.filename = filename - command = 'cat %s |wc -l' % filename - times = int(subprocess.getstatusoutput(command)[1]) - return times - - # 获取restful接口查询次数 - def queryTimesRestful(self, filename): - self.filename = filename - command = 'cat %s |grep "200 OK" |wc -l' % filename - times = int(subprocess.getstatusoutput(command)[1]) - return times - - # 定义断言结果是否正确。不正确返回错误结果,正确即通过。 - def assertCheck(self, filename, queryResult, expectResult): - self.filename = filename - self.queryResult = queryResult - self.expectResult = expectResult - args0 = (filename, queryResult, expectResult) - assert queryResult == expectResult, "Queryfile:%s ,result is %s != expect: %s" % args0 - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" - - # delete useless files - os.system("rm -rf ./query_res*") - os.system("rm -rf ./all_query*") - - # taosc query: query specified table and query super table - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryInsertdata.json" % - binPath) - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryTaosc.json" % - binPath) - os.system("cat query_res0.txt* > all_query_res0_taosc.txt") - os.system("cat query_res1.txt* > all_query_res1_taosc.txt") - os.system("cat query_res2.txt* > all_query_res2_taosc.txt") - - # correct Times testcases - queryTimes0Taosc = self.queryTimesTaosc("all_query_res0_taosc.txt") - self.assertCheck("all_query_res0_taosc.txt", queryTimes0Taosc, 6) - - queryTimes1Taosc = self.queryTimesTaosc("all_query_res1_taosc.txt") - self.assertCheck("all_query_res1_taosc.txt", queryTimes1Taosc, 6) - - queryTimes2Taosc = self.queryTimesTaosc("all_query_res2_taosc.txt") - self.assertCheck("all_query_res2_taosc.txt", queryTimes2Taosc, 20) - - # correct data testcase - self.assertfileDataTaosc("all_query_res0_taosc.txt", "1604160000099") - self.assertfileDataTaosc("all_query_res1_taosc.txt", "100") - self.assertfileDataTaosc("all_query_res2_taosc.txt", "1604160000199") - - # delete useless files - os.system("rm -rf ./query_res*") - os.system("rm -rf ./all_query*") - - # use restful api to query - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryInsertrestdata.json" % - binPath) - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryRestful.json" % - binPath) - os.system("cat query_res0.txt* > all_query_res0_rest.txt") - os.system("cat query_res1.txt* > all_query_res1_rest.txt") - os.system("cat query_res2.txt* > all_query_res2_rest.txt") - - # correct Times testcases - queryTimes0Restful = self.queryTimesRestful("all_query_res0_rest.txt") - self.assertCheck("all_query_res0_rest.txt", queryTimes0Restful, 6) - - queryTimes1Restful = self.queryTimesRestful("all_query_res1_rest.txt") - self.assertCheck("all_query_res1_rest.txt", queryTimes1Restful, 6) - - queryTimes2Restful = self.queryTimesRestful("all_query_res2_rest.txt") - self.assertCheck("all_query_res2_rest.txt", queryTimes2Restful, 4) - - # correct data testcase - data0 = self.getfileDataRestful("all_query_res0_rest.txt") - self.assertCheck( - 'all_query_res0_rest.txt', - data0, - "2020-11-01 00:00:00.009") - - data1 = self.getfileDataRestful("all_query_res1_rest.txt") - self.assertCheck('all_query_res1_rest.txt', data1, 10) - - data2 = self.getfileDataRestful("all_query_res2_rest.txt") - self.assertCheck( - 'all_query_res2_rest.txt', - data2, - "2020-11-01 00:00:00.004") - - # query times less than or equal to 100 - assert os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryInsertdata.json" % - binPath) == 0 - assert os.system( - "%staosBenchmark -f tools/taosdemoAllTest/querySpeciMutisql100.json" % - binPath) != 0 - assert os.system( - "%staosBenchmark -f tools/taosdemoAllTest/querySuperMutisql100.json" % - binPath) == 0 - - # query result print QPS - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryInsertdata.json" % - binPath) - exceptcode = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryQps.json" % - binPath) - assert exceptcode == 0 - - # use illegal or out of range parameters query json file - os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryInsertdata.json" % - binPath) - exceptcode = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryTimes0.json" % - binPath) - assert exceptcode != 0 - - exceptcode0 = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryTimesless0.json" % - binPath) - assert exceptcode0 != 0 - - exceptcode1 = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryConcurrentless0.json" % - binPath) - assert exceptcode1 != 0 - - exceptcode2 = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/queryConcurrent0.json" % - binPath) - assert exceptcode2 != 0 - - exceptcode3 = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/querrThreadsless0.json" % - binPath) - assert exceptcode3 != 0 - - exceptcode4 = os.system( - "%staosBenchmark -f tools/taosdemoAllTest/querrThreads0.json" % - binPath) - assert exceptcode4 != 0 - - # delete useless files - os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/*.py.sql") - os.system("rm -rf ./querySystemInfo*") - os.system("rm -rf ./query_res*") - os.system("rm -rf ./all_query*") - os.system("rm -rf ./test_query_res0.txt") - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJson.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJson.py deleted file mode 100644 index 265f50237bf2b5dae80eccc94aad885a7b84f5f2..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJson.py +++ /dev/null @@ -1,204 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * -import time -from datetime import datetime -import subprocess - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - # get the number of subscriptions - def subTimes(self,filename): - self.filename = filename - command = 'cat %s |wc -l'% filename - times = int(subprocess.getstatusoutput(command)[1]) - return times - - # assert results - def assertCheck(self,filename,subResult,expectResult): - self.filename = filename - self.subResult = subResult - self.expectResult = expectResult - args0 = (filename, subResult, expectResult) - assert subResult == expectResult , "Queryfile:%s ,result is %s != expect: %s" % args0 - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # clear env - os.system("ps -ef |grep 'taosdemoAllTest/subSync.json' |grep -v 'grep' |awk '{print $2}'|xargs kill -9") - os.system("ps -ef |grep 'taosdemoAllTest/subSyncKeepStart.json' |grep -v 'grep' |awk '{print $2}'|xargs kill -9") - sleep(1) - os.system("rm -rf ./subscribe_res*") - os.system("rm -rf ./all_subscribe_res*") - sleep(2) - # subscribe: sync - os.system("%staosBenchmark -f tools/taosdemoAllTest/subInsertdata.json" % binPath) - os.system("nohup %staosBenchmark -f tools/taosdemoAllTest/subSync.json &" % binPath) - query_pid = int(subprocess.getstatusoutput('ps aux|grep "taosdemoAllTest/subSync.json" |grep -v "grep"|awk \'{print $2}\'')[1]) - - # insert extral data - tdSql.execute("use db") - tdSql.execute("insert into stb00_0 values(1614218412000,'R','bf3',8637,98.861045)") - tdSql.execute("insert into stb00_1 values(1614218412000,'R','bf3',8637,78.861045)(1614218422000,'R','bf3',8637,98.861045)") - sleep(5) - - # merge result files - os.system("cat subscribe_res0.txt* > all_subscribe_res0.txt") - os.system("cat subscribe_res1.txt* > all_subscribe_res1.txt") - os.system("cat subscribe_res2.txt* > all_subscribe_res2.txt") - os.system("cat subscribe_res3.txt* > all_subscribe_res3.txt") - - - # correct subscribeTimes testcase - subTimes0 = self.subTimes("all_subscribe_res0.txt") - self.assertCheck("all_subscribe_res0.txt",subTimes0 ,22) - - subTimes1 = self.subTimes("all_subscribe_res1.txt") - self.assertCheck("all_subscribe_res1.txt",subTimes1 ,24) - - subTimes2 = self.subTimes("all_subscribe_res2.txt") - self.assertCheck("all_subscribe_res2.txt",subTimes2 ,21) - - subTimes3 = self.subTimes("all_subscribe_res3.txt") - self.assertCheck("all_subscribe_res3.txt",subTimes3 ,13) - - - # correct data testcase - os.system("kill -9 %d" % query_pid) - sleep(3) - os.system("rm -rf ./subscribe_res*") - os.system("rm -rf ./all_subscribe*") - - # # sql number lager 100 - os.system("%staosBenchmark -f tools/taosdemoAllTest/subInsertdataMaxsql100.json" % binPath) - assert os.system("%staosBenchmark -f tools/taosdemoAllTest/subSyncSpecMaxsql100.json" % binPath) != 0 - assert os.system("%staosBenchmark -f tools/taosdemoAllTest/subSyncSuperMaxsql100.json" % binPath) != 0 - - # # result files is null - # os.system("%staosBenchmark -f tools/taosdemoAllTest/subInsertdataMaxsql100.json" % binPath) - # os.system("%staosBenchmark -f tools/taosdemoAllTest/subSyncResFileNull.json" % binPath) - # # assert os.system("%staosBenchmark -f tools/taosdemoAllTest/subSyncResFileNull.json" % binPath) != 0 - - - - - # resubAfterConsume= -1 endAfter=-1 ; - os.system('kill -9 `ps aux|grep "subSyncResubACMinus1.json" |grep -v "grep"|awk \'{print $2}\'` ') - os.system("nohup %staosBenchmark -f tools/taosdemoAllTest/Resubjson/subSyncResubACMinus1.json & " % binPath) - sleep(2) - query_pid1 = int(subprocess.getstatusoutput('ps aux|grep "subSyncResubACMinus1.json" |grep -v "grep"|awk \'{print $2}\'')[1]) - print("get sub1 process'pid") - subres0Number1 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res0* |wc -l' )[1]) - subres2Number1 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res2* |wc -l' )[1]) - assert 0==subres0Number1 , "subres0Number1 error" - assert 0==subres2Number1 , "subres2Number1 error" - tdSql.execute("insert into db.stb00_0 values(1614218412000,'R','bf3',8637,78.861045)(1614218413000,'R','bf3',8637,98.861045)") - sleep(4) - subres2Number2 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res0* |wc -l' )[1]) - subres0Number2 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res0* |wc -l' )[1]) - assert 0!=subres2Number2 , "subres2Number2 error" - assert 0!=subres0Number2 , "subres0Number2 error" - os.system("kill -9 %d" % query_pid1) - os.system("rm -rf ./subscribe_res*") - - # # resubAfterConsume= -1 endAfter=0 ; - # os.system("%staosBenchmark -f tools/taosdemoAllTest/subInsertdataMaxsql100.json" % binPath) - # os.system('kill -9 `ps aux|grep "subSyncResubACMinus1endAfter0.json" |grep -v "grep"|awk \'{print $2}\'` ') - # os.system("nohup %staosBenchmark -f tools/taosdemoAllTest/Resubjson/subSyncResubACMinus1endAfter0.json & " % binPath) - # sleep(2) - # query_pid1 = int(subprocess.getstatusoutput('ps aux|grep "subSyncResubACMinus1endAfter0.json" |grep -v "grep"|awk \'{print $2}\'')[1]) - # print("get sub2 process'pid") - # subres0Number1 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res0* |wc -l' )[1]) - # subres2Number1 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res2* |wc -l' )[1]) - # assert 0==subres0Number1 , "subres0Number1 error" - # assert 0==subres2Number1 , "subres2Number1 error" - # tdSql.execute("insert into db.stb00_0 values(1614218412000,'R','bf3',8637,78.861045)(1614218413000,'R','bf3',8637,98.861045)") - # sleep(4) - # subres2Number2 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res0* |wc -l' )[1]) - # subres0Number2 =int(subprocess.getstatusoutput('grep "1614218412000" subscribe_res0* |wc -l' )[1]) - # assert 0!=subres2Number2 , "subres2Number2 error" - # assert 0!=subres0Number2 , "subres0Number2 error" - # os.system("kill -9 %d" % query_pid1) - # os.system("rm -rf ./subscribe_res*") - - - - - # # # merge result files - # os.system("cat subscribe_res0.txt* > all_subscribe_res0.txt") - # os.system("cat subscribe_res1.txt* > all_subscribe_res1.txt") - # os.system("cat subscribe_res2.txt* > all_subscribe_res2.txt") - # # os.system("cat subscribe_res3.txt* > all_subscribe_res3.txt") - - # sleep(3) - - # # correct subscribeTimes testcase - # subTimes0 = self.subTimes("all_subscribe_res0.txt") - # self.assertCheck("all_subscribe_res0.txt",subTimes0 ,3960) - - # subTimes1 = self.subTimes("all_subscribe_res1.txt") - # self.assertCheck("all_subscribe_res1.txt",subTimes1 ,40) - - # subTimes2 = self.subTimes("all_subscribe_res2.txt") - # self.assertCheck("all_subscribe_res2.txt",subTimes2 ,1900) - - - # os.system("%staosBenchmark -f tools/taosdemoAllTest/subSupermaxsql100.json" % binPath) - # os.system("%staosBenchmark -f tools/taosdemoAllTest/subSupermaxsql100.json" % binPath) - - - - # delete useless files - os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/*.py.sql") - os.system("rm -rf ./subscribe_res*") - os.system("rm -rf ./all_subscribe*") - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJsonAsync.py b/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJsonAsync.py deleted file mode 100644 index b236b2b48b93f210f0e73ebb5be240413f82d878..0000000000000000000000000000000000000000 --- a/tests/pytest/tools/taosdemoAllTest/taosdemoTestSubWithJsonAsync.py +++ /dev/null @@ -1,124 +0,0 @@ -################################################################### -# Copyright (c) 2016 by TAOS Technologies, Inc. -# All rights reserved. -# -# This file is proprietary and confidential to TAOS Technologies. -# No part of this file may be reproduced, stored, transmitted, -# disclosed or used in any form or by any means other than as -# expressly provided by the written permission from Jianhui Tao -# -################################################################### - -# -*- coding: utf-8 -*- - -import sys -import os -from util.log import * -from util.cases import * -from util.sql import * -from util.dnodes import * -import time -from datetime import datetime -import subprocess - - -class TDTestCase: - def init(self, conn, logSql): - tdLog.debug("start to execute %s" % __file__) - tdSql.init(conn.cursor(), logSql) - - def getBuildPath(self): - selfPath = os.path.dirname(os.path.realpath(__file__)) - - if ("community" in selfPath): - projPath = selfPath[:selfPath.find("community")] - else: - projPath = selfPath[:selfPath.find("tests")] - - for root, dirs, files in os.walk(projPath): - if ("taosd" in files): - rootRealPath = os.path.dirname(os.path.realpath(root)) - if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] - break - return buildPath - - # 获取订阅次数 - def subTimes(self,filename): - self.filename = filename - command = 'cat %s |wc -l'% filename - times = int(subprocess.getstatusoutput(command)[1]) - return times - - def assertCheck(self,filename,queryResult,expectResult): - self.filename = filename - self.queryResult = queryResult - self.expectResult = expectResult - args0 = (filename, queryResult, expectResult) - assert queryResult == expectResult , "Queryfile:%s ,result is %s != expect: %s" % args0 - - def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") - else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - - # clear env - os.system("ps -ef |grep 'taosdemoAllTest/subAsync.json' |grep -v 'grep' |awk '{print $2}'|xargs kill -9") - sleep(1) - os.system("rm -rf ./subscribe_res*") - os.system("rm -rf ./all_subscribe_res*") - - # subscribe: resultfile - os.system("%staosBenchmark -f tools/taosdemoAllTest/subInsertdata.json" % binPath) - os.system("nohup %staosBenchmark -f tools/taosdemoAllTest/subAsync.json &" % binPath) - query_pid = int(subprocess.getstatusoutput('ps aux|grep "taosdemoAllTest/subAsync.json" |grep -v "grep"|awk \'{print $2}\'')[1]) - - # insert extral data - tdSql.execute("use db") - tdSql.execute("insert into stb00_0 values(1614218412000,'R','bf3',8637,98.861045)") - tdSql.execute("insert into stb00_1 values(1614218412000,'R','bf3',8637,78.861045)(1614218422000,'R','bf3',8637,98.861045)") - sleep(5) - - # merge result files - os.system("cat subscribe_res0.txt* > all_subscribe_res0.txt") - os.system("cat subscribe_res1.txt* > all_subscribe_res1.txt") - os.system("cat subscribe_res2.txt* > all_subscribe_res2.txt") - os.system("cat subscribe_res3.txt* > all_subscribe_res3.txt") - - # correct subscribeTimes testcase - subTimes0 = self.subTimes("all_subscribe_res0.txt") - self.assertCheck("all_subscribe_res0.txt",subTimes0 ,22) - - subTimes1 = self.subTimes("all_subscribe_res1.txt") - self.assertCheck("all_subscribe_res1.txt",subTimes1 ,24) - - subTimes2 = self.subTimes("all_subscribe_res2.txt") - self.assertCheck("all_subscribe_res2.txt",subTimes2 ,21) - - subTimes3 = self.subTimes("all_subscribe_res3.txt") - self.assertCheck("all_subscribe_res3.txt",subTimes3 ,13) - - # correct data testcase - - os.system("kill -9 %d" % query_pid) - - # # query times less than or equal to 100 - os.system("%staosBenchmark -f tools/taosdemoAllTest/subInsertdataMaxsql100.json" % binPath) - assert os.system("%staosBenchmark -f tools/taosdemoAllTest/subSyncSpecMaxsql100.json" % binPath) != 0 - assert os.system("%staosBenchmark -f tools/taosdemoAllTest/subSyncSuperMaxsql100.json" % binPath) != 0 - - # delete useless files - os.system("rm -rf ./insert_res.txt") - os.system("rm -rf tools/taosdemoAllTest/*.py.sql") - os.system("rm -rf ./subscribe_res*") - os.system("rm -rf ./all_subscribe*") - - def stop(self): - tdSql.close() - tdLog.success("%s successfully executed" % __file__) - -tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdemoTest.py b/tests/pytest/tools/taosdemoTest.py index 54e0906672637c1187cb8b078f1e8496e461e150..3de3961faf36f113ae4cc260be8005b0fb5a8bf8 100644 --- a/tests/pytest/tools/taosdemoTest.py +++ b/tests/pytest/tools/taosdemoTest.py @@ -27,7 +27,7 @@ class TDTestCase: self.numberOfTables = 1000 self.numberOfRecords = 100 - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -35,23 +35,23 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosdemo not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosdemo found in %s" % buildPath) - binPath = buildPath + "/build/bin/" - os.system("%staosBenchmark -y -t %d -n %d -b INT,INT,INT,INT" % + tdLog.info("taosBenchmark found: %s" % binPath) + os.system("%s -y -t %d -n %d -b INT,INT,INT,INT" % (binPath, self.numberOfTables, self.numberOfRecords)) tdSql.execute("use test") diff --git a/tests/pytest/tools/taosdemoTestInterlace.py b/tests/pytest/tools/taosdemoTestInterlace.py index 72f70edcbaa582231189677b9e15d76e507d3dec..8c2f0bd0eefd6a4e8a8c69090c571f922e759517 100644 --- a/tests/pytest/tools/taosdemoTestInterlace.py +++ b/tests/pytest/tools/taosdemoTestInterlace.py @@ -25,7 +25,7 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -33,24 +33,23 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] - buildPath = "" + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" - taosdemoCmd = "%staosBenchmark -f tools/insert-interlace.json -G 2>&1 | grep sleep | wc -l" % binPath + tdLog.info("taosBenchmark found in %s" % binPath) + taosdemoCmd = "%s -f tools/insert-interlace.json -G 2>&1 | grep sleep | wc -l" % binPath sleepTimes = subprocess.check_output( taosdemoCmd, shell=True).decode("utf-8") print("sleep times: %d" % int(sleepTimes)) diff --git a/tests/pytest/tools/taosdemoTestLimitOffset.py b/tests/pytest/tools/taosdemoTestLimitOffset.py index e69098b7f562f996b2bad58b10df63fdaf8a8398..b5aa8d75b9bfddd4fd45c3c349f45920649e1350 100644 --- a/tests/pytest/tools/taosdemoTestLimitOffset.py +++ b/tests/pytest/tools/taosdemoTestLimitOffset.py @@ -27,7 +27,7 @@ class TDTestCase: self.numberOfTables = 10000 self.numberOfRecords = 100 - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -35,24 +35,28 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath("taosBenchmark") + if (binPath == ""): tdLog.exit("taosd not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - os.system("%staosBenchmark -f tools/insert-tblimit-tboffset-createdb.json" % binPath) - os.system("%staosBenchmark -f tools/insert-tblimit-tboffset-insertrec.json" % binPath) + tdLog.info("taosd found in %s" % binPath) + os.system( + "%s -f tools/insert-tblimit-tboffset-createdb.json" % + binPath) + os.system( + "%s -f tools/insert-tblimit-tboffset-insertrec.json" % + binPath) tdSql.execute("use db") tdSql.query("select count(tbname) from db.stb") @@ -60,8 +64,10 @@ class TDTestCase: tdSql.query("select count(*) from db.stb") tdSql.checkData(0, 0, 33000) - os.system("%staosBenchmark -f tools/insert-tblimit-tboffset-createdb.json" % binPath) - os.system("%staosBenchmark -f tools/insert-tblimit-tboffset0.json" % binPath) + os.system( + "%s -f tools/insert-tblimit-tboffset-createdb.json" % + binPath) + os.system("%s -f tools/insert-tblimit-tboffset0.json" % binPath) tdSql.execute("reset query cache") tdSql.execute("use db") @@ -70,8 +76,10 @@ class TDTestCase: tdSql.query("select count(*) from db.stb") tdSql.checkData(0, 0, 20000) - os.system("%staosBenchmark -f tools/insert-tblimit-tboffset-createdb.json" % binPath) - os.system("%staosBenchmark -f tools/insert-tblimit1-tboffset.json" % binPath) + os.system( + "%s -f tools/insert-tblimit-tboffset-createdb.json" % + binPath) + os.system("%s -f tools/insert-tblimit1-tboffset.json" % binPath) tdSql.execute("reset query cache") tdSql.execute("use db") diff --git a/tests/pytest/tools/taosdemoTestQuery.py b/tests/pytest/tools/taosdemoTestQuery.py index c77688aefaf93898ae33044408dd4027d71b07e9..4d30835ec0533014644041f074f979be69b817e3 100644 --- a/tests/pytest/tools/taosdemoTestQuery.py +++ b/tests/pytest/tools/taosdemoTestQuery.py @@ -29,7 +29,7 @@ class TDTestCase: self.numberOfTables = 1000 self.numberOfRecords = 100 - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -37,28 +37,28 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" - os.system("%staosBenchmark -y -t %d -n %d" % + tdLog.info("taosBenchmark found in %s" % binPath) + os.system("%s -y -t %d -n %d" % (binPath, self.numberOfTables, self.numberOfRecords)) print("Sleep 2 seconds..") time.sleep(2) - os.system('%staosBenchmark -f tools/query.json ' % binPath) -# taosdemoCmd = '%staosBenchmark -f tools/query.json ' % binPath + os.system('%s -f tools/query.json ' % binPath) +# taosdemoCmd = '%s tools/query.json ' % binPath # threads = subprocess.check_output( # taosdemoCmd, shell=True).decode("utf-8") # print("threads: %d" % int(threads)) diff --git a/tests/pytest/tools/taosdemoTestSampleData.py b/tests/pytest/tools/taosdemoTestSampleData.py index 09a2e6c43b68d8271cb0472b288279b54789fded..5f1d6a28bfd954ad750f09df8a4c2c69b9297b0a 100644 --- a/tests/pytest/tools/taosdemoTestSampleData.py +++ b/tests/pytest/tools/taosdemoTestSampleData.py @@ -27,7 +27,7 @@ class TDTestCase: self.numberOfTables = 10000 self.numberOfRecords = 100 - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -35,23 +35,23 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath+ "/build/bin/" - os.system("%staosBenchmark -f tools/taosdemo-sampledata.json" % binPath) + tdLog.info("taosBenchmark found in %s" % binPath) + os.system("%s -f tools/taosdemo-sampledata.json" % binPath) tdSql.execute("use db") tdSql.query("select count(tbname) from db.stb") diff --git a/tests/pytest/tools/taosdemoTestTblAlt.py b/tests/pytest/tools/taosdemoTestTblAlt.py index 444aab519bf7089b792125ffa3caa6de5ad4eb8d..6abdaa7a8045b091ed2ddcb34d84e4cf78e2a827 100644 --- a/tests/pytest/tools/taosdemoTestTblAlt.py +++ b/tests/pytest/tools/taosdemoTestTblAlt.py @@ -29,8 +29,7 @@ class TDTestCase: self.numberOfTables = 8 self.numberOfRecords = 1000000 - def getBuildPath(self): - buildPath="" + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -38,26 +37,26 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files and "taosBenchmark" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def insertDataAndAlterTable(self, threadID): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd or staosBenchmark not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) if(threadID == 0): - print("%staosBenchmark -y -t %d -n %d -b INT,INT,INT,INT" % - (binPath, self.numberOfTables, self.numberOfRecords)) - os.system("%staosBenchmark -y -t %d -n %d -b INT,INT,INT,INT" % + print("%s -y -t %d -n %d -b INT,INT,INT,INT" % + (binPath, self.numberOfTables, self.numberOfRecords)) + os.system("%s -y -t %d -n %d -b INT,INT,INT,INT" % (binPath, self.numberOfTables, self.numberOfRecords)) if(threadID == 1): time.sleep(2) diff --git a/tests/pytest/tools/taosdemoTestWithJson.py b/tests/pytest/tools/taosdemoTestWithJson.py index 0868d07fd99f7731424a3f11883ae52d12f1e878..7bf076ea4b23618c14015f53691a91283e9e7f4b 100644 --- a/tests/pytest/tools/taosdemoTestWithJson.py +++ b/tests/pytest/tools/taosdemoTestWithJson.py @@ -24,31 +24,31 @@ class TDTestCase: tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) - if "community" in selfPath: - projPath = selfPath[: selfPath.find("community")] + if ("community" in selfPath): + projPath = selfPath[:selfPath.find("community")] else: - projPath = selfPath[: selfPath.find("tests")] + projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if "taosd" in files: + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) - if "packaging" not in rootRealPath: - buildPath = root[: len(root) - len("/build/bin")] + if ("packaging" not in rootRealPath): + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): tdSql.prepare() - buildPath = self.getBuildPath() - if buildPath == "": - tdLog.exit("taosd not found!") + binPath = self.getPath("taosBenchmark") + if binPath == "": + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" - os.system("%staosBenchmark -f tools/insert.json -y" % binPath) + tdLog.info("taosBenchmark found: %s" % binPath) + os.system("%s -f tools/insert.json -y" % binPath) tdSql.execute("use db01") tdSql.query("select count(*) from stb01") diff --git a/tests/pytest/tools/taosdemoTestWithoutMetric.py b/tests/pytest/tools/taosdemoTestWithoutMetric.py index a92a4519e2d716b85df0ec29c9cf49abb0812b47..c41656c508b2129cf8e633822287861b792a22ef 100644 --- a/tests/pytest/tools/taosdemoTestWithoutMetric.py +++ b/tests/pytest/tools/taosdemoTestWithoutMetric.py @@ -27,7 +27,7 @@ class TDTestCase: self.numberOfTables = 100 self.numberOfRecords = 1000 - def getBuildPath(self): + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -35,32 +35,32 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosd not found!") + binPath = self.getPath() + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosd found in %s" % buildPath) - binPath = buildPath + "/build/bin/" - os.system("%staosBenchmark -N -y -t %d -n %d" % + tdLog.info("taosBenchmark found in %s" % binPath) + os.system("%s -N -y -t %d -n %d" % (binPath, self.numberOfTables, self.numberOfRecords)) tdSql.query("show databases") for i in range(18): - print(tdSql.getData(0, i) ) + print(tdSql.getData(0, i)) tdSql.checkData(0, 2, self.numberOfTables) tdSql.execute("use test") tdSql.query( - "select count(*) from test.d%d" % (self.numberOfTables -1)) + "select count(*) from test.d%d" % (self.numberOfTables - 1)) tdSql.checkData(0, 0, self.numberOfRecords) def stop(self): diff --git a/tests/pytest/tools/taosdemoTestdatatype.py b/tests/pytest/tools/taosdemoTestdatatype.py index ba99b0c532af3497de2daf4d0757b9105405dc1d..c27d65ee1ca84cc6d79d66770547ec54cae61a0d 100644 --- a/tests/pytest/tools/taosdemoTestdatatype.py +++ b/tests/pytest/tools/taosdemoTestdatatype.py @@ -18,6 +18,7 @@ from util.cases import * from util.sql import * from util.dnodes import * + class TDTestCase: def init(self, conn, logSql): tdLog.debug("start to execute %s" % __file__) @@ -25,8 +26,8 @@ class TDTestCase: self.numberOfTables = 10 self.numberOfRecords = 10 - - def getBuildPath(self): + + def getPath(self, tool="taosBenchmark"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -34,61 +35,63 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): - buildPath = self.getBuildPath() - if (buildPath == ""): - tdLog.exit("taosdemo not found!") + binPath = self.getPath("taosBenchmark") + if (binPath == ""): + tdLog.exit("taosBenchmark not found!") else: - tdLog.info("taosdemo found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosBenchmark found in %s" % binPath) + + os.system( + "%s -d test002 -y -t %d -n %d -b INT,nchar\\(8\\),binary\\(16\\),binary,nchar -w 8" % + (binPath, self.numberOfTables, self.numberOfRecords)) - os.system("%staosBenchmark -d test002 -y -t %d -n %d -b INT,nchar\\(8\\),binary\\(16\\),binary,nchar -w 8" % - (binPath, self.numberOfTables, self.numberOfRecords)) - tdSql.execute('use test002') tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, self.numberOfTables * self.numberOfRecords) tdSql.query("select * from meters") tdSql.checkRows(self.numberOfTables * self.numberOfRecords) - - tdLog.info('insert into d1 values(now,100,"abcd1234","abcdefgh12345678","abcdefgh","abcdefgh")') - tdSql.execute('insert into d1 values(now,100,"abcd1234","abcdefgh12345678","abcdefgh","abcdefgh")') + + tdLog.info( + 'insert into d1 values(now,100,"abcd1234","abcdefgh12345678","abcdefgh","abcdefgh")') + tdSql.execute( + 'insert into d1 values(now,100,"abcd1234","abcdefgh12345678","abcdefgh","abcdefgh")') tdSql.query("select * from meters") tdSql.checkRows(101) tdSql.error('insert into d1 values(now,100,"abcd","abcd"') tdSql.error('insert into d1 values(now,100,100,100)') - os.system("%staosBenchmark -d test002 -y -t %d -n %d --data-type INT,nchar\\(8\\),binary\\(16\\),binary,nchar -w 8" % - (binPath, self.numberOfTables, self.numberOfRecords)) + os.system( + "%s -d test002 -y -t %d -n %d --data-type INT,nchar\\(8\\),binary\\(16\\),binary,nchar -w 8" % + (binPath, self.numberOfTables, self.numberOfRecords)) tdSql.execute('use test002') tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, self.numberOfTables * self.numberOfRecords) - - os.system("%staosBenchmark -d test002 -y -t %d -n %d -bINT,nchar\\(8\\),binary\\(16\\),binary,nchar -w 8" % - (binPath, self.numberOfTables, self.numberOfRecords)) + os.system( + "%s -d test002 -y -t %d -n %d -bINT,nchar\\(8\\),binary\\(16\\),binary,nchar -w 8" % + (binPath, self.numberOfTables, self.numberOfRecords)) tdSql.execute('use test002') tdSql.query("select count(*) from meters") tdSql.checkData(0, 0, self.numberOfTables * self.numberOfRecords) - - def stop(self): tdSql.close() tdLog.success("%s successfully executed" % __file__) tdCases.addWindows(__file__, TDTestCase()) -tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file +tdCases.addLinux(__file__, TDTestCase()) diff --git a/tests/pytest/tools/taosdumpTest.py b/tests/pytest/tools/taosdumpTest.py index 628617e27b4af8695b96961441c6b135bdb15416..a92c2421193863769d749665827a5e0b31a0a5c0 100644 --- a/tests/pytest/tools/taosdumpTest.py +++ b/tests/pytest/tools/taosdumpTest.py @@ -35,7 +35,7 @@ class TDTestCase: else: return True - def getBuildPath(self): + def getPath(self, tool="taosdump"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -43,13 +43,14 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosdump" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): if not os.path.exists("./taosdumptest/tmp1"): @@ -78,16 +79,15 @@ class TDTestCase: sql += "(%d, %d, 'nchar%d')" % (currts + i, i % 100, i % 100) tdSql.execute(sql) - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath() + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found: %s" % binPath) - os.system("%staosdump --databases db -o ./taosdumptest/tmp1" % binPath) + os.system("%s -y --databases db -o ./taosdumptest/tmp1" % binPath) os.system( - "%staosdump --databases db1 -o ./taosdumptest/tmp2" % + "%s -y --databases db1 -o ./taosdumptest/tmp2" % binPath) tdSql.execute("drop database db") @@ -95,8 +95,8 @@ class TDTestCase: tdSql.query("show databases") tdSql.checkRows(0) - os.system("%staosdump -i ./taosdumptest/tmp1" % binPath) - os.system("%staosdump -i ./taosdumptest/tmp2" % binPath) + os.system("%s -i ./taosdumptest/tmp1" % binPath) + os.system("%s -i ./taosdumptest/tmp2" % binPath) tdSql.execute("use db") tdSql.query("show databases") @@ -168,9 +168,10 @@ class TDTestCase: tdSql.query("show stables") tdSql.checkRows(2) os.system( - "%staosdump --databases db12312313231231321312312312_323 -o ./taosdumptest/tmp1" % binPath) + "%s -y --databases db12312313231231321312312312_323 -o ./taosdumptest/tmp1" % + binPath) tdSql.execute("drop database db12312313231231321312312312_323") - os.system("%staosdump -i ./taosdumptest/tmp1" % binPath) + os.system("%s -i ./taosdumptest/tmp1" % binPath) tdSql.execute("use db12312313231231321312312312_323") tdSql.query("show stables") tdSql.checkRows(2) diff --git a/tests/pytest/tools/taosdumpTest2.py b/tests/pytest/tools/taosdumpTest2.py index c405d4c5c67611ff87bee69e87c79820237419cb..53c5109830f389395afbb354a77fa56f1bef7f65 100644 --- a/tests/pytest/tools/taosdumpTest2.py +++ b/tests/pytest/tools/taosdumpTest2.py @@ -22,7 +22,7 @@ import string import random -class TDTestCase: +class TDTestCase: def init(self, conn, logSql): tdLog.debug("start to execute %s" % __file__) @@ -32,7 +32,7 @@ class TDTestCase: self.numberOfTables = 1 self.numberOfRecords = 15000 - def getBuildPath(self): + def getPath(self, tool="taosdump"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -40,13 +40,14 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def generateString(self, length): chars = string.ascii_uppercase + string.ascii_lowercase @@ -71,24 +72,23 @@ class TDTestCase: break tdSql.execute(sql) - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath() + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found in %s" % binPath) os.system("rm /tmp/*.sql") os.system("rm /tmp/*.avro*") os.system( - "%staosdump --databases db -o /tmp " % + "%s --databases db -o /tmp " % binPath) tdSql.execute("drop database db") tdSql.query("show databases") tdSql.checkRows(0) - os.system("%staosdump -i /tmp -y" % binPath) + os.system("%s -i /tmp -y" % binPath) tdSql.query("show databases") tdSql.checkRows(1) @@ -100,23 +100,28 @@ class TDTestCase: tdSql.checkData(0, 0, 'st') tdSql.query("select count(*) from t1") - tdSql.checkData(0, 0, self.numberOfRecords) + tdSql.checkData(0, 0, self.numberOfRecords) # test case for TS-1225 tdSql.execute("create database test") tdSql.execute("use test") - tdSql.execute("create table stb(ts timestamp, c1 binary(16374), c2 binary(16374), c3 binary(16374)) tags(t1 nchar(256))") - tdSql.execute("insert into t1 using stb tags('t1') values(now, '%s', '%s', '%s')" % (self.generateString(16374), self.generateString(16374), self.generateString(16374))) - + tdSql.execute( + "create table stb(ts timestamp, c1 binary(16374), c2 binary(16374), c3 binary(16374)) tags(t1 nchar(256))") + tdSql.execute( + "insert into t1 using stb tags('t1') values(now, '%s', '%s', '%s')" % + (self.generateString(16374), + self.generateString(16374), + self.generateString(16374))) + os.system("rm /tmp/*.sql") os.system("rm /tmp/*.avro*") - os.system("%staosdump -D test -o /tmp -y" % binPath) + os.system("%s -D test -o /tmp -y" % binPath) tdSql.execute("drop database test") tdSql.query("show databases") tdSql.checkRows(1) - os.system("%staosdump -i /tmp -y" % binPath) + os.system("%s -i /tmp -y" % binPath) tdSql.execute("use test") tdSql.error("show vnodes '' ") diff --git a/tests/pytest/tools/taosdumpTest3.py b/tests/pytest/tools/taosdumpTest3.py index e506d5b7e889adc326650a3b0016cda71b97c746..e91540fdd156d4b5462980dbcd5b37789cbea963 100644 --- a/tests/pytest/tools/taosdumpTest3.py +++ b/tests/pytest/tools/taosdumpTest3.py @@ -35,7 +35,7 @@ class TDTestCase: else: return True - def getBuildPath(self): + def getPath(self, tool="taosdump"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -43,166 +43,201 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosdump" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def run(self): if not os.path.exists("./taosdumptest"): os.makedirs("./taosdumptest") - for i in range(1,9): - if not os.path.exists("./taosdumptest/tmp%d"%i): - os.makedirs("./taosdumptest/tmp%d"%i) + for i in range(1, 9): + if not os.path.exists("./taosdumptest/tmp%d" % i): + os.makedirs("./taosdumptest/tmp%d" % i) else: - os.system("rm -rf ./taosdumptest/tmp%d"%i) - os.makedirs("./taosdumptest/tmp%d"%i) + os.system("rm -rf ./taosdumptest/tmp%d" % i) + os.makedirs("./taosdumptest/tmp%d" % i) - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath("taosdump") + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found in %s" % binPath) # create db1 , one stables and one table ; create general tables tdSql.execute("drop database if exists dp1") tdSql.execute("drop database if exists dp2") tdSql.execute("create database if not exists dp1") tdSql.execute("use dp1") - tdSql.execute("create stable st0(ts timestamp, c1 int, c2 nchar(10)) tags(t1 int)") - tdSql.execute("create table st0_0 using st0 tags(0) st0_1 using st0 tags (1) ") - tdSql.execute("insert into st0_0 values(1614218412000,8537,'R')(1614218422000,8538,'E')") - tdSql.execute("insert into st0_1 values(1614218413000,1537,'A')(1614218423000,1538,'D')") - tdSql.execute("create table if not exists gt0 (ts timestamp, c0 int, c1 float) ") - tdSql.execute("create table if not exists gt1 (ts timestamp, c0 int, c1 double) ") + tdSql.execute( + "create stable st0(ts timestamp, c1 int, c2 nchar(10)) tags(t1 int)") + tdSql.execute( + "create table st0_0 using st0 tags(0) st0_1 using st0 tags (1) ") + tdSql.execute( + "insert into st0_0 values(1614218412000,8537,'R')(1614218422000,8538,'E')") + tdSql.execute( + "insert into st0_1 values(1614218413000,1537,'A')(1614218423000,1538,'D')") + tdSql.execute( + "create table if not exists gt0 (ts timestamp, c0 int, c1 float) ") + tdSql.execute( + "create table if not exists gt1 (ts timestamp, c0 int, c1 double) ") tdSql.execute("insert into gt0 values(1614218412000,637,8.861)") tdSql.execute("insert into gt1 values(1614218413000,638,8.862)") - # create db1 , three stables:stb0,include ctables stb0_0 \ stb0_1,stb1 include ctables stb1_0 and stb1_1 - # \stb3,include ctables stb3_0 and stb3_1 + # create db1 , three stables:stb0,include ctables stb0_0 \ stb0_1,stb1 include ctables stb1_0 and stb1_1 + # \stb3,include ctables stb3_0 and stb3_1 # create general three tables gt0 gt1 gt2 tdSql.execute("create database if not exists dp2") tdSql.execute("use dp2") - tdSql.execute("create stable st0(ts timestamp, c01 int, c02 nchar(10)) tags(t1 int)") - tdSql.execute("create table st0_0 using st0 tags(0) st0_1 using st0 tags(1) ") - tdSql.execute("insert into st0_0 values(1614218412000,8600,'R')(1614218422000,8600,'E')") - tdSql.execute("insert into st0_1 values(1614218413000,8601,'A')(1614218423000,8601,'D')") - tdSql.execute("create stable st1(ts timestamp, c11 float, c12 nchar(10)) tags(t1 int)") - tdSql.execute("create table st1_0 using st1 tags(0) st1_1 using st1 tags(1) ") - tdSql.execute("insert into st1_0 values(1614218412000,8610.1,'R')(1614218422000,8610.1,'E')") - tdSql.execute("insert into st1_1 values(1614218413000,8611.2,'A')(1614218423000,8611.1,'D')") - tdSql.execute("create stable st2(ts timestamp, c21 float, c22 nchar(10)) tags(t1 int)") - tdSql.execute("create table st2_0 using st2 tags(0) st2_1 using st2 tags(1) ") - tdSql.execute("insert into st2_0 values(1614218412000,8620.3,'R')(1614218422000,8620.3,'E')") - tdSql.execute("insert into st2_1 values(1614218413000,8621.4,'A')(1614218423000,8621.4,'D')") - tdSql.execute("create table if not exists gt0 (ts timestamp, c00 int, c01 float) ") - tdSql.execute("create table if not exists gt1 (ts timestamp, c10 int, c11 double) ") - tdSql.execute("create table if not exists gt2 (ts timestamp, c20 int, c21 float) ") + tdSql.execute( + "create stable st0(ts timestamp, c01 int, c02 nchar(10)) tags(t1 int)") + tdSql.execute( + "create table st0_0 using st0 tags(0) st0_1 using st0 tags(1) ") + tdSql.execute( + "insert into st0_0 values(1614218412000,8600,'R')(1614218422000,8600,'E')") + tdSql.execute( + "insert into st0_1 values(1614218413000,8601,'A')(1614218423000,8601,'D')") + tdSql.execute( + "create stable st1(ts timestamp, c11 float, c12 nchar(10)) tags(t1 int)") + tdSql.execute( + "create table st1_0 using st1 tags(0) st1_1 using st1 tags(1) ") + tdSql.execute( + "insert into st1_0 values(1614218412000,8610.1,'R')(1614218422000,8610.1,'E')") + tdSql.execute( + "insert into st1_1 values(1614218413000,8611.2,'A')(1614218423000,8611.1,'D')") + tdSql.execute( + "create stable st2(ts timestamp, c21 float, c22 nchar(10)) tags(t1 int)") + tdSql.execute( + "create table st2_0 using st2 tags(0) st2_1 using st2 tags(1) ") + tdSql.execute( + "insert into st2_0 values(1614218412000,8620.3,'R')(1614218422000,8620.3,'E')") + tdSql.execute( + "insert into st2_1 values(1614218413000,8621.4,'A')(1614218423000,8621.4,'D')") + tdSql.execute( + "create table if not exists gt0 (ts timestamp, c00 int, c01 float) ") + tdSql.execute( + "create table if not exists gt1 (ts timestamp, c10 int, c11 double) ") + tdSql.execute( + "create table if not exists gt2 (ts timestamp, c20 int, c21 float) ") tdSql.execute("insert into gt0 values(1614218412700,8637,78.86155)") - tdSql.execute("insert into gt1 values(1614218413800,8638,78.862020199)") + tdSql.execute( + "insert into gt1 values(1614218413800,8638,78.862020199)") tdSql.execute("insert into gt2 values(1614218413900,8639,78.863)") - # create + # create tdSql.execute("create database if not exists dp3 precision 'ns'") tdSql.execute("use dp3") - tdSql.execute("create stable st0(ts timestamp, c01 int, c02 nchar(10)) tags(t1 int)") - tdSql.execute("create table st0_0 using st0 tags(0) st0_1 using st0 tags(1) ") - tdSql.execute("insert into st0_0 values(1614218412000000001,8600,'R')(1614218422000000002,8600,'E')") - tdSql.execute("insert into st0_1 values(1614218413000000001,8601,'A')(1614218423000000002,8601,'D')") - + tdSql.execute( + "create stable st0(ts timestamp, c01 int, c02 nchar(10)) tags(t1 int)") + tdSql.execute( + "create table st0_0 using st0 tags(0) st0_1 using st0 tags(1) ") + tdSql.execute( + "insert into st0_0 values(1614218412000000001,8600,'R')(1614218422000000002,8600,'E')") + tdSql.execute( + "insert into st0_1 values(1614218413000000001,8601,'A')(1614218423000000002,8601,'D')") # # taosdump stable and general table - os.system("%staosdump -o ./taosdumptest/tmp1 -D dp1,dp2 -T 8 " % binPath) - os.system("%staosdump -o ./taosdumptest/tmp2 dp1 st0 gt0 -T 8 " % binPath) - os.system("%staosdump -o ./taosdumptest/tmp3 dp2 st0 st1_0 gt0 -T 8 " % binPath) - os.system("%staosdump -o ./taosdumptest/tmp4 dp2 st0 st2 gt0 gt2 -T 8 " % binPath) - - # verify ns - os.system("%staosdump -o ./taosdumptest/tmp6 dp3 st0_0 -T 8 " % binPath) + os.system("%s -o ./taosdumptest/tmp1 -D dp1,dp2 -T 8 " % binPath) + os.system("%s -o ./taosdumptest/tmp2 dp1 st0 gt0 -T 8 " % binPath) + os.system( + "%s -o ./taosdumptest/tmp3 dp2 st0 st1_0 gt0 -T 8 " % + binPath) + os.system( + "%s -o ./taosdumptest/tmp4 dp2 st0 st2 gt0 gt2 -T 8 " % + binPath) + + # verify ns + os.system("%s -o ./taosdumptest/tmp6 dp3 st0_0 -T 8 " % binPath) # verify -D:--database - assert os.system("%staosdump -o ./taosdumptest/tmp5 --databases dp1,dp2 -T 8 " % binPath) == 0 + assert os.system( + "%s -o ./taosdumptest/tmp5 --databases dp1,dp2 -T 8 " % + binPath) == 0 # verify mixed -D:--database and dbname tbname - assert os.system("%staosdump --databases dp1 -o ./taosdumptest/tmp5 dp2 st0 st1_0 gt0 -T 8 " % binPath) != 0 + assert os.system( + "%s --databases dp1 -o ./taosdumptest/tmp5 dp2 st0 st1_0 gt0 -T 8 " % + binPath) != 0 # verify -N - os.system("%staosdump -o ./taosdumptest/tmp7 dp3 st0_0 -N -d null -T 8 " % binPath) + os.system( + "%s -o ./taosdumptest/tmp7 dp3 st0_0 -N -d null -T 8 " % + binPath) # verify -N -s - os.system("%staosdump -o ./taosdumptest/tmp8 dp3 st0_0 -N -s -T 8 " % binPath) + os.system( + "%s -o ./taosdumptest/tmp8 dp3 st0_0 -N -s -T 8 " % + binPath) - #check taosdumptest/tmp1 + # check taosdumptest/tmp1 tdSql.execute("drop database dp1") tdSql.execute("drop database dp2") - os.system("%staosdump -i ./taosdumptest/tmp1 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp1 -T 8 " % binPath) tdSql.execute("use dp1") tdSql.query("show stables") tdSql.checkRows(1) tdSql.query("show tables") tdSql.checkRows(4) tdSql.query("select c1 from st0_0 order by ts") - tdSql.checkData(0,0,8537) + tdSql.checkData(0, 0, 8537) tdSql.query("select c2 from st0_1 order by ts") - tdSql.checkData(1,0,"D") + tdSql.checkData(1, 0, "D") tdSql.query("select * from gt0") - tdSql.checkData(0,0,'2021-02-25 10:00:12.000') - tdSql.checkData(0,1,637) + tdSql.checkData(0, 0, '2021-02-25 10:00:12.000') + tdSql.checkData(0, 1, 637) tdSql.execute("use dp2") tdSql.query("show stables") tdSql.checkRows(3) tdSql.query("show tables") tdSql.checkRows(9) tdSql.query("select ts from gt0") - tdSql.checkData(0,0,'2021-02-25 10:00:12.700') + tdSql.checkData(0, 0, '2021-02-25 10:00:12.700') tdSql.query("select c10 from gt1") tdSql.checkData(0, 0, 8638) tdSql.query("select c20 from gt2") tdSql.checkData(0, 0, 8639) - - #check taosdumptest/tmp2 + # check taosdumptest/tmp2 tdSql.execute("drop database dp1") tdSql.execute("drop database dp2") - os.system("%staosdump -i ./taosdumptest/tmp2 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp2 -T 8 " % binPath) tdSql.execute("use dp1") tdSql.query("show stables") tdSql.checkRows(1) tdSql.query("show tables") tdSql.checkRows(3) tdSql.query("select c1 from st0_0 order by ts") - tdSql.checkData(0,0,8537) + tdSql.checkData(0, 0, 8537) tdSql.query("select c2 from st0_1 order by ts") - tdSql.checkData(1,0,"D") + tdSql.checkData(1, 0, "D") tdSql.query("select * from gt0") - tdSql.checkData(0,0,'2021-02-25 10:00:12.000') - tdSql.checkData(0,1,637) + tdSql.checkData(0, 0, '2021-02-25 10:00:12.000') + tdSql.checkData(0, 1, 637) tdSql.error("select count(*) from gt1") tdSql.error("use dp2") - - #check taosdumptest/tmp3 + # check taosdumptest/tmp3 tdSql.execute("drop database dp1") - os.system("%staosdump -i ./taosdumptest/tmp3 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp3 -T 8 " % binPath) tdSql.execute("use dp2") tdSql.query("show stables") tdSql.checkRows(2) tdSql.query("show tables") tdSql.checkRows(4) tdSql.query("select count(*) from st1_0") - tdSql.checkData(0,0,2) + tdSql.checkData(0, 0, 2) tdSql.query("select ts from gt0") - tdSql.checkData(0,0,'2021-02-25 10:00:12.700') + tdSql.checkData(0, 0, '2021-02-25 10:00:12.700') tdSql.error("use dp1") tdSql.error("select count(*) from st2_0") tdSql.error("select count(*) from gt2") - #check taosdumptest/tmp4 + # check taosdumptest/tmp4 tdSql.execute("drop database dp2") - os.system("%staosdump -i ./taosdumptest/tmp4 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp4 -T 8 " % binPath) tdSql.execute("use dp2") tdSql.query("show stables") tdSql.checkRows(2) @@ -223,10 +258,9 @@ class TDTestCase: tdSql.error("select count(*) from st1_1") tdSql.error("select count(*) from gt3") - - #check taosdumptest/tmp5 + # check taosdumptest/tmp5 tdSql.execute("drop database dp2") - os.system("%staosdump -i ./taosdumptest/tmp5 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp5 -T 8 " % binPath) tdSql.execute("use dp2") tdSql.query("show stables") tdSql.checkRows(3) @@ -252,39 +286,39 @@ class TDTestCase: tdSql.query("show tables") tdSql.checkRows(4) tdSql.query("select c1 from st0_0 order by ts") - tdSql.checkData(0,0,8537) + tdSql.checkData(0, 0, 8537) tdSql.query("select c2 from st0_1 order by ts") - tdSql.checkData(1,0,"D") + tdSql.checkData(1, 0, "D") tdSql.query("select * from gt0") - tdSql.checkData(0,0,'2021-02-25 10:00:12.000') - tdSql.checkData(0,1,637) + tdSql.checkData(0, 0, '2021-02-25 10:00:12.000') + tdSql.checkData(0, 1, 637) # check taosdumptest/tmp6 tdSql.execute("drop database dp1") tdSql.execute("drop database dp2") tdSql.execute("drop database dp3") - os.system("%staosdump -i ./taosdumptest/tmp6 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp6 -T 8 " % binPath) tdSql.execute("use dp3") tdSql.query("show databases") tdSql.checkRows(1) - tdSql.checkData(0,16,'ns') + tdSql.checkData(0, 16, 'ns') tdSql.query("show stables") tdSql.checkRows(1) tdSql.query("show tables") tdSql.checkRows(1) tdSql.query("select count(*) from st0_0") - tdSql.checkData(0, 0, 2) + tdSql.checkData(0, 0, 2) tdSql.query("select * from st0 order by ts") - tdSql.checkData(0,0,'2021-02-25 10:00:12.000000001') - tdSql.checkData(0,1,8600) + tdSql.checkData(0, 0, '2021-02-25 10:00:12.000000001') + tdSql.checkData(0, 1, 8600) # check taosdumptest/tmp7 tdSql.execute("drop database dp3") - os.system("%staosdump -i ./taosdumptest/tmp7 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp7 -T 8 " % binPath) tdSql.execute("use dp3") tdSql.query("show databases") tdSql.checkRows(1) - tdSql.checkData(0,16,'ms') + tdSql.checkData(0, 16, 'ms') tdSql.query("show stables") tdSql.checkRows(1) tdSql.query("show tables") @@ -297,20 +331,20 @@ class TDTestCase: # check taosdumptest/tmp8 tdSql.execute("drop database dp3") - os.system("%staosdump -i ./taosdumptest/tmp8 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp8 -T 8 " % binPath) tdSql.execute("use dp3") tdSql.query("show stables") tdSql.checkRows(1) tdSql.query("show tables") tdSql.checkRows(1) tdSql.query("select count(*) from st0_0") - tdSql.checkRows(0) + tdSql.checkRows(0) # tdSql.query("select * from st0 order by ts") # tdSql.checkData(0,0,'2021-02-25 10:00:12.000000001') # tdSql.checkData(0,1,8600) - for i in range(1,9): - os.system("rm -rf ./taosdumptest/tmp%d"%i) + for i in range(1, 9): + os.system("rm -rf ./taosdumptest/tmp%d" % i) os.system("rm -rf ./dump_result.txt") os.system("rm -rf ./db.csv") diff --git a/tests/pytest/tools/taosdumpTestBenchmark.py b/tests/pytest/tools/taosdumpTestBenchmark.py index 97dcf3e54bc972bceec4b250df690436fa3bbbc3..75238b7f7337f5316cde3b2cdba5a78cc26d496a 100644 --- a/tests/pytest/tools/taosdumpTestBenchmark.py +++ b/tests/pytest/tools/taosdumpTestBenchmark.py @@ -35,7 +35,7 @@ class TDTestCase: else: return True - def getBuildPath(self): + def getPath(self, tool="taosdump"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -43,13 +43,14 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosdump" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def insert_data(self, tbname, ts_start, count): pre_insert = "insert into %s values" % tbname @@ -81,12 +82,11 @@ class TDTestCase: os.system("rm -rf ./taosdumptest/tmp%d" % i) os.makedirs("./taosdumptest/tmp%d" % i) - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath("taosdump") + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found: %s" % binPath) # create db1 , one stables and one table ; create general tables tdSql.execute("drop database if exists dp1") @@ -158,7 +158,7 @@ class TDTestCase: 2, i + 1, i + 1, i + 1, i + 1, i + 1, i + 1, self.ts)) intData.append(i + 1) floatData.append(i + 0.1) - # os.system("%staosBenchmark -f tools/taosdump-insert-dp1.json -y " % binPath) + # os.system("%staosBenchmark -f tools/taosdump-insert-dp1.json -y " % benchBinPath) # create db1 , three stables:stb0,include ctables stb0_0 \ stb0_1,stb1 include ctables stb1_0 and stb1_1 # \stb3,include ctables stb3_0 and stb3_1 @@ -200,22 +200,22 @@ class TDTestCase: "insert into gt1 values(1614218413800,8638,78.862020199)") tdSql.execute("insert into gt2 values(1614218413900,8639,78.863)") # self.insert_data("t", self.ts, 300*10000); - # os.system("%staosBenchmark -f tools/taosdump-insert-dp2.json -y " % binPath) + # os.system("%staosBenchmark -f tools/taosdump-insert-dp2.json -y " % benchBinPath) # # taosdump data - # os.system("%staosdump -o ./taosdumptest/tmp1 taosdump -h -ptaosdata -P 6030 -u root -o taosdumptest \ + # os.system("%s -o ./taosdumptest/tmp1 taosdump -h -ptaosdata -P 6030 -u root -o taosdumptest \ # -D dp1,dp3 -N -c /home/chr/TDinternal/community/sim/dnode1/cfg/taos.cfg -s -d deflate" % binPath) os.system( - "%staosdump -o ./taosdumptest/tmp0 -D dp2,dp1 -T 8" % + "%s -o ./taosdumptest/tmp0 -D dp2,dp1 -T 8" % binPath) os.system( - "%staosdump -o ./taosdumptest/tmp1 dp2 st0 st1_0 gt0 -T 8" % + "%s -o ./taosdumptest/tmp1 dp2 st0 st1_0 gt0 -T 8" % binPath) # check taosdumptest/tmp0 tdSql.execute("drop database dp1") tdSql.execute("drop database dp2") - os.system("%staosdump -i ./taosdumptest/tmp0 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp0 -T 8 " % binPath) tdSql.execute("reset query cache") tdSql.execute("use dp1") @@ -265,7 +265,7 @@ class TDTestCase: # check taosdumptest/tmp1 tdSql.execute("drop database dp1") tdSql.execute("drop database dp2") - os.system("%staosdump -i ./taosdumptest/tmp1 -T 8 " % binPath) + os.system("%s -i ./taosdumptest/tmp1 -T 8 " % binPath) tdSql.execute("reset query cache") tdSql.execute("use dp2") tdSql.query("show stables") @@ -283,7 +283,7 @@ class TDTestCase: # #check taosdumptest/tmp2 # tdSql.execute("drop database dp1") # tdSql.execute("drop database dp2") - # os.system("%staosdump -i ./taosdumptest/tmp2 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp2 -T 8 " % binPath) # tdSql.execute("use dp1") # tdSql.query("show stables") # tdSql.checkRows(1) @@ -301,7 +301,7 @@ class TDTestCase: # #check taosdumptest/tmp3 # tdSql.execute("drop database dp1") - # os.system("%staosdump -i ./taosdumptest/tmp3 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp3 -T 8 " % binPath) # tdSql.execute("use dp2") # tdSql.query("show stables") # tdSql.checkRows(2) @@ -317,7 +317,7 @@ class TDTestCase: # #check taosdumptest/tmp4 # tdSql.execute("drop database dp2") - # os.system("%staosdump -i ./taosdumptest/tmp4 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp4 -T 8 " % binPath) # tdSql.execute("use dp2") # tdSql.query("show stables") # tdSql.checkRows(2) @@ -340,7 +340,7 @@ class TDTestCase: # #check taosdumptest/tmp5 # tdSql.execute("drop database dp2") - # os.system("%staosdump -i ./taosdumptest/tmp5 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp5 -T 8 " % binPath) # tdSql.execute("use dp2") # tdSql.query("show stables") # tdSql.checkRows(3) @@ -377,7 +377,7 @@ class TDTestCase: # tdSql.execute("drop database dp1") # tdSql.execute("drop database dp2") # tdSql.execute("drop database dp3") - # os.system("%staosdump -i ./taosdumptest/tmp6 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp6 -T 8 " % binPath) # tdSql.execute("use dp3") # tdSql.query("show databases") # tdSql.checkRows(1) @@ -394,7 +394,7 @@ class TDTestCase: # # check taosdumptest/tmp7 # tdSql.execute("drop database dp3") - # os.system("%staosdump -i ./taosdumptest/tmp7 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp7 -T 8 " % binPath) # tdSql.execute("use dp3") # tdSql.query("show databases") # tdSql.checkRows(1) @@ -411,7 +411,7 @@ class TDTestCase: # # check taosdumptest/tmp8 # tdSql.execute("drop database dp3") - # os.system("%staosdump -i ./taosdumptest/tmp8 -T 8 " % binPath) + # os.system("%s -i ./taosdumptest/tmp8 -T 8 " % binPath) # tdSql.execute("use dp3") # tdSql.query("show stables") # tdSql.checkRows(1) diff --git a/tests/pytest/tools/taosdumpTestNanoSupport.py b/tests/pytest/tools/taosdumpTestNanoSupport.py index 81e315934662184aa7828c2bf5ac5ef0a8cb368a..cbcf57db0a3a9493a05b6a7fcb43e689a8c16549 100644 --- a/tests/pytest/tools/taosdumpTestNanoSupport.py +++ b/tests/pytest/tools/taosdumpTestNanoSupport.py @@ -35,7 +35,7 @@ class TDTestCase: else: return True - def getBuildPath(self): + def getPath(self, tool="taosdump"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -43,13 +43,14 @@ class TDTestCase: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root) - len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def createdb(self, precision="ns"): tb_nums = self.numberOfTables @@ -118,12 +119,11 @@ class TDTestCase: if not os.path.exists("./taosdumptest/dumptmp3"): os.makedirs("./taosdumptest/dumptmp3") - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath("taosdump") + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found: %s" % binPath) # create nano second database @@ -132,40 +132,40 @@ class TDTestCase: # dump all data os.system( - "%staosdump --databases timedb1 -o ./taosdumptest/dumptmp1" % + "%s -y -g --databases timedb1 -o ./taosdumptest/dumptmp1" % binPath) # dump part data with -S -E os.system( - '%staosdump --databases timedb1 -S 1625068810000000000 -E 1625068860000000000 -o ./taosdumptest/dumptmp2 ' % + '%s -y -g --databases timedb1 -S 1625068810000000000 -E 1625068860000000000 -o ./taosdumptest/dumptmp2 ' % binPath) os.system( - '%staosdump --databases timedb1 -S 1625068810000000000 -o ./taosdumptest/dumptmp3 ' % + '%s -y -g --databases timedb1 -S 1625068810000000000 -o ./taosdumptest/dumptmp3 ' % binPath) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp2" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp2" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 510) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp3" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp3" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 900) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 1000) # check data origin_res = tdSql.getResult("select * from timedb1.st") tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + # dump data and check for taosdump dump_res = tdSql.getResult("select * from timedb1.st") if origin_res == dump_res: tdLog.info("test nano second : dump check data pass for all data!") @@ -177,7 +177,6 @@ class TDTestCase: os.system("rm -rf ./taosdumptest/") tdSql.execute("drop database if exists timedb1") - if not os.path.exists("./taosdumptest/tmp1"): os.makedirs("./taosdumptest/dumptmp1") @@ -190,53 +189,52 @@ class TDTestCase: if not os.path.exists("./taosdumptest/dumptmp3"): os.makedirs("./taosdumptest/dumptmp3") - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath() + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found: %s" % binPath) self.createdb(precision="us") os.system( - "%staosdump --databases timedb1 -o ./taosdumptest/dumptmp1" % + "%s -y -g --databases timedb1 -o ./taosdumptest/dumptmp1" % binPath) os.system( - '%staosdump --databases timedb1 -S 1625068810000000 -E 1625068860000000 -o ./taosdumptest/dumptmp2 ' % + '%s -y -g --databases timedb1 -S 1625068810000000 -E 1625068860000000 -o ./taosdumptest/dumptmp2 ' % binPath) os.system( - '%staosdump --databases timedb1 -S 1625068810000000 -o ./taosdumptest/dumptmp3 ' % + '%s -y -g --databases timedb1 -S 1625068810000000 -o ./taosdumptest/dumptmp3 ' % binPath) - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - os.system("%staosdump -i ./taosdumptest/dumptmp2" % binPath) - os.system("%staosdump -i ./taosdumptest/dumptmp3" % binPath) + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + os.system("%s -i ./taosdumptest/dumptmp2" % binPath) + os.system("%s -i ./taosdumptest/dumptmp3" % binPath) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp2" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp2" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 510) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp3" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp3" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 900) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 1000) # check data origin_res = tdSql.getResult("select * from timedb1.st") tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + # dump data and check for taosdump dump_res = tdSql.getResult("select * from timedb1.st") if origin_res == dump_res: tdLog.info("test micro second : dump check data pass for all data!") @@ -260,56 +258,56 @@ class TDTestCase: if not os.path.exists("./taosdumptest/dumptmp3"): os.makedirs("./taosdumptest/dumptmp3") - buildPath = self.getBuildPath() - if (buildPath == ""): + binPath = self.getPath() + if (binPath == ""): tdLog.exit("taosdump not found!") else: - tdLog.info("taosdump found in %s" % buildPath) - binPath = buildPath + "/build/bin/" + tdLog.info("taosdump found: %s" % binPath) self.createdb(precision="ms") os.system( - "%staosdump --databases timedb1 -o ./taosdumptest/dumptmp1" % + "%s -y -g --databases timedb1 -o ./taosdumptest/dumptmp1" % binPath) os.system( - '%staosdump --databases timedb1 -S 1625068810000 -E 1625068860000 -o ./taosdumptest/dumptmp2 ' % + '%s -y -g --databases timedb1 -S 1625068810000 -E 1625068860000 -o ./taosdumptest/dumptmp2 ' % binPath) os.system( - '%staosdump --databases timedb1 -S 1625068810000 -o ./taosdumptest/dumptmp3 ' % + '%s -y -g --databases timedb1 -S 1625068810000 -o ./taosdumptest/dumptmp3 ' % binPath) - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - os.system("%staosdump -i ./taosdumptest/dumptmp2" % binPath) - os.system("%staosdump -i ./taosdumptest/dumptmp3" % binPath) + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + os.system("%s -i ./taosdumptest/dumptmp2" % binPath) + os.system("%s -i ./taosdumptest/dumptmp3" % binPath) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp2" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp2" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 510) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp3" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp3" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 900) tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + # dump data and check for taosdump tdSql.query("select count(*) from timedb1.st") tdSql.checkData(0, 0, 1000) # check data origin_res = tdSql.getResult("select * from timedb1.st") tdSql.execute("drop database timedb1") - os.system("%staosdump -i ./taosdumptest/dumptmp1" % binPath) - # dump data and check for taosdump + os.system("%s -i ./taosdumptest/dumptmp1" % binPath) + # dump data and check for taosdump dump_res = tdSql.getResult("select * from timedb1.st") if origin_res == dump_res: - tdLog.info("test million second : dump check data pass for all data!") + tdLog.info( + "test million second : dump check data pass for all data!") else: tdLog.info( "test million second : dump check data failed for all data!") diff --git a/tests/pytest/update/update2.py b/tests/pytest/update/update2.py new file mode 100644 index 0000000000000000000000000000000000000000..e731e70b33b089d7e37727e3356e07712a9b25b9 --- /dev/null +++ b/tests/pytest/update/update2.py @@ -0,0 +1,90 @@ +################################################################### +# Copyright (c) 2016 by TAOS Technologies, Inc. +# All rights reserved. +# +# This file is proprietary and confidential to TAOS Technologies. +# No part of this file may be reproduced, stored, transmitted, +# disclosed or used in any form or by any means other than as +# expressly provided by the written permission from Jianhui Tao +# +################################################################### + +# -*- coding: utf-8 -*- + +import sys +import taos +from util.log import * +from util.cases import * +from util.sql import * +from util.dnodes import * +import random +import datetime +import threading + + +class TDTestCase: + def init(self, conn, logSql): + tdLog.debug("start to execute %s" % __file__) + tdSql.init(conn.cursor()) + + self.lock = threading.RLock() + self.ts = [] + + def restartTaosd(self): + tdDnodes.stop(1) + tdDnodes.startWithoutSleep(1) + tdSql.execute("use db") + + def insertData(self): + self.lock.acquire() + try: + sql = "insert into test2.warning_1 values " + for i in range(10): + ct = datetime.datetime.now() + t = int(ct.timestamp() * 1000) + self.ts.append(t) + wait = random.randint(1, 9) + time.sleep(0.0001 * wait) + sql += "(%d, %d, 0, 0, 0, %d, 0, %f, %f, 0, 0, %d, %d, False, 0, '', '', 0, False, %d)" % (t, random.randint(0, 20), random.randint(1, 10000), random.uniform(0, 1), random.uniform(0, 1), random.randint(1, 10000), random.randint(1, 10000), t) + tdSql.execute(sql) + finally: + self.lock.release() + + def updateData(self): + self.lock.acquire() + try: + sql = "insert into test2.warning_1(ts,endtime,maxspeed,endlongitude,endlatitude,drivercard_id,status,endmileage) values " + for t in self.ts: + sql += "(%d, %d, 0, %f, %f, 0, False, %d)" % (t, t, random.uniform(0, 1), random.uniform(0, 1), random.randint(1, 10000)) + tdSql.execute(sql) + self.ts.clear() + finally: + self.lock.release() + + def run(self): + + tdSql.execute("CREATE DATABASE test2 CACHE 1 BLOCKS 3 UPDATE 2") + tdSql.execute("use test2") + tdSql.execute('''CREATE TABLE test2.fx_car_warning (ts TIMESTAMP, type TINYINT, level TINYINT, origin TINYINT, endtime BIGINT, mileage INT, maxspeed DOUBLE, + longitude DOUBLE, latitude DOUBLE, endlongitude DOUBLE, endlatitude DOUBLE, drivercard_id BIGINT, infoid INT, status BOOL, endmileage INT, + duty_officer NCHAR(10), content NCHAR(100), cltime BIGINT, clstatus BOOL, starttime BIGINT) TAGS (catid BIGINT, car_id BIGINT, mytype TINYINT)''') + tdSql.execute("create table test2.warning_1 using test2.fx_car_warning tags(1, 1, 0)") + tdLog.sleep(1) + + for i in range(1000): + t1 = threading.Thread(target=self.insertData, args=( )) + t2 = threading.Thread(target=self.updateData, args=( )) + t1.start() + t2.start() + t1.join() + t2.join() + + tdSql.query("select * from test2.fx_car_warning where type is null") + tdSql.checkRows(0) + + def stop(self): + tdSql.close() + tdLog.success("%s successfully executed" % __file__) + +tdCases.addWindows(__file__, TDTestCase()) +tdCases.addLinux(__file__, TDTestCase()) \ No newline at end of file diff --git a/tests/pytest/util/dnodes-default.py b/tests/pytest/util/dnodes-default.py index 7d8fc3f630d6712e8d984f17fbcb701a4a81172c..055d3085d30c959490ea01815394a4c5bfe4d2ec 100644 --- a/tests/pytest/util/dnodes-default.py +++ b/tests/pytest/util/dnodes-default.py @@ -40,7 +40,8 @@ class TDSimClient: "jnidebugFlag": "135", "qdebugFlag": "135", "telemetryReporting": "0", - } + } + def init(self, path): self.__init__() self.path = path @@ -72,14 +73,14 @@ class TDSimClient: cmd = "rm -rf " + self.logDir if os.system(cmd) != 0: tdLog.exit(cmd) - - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" cmd = "rm -rf " + self.cfgDir if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -145,11 +146,11 @@ class TDDnode: if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -198,7 +199,7 @@ class TDDnode: "dnode:%d is deployed and configured by %s" % (self.index, self.cfgPath)) - def getBuildPath(self): + def getPath(self, tool="taosd"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -206,23 +207,22 @@ class TDDnode: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def start(self): - buildPath = self.getBuildPath() + binPath = self.getPath() - if (buildPath == ""): + if (binPath == ""): tdLog.exit("taosd not found!") else: - tdLog.info("taosd found in %s" % buildPath) - - binPath = buildPath + "/build/bin/taosd" + tdLog.info("taosd found: %s" % binPath) if self.deployed == 0: tdLog.exit("dnode:%d is not deployed" % (self.index)) diff --git a/tests/pytest/util/dnodes-no-random-fail.py b/tests/pytest/util/dnodes-no-random-fail.py index 86ef9e178e7776b1f2bf160e513d8392531ae5c2..467a19fa4d0e96b6a0201c889bd82ff5bd3e0881 100644 --- a/tests/pytest/util/dnodes-no-random-fail.py +++ b/tests/pytest/util/dnodes-no-random-fail.py @@ -37,7 +37,7 @@ class TDSimClient: "jnidebugFlag": "135", "qdebugFlag": "135", "telemetryReporting": "0", - } + } def init(self, path): self.__init__() @@ -70,14 +70,14 @@ class TDSimClient: cmd = "rm -rf " + self.logDir if os.system(cmd) != 0: tdLog.exit(cmd) - - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" cmd = "rm -rf " + self.cfgDir if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -143,11 +143,11 @@ class TDDnode: if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -196,7 +196,7 @@ class TDDnode: "dnode:%d is deployed and configured by %s" % (self.index, self.cfgPath)) - def getBuildPath(self): + def getPath(self, tool="taosd"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -204,23 +204,22 @@ class TDDnode: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def start(self): - buildPath = self.getBuildPath() + binPath = self.getPath() - if (buildPath == ""): + if (binPath == ""): tdLog.exit("taosd not found!") else: - tdLog.info("taosd found in %s" % buildPath) - - binPath = buildPath + "/build/bin/taosd" + tdLog.info("taosd found: %s" % binPath) if self.deployed == 0: tdLog.exit("dnode:%d is not deployed" % (self.index)) diff --git a/tests/pytest/util/dnodes-random-fail.py b/tests/pytest/util/dnodes-random-fail.py index 6590f1e2048521893d9eee5cd901ff9abde36ad1..6edd5f1f6a129f1890c6eff6cb0d282acdf03e45 100644 --- a/tests/pytest/util/dnodes-random-fail.py +++ b/tests/pytest/util/dnodes-random-fail.py @@ -37,7 +37,7 @@ class TDSimClient: "jnidebugFlag": "135", "qdebugFlag": "135", "telemetryReporting": "0", - } + } def init(self, path): self.__init__() @@ -70,14 +70,14 @@ class TDSimClient: cmd = "rm -rf " + self.logDir if os.system(cmd) != 0: tdLog.exit(cmd) - - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" cmd = "rm -rf " + self.cfgDir if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -143,11 +143,11 @@ class TDDnode: if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -196,7 +196,7 @@ class TDDnode: "dnode:%d is deployed and configured by %s" % (self.index, self.cfgPath)) - def getBuildPath(self): + def getPath(self, tool="taosd"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -204,23 +204,22 @@ class TDDnode: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): - if ("taosd" in files): + if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + return paths[0] def start(self): - buildPath = self.getBuildPath() + binPath = self.getPath() - if (buildPath == ""): + if (binPath == ""): tdLog.exit("taosd not found!") else: - tdLog.info("taosd found in %s" % buildPath) - - binPath = buildPath + "/build/bin/taosd" + tdLog.info("taosd found: %s" % binPath) if self.deployed == 0: tdLog.exit("dnode:%d is not deployed" % (self.index)) diff --git a/tests/pytest/util/dnodes.py b/tests/pytest/util/dnodes.py index 427cfe349e6ea9a43c0eab93dbee12828c8c3db1..3f54d264dfc827b7128166aaab959926ba790a73 100644 --- a/tests/pytest/util/dnodes.py +++ b/tests/pytest/util/dnodes.py @@ -65,9 +65,11 @@ class TDSimClient: cmd = "echo %s %s >> %s" % (option, value, self.cfgPath) if os.system(cmd) != 0: tdLog.exit(cmd) - def os_string(self,path): - os_path = path.replace("/",os.sep) + + def os_string(self, path): + os_path = path.replace("/", os.sep) return os_path + def deploy(self): self.logDir = self.os_string("%s/sim/psim/log" % (self.path)) self.cfgDir = self.os_string("%s/sim/psim/cfg" % (self.path)) @@ -76,11 +78,11 @@ class TDSimClient: # cmd = "rm -rf " + self.logDir # if os.system(cmd) != 0: # tdLog.exit(cmd) - if os.path.exists(self.logDir): + if os.path.exists(self.logDir): try: shutil.rmtree(self.logDir) - except: - tdLog.exit("del %s failed"%self.logDir) + except BaseException: + tdLog.exit("del %s failed" % self.logDir) # cmd = "mkdir -p " + self.logDir # if os.system(cmd) != 0: # tdLog.exit(cmd) @@ -88,11 +90,11 @@ class TDSimClient: # cmd = "rm -rf " + self.cfgDir # if os.system(cmd) != 0: # tdLog.exit(cmd) - if os.path.exists(self.cfgDir): + if os.path.exists(self.cfgDir): try: shutil.rmtree(self.cfgDir) - except: - tdLog.exit("del %s failed"%self.cfgDir) + except BaseException: + tdLog.exit("del %s failed" % self.cfgDir) # cmd = "mkdir -p " + self.cfgDir # if os.system(cmd) != 0: # tdLog.exit(cmd) @@ -102,8 +104,8 @@ class TDSimClient: # tdLog.exit(cmd) try: pathlib.Path(self.cfgPath).touch() - except: - tdLog.exit("create %s failed"%self.cfgPath) + except BaseException: + tdLog.exit("create %s failed" % self.cfgPath) if self.testCluster: self.cfg("masterIp", "192.168.0.1") self.cfg("secondIp", "192.168.0.2") @@ -123,36 +125,36 @@ class TDDnode: self.testCluster = False self.valgrind = 0 self.cfgDict = { - "numOfLogLines":"100000000", - "mnodeEqualVnodeNum":"0", - "walLevel":"2", - "fsync":"1000", - "statusInterval":"1", - "numOfMnodes":"3", - "numOfThreadsPerCore":"2.0", - "monitor":"0", - "maxVnodeConnections":"30000", - "maxMgmtConnections":"30000", - "maxMeterConnections":"30000", - "maxShellConns":"30000", - "locale":"en_US.UTF-8", - "charset":"UTF-8", - "asyncLog":"0", - "anyIp":"0", - "telemetryReporting":"0", - "dDebugFlag":"135", - "tsdbDebugFlag":"135", - "mDebugFlag":"135", - "sdbDebugFlag":"135", - "rpcDebugFlag":"135", - "tmrDebugFlag":"131", - "cDebugFlag":"135", - "httpDebugFlag":"135", - "monitorDebugFlag":"135", - "udebugFlag":"135", - "jnidebugFlag":"135", - "qdebugFlag":"135", - "maxSQLLength":"1048576", + "numOfLogLines": "100000000", + "mnodeEqualVnodeNum": "0", + "walLevel": "2", + "fsync": "1000", + "statusInterval": "1", + "numOfMnodes": "3", + "numOfThreadsPerCore": "2.0", + "monitor": "0", + "maxVnodeConnections": "30000", + "maxMgmtConnections": "30000", + "maxMeterConnections": "30000", + "maxShellConns": "30000", + "locale": "en_US.UTF-8", + "charset": "UTF-8", + "asyncLog": "0", + "anyIp": "0", + "telemetryReporting": "0", + "dDebugFlag": "135", + "tsdbDebugFlag": "135", + "mDebugFlag": "135", + "sdbDebugFlag": "135", + "rpcDebugFlag": "135", + "tmrDebugFlag": "131", + "cDebugFlag": "135", + "httpDebugFlag": "135", + "monitorDebugFlag": "135", + "udebugFlag": "135", + "jnidebugFlag": "135", + "qdebugFlag": "135", + "maxSQLLength": "1048576", "enableCoreFile": "1", } @@ -200,11 +202,11 @@ class TDDnode: if os.system(cmd) != 0: tdLog.exit(cmd) - os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.dataDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.logDir, exist_ok=True) # like "mkdir -p" - os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" + os.makedirs(self.cfgDir, exist_ok=True) # like "mkdir -p" cmd = "touch " + self.cfgPath if os.system(cmd) != 0: @@ -227,16 +229,16 @@ class TDDnode: isFirstDir = 1 if bool(updatecfgDict) and updatecfgDict[0] and updatecfgDict[0][0]: print(updatecfgDict[0][0]) - for key,value in updatecfgDict[0][0].items(): - if value == 'dataDir' : + for key, value in updatecfgDict[0][0].items(): + if value == 'dataDir': if isFirstDir: self.cfgDict.pop('dataDir') - self.cfg(value,key) + self.cfg(value, key) isFirstDir = 0 else: - self.cfg(value,key) + self.cfg(value, key) else: - self.addExtraCfg(key,value) + self.addExtraCfg(key, value) for key, value in self.cfgDict.items(): self.cfg(key, value) @@ -245,8 +247,7 @@ class TDDnode: "dnode:%d is deployed and configured by %s" % (self.index, self.cfgPath)) - def getBuildPath(self, tool="taosd"): - buildPath = "" + def getPath(self, tool="taosd"): selfPath = os.path.dirname(os.path.realpath(__file__)) if ("community" in selfPath): @@ -254,24 +255,30 @@ class TDDnode: else: projPath = selfPath[:selfPath.find("tests")] + paths = [] for root, dirs, files in os.walk(projPath): if ((tool) in files): rootRealPath = os.path.dirname(os.path.realpath(root)) if ("packaging" not in rootRealPath): - buildPath = root[:len(root)-len("/build/bin")] + paths.append(os.path.join(root, tool)) break - return buildPath + if (len(paths) == 0): + return "" + return paths[0] def start(self): - buildPath = self.getBuildPath() + binPath = self.getPath() - if (buildPath == ""): + if (binPath == ""): tdLog.exit("taosd not found!") else: - tdLog.info("taosd found in %s" % buildPath) + tdLog.info("taosd found: %s" % binPath) - binPath = buildPath + "/build/bin/taosd" - taosadapterBinPath = buildPath + "/build/bin/taosadapter" + taosadapterBinPath = self.getPath("taosadapter") + if (taosadapterBinPath == ""): + tdLog.info("taosAdapter not found!") + else: + tdLog.info("taosAdapter found: %s" % taosadapterBinPath) if self.deployed == 0: tdLog.exit("dnode:%d is not deployed" % (self.index)) @@ -288,7 +295,7 @@ class TDDnode: print(cmd) taosadapterCmd = "nohup %s --opentsdb_telnet.enable=true > /dev/null 2>&1 & " % ( - taosadapterBinPath) + taosadapterBinPath) tdLog.info(taosadapterCmd) if os.system(taosadapterCmd) != 0: tdLog.exit(taosadapterCmd) @@ -301,18 +308,22 @@ class TDDnode: if self.valgrind == 0: time.sleep(0.1) key = 'from offline to online' - bkey = bytes(key,encoding="utf8") + bkey = bytes(key, encoding="utf8") logFile = self.logDir + "/taosdlog.0" i = 0 while not os.path.exists(logFile): sleep(0.1) i += 1 - if i>50: + if i > 50: break - popen = subprocess.Popen('tail -f ' + logFile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) + popen = subprocess.Popen( + 'tail -f ' + logFile, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=True) pid = popen.pid # print('Popen.pid:' + str(pid)) - timeout = time.time() + 60*2 + timeout = time.time() + 60 * 2 while True: line = popen.stdout.readline().strip() if bkey in line: @@ -322,30 +333,35 @@ class TDDnode: tdLog.exit('wait too long for taosd start') tdLog.debug("the dnode:%d has been started." % (self.index)) else: - tdLog.debug("wait 10 seconds for the dnode:%d to start." % (self.index)) + tdLog.debug( + "wait 10 seconds for the dnode:%d to start." % + (self.index)) time.sleep(10) - # time.sleep(5) + def startWin(self): - buildPath = self.getBuildPath("taosd.exe") + binPath = self.getPath("taosd.exe") - if (buildPath == ""): + if (binPath == ""): tdLog.exit("taosd.exe not found!") else: - tdLog.info("taosd.exe found in %s" % buildPath) + tdLog.info("taosd.exe found: %s" % binPath) - binPath = buildPath + "/build/bin/taosd.exe" - taosadapterBinPath = buildPath + "/build/bin/taosadapter.exe" + taosadapterBinPath = self.getPath("taosadapter.exe") + if (taosadapterBinPath == ""): + tdLog.info("taosAdapter.exe not found!") + else: + tdLog.info("taosAdapter.exe found in %s" % taosadapterBuildPath) if self.deployed == 0: tdLog.exit("dnode:%d is not deployed" % (self.index)) cmd = "mintty -h never -w hide %s -c %s" % ( - binPath, self.cfgDir) + binPath, self.cfgDir) taosadapterCmd = "mintty -h never -w hide %s " % ( - taosadapterBinPath) + taosadapterBinPath) if os.system(taosadapterCmd) != 0: tdLog.exit(taosadapterCmd) @@ -357,18 +373,22 @@ class TDDnode: if self.valgrind == 0: time.sleep(0.1) key = 'from offline to online' - bkey = bytes(key,encoding="utf8") + bkey = bytes(key, encoding="utf8") logFile = self.logDir + "/taosdlog.0" i = 0 while not os.path.exists(logFile): sleep(0.1) i += 1 - if i>50: + if i > 50: break - popen = subprocess.Popen('tail -n +0 -f ' + logFile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) + popen = subprocess.Popen( + 'tail -n +0 -f ' + logFile, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=True) pid = popen.pid # print('Popen.pid:' + str(pid)) - timeout = time.time() + 60*2 + timeout = time.time() + 60 * 2 while True: line = popen.stdout.readline().strip() if bkey in line: @@ -378,19 +398,24 @@ class TDDnode: tdLog.exit('wait too long for taosd start') tdLog.debug("the dnode:%d has been started." % (self.index)) else: - tdLog.debug("wait 10 seconds for the dnode:%d to start." % (self.index)) + tdLog.debug( + "wait 10 seconds for the dnode:%d to start." % + (self.index)) time.sleep(10) - + def startWithoutSleep(self): - buildPath = self.getBuildPath() + binPath = self.getPath() - if (buildPath == ""): + if (binPath == ""): tdLog.exit("taosd not found!") else: - tdLog.info("taosd found in %s" % buildPath) + tdLog.info("taosd found: %s" % binPath) - binPath = buildPath + "/build/bin/taosd" - taosadapterBinPath = buildPath + "/build/bin/taosadapter" + taosadapterBinPath = self.getPath("taosadapter") + if (taosadapterBinPath == ""): + tdLog.exit("taosAdapter not found!") + else: + tdLog.info("taosAdapter found: %s" % taosadapterBinPath) if self.deployed == 0: tdLog.exit("dnode:%d is not deployed" % (self.index)) @@ -420,14 +445,14 @@ class TDDnode: taosadapterPsCmd = "ps -ef|grep -w %s| grep -v grep | awk '{print $2}'" % taosadapterToBeKilled taosadapterProcessID = subprocess.check_output( - taosadapterPsCmd, shell=True).decode("utf-8") + taosadapterPsCmd, shell=True).decode("utf-8") while(taosadapterProcessID): taosadapterKillCmd = "kill -INT %s > /dev/null 2>&1" % taosadapterProcessID os.system(taosadapterKillCmd) time.sleep(1) taosadapterProcessID = subprocess.check_output( - taosadapterPsCmd, shell=True).decode("utf-8") + taosadapterPsCmd, shell=True).decode("utf-8") if self.valgrind == 0: toBeKilled = "taosd" @@ -599,7 +624,7 @@ class TDDnodes: def startWin(self, index): self.check(index) self.dnodes[index - 1].startWin() - + def startWithoutSleep(self, index): self.check(index) self.dnodes[index - 1].startWithoutSleep() diff --git a/tests/pytest/util/dockerNodes.py b/tests/pytest/util/dockerNodes.py index 595700a670f17968aa4595e2e006b30cb775571b..3edbfbb835ffa2bb0e0f85629d3948fede39f378 100644 --- a/tests/pytest/util/dockerNodes.py +++ b/tests/pytest/util/dockerNodes.py @@ -142,10 +142,8 @@ class BuildDockerCluser: print("create dnode tdnode%d" % i) self.cursor.execute("create dnode tdnode%d" % i) - def startArbitrator(self): - for i in range(1, self.numOfNodes + 1): - self.cfg("arbitrator", "tdnode1:6042", i) - cmd = "docker exec -d $(docker ps|grep tdnode1|awk '{print $1}') tarbitrator" + def startArbitrator(self, hostname = 'tdnode1'): + cmd = "docker exec -d $(docker ps|grep '%s'|awk '{print $1}') tarbitrator" % hostname self.execCmd(cmd) def prepardBuild(self): diff --git a/tests/script/general/compute/cast_query1.sim b/tests/script/general/compute/cast_query1.sim index de0722bcd8c3911d94b4558c302c22bbc607defd..4bc7af7941b8fd9104a59b053d29ad4a0fa8cc5e 100644 --- a/tests/script/general/compute/cast_query1.sim +++ b/tests/script/general/compute/cast_query1.sim @@ -1159,10 +1159,14 @@ if $data40 != 4 then return -1 endi if $data50 != NULL then - return -1 + if $data50 != 9223372036854775807 then #for arm64 + return -1 + endi endi if $data60 != NULL then - return -1 + if $data60 != 9223372036854775807 then #for arm64 + return -1 + endi endi sql select cast(c6 as binary(60)) from tb1; if $rows != 7 then @@ -1234,10 +1238,14 @@ if $data40 != @70-01-01 08:00:00.004@ then return -1 endi if $data50 != NULL then - return -1 + if $data50 != @94-08-17 15:12:55.807@ then #for arm64 + return -1 + endi endi if $data60 != NULL then - return -1 + if $data60 != @94-08-17 15:12:55.807@ then #for arm64 + return -1 + endi endi sql select cast(c6 as nchar(50)) from tb1; if $rows != 7 then @@ -1332,10 +1340,14 @@ if $data40 != 4 then return -1 endi if $data50 != NULL then - return -1 + if $data50 != 9223372036854775807 then #for arm64 + return -1 + endi endi if $data60 != NULL then - return -1 + if $data60 != 9223372036854775807 then #for arm64 + return -1 + endi endi sql select cast(c7 as binary(400)) from tb1; if $rows != 7 then @@ -1407,10 +1419,14 @@ if $data40 != @70-01-01 08:00:00.004@ then return -1 endi if $data50 != NULL then - return -1 + if $data50 != @94-08-17 15:12:55.807@ then #for arm64 + return -1 + endi endi if $data60 != NULL then - return -1 + if $data60 != @94-08-17 15:12:55.807@ then #for arm64 + return -1 + endi endi sql select cast(c7 as nchar(500)) from tb1; if $rows != 7 then diff --git a/tests/script/general/compute/scalar_triangle.sim b/tests/script/general/compute/scalar_triangle.sim deleted file mode 100644 index 524a544e9fe88cc4fe5fa1d639e52a032f06222e..0000000000000000000000000000000000000000 --- a/tests/script/general/compute/scalar_triangle.sim +++ /dev/null @@ -1,1763 +0,0 @@ -system sh/stop_dnodes.sh - -system sh/deploy.sh -n dnode1 -i 1 -system sh/cfg.sh -n dnode1 -c walLevel -v 1 -system sh/exec.sh -n dnode1 -s start -sleep 500 -sql connect - -$dbPrefix = db -$tbPrefix = ct -$mtPrefix = st -$tbNum = 2 -$rowNum = 50 - -print =============== step1 create stable/table -$i = 0 -$db = $dbPrefix . $i -$mt = $mtPrefix . $i - -sql drop database $db -x step1 -step1: -sql create database $db -sql use $db -sql create table $mt (ts timestamp, c1 int, c2 float, c3 bigint, c4 smallint, c5 tinyint, c6 double, c7 bool, c8 nchar(5), c9 binary(10)) TAGS (tgcol int) -$i = 0 -while $i < $tbNum - $tb = $tbPrefix . $i - sql create table $tb using $mt tags( $i ) - - $x = 0 - $y = 0.25 - - while $x < $rowNum - $cc = $x * 60000 - $ms = 1601481600000 + $cc - sql insert into $tb values ($ms , $x , $y , $x , $x , $x , $y , $x , $x , $x ) - $x = $x + 1 - $y = $y + 1 - endw - - $i = $i + 1 -endw - -print ================= step2 -$i = 1 -$tb = $tbPrefix . $i -$stb = $mtPrefix . 0 - - -print execute sql select c1, sin(c1), cos(c1), tan(c1), asin(c1), acos(c1), atan(c1) from ct1 -sql select c1, sin(c1), cos(c1), tan(c1), asin(c1), acos(c1), atan(c1) from ct1 -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.000000000@ then - return -1 -endi -if $data02 != @1.000000000@ then - return -1 -endi -if $data03 != @0.000000000@ then - return -1 -endi -if $data04 != @0.000000000@ then - return -1 -endi -if $data05 != @1.570796327@ then - return -1 -endi -if $data06 != @0.000000000@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.841470985@ then - return -1 -endi -if $data12 != @0.540302306@ then - return -1 -endi -if $data13 != @1.557407725@ then - return -1 -endi -if $data14 != @1.570796327@ then - return -1 -endi -if $data15 != @0.000000000@ then - return -1 -endi -if $data16 != @0.785398163@ then - return -1 -endi -if $data20 != @2@ then - return -1 -endi -if $data21 != @0.909297427@ then - return -1 -endi -if $data22 != @-0.416146837@ then - return -1 -endi -if $data23 != @-2.185039863@ then - return -1 -endi -if $data24 != @nan@ then - return -1 -endi -if $data25 != @nan@ then - return -1 -endi -if $data26 != @1.107148718@ then - return -1 -endi -if $data30 != @3@ then - return -1 -endi -if $data31 != @0.141120008@ then - return -1 -endi -if $data32 != @-0.989992497@ then - return -1 -endi -if $data33 != @-0.142546543@ then - return -1 -endi -if $data34 != @nan@ then - return -1 -endi -if $data35 != @nan@ then - return -1 -endi -if $data36 != @1.249045772@ then - return -1 -endi -if $data40 != @4@ then - return -1 -endi -if $data41 != @-0.756802495@ then - return -1 -endi -if $data42 != @-0.653643621@ then - return -1 -endi -if $data43 != @1.157821282@ then - return -1 -endi -if $data44 != @nan@ then - return -1 -endi -if $data45 != @nan@ then - return -1 -endi -if $data46 != @1.325817664@ then - return -1 -endi -if $data50 != @5@ then - return -1 -endi -if $data51 != @-0.958924275@ then - return -1 -endi -if $data52 != @0.283662185@ then - return -1 -endi -if $data53 != @-3.380515006@ then - return -1 -endi -if $data54 != @nan@ then - return -1 -endi -if $data55 != @nan@ then - return -1 -endi -if $data56 != @1.373400767@ then - return -1 -endi -if $data60 != @6@ then - return -1 -endi -if $data61 != @-0.279415498@ then - return -1 -endi -if $data62 != @0.960170287@ then - return -1 -endi -if $data63 != @-0.291006191@ then - return -1 -endi -if $data64 != @nan@ then - return -1 -endi -if $data65 != @nan@ then - return -1 -endi -if $data66 != @1.405647649@ then - return -1 -endi -if $data70 != @7@ then - return -1 -endi -if $data71 != @0.656986599@ then - return -1 -endi -if $data72 != @0.753902254@ then - return -1 -endi -if $data73 != @0.871447983@ then - return -1 -endi -if $data74 != @nan@ then - return -1 -endi -if $data75 != @nan@ then - return -1 -endi -if $data76 != @1.428899272@ then - return -1 -endi -if $data80 != @8@ then - return -1 -endi -if $data81 != @0.989358247@ then - return -1 -endi -if $data82 != @-0.145500034@ then - return -1 -endi -if $data83 != @-6.799711455@ then - return -1 -endi -if $data84 != @nan@ then - return -1 -endi -if $data85 != @nan@ then - return -1 -endi -if $data86 != @1.446441332@ then - return -1 -endi -if $data90 != @9@ then - return -1 -endi -if $data91 != @0.412118485@ then - return -1 -endi -if $data92 != @-0.911130262@ then - return -1 -endi -if $data93 != @-0.452315659@ then - return -1 -endi -if $data94 != @nan@ then - return -1 -endi -if $data95 != @nan@ then - return -1 -endi -if $data96 != @1.460139106@ then - return -1 -endi -print execute sql select c1, sin(c2)+2, cos(c2)+2, cos(pow(c2,2)+2), tan(pow(c2,3)+log(c3, 2)+pow(c5,2)) as v4, asin(pow(c4, 4.5)+pow(c3, 2)), acos(log(c1,2)+log(c3,4)+pow(c6,2.8)+2) as v6 from ct1 where ts == 1601481600000 -sql select c1, sin(c2)+2, cos(c2)+2, cos(pow(c2,2)+2), tan(pow(c2,3)+log(c3, 2)+pow(c5,2)) as v4, asin(pow(c4, 4.5)+pow(c3, 2)), acos(log(c1,2)+log(c3,4)+pow(c6,2.8)+2) as v6 from ct1 where ts == 1601481600000 -if $data00 != @0@ then - return -1 -endi -if $data01 != @2.247403959@ then - return -1 -endi -if $data02 != @2.968912422@ then - return -1 -endi -if $data03 != @-0.472128411@ then - return -1 -endi -if $data04 != @-nan@ then - return -1 -endi -if $data05 != @0.000000000@ then - return -1 -endi -if $data06 != @nan@ then - return -1 -endi -print execute sql select c1, sin(c2), cos(c1+2), tan(c2+2)+2, sin(c2+3)+cos(c3+2)+tan(c5+2) as v4, sin(c4+4.5)+tan(c3+2), sin(c1+2)+cos(c3+4)+acos(c6+2.8)+2 as v6 from st0 where ts == 1601481600000 -sql select c1, sin(c2), cos(c1+2), tan(c2+2)+2, sin(c2+3)+cos(c3+2)+tan(c5+2) as v4, sin(c4+4.5)+tan(c3+2), sin(c1+2)+cos(c3+4)+acos(c6+2.8)+2 as v6 from st0 where ts == 1601481600000 -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.247403959@ then - return -1 -endi -if $data02 != @-0.416146837@ then - return -1 -endi -if $data03 != @0.761372384@ then - return -1 -endi -if $data04 != @-2.709381834@ then - return -1 -endi -if $data05 != @-3.162569981@ then - return -1 -endi -if $data06 != @nan@ then - return -1 -endi -if $data10 != @0@ then - return -1 -endi -if $data11 != @0.247403959@ then - return -1 -endi -if $data12 != @-0.416146837@ then - return -1 -endi -if $data13 != @0.761372384@ then - return -1 -endi -if $data14 != @-2.709381834@ then - return -1 -endi -if $data15 != @-3.162569981@ then - return -1 -endi -if $data16 != @nan@ then - return -1 -endi -print execute sql select c1, tan(c2+ 2), sin(pow(c1,2)), cos(pow(c2,2)+2), tan(pow(c2,3)+log(c3, 2)+pow(c5,2)) as v4, asin(pow(c4, 4.5)+pow(c3, 2)), acos(log(c1,2)+log(c3,4)+pow(c6,2.8)+2) as v6 from st0 where c1 == 0 -sql select c1, tan(c2+ 2), sin(pow(c1,2)), cos(pow(c2,2)+2), tan(pow(c2,3)+log(c3, 2)+pow(c5,2)) as v4, asin(pow(c4, 4.5)+pow(c3, 2)), acos(log(c1,2)+log(c3,4)+pow(c6,2.8)+2) as v6 from st0 where c1 == 0 -if $data00 != @0@ then - return -1 -endi -if $data01 != @-1.238627616@ then - return -1 -endi -if $data02 != @0.000000000@ then - return -1 -endi -if $data03 != @-0.472128411@ then - return -1 -endi -if $data04 != @-nan@ then - return -1 -endi -if $data05 != @0.000000000@ then - return -1 -endi -if $data06 != @nan@ then - return -1 -endi -if $data10 != @0@ then - return -1 -endi -if $data11 != @-1.238627616@ then - return -1 -endi -if $data12 != @0.000000000@ then - return -1 -endi -if $data13 != @-0.472128411@ then - return -1 -endi -if $data14 != @-nan@ then - return -1 -endi -if $data15 != @0.000000000@ then - return -1 -endi -if $data16 != @nan@ then - return -1 -endi -print execute sql select c1, atan(c2+2), asin(c1+2), acos(c2+c1)+2, acos(c2+c3)+asin(c3+c2)+pow(c5,2) as v4, acos(c4/4.5)+asin(c3-2), asin(c1/2)+log(c3,c4)+pow(c6, 2.8)+2 as v6 from st0 where c1 == 0 -sql select c1, atan(c2+2), asin(c1+2), acos(c2+c1)+2, acos(c2+c3)+asin(c3+c2)+pow(c5,2) as v4, acos(c4/4.5)+asin(c3-2), asin(c1/2)+log(c3,c4)+pow(c6, 2.8)+2 as v6 from st0 where c1 == 0 -if $data00 != @0@ then - return -1 -endi -if $data01 != @1.152571997@ then - return -1 -endi -if $data02 != @nan@ then - return -1 -endi -if $data03 != @3.318116072@ then - return -1 -endi -if $data04 != @1.570796327@ then - return -1 -endi -if $data05 != @nan@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data10 != @0@ then - return -1 -endi -if $data11 != @1.152571997@ then - return -1 -endi -if $data12 != @nan@ then - return -1 -endi -if $data13 != @3.318116072@ then - return -1 -endi -if $data14 != @1.570796327@ then - return -1 -endi -if $data15 != @nan@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -print execute sql select c1, cos(c2+2), cos(ceil(pow(c1,2))), sin(floor(pow(c2,2)+2)), sin(ceil(c2)+floor(c3+c2)+round(c5+c2)) as v4, atan(pow(c4, 4.5)+pow(c3, 2)), tan(log(c1,2)+cos(c3+4)+pow(c6,2.8)+2) as v6 from st0 order by ts desc -sql select c1, cos(c2+2), cos(ceil(pow(c1,2))), sin(floor(pow(c2,2)+2)), sin(ceil(c2)+floor(c3+c2)+round(c5+c2)) as v4, atan(pow(c4, 4.5)+pow(c3, 2)), tan(log(c1,2)+cos(c3+4)+pow(c6,2.8)+2) as v6 from st0 order by ts desc -if $data00 != @49@ then - return -1 -endi -if $data01 != @0.742154197@ then - return -1 -endi -if $data02 != @0.679868770@ then - return -1 -endi -if $data03 != @0.313028384@ then - return -1 -endi -if $data04 != @-0.044212563@ then - return -1 -endi -if $data05 != @1.570796302@ then - return -1 -endi -if $data06 != @0.036525682@ then - return -1 -endi -if $data10 != @49@ then - return -1 -endi -if $data11 != @0.742154197@ then - return -1 -endi -if $data12 != @0.679868770@ then - return -1 -endi -if $data13 != @0.313028384@ then - return -1 -endi -if $data14 != @-0.044212563@ then - return -1 -endi -if $data15 != @1.570796302@ then - return -1 -endi -if $data16 != @0.036525682@ then - return -1 -endi -if $data20 != @48@ then - return -1 -endi -if $data21 != @0.964966028@ then - return -1 -endi -if $data22 != @-0.350599733@ then - return -1 -endi -if $data23 != @0.070932648@ then - return -1 -endi -if $data24 != @0.945445155@ then - return -1 -endi -if $data25 != @1.570796300@ then - return -1 -endi -if $data26 != @-2.376507095@ then - return -1 -endi -if $data30 != @48@ then - return -1 -endi -if $data31 != @0.964966028@ then - return -1 -endi -if $data32 != @-0.350599733@ then - return -1 -endi -if $data33 != @0.070932648@ then - return -1 -endi -if $data34 != @0.945445155@ then - return -1 -endi -if $data35 != @1.570796300@ then - return -1 -endi -if $data36 != @-2.376507095@ then - return -1 -endi -if $data40 != @47@ then - return -1 -endi -if $data41 != @0.300592544@ then - return -1 -endi -if $data42 != @-0.895890607@ then - return -1 -endi -if $data43 != @-0.629747508@ then - return -1 -endi -if $data44 != @0.580586641@ then - return -1 -endi -if $data45 != @1.570796297@ then - return -1 -endi -if $data46 != @-0.760993034@ then - return -1 -endi -if $data50 != @47@ then - return -1 -endi -if $data51 != @0.300592544@ then - return -1 -endi -if $data52 != @-0.895890607@ then - return -1 -endi -if $data53 != @-0.629747508@ then - return -1 -endi -if $data54 != @0.580586641@ then - return -1 -endi -if $data55 != @1.570796297@ then - return -1 -endi -if $data56 != @-0.760993034@ then - return -1 -endi -if $data60 != @46@ then - return -1 -endi -if $data61 != @-0.640144339@ then - return -1 -endi -if $data62 != @0.136916383@ then - return -1 -endi -if $data63 != @0.536725534@ then - return -1 -endi -if $data64 != @-0.616064204@ then - return -1 -endi -if $data65 != @1.570796294@ then - return -1 -endi -if $data66 != @-1.929269971@ then - return -1 -endi -if $data70 != @46@ then - return -1 -endi -if $data71 != @-0.640144339@ then - return -1 -endi -if $data72 != @0.136916383@ then - return -1 -endi -if $data73 != @0.536725534@ then - return -1 -endi -if $data74 != @-0.616064204@ then - return -1 -endi -if $data75 != @1.570796294@ then - return -1 -endi -if $data76 != @-1.929269971@ then - return -1 -endi -if $data80 != @45@ then - return -1 -endi -if $data81 != @-0.992335469@ then - return -1 -endi -if $data82 != @-0.241134582@ then - return -1 -endi -if $data83 != @-0.623130100@ then - return -1 -endi -if $data84 != @-0.930094878@ then - return -1 -endi -if $data85 != @1.570796290@ then - return -1 -endi -if $data86 != @-7.205947409@ then - return -1 -endi -if $data90 != @45@ then - return -1 -endi -if $data91 != @-0.992335469@ then - return -1 -endi -if $data92 != @-0.241134582@ then - return -1 -endi -if $data93 != @-0.623130100@ then - return -1 -endi -if $data94 != @-0.930094878@ then - return -1 -endi -if $data95 != @1.570796290@ then - return -1 -endi -if $data96 != @-7.205947409@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5+c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from ct1 order by ts limit 2; -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5+c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from ct1 order by ts limit 2; -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.778073197@ then - return -1 -endi -if $data02 != @0.614300282@ then - return -1 -endi -if $data03 != @3.203726628@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.022469882@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.141120008@ then - return -1 -endi -if $data12 != @0.666366745@ then - return -1 -endi -if $data13 != @1.558041126@ then - return -1 -endi -if $data14 != @2.154346269@ then - return -1 -endi -if $data15 != @0.172042236@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 order by ts desc) -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 order by ts desc) -if $data00 != @49@ then - return -1 -endi -if $data01 != @0.670229176@ then - return -1 -endi -if $data02 != @0.992374553@ then - return -1 -endi -if $data03 != @0.929814367@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.713618282@ then - return -1 -endi -if $data06 != @-0.746290424@ then - return -1 -endi -if $data10 != @49@ then - return -1 -endi -if $data11 != @0.670229176@ then - return -1 -endi -if $data12 != @0.992374553@ then - return -1 -endi -if $data13 != @0.929814367@ then - return -1 -endi -if $data14 != @nan@ then - return -1 -endi -if $data15 != @0.713618282@ then - return -1 -endi -if $data16 != @-0.746290424@ then - return -1 -endi -if $data20 != @48@ then - return -1 -endi -if $data21 != @-0.262374854@ then - return -1 -endi -if $data22 != @0.620208114@ then - return -1 -endi -if $data23 != @1.817585733@ then - return -1 -endi -if $data24 != @nan@ then - return -1 -endi -if $data25 != @1.211884234@ then - return -1 -endi -if $data26 != @5.183714989@ then - return -1 -endi -if $data30 != @48@ then - return -1 -endi -if $data31 != @-0.262374854@ then - return -1 -endi -if $data32 != @0.620208114@ then - return -1 -endi -if $data33 != @1.817585733@ then - return -1 -endi -if $data34 != @nan@ then - return -1 -endi -if $data35 != @1.211884234@ then - return -1 -endi -if $data36 != @5.183714989@ then - return -1 -endi -if $data40 != @47@ then - return -1 -endi -if $data41 != @-0.953752653@ then - return -1 -endi -if $data42 != @0.659304076@ then - return -1 -endi -if $data43 != @3.457510675@ then - return -1 -endi -if $data44 != @nan@ then - return -1 -endi -if $data45 != @0.882083819@ then - return -1 -endi -if $data46 != @2.630220446@ then - return -1 -endi -if $data50 != @47@ then - return -1 -endi -if $data51 != @-0.953752653@ then - return -1 -endi -if $data52 != @0.659304076@ then - return -1 -endi -if $data53 != @3.457510675@ then - return -1 -endi -if $data54 != @nan@ then - return -1 -endi -if $data55 != @0.882083819@ then - return -1 -endi -if $data56 != @2.630220446@ then - return -1 -endi -if $data60 != @46@ then - return -1 -endi -if $data61 != @-0.768254661@ then - return -1 -endi -if $data62 != @0.999843325@ then - return -1 -endi -if $data63 != @1.276316926@ then - return -1 -endi -if $data64 != @nan@ then - return -1 -endi -if $data65 != @-0.300459259@ then - return -1 -endi -if $data66 != @0.133920399@ then - return -1 -endi -if $data70 != @46@ then - return -1 -endi -if $data71 != @-0.768254661@ then - return -1 -endi -if $data72 != @0.999843325@ then - return -1 -endi -if $data73 != @1.276316926@ then - return -1 -endi -if $data74 != @nan@ then - return -1 -endi -if $data75 != @-0.300459259@ then - return -1 -endi -if $data76 != @0.133920399@ then - return -1 -endi -if $data80 != @45@ then - return -1 -endi -if $data81 != @0.123573123@ then - return -1 -endi -if $data82 != @0.673565060@ then - return -1 -endi -if $data83 != @1.519318619@ then - return -1 -endi -if $data84 != @nan@ then - return -1 -endi -if $data85 != @-1.566189594@ then - return -1 -endi -if $data86 != @5.513771854@ then - return -1 -endi -if $data90 != @45@ then - return -1 -endi -if $data91 != @0.123573123@ then - return -1 -endi -if $data92 != @0.673565060@ then - return -1 -endi -if $data93 != @1.519318619@ then - return -1 -endi -if $data94 != @nan@ then - return -1 -endi -if $data95 != @-1.566189594@ then - return -1 -endi -if $data96 != @5.513771854@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 order by ts limit 2); -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 order by ts limit 2); -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.778073197@ then - return -1 -endi -if $data02 != @0.614300282@ then - return -1 -endi -if $data03 != @3.203726628@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.022469882@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.141120008@ then - return -1 -endi -if $data12 != @0.666366745@ then - return -1 -endi -if $data13 != @1.558041126@ then - return -1 -endi -if $data14 != @1.832595715@ then - return -1 -endi -if $data15 != @0.172042236@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 ) order by ts desc -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 ) order by ts desc -if $data00 != @49@ then - return -1 -endi -if $data01 != @0.670229176@ then - return -1 -endi -if $data02 != @0.992374553@ then - return -1 -endi -if $data03 != @0.929814367@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.713618282@ then - return -1 -endi -if $data06 != @-0.746290424@ then - return -1 -endi -if $data10 != @49@ then - return -1 -endi -if $data11 != @0.670229176@ then - return -1 -endi -if $data12 != @0.992374553@ then - return -1 -endi -if $data13 != @0.929814367@ then - return -1 -endi -if $data14 != @nan@ then - return -1 -endi -if $data15 != @0.713618282@ then - return -1 -endi -if $data16 != @-0.746290424@ then - return -1 -endi -if $data20 != @48@ then - return -1 -endi -if $data21 != @-0.262374854@ then - return -1 -endi -if $data22 != @0.620208114@ then - return -1 -endi -if $data23 != @1.817585733@ then - return -1 -endi -if $data24 != @nan@ then - return -1 -endi -if $data25 != @1.211884234@ then - return -1 -endi -if $data26 != @5.183714989@ then - return -1 -endi -if $data30 != @48@ then - return -1 -endi -if $data31 != @-0.262374854@ then - return -1 -endi -if $data32 != @0.620208114@ then - return -1 -endi -if $data33 != @1.817585733@ then - return -1 -endi -if $data34 != @nan@ then - return -1 -endi -if $data35 != @1.211884234@ then - return -1 -endi -if $data36 != @5.183714989@ then - return -1 -endi -if $data40 != @47@ then - return -1 -endi -if $data41 != @-0.953752653@ then - return -1 -endi -if $data42 != @0.659304076@ then - return -1 -endi -if $data43 != @3.457510675@ then - return -1 -endi -if $data44 != @nan@ then - return -1 -endi -if $data45 != @0.882083819@ then - return -1 -endi -if $data46 != @2.630220446@ then - return -1 -endi -if $data50 != @47@ then - return -1 -endi -if $data51 != @-0.953752653@ then - return -1 -endi -if $data52 != @0.659304076@ then - return -1 -endi -if $data53 != @3.457510675@ then - return -1 -endi -if $data54 != @nan@ then - return -1 -endi -if $data55 != @0.882083819@ then - return -1 -endi -if $data56 != @2.630220446@ then - return -1 -endi -if $data60 != @46@ then - return -1 -endi -if $data61 != @-0.768254661@ then - return -1 -endi -if $data62 != @0.999843325@ then - return -1 -endi -if $data63 != @1.276316926@ then - return -1 -endi -if $data64 != @nan@ then - return -1 -endi -if $data65 != @-0.300459259@ then - return -1 -endi -if $data66 != @0.133920399@ then - return -1 -endi -if $data70 != @46@ then - return -1 -endi -if $data71 != @-0.768254661@ then - return -1 -endi -if $data72 != @0.999843325@ then - return -1 -endi -if $data73 != @1.276316926@ then - return -1 -endi -if $data74 != @nan@ then - return -1 -endi -if $data75 != @-0.300459259@ then - return -1 -endi -if $data76 != @0.133920399@ then - return -1 -endi -if $data80 != @45@ then - return -1 -endi -if $data81 != @0.123573123@ then - return -1 -endi -if $data82 != @0.673565060@ then - return -1 -endi -if $data83 != @1.519318619@ then - return -1 -endi -if $data84 != @nan@ then - return -1 -endi -if $data85 != @-1.566189594@ then - return -1 -endi -if $data86 != @5.513771854@ then - return -1 -endi -if $data90 != @45@ then - return -1 -endi -if $data91 != @0.123573123@ then - return -1 -endi -if $data92 != @0.673565060@ then - return -1 -endi -if $data93 != @1.519318619@ then - return -1 -endi -if $data94 != @nan@ then - return -1 -endi -if $data95 != @-1.566189594@ then - return -1 -endi -if $data96 != @5.513771854@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 ) -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from st0 ) -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.778073197@ then - return -1 -endi -if $data02 != @0.614300282@ then - return -1 -endi -if $data03 != @3.203726628@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.022469882@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.141120008@ then - return -1 -endi -if $data12 != @0.666366745@ then - return -1 -endi -if $data13 != @1.558041126@ then - return -1 -endi -if $data14 != @1.832595715@ then - return -1 -endi -if $data15 != @0.172042236@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -if $data20 != @2@ then - return -1 -endi -if $data21 != @-0.756802495@ then - return -1 -endi -if $data22 != @1.000000000@ then - return -1 -endi -if $data23 != @1.234030298@ then - return -1 -endi -if $data24 != @nan@ then - return -1 -endi -if $data25 != @0.755422294@ then - return -1 -endi -if $data26 != @0.058157641@ then - return -1 -endi -if $data30 != @3@ then - return -1 -endi -if $data31 != @-0.958924275@ then - return -1 -endi -if $data32 != @0.666366745@ then - return -1 -endi -if $data33 != @3.428875323@ then - return -1 -endi -if $data34 != @nan@ then - return -1 -endi -if $data35 != @1.008737178@ then - return -1 -endi -if $data36 != @2.578037959@ then - return -1 -endi -if $data40 != @4@ then - return -1 -endi -if $data41 != @-0.279415498@ then - return -1 -endi -if $data42 != @0.614300282@ then - return -1 -endi -if $data43 != @1.853464439@ then - return -1 -endi -if $data44 != @nan@ then - return -1 -endi -if $data45 != @0.382340276@ then - return -1 -endi -if $data46 != @5.147179529@ then - return -1 -endi -if $data50 != @5@ then - return -1 -endi -if $data51 != @0.656986599@ then - return -1 -endi -if $data52 != @0.990059086@ then - return -1 -endi -if $data53 != @0.886449574@ then - return -1 -endi -if $data54 != @nan@ then - return -1 -endi -if $data55 != @-0.876294736@ then - return -1 -endi -if $data56 != @-0.924536117@ then - return -1 -endi -if $data60 != @6@ then - return -1 -endi -if $data61 != @0.989358247@ then - return -1 -endi -if $data62 != @0.727035131@ then - return -1 -endi -if $data63 != @3.124320480@ then - return -1 -endi -if $data64 != @nan@ then - return -1 -endi -if $data65 != @-1.869688257@ then - return -1 -endi -if $data66 != @2.172420891@ then - return -1 -endi -if $data70 != @7@ then - return -1 -endi -if $data71 != @0.412118485@ then - return -1 -endi -if $data72 != @0.574400879@ then - return -1 -endi -if $data73 != @2.137595835@ then - return -1 -endi -if $data74 != @nan@ then - return -1 -endi -if $data75 != @-1.811908862@ then - return -1 -endi -if $data76 != @4.862055338@ then - return -1 -endi -if $data80 != @8@ then - return -1 -endi -if $data81 != @-0.544021111@ then - return -1 -endi -if $data82 != @0.961216805@ then - return -1 -endi -if $data83 != @0.578734473@ then - return -1 -endi -if $data84 != @nan@ then - return -1 -endi -if $data85 != @-0.719965518@ then - return -1 -endi -if $data86 != @-4.087614772@ then - return -1 -endi -if $data90 != @9@ then - return -1 -endi -if $data91 != @-0.999990207@ then - return -1 -endi -if $data92 != @0.791836209@ then - return -1 -endi -if $data93 != @2.776612512@ then - return -1 -endi -if $data94 != @nan@ then - return -1 -endi -if $data95 != @0.592988627@ then - return -1 -endi -if $data96 != @1.796697094@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 ) order by ts limit 2; -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 ) order by ts limit 2; -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.778073197@ then - return -1 -endi -if $data02 != @0.614300282@ then - return -1 -endi -if $data03 != @3.203726628@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.022469882@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.141120008@ then - return -1 -endi -if $data12 != @0.666366745@ then - return -1 -endi -if $data13 != @1.558041126@ then - return -1 -endi -if $data14 != @1.832595715@ then - return -1 -endi -if $data15 != @0.172042236@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -print execute sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 ) limit 2; -sql select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6 from (select * from ct1 ) limit 2; -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.778073197@ then - return -1 -endi -if $data02 != @0.614300282@ then - return -1 -endi -if $data03 != @3.203726628@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.022469882@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.141120008@ then - return -1 -endi -if $data12 != @0.666366745@ then - return -1 -endi -if $data13 != @1.558041126@ then - return -1 -endi -if $data14 != @1.832595715@ then - return -1 -endi -if $data15 != @0.172042236@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -print execute sql select * from (select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6, ts from st0 order by ts desc) -sql select * from (select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6, ts from st0 order by ts desc) -if $data00 != @49@ then - return -1 -endi -if $data01 != @0.670229176@ then - return -1 -endi -if $data02 != @0.992374553@ then - return -1 -endi -if $data03 != @0.929814367@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.713618282@ then - return -1 -endi -if $data06 != @-0.746290424@ then - return -1 -endi -if $data07 != @20-10-01 00:49:00.000@ then - return -1 -endi -if $data10 != @49@ then - return -1 -endi -if $data11 != @0.670229176@ then - return -1 -endi -if $data12 != @0.992374553@ then - return -1 -endi -if $data13 != @0.929814367@ then - return -1 -endi -if $data14 != @nan@ then - return -1 -endi -if $data15 != @0.713618282@ then - return -1 -endi -if $data16 != @-0.746290424@ then - return -1 -endi -if $data17 != @20-10-01 00:49:00.000@ then - return -1 -endi -if $data20 != @48@ then - return -1 -endi -if $data21 != @-0.262374854@ then - return -1 -endi -if $data22 != @0.620208114@ then - return -1 -endi -if $data23 != @1.817585733@ then - return -1 -endi -if $data24 != @nan@ then - return -1 -endi -if $data25 != @1.211884234@ then - return -1 -endi -if $data26 != @5.183714989@ then - return -1 -endi -if $data27 != @20-10-01 00:48:00.000@ then - return -1 -endi -if $data30 != @48@ then - return -1 -endi -if $data31 != @-0.262374854@ then - return -1 -endi -if $data32 != @0.620208114@ then - return -1 -endi -if $data33 != @1.817585733@ then - return -1 -endi -if $data34 != @nan@ then - return -1 -endi -if $data35 != @1.211884234@ then - return -1 -endi -if $data36 != @5.183714989@ then - return -1 -endi -if $data37 != @20-10-01 00:48:00.000@ then - return -1 -endi -if $data40 != @47@ then - return -1 -endi -if $data41 != @-0.953752653@ then - return -1 -endi -if $data42 != @0.659304076@ then - return -1 -endi -if $data43 != @3.457510675@ then - return -1 -endi -if $data44 != @nan@ then - return -1 -endi -if $data45 != @0.882083819@ then - return -1 -endi -if $data46 != @2.630220446@ then - return -1 -endi -if $data47 != @20-10-01 00:47:00.000@ then - return -1 -endi -if $data50 != @47@ then - return -1 -endi -if $data51 != @-0.953752653@ then - return -1 -endi -if $data52 != @0.659304076@ then - return -1 -endi -if $data53 != @3.457510675@ then - return -1 -endi -if $data54 != @nan@ then - return -1 -endi -if $data55 != @0.882083819@ then - return -1 -endi -if $data56 != @2.630220446@ then - return -1 -endi -if $data57 != @20-10-01 00:47:00.000@ then - return -1 -endi -if $data60 != @46@ then - return -1 -endi -if $data61 != @-0.768254661@ then - return -1 -endi -if $data62 != @0.999843325@ then - return -1 -endi -if $data63 != @1.276316926@ then - return -1 -endi -if $data64 != @nan@ then - return -1 -endi -if $data65 != @-0.300459259@ then - return -1 -endi -if $data66 != @0.133920399@ then - return -1 -endi -if $data67 != @20-10-01 00:46:00.000@ then - return -1 -endi -if $data70 != @46@ then - return -1 -endi -if $data71 != @-0.768254661@ then - return -1 -endi -if $data72 != @0.999843325@ then - return -1 -endi -if $data73 != @1.276316926@ then - return -1 -endi -if $data74 != @nan@ then - return -1 -endi -if $data75 != @-0.300459259@ then - return -1 -endi -if $data76 != @0.133920399@ then - return -1 -endi -if $data77 != @20-10-01 00:46:00.000@ then - return -1 -endi -if $data80 != @45@ then - return -1 -endi -if $data81 != @0.123573123@ then - return -1 -endi -if $data82 != @0.673565060@ then - return -1 -endi -if $data83 != @1.519318619@ then - return -1 -endi -if $data84 != @nan@ then - return -1 -endi -if $data85 != @-1.566189594@ then - return -1 -endi -if $data86 != @5.513771854@ then - return -1 -endi -if $data87 != @20-10-01 00:45:00.000@ then - return -1 -endi -if $data90 != @45@ then - return -1 -endi -if $data91 != @0.123573123@ then - return -1 -endi -if $data92 != @0.673565060@ then - return -1 -endi -if $data93 != @1.519318619@ then - return -1 -endi -if $data94 != @nan@ then - return -1 -endi -if $data95 != @-1.566189594@ then - return -1 -endi -if $data96 != @5.513771854@ then - return -1 -endi -if $data97 != @20-10-01 00:45:00.000@ then - return -1 -endi -print execute sql select * from (select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6, ts from ct1 order by ts limit 2); -sql select * from (select c1, sin(c2+2), cos(sin(c1-2)), tan(cos(c2*2))+2, asin(acos(c2%3))+acos(c3/2)+atan(c5*c2) as v4, sin(c4+4.5)+cos(c3/2), tan(c1)+log(c3, c4)+sin(c6+c3)+2 as v6, ts from ct1 order by ts limit 2); -if $data00 != @0@ then - return -1 -endi -if $data01 != @0.778073197@ then - return -1 -endi -if $data02 != @0.614300282@ then - return -1 -endi -if $data03 != @3.203726628@ then - return -1 -endi -if $data04 != @nan@ then - return -1 -endi -if $data05 != @0.022469882@ then - return -1 -endi -if $data06 != @-nan@ then - return -1 -endi -if $data07 != @20-10-01 00:00:00.000@ then - return -1 -endi -if $data10 != @1@ then - return -1 -endi -if $data11 != @0.141120008@ then - return -1 -endi -if $data12 != @0.666366745@ then - return -1 -endi -if $data13 != @1.558041126@ then - return -1 -endi -if $data14 != @1.832595715@ then - return -1 -endi -if $data15 != @0.172042236@ then - return -1 -endi -if $data16 != @-nan@ then - return -1 -endi -if $data17 != @20-10-01 00:01:00.000@ then - return -1 -endi - -print ===============> step 3 sql_error stable, group by, window -sql_error select sin(c2) from $stb group by tbname; - -sql_error select sin(c2) from $stb group by tgcol; - -sql_error select sin(c2) from $stb group by c3; - -sql_error select sin(c2) from $stb interval(1m); - -sql_error select sin(c2) from $stb state_window(c7); - -sql_error select sin(c2) from $tb state_window(c7); - -sql_error select sin(c2) from $stb session(ts, 30s); - -sql_error select sin(c2) from $tb session(ts, 30s); - -sql_error select sin(c2) from $stb slimit 2; - -sql_error select sin(c2) from $stb interval(1m) slimit 2; - -print =============== clear -#sql drop database $db -#sql show databases -#if $rows != 0 then -# return -1 -#endi - -#system sh/exec.sh -n dnode1 -s stop -x SIGINT - diff --git a/tests/script/general/compute/str_char_length.sim b/tests/script/general/compute/str_char_length.sim index 5ef295db8893dfbcf9fd38f07c6849764251dcce..97365867d91831487d8605e341f1e23395ee216d 100644 --- a/tests/script/general/compute/str_char_length.sim +++ b/tests/script/general/compute/str_char_length.sim @@ -1024,7 +1024,7 @@ if $data60 != @10@ then endi print execute sql select char_length(c15) from (select * from stb1); sql select char_length(c15) from (select * from stb1); -if $data00 != @0@ then +if $data00 != @1@ then return -1 endi if $data10 != @NULL@ then @@ -1033,25 +1033,25 @@ endi if $data20 != @NULL@ then return -1 endi -if $data30 != @0@ then +if $data30 != @1@ then return -1 endi -if $data40 != @0@ then +if $data40 != @1@ then return -1 endi -if $data50 != @0@ then +if $data50 != @3@ then return -1 endi if $data60 != @0@ then return -1 endi -if $data70 != @0@ then +if $data70 != @1@ then return -1 endi -if $data80 != @0@ then +if $data80 != @1@ then return -1 endi -if $data90 != @0@ then +if $data90 != @1@ then return -1 endi print execute sql select char_length(cast(a as binary(10))) from (select avg(c2) as a from stb1 where ts >= '2021-11-11 09:00:00.000' and ts <= '2021-11-11 09:00:09.000' interval(1s) fill(null)); diff --git a/tests/script/general/parser/columnValue_unsign.sim b/tests/script/general/parser/columnValue_unsign.sim index 9e011dd74ab49d8fc9617a20e6478d1e463c2433..e0507870c0e71720d0082775b06147d567998b05 100644 --- a/tests/script/general/parser/columnValue_unsign.sim +++ b/tests/script/general/parser/columnValue_unsign.sim @@ -116,7 +116,7 @@ if $data00 != NULL then return -1 endi -sql select count(*), a from mt_unsigned_1 group by a; +sql select count(*), a from mt_unsigned_1 group by a order by a desc; if $rows != 2 then return -1 endi @@ -137,7 +137,7 @@ if $data11 != 1 then return -1 endi -sql select count(*), b from mt_unsigned_1 group by b; +sql select count(*), b from mt_unsigned_1 group by b order by b desc; if $rows != 2 then return -1 endi @@ -158,7 +158,7 @@ if $data11 != 2 then return -1 endi -sql select count(*), c from mt_unsigned_1 group by c; +sql select count(*), c from mt_unsigned_1 group by c order by c desc; if $rows != 2 then return -1 endi @@ -179,7 +179,7 @@ if $data11 != 3 then return -1 endi -sql select count(*), d from mt_unsigned_1 group by d; +sql select count(*), d from mt_unsigned_1 group by d order by d desc; if $rows != 2 then return -1 endi diff --git a/tests/script/general/parser/groupby.sim b/tests/script/general/parser/groupby.sim index 1fe19714bbd516c2e8938ce1290f04f8d2053839..9baf028bc8233c0fd6c3ada9392bca717270b3be 100644 --- a/tests/script/general/parser/groupby.sim +++ b/tests/script/general/parser/groupby.sim @@ -594,7 +594,8 @@ if $data10 != @{slop:0.000000, intercept:1.000000}@ then return -1 endi -if $data90 != @{slop:0.000000, intercept:9.000000}@ then +if $data90 != @{slop:0.000000, intercept:17.000000}@ then + print " data90 expect: {slop:0.000000, intercept:17.000000} real:"$data90 return -1 endi diff --git a/tests/script/general/parser/limit_stb.sim b/tests/script/general/parser/limit_stb.sim index 2e6c10cd96db8536e12acf57bf9283eb20f59d1b..498632252b269d872e28928300aaeb0ebf6e5911 100644 --- a/tests/script/general/parser/limit_stb.sim +++ b/tests/script/general/parser/limit_stb.sim @@ -168,9 +168,9 @@ sql select * from $stb limit 2 offset $offset if $rows != 2 then return -1 endi -if $data00 != @18-09-17 10:30:00.002@ then - return -1 -endi +#if $data00 != @18-09-17 10:30:00.002@ then +# return -1 +#endi if $data01 != 9 then return -1 endi diff --git a/tests/script/general/parser/scalar_expression.sim b/tests/script/general/parser/scalar_expression.sim deleted file mode 100644 index 9f8c9c38caa81613a58aa4de596d453eae162ad7..0000000000000000000000000000000000000000 --- a/tests/script/general/parser/scalar_expression.sim +++ /dev/null @@ -1,251 +0,0 @@ - -system sh/stop_dnodes.sh - -system sh/deploy.sh -n dnode1 -i 1 -system sh/cfg.sh -n dnode1 -c walLevel -v 1 -system sh/exec.sh -n dnode1 -s start -sleep 500 -sql connect - -$dbPrefix = db -$tbPrefix = ct -$mtPrefix = st -$tbNum = 2 -$rowNum = 50 - -print =============== step1 create stable/table -$i = 0 -$db = $dbPrefix . $i -$mt = $mtPrefix . $i - -sql drop database $db -x step1 -step1: -sql create database $db -sql use $db -sql create table $mt (ts timestamp, c1 int, c2 float, c3 bigint, c4 smallint, c5 tinyint, c6 double, c7 bool, c8 nchar(5), c9 binary(10)) TAGS (tgcol int) -$i = 0 -while $i < $tbNum - $tb = $tbPrefix . $i - sql create table $tb using $mt tags( $i ) - - $x = 0 - $y = 0.25 - - while $x < $rowNum - $cc = $x * 60000 - $ms = 1601481600000 + $cc - sql insert into $tb values ($ms , $x , $y , $x , $x , $x , $y , $x , $x , $x ) - $x = $x + 1 - $y = $y + 1 - endw - - $i = $i + 1 -endw - -print ================= step2 - -print execute sql select floor(3.0)+ceil(4.0) from ct0 -sql select floor(3.0)+ceil(4.0) from ct0 -if $data00 != @7.000000000@ then - return -1 -endi -if $data10 != @7.000000000@ then - return -1 -endi -if $data20 != @7.000000000@ then - return -1 -endi -if $data30 != @7.000000000@ then - return -1 -endi -if $data40 != @7.000000000@ then - return -1 -endi -if $data50 != @7.000000000@ then - return -1 -endi -if $data60 != @7.000000000@ then - return -1 -endi -if $data70 != @7.000000000@ then - return -1 -endi -if $data80 != @7.000000000@ then - return -1 -endi -if $data90 != @7.000000000@ then - return -1 -endi -print execute sql select sum(c1)+3.0+4.0 from st0 -sql select sum(c1)+3.0+4.0 from st0 -if $data00 != @2457.000000000@ then - return -1 -endi -print execute sql select sin(log(avg(c1),sum(c2))+3)%4 from st0 -sql select sin(log(avg(c1),sum(c2))+3)%4 from st0 -if $data00 != @-0.265074286@ then - return -1 -endi -print execute sql select log(pow(length(concat('3','4')),2),c2) from st0 -sql select log(pow(length(concat('3','4')),2),c2) from st0 -if $data00 != @-1.000000000@ then - return -1 -endi -if $data10 != @inf@ then - return -1 -endi -if $data20 != @2.000000000@ then - return -1 -endi -if $data30 != @1.261859507@ then - return -1 -endi -if $data40 != @1.000000000@ then - return -1 -endi -if $data50 != @0.861353116@ then - return -1 -endi -if $data60 != @0.773705614@ then - return -1 -endi -if $data70 != @0.712414374@ then - return -1 -endi -if $data80 != @0.666666667@ then - return -1 -endi -if $data90 != @0.630929754@ then - return -1 -endi -print execute sql select round(log(pow(length(concat('3','4')),2),c2)+floor(c3))+2 from st0 -sql select round(log(pow(length(concat('3','4')),2),c2)+floor(c3))+2 from st0 -if $data00 != @1.000000000@ then - return -1 -endi -if $data10 != @inf@ then - return -1 -endi -if $data20 != @6.000000000@ then - return -1 -endi -if $data30 != @6.000000000@ then - return -1 -endi -if $data40 != @7.000000000@ then - return -1 -endi -if $data50 != @8.000000000@ then - return -1 -endi -if $data60 != @9.000000000@ then - return -1 -endi -if $data70 != @10.000000000@ then - return -1 -endi -if $data80 != @11.000000000@ then - return -1 -endi -if $data90 != @12.000000000@ then - return -1 -endi -print execute sql select sin(pow(c1,log(c2,2))+pow(c2,2)) as val from ct0 union all select pow(c4,2)+tan(sin(c5)/cos(c6)) as val from ct1 -sql select sin(pow(c1,log(c2,2))+pow(c2,2)) as val from ct0 union all select pow(c4,2)+tan(sin(c5)/cos(c6)) as val from ct1 -if $data00 != @-nan@ then - return -1 -endi -if $data10 != @0.909297427@ then - return -1 -endi -if $data20 != @-0.279415498@ then - return -1 -endi -if $data30 != @0.843325058@ then - return -1 -endi -if $data40 != @0.551426681@ then - return -1 -endi -if $data50 != @-0.840606612@ then - return -1 -endi -if $data60 != @0.436161076@ then - return -1 -endi -if $data70 != @0.897498185@ then - return -1 -endi -if $data80 != @-0.885952778@ then - return -1 -endi -if $data90 != @0.429470715@ then - return -1 -endi -print execute sql select asin(c1) from st0 limit 1 -sql select asin(c1) from st0 limit 1 -if $data00 != @0.000000000@ then - return -1 -endi -print execute sql select pow(c1,2) from st0 limit 1 offset 2; -sql select pow(c1,2) from st0 limit 1 offset 2; -if $data00 != @4.000000000@ then - return -1 -endi -print execute sql select cos(c1) from db0.ct0, db0.ct1 where ct0.ts==ct1.ts -sql select cos(c1) from db0.ct0, db0.ct1 where ct0.ts==ct1.ts -if $data00 != @1.000000000@ then - return -1 -endi -if $data10 != @0.540302306@ then - return -1 -endi -if $data20 != @-0.416146837@ then - return -1 -endi -if $data30 != @-0.989992497@ then - return -1 -endi -if $data40 != @-0.653643621@ then - return -1 -endi -if $data50 != @0.283662185@ then - return -1 -endi -if $data60 != @0.960170287@ then - return -1 -endi -if $data70 != @0.753902254@ then - return -1 -endi -if $data80 != @-0.145500034@ then - return -1 -endi -if $data90 != @-0.911130262@ then - return -1 -endi -print ============== invalid expressions -$stb = st0 -sql_error select agg(c1)+c2 from $stb -sql_error select agg(c1+2) from $stb -sql_error select agg(ceil(c1))+c2 from $stb -sql_error select agg(ceil(c1)) from $stb -sql_error select asin(c1) from $stb group by tbname -sql_error select asin(c2) from $stb group by tgcol -sql_error select asin(c1) from $stb session_window(ts, 1s) -sql_error select cos(c1) from $stb state_window(f1) -sql_error select pow(c2,2) from $stb interval(1s) sliding(500a) -sql_error select pow(c2,2) from $stb state_window(f1) -sql_error select tan(c1) from $stb from d.st slimit 1 -sql_error select c1+2, tbname from $stb group by tbname -sql select sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(c1)))))))))))))))) from $stb -sql_error select sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(c1))))))))))))))))) from $stb -print =============== clear -sql drop database $db -sql show databases -if $rows != 0 then - return -1 -endi - -system sh/exec.sh -n dnode1 -s stop -x SIGINT - diff --git a/tests/script/unique/big/maxvnodes.sim b/tests/script/unique/big/maxvnodes.sim index 10dbc8bbff1a7be19791b75d77c705ffb060e48a..4d99ace03dda48a240a05ddb4928c7aacc11af7a 100644 --- a/tests/script/unique/big/maxvnodes.sim +++ b/tests/script/unique/big/maxvnodes.sim @@ -52,7 +52,7 @@ $x = 0 show3: $x = $x + 1 sleep 2000 - if $x == 1000 then + if $x == 100 then return -1 endi @@ -86,4 +86,4 @@ system sh/exec.sh -n dnode4 -s stop -x SIGINT system sh/exec.sh -n dnode5 -s stop -x SIGINT system sh/exec.sh -n dnode6 -s stop -x SIGINT system sh/exec.sh -n dnode7 -s stop -x SIGINT -system sh/exec.sh -n dnode8 -s stop -x SIGINT \ No newline at end of file +system sh/exec.sh -n dnode8 -s stop -x SIGINT diff --git a/tests/system-test/5-taos-tools/basic.py b/tests/system-test/5-taos-tools/basic.py index a05cf39001e600085b654d20e0180351cc94f195..f2f273b9a78745d027d59c4a9a10246516f4d342 100644 --- a/tests/system-test/5-taos-tools/basic.py +++ b/tests/system-test/5-taos-tools/basic.py @@ -23,33 +23,34 @@ import subprocess class TDTestCase: def caseDescription(self): ''' - case1: [TD-11977] start taosdump without taosd + case1: [TD-11977] start taosdump without taosd case1: [TD-11977] start taosBenchmark without taosd case1: [TD-11977] start taosAdaptor without taosd - ''' + ''' return - + def init(self, conn, logSql): tdLog.debug("start to execute %s" % __file__) tdSql.init(conn.cursor(), logSql) def run(self): - tdSql.prepare() - - tools = ["taosdump", "taosBenchmark", "taosAdaptor"] + tdSql.prepare() + + tools = ["taosdump", "taosBenchmark", "taosadapter"] tdDnodes.stop(1) - for tool in tools: - path = tdDnodes.dnodes[1].getBuildPath(tool) + for tool in tools: + path = tdDnodes.dnodes[1].getPath(tool) try: - path += "/build/bin/" print(f"{path}{tool}") if tool == "taosBenchmark": - os.system(f"{path}{tool} -y") + os.system(f"{path}{tool} -y") + elif tool == "taosadapter": + os.system(f"pkill -9 {tool}") else: os.system(f"{path}{tool}") - except: + except BaseException: pass def stop(self):